the algorithm is hard to decipher, but in general your solutions are to either express it without a loop (so torch.zeros() buffers wouldn’t need to be explicitly created), or write parts to a python list and use torch.stack afterwards.