 # Why does ".backward(retain_graph=True)" gives different values each time is called?

Starting with a simple example from here.

``````from torch import tensor,empty,zeros
y = empty(3)
y = 3*x**2
y = x**2 + 2*x**3
y = 10*x
``````

This is a 2 input, 3 outputs model. I’m interested in getting the full Jacobian matrix. To do that, I was thinking:

``````J = zeros((y.shape,x.shape))
for i in range(y.shape):
xU = zeros(y.shape)
xU[i] = 1.0
y.backward(xU,retain_graph=True)
``````

However, the output of this is:

``````tensor([[ 6.,  0.],
[ 8., 24.],
[ 8., 34.]])
``````

while it should be:

``````tensor([[ 6.,  0.],
[ 2., 24.],
[ 0, 10.]])
``````

Trying to debug what’s going on, I found out the following:

``````y.backward(retain_graph=True); print(x.grad)
``````

gives:

``````tensor([6., 0.])
tensor([12.,  0.])
``````

Can someone explain what is going on under the hood with the call to “.backward(retain_graph=True)”? Why does it give different values when called twice?

I think that’s the key to why my calculation of the Jacobian matrix is not correct.
Thanks

Hi,

Whenever you call backward, it accumulates gradients on parameters. That’s why you call optimizer.zero_grad() before calling loss.backward(). Here, it’s the same thing happening. By the second call to backward you add more gradients on top of the previously added gradients by the first call.

Another way to solve this is to use `autograd.grad()` that returns the gradient instead of accumulating them.