did you try vectorization before send them to function g
stacked_x = torch.stack(x, dim=0)
shift_x = torch.stack((x[1:n-1,:], torch.zeros_like(x[0]), dim=0)
detached_x = shift_x.detach()
g(stacked_x, detached_x)  # vectorization of function g is needed.