I am solving a non-linear optimization problem and use torch.autograd.grad to provide Jacobian that an optimizer requires.
Please see the code snippet below:

where x is a tensor variable with respect to which I want to compute the gradient.
I add the .numpy() argument, because the .evaluate() accepts only numpy array.

But in this case, I encounter the following error as expected:

RuntimeError: Can't call numpy() on Variable that requires grad. Use var.detach().numpy() instead.

I think the detach().numpy() argument breaks the computational graph, but I need a gradient with respect to x.

Unfortunately, you will only be able to get gradients using autograd if you use pytorch’s Tensor and operators to do all the computations.

If you have an operation that you cannot do this way, you will need to provide the gradient formula yourself for that step. You can see how to extend the autograd in this Note.

So you meant var.detach().numpy() breaks the computational graph and we cannot compute the gradient correctly anymore by using torch.autograd.grad(). Is it correct?

So you meant var.detach().numpy() breaks the computational graph and we cannot compute the gradient correctly anymore by using torch.autograd.grad() . Is it correct?

It is correct. Because you convert the Tensor into a numpy array, we cannot track gradients anymore.

Unfortunately we cannot do magic For AD to work, we need to know everything that you do with the data. If we cannot know what you function did, we cannot compute gradients for it.