Solved by eqy in post #4 
              
              
                I think something simpler can be done e.g., 
import torch

n, p, q = 9, 2, 3
x = torch.randn(p, q, requires_grad=True)
A = torch.randn(q, p)
z = torch.randn(q, 1)

f = A@x
y = None
for k in range(int(n/q)):
    if(y is None):                                                                           …