Why cant I see .grad of an intermediate variable?

Kalamaya: Hi! I am loving this framework… Since Im a noob, I am probably not getting something, but I am wondering why I cant get the gradient of an intermediate variable with .grad? Here is an example of what I mean: <SCODE>xx = Variable(torch.randn(1,1), requires_grad = True)
yy = 3*xx
zz = yy**2
zz.backward()
xx.grad # This is ok
yy.grad # This gives 0! 
zz.grad # This should give 1! 
<ECODE> So I get the correct result for xx.grad, but why does yy.grad show 0, as does zz.grad? How can I get the yy.grad value in this case? Thanks!

smth: Hi Kalamaya, By default, gradients are only retained for leaf variables. non-leaf variables’ gradients are not retained to be inspected later. This was done by design, to save memory. <SCODE>from __future__ import print_function
from torch.autograd import Variable
import torch

xx = Variable(torch.randn(1,1), requires_grad = True)
yy = 3*xx
zz = yy**2

yy.register_hook(print)
zz.backward()
<ECODE> Output: <SCODE>Variable containing:
-3.2480
[torch.FloatTensor of size 1x1]
<ECODE>

Kalamaya: The only way I have been able to really extract the gradient however is via a global variable at the moment. This is because the function I pass in (apparently) only allows me to pass in one argument, and that is reserved for the yy.grad. What I mean is given here: <SCODE>yGrad = torch.zeros(1,1)
def extract(xVar):
	global yGrad
	yGrad = xVar	

xx = Variable(torch.randn(1,1), requires_grad = True)
yy = 3*xx
zz = yy**2

yy.register_hook(extract)

#### Run the backprop:
print (yGrad) # Shows 0.
zz.backward()
print (yGrad) # Show the correct dzdy
<ECODE> So here, I am able to extract the yy.grad, BUT, I can only do so with a global variable, which I would rather not do. Is there a simpler way? Many thanks.

mrdrozdov: 

apaszke: 

Kalamaya: 

apaszke: <SCODE>grads = {}
def save_grad(name):
    def hook(grad):
        grads[name] = grad
    return hook

x = Variable(torch.randn(1,1), requires_grad=True)
y = 3*x
z = y**2

# In here, save_grad('y') returns a hook (a function) that keeps 'y' as name
y.register_hook(save_grad('y'))
z.register_hook(save_grad('z'))
z.backward()

print(grads['y'])
print(grads['z'])
<ECODE>

Kalamaya: Just for my own knowledge, am I to understand that, given what I am trying to do, the only ways we have are i) global variables, and ii) closures? Thanks again.

apaszke: I’d say that these are the most obvious ways, but you could probably come up with more sophisticated solutions too. As I said, the best one depends on the specific use case, and it’s hard to provide a one that fits all. I find using closures like above to be ok, others will find something else better.

Kalamaya: Thanks again. I will process it tonight and reply back here for my exact use case. Thanks again!

EvanZ: Aren’t the gradients of internal nodes necessary for doing backprop?

fmassa: Yes, they are, but as soon as they have been used and are not necessary anymore, they are freed to save memory

vitchyr: While I understand why this design decision was made, are there any plans to make it easier to save the gradients of intermediate variables? For example, it’d be nice if something like this was supported: <SCODE>from torch.autograd import Variable
import torch

xx = Variable(torch.randn(1,1), requires_grad = True)
yy = 3*xx
yy.require_grad = True  # <-- Override default behavior
zz = yy**2

zz.backward()

# do something with yy.grad
<ECODE> It seems like it’d be easier to let variables keep track of their own gradients rather than having to keep track of them with my own closures. Then if I want to analyze the gradients of my variables (leaf or not), I can do something like <SCODE>do_something_with_data_and_grad_of(xx)
do_something_with_data_and_grad_of(yy)
<ECODE>

chenjus: Is it possible to get the gradients of a torch.nn.Linear module using the way you suggested or am I limited to capturing gradients by defining Variables? Would this work for convolutions or recurrent layers?

miguelvr: Is it possible to create a (torch.autograd) flag in order to save all the variable’s gradients?

yusaku: 

blackyang: For example, how to get yy’s grad_output from zz1 part? <SCODE>xx = Variable(torch.randn(1,1), requires_grad = True)
yy = 3*xx
zz1 = yy**2
zz2 = yy**2

yy.register_hook(print)
(zz1+zz2).backward()
<ECODE>

SimonW: Ha, I recently did exactly this. Not sure if its the best way, but I did:

blackyang: Great, thanks! That’s also what in my mind, basically we need a dummy variable. BTW, is there something like nn.Identity() in torch? I didn’t find it