Does replacing this:
grad_x, = torch.autograd.grad(flat_y, x, grad_y, retain_graph=True, create_graph=create_graph)

by
grad_x, = torch.autograd.grad(flat_y[i], x, retain_graph=True, create_graph=create_graph)

solves the error?