Thank you for your reply. Actually you can ignore the func(), i realized i am overcomplicating things. Here is what I need. So my output has 2 numbers: y_pred[0] and y_pred[1]. I want my loss to be this: L = MSE(y,y_pred) + abs(sqrt((d(y_pred[0])/d(z))**2 + (d(y_pred[1])/d(z))**2)-1). So I want the norm of my Jacobian to be 1. I tried using this: torch.autograd.grad(output[0][0], output[1], create_graph=True)[0] to get, for example, d(y_pred[0])/d(z). It works for one example, but if I have a batch it doesn’t work anymore (I am not sure how to handle the dimensionality of the tensors so that I can take gradients properly).