Help needed in understanding how autograd works

username: Asger_Kjaerulff
cooked: <p>This is just a super basic question that I have not been able to successfully google an answer to.</p>
<p>I’m trying to understand how the torch.Tensor object stores information on its position in the graph. Since autograd can calculate gradients based on operational relations between torch.Tensor objects, information about these relations must be stored somewhere. Is it an attribute in the Tensor objects that I cannot find, or is there somewhere else I should look?</p>

username: albanD
cooked: <p>Hi,</p>
<p>The Tensors are not linked to the internal part of the graph.<br>
Only the final output has a .grad_fn attribute that contains the backward of the Function that created this Tensor.<br>
Then there is a full graph a backwardFunction that represent how the backward pass should be computed. Where each Function points to the next one(s) to call when doing the backward pass. These functions can, depending on their needs, save some Tensors but the Tensors never have a reference to all the Functions that use them.</p>
<p>I hope this is clear, don’t hesitate to ask more questions if it is not.</p>

username: Asger_Kjaerulff
cooked: <p>Thank you for the reply.</p>
<p>It certainly made it clearer, but I still have questions:</p>
<p>I am doing my best to find answers by looking through documentation, source code and inspecting objects in Jupyter notebook, but I still cannot find the answers I’m looking for. Forgive my incompetence, I have previously mostly worked with C# and am apparently finding it hard to investigate documentation and source code for Python.</p>
<p>Let’s take a simple example:</p>
<p>import torch<br>
x=torch.randn(4,4)<br>
y=2*x<br>
z = y.sum()<br>
z.backward()</p>
<p>Calling z.backward() has resulted in x.grad being updated. Ultimately, my question is how.</p>
<p>You say that z.grad_fn contains something leading back to x? From what I can see type(z.grad_fn)=SumBackward0, which is not a type/class that I have been able to find source or documentation for. Perhaps it is a subclass to the Function class? Basically I am trying to find some attribute of z which points back to x. If z.grad_fn points back to x, then my question is how/where? Is it possible to inspect z.grad_fn to gain full information on the graph?</p>
<p>Since I am not able to find answers to my own questions, it seems that I must be using the documenation wrong. For instance I find it hard to get information on grad_fn. If you have any sense of how I might be going at this the wrong way, any guidance is appreciated.</p>

username: albanD
cooked: <p>Hi,</p>
<p>First, this part is not really documented more on less on purpose as the backend is moving quite a lot still. Even though we make sure the python/cpp user facing interface do not change, there are still some changes in the backend and what I’m going to describe below is the current state and may not be true forever !</p>
<p>In you example, I guess you miss a <code>requires_grad=True</code> in the x creation, otherwise, no gradient will be computed.</p>
<p>Then in your example:</p>
<ul>
<li>
<code>SB = z.grad_fn</code> is indeed a subclass of Function that corresponds to the backward method that should be called to perform the backward of the sum op that you did.</li>
<li>
<code>SB.next_functions</code> is a tuple that contains information of what should be called next. Each entry in the tuple contains another tuple with two elements: The next backward function to call and which output of this other function this input corresponds to. In your case, it should contain a MulBackward0 method for the input and links to the 0th output of the previous function. The input is <code>y</code> and it was created by the multiplication by 2 op. This op had only one output <code>y</code> and so it’s the output 0.</li>
<li>
<code>MB = SB.next_functions[0][0]</code> here we get the MulBackward0 Function.</li>
<li>
<code>MB.next_functions</code> will contain two things (note that because of the wrapping, the order of arguments here does not match what you wrote in python: <code>x</code> is the first input argument and <code>2</code> the second one):
<ul>
<li>The first argument was created by an <code>AccumulateGrad</code> op and is it’s 0th output.</li>
<li>The second argument has a <code>None</code> backward method as it is the <code>2</code> number and no gradients need to flow back to it.</li>
</ul>
</li>
<li>
<code>AG = MB.next_functions[0][0]</code> get the <code>AccumulateGrad</code> Function.</li>
<li>
<code>AG.variable is x -&gt; True</code> This particular subclass of Function has a <code>.variable</code> attribute that contains the Tensor in which the gradients need to be accumulated. In this case it will contain the Tensor <code>x</code>. And so when calling backward, it will accumulate into the <code>.grad</code> field of the <code>x</code> Tensor.</li>
</ul>
<p>Final note: Most of the Function subclasses are created by automatically generated cpp code. So it is quite tricky to find them. The file used to generate them can be found <a href="https://github.com/pytorch/pytorch/blob/961f829067af733ccd4a4aea80b5192c385d9400/tools/autograd/derivatives.yaml#L757-L758" rel="nofollow noopener">here</a>, in the link, the backward for the sum is just passing the same gradient value to all the inputs.</p>
<p>I hope this helps <img src="https://discuss.pytorch.org/images/emoji/apple/slight_smile.png?v=6" title=":slight_smile:" class="emoji" alt=":slight_smile:"></p>

username: BruceDai003
cooked: <aside class="quote no-group" data-username="albanD" data-post="4" data-topic="34039">
<div class="title">
<div class="quote-controls"></div>
<img loading="lazy" alt="" width="24" height="24" src="https://discuss.pytorch.org/user_avatar/discuss.pytorch.org/alband/48/215_2.png" class="avatar"> albanD:</div>
<blockquote>
<p>MB.next_functions</p>
</blockquote>
</aside>
<p>This explanation solves a lot of my problems, thanks. But I still got a little bit of confusion. Let’s come back to the toy example. I understand now that we can trace back from the next_functions graph-sort of thing to the x. But as we know in this example, x.grad will be a 4x4 matrix of '2’s. How can we retrieve this number ‘2’ information from the backward pass? For example, in the MulBackward, which correponds to y = x*2. How does it know we are using what to multiply what? The x can be further traced from the AccumelateGrad.x, but where is the information of 2? Since MB.next_functions[1] is just (None, 0). There is no Function subclass in it anymore.<br>
So, my actually final quesion is how can we mannually use the z.grad_fn instance to calculate the grads for all the inputs. I just need to see the actual dataflow. Not only the backward functions called, you still need to store the inputs to the backward functions, I think. But I don’t know where to find it.<br>
Another question is can we directly call the grad_fn() to calculate something?<br>
I tried to use grad_fn(), and I clealy see that if I don’t pass the correct shape, it will throw an error. So the Function subclass instance does store some shape information, right? But I don’t see how to access it.</p>

username: albanD
cooked: <p>I think you should open a new topic with more details on what you want to do.</p>
<p>The backward Nodes are just called one after the other, piping the output of one as the input to the next.<br>
These Node also contain any data that they need from the forward to perform their computation.</p>