in a simple test in pytorch, I want to see grad in a non-leaf tensor, so I use retain_grad():
import torch
a = torch.tensor([1.], requires_grad=True)
y = torch.zeros((10))
gt = torch.zeros((10))
y[0] = a
y[1] = y[0] * 2
y.retain_grad()
loss = torch.sum((y-gt) ** 2)
loss.backward()
print(y.grad)
it gives me a normal output:
tensor([2., 4., 0., 0., 0., 0., 0., 0., 0., 0.])
but when I use retain grad() before y[1] and after y[0] is assigned:
import torch
a = torch.tensor([1.], requires_grad=True)
y = torch.zeros((10))
gt = torch.zeros((10))
y[0] = a
y.retain_grad()
y[1] = y[0] * 2
loss = torch.sum((y-gt) ** 2)
loss.backward()
print(y.grad)
now the output changes to:
tensor([10., 0., 0., 0., 0., 0., 0., 0., 0., 0.])
I can't understand the result at all.
