Backpropagation - Graph is reused while it shouldn't

username: Dominik
cooked: <p>Consider the following (made up) example snippet:</p>
<pre><code class="lang-python">import torch

measure = torch.nn.MSELoss()

x = torch.tensor([1, 0], dtype=torch.float64)
t = torch.eye(2, dtype=torch.float64, requires_grad=True)
a = torch.ones(2, dtype=torch.float64, requires_grad=True)
y = t @ a

for __ in range(2):
    x_out = t @ (x + y)  # Raises `RuntimeError` later on.
    # x_out = t @ (x + t @ a)  # Works fine.
    loss = measure(x_out, x)
    loss.backward()
</code></pre>
<p>During the second iteration of the <code>for</code> loop the <code>loss.backward()</code> raises the following exception:</p>
<pre><code class="lang-auto">RuntimeError: Trying to backward through the graph a second time, but the buffers have already been freed. Specify retain_graph=True when calling backward the first time.
</code></pre>
<p>I am not sure why this happens since in every iteration I create a new computational graph by redefining <code>x_out</code> and <code>loss</code>. What is reused in every iteration is the <code>y</code> tensor and when I replace <code>y</code> with its original expression <code>t @ a</code> then the code runs without error.</p>
<p>So I suppose that by reusing <code>y</code> among the iterations that part of the graph is shared and reused. However the underlying mechanism is not really clear to me. I thought that the first call to <code>loss.backward()</code> should detach the graph and so subsequent iterations should build a new one? But apparently the sub-graph <code>y = t @ a</code> is reused in the following iterations (which makes sense since I don’t provide information about that part anymore). So for the above example, which graph is actually being built and what parts of it are freed again upon calling <code>loss.backward()</code>?</p>
<p>My second question is, In order to make the above example work without recomputing <code>t @ a</code> at every iteration, what is the preferred way of dealing with the problem? Should I specify <code>retain_graph=True</code>? However I don’t want to retain the full graph, since the “tail” is rebuilt on every iteration. Also I read in <a href="https://discuss.pytorch.org/t/how-to-free-graph-manually/9255/2">this topic</a> that a graph will be freed when the corresponding output variables run out of scope (when their reference count drops to zero) and since for <code>loss</code> that happens at every iteration I would expect the whole graph to be rebuilt on every iteration. According to the error message that doesn’t seem the case though. The <code>y</code> variable never runs out of scope, so does that mean that the sub-graph corresponding to <code>y = t @ a</code> is not freed? And how can I free this (sub-) graph manually then (after the loop)?</p>
<p>My third question is if someone could explain the details about graph creation and graph (buffer) freeing. According to the error message torch is aware of the fact that I want to reuse a (part of the) graph however it already freed the relevant resources. So what information does torch use in order to evaluate the structure of graphs (I suppose it’s <code>.grad_fn</code>) and what resources are allocated and then freed during backpropagation?</p>

username: albanD
cooked: <p>Hi,</p>
<p>There are many questions here, I’ll try and answer in the order you asked them even if they overlap.</p>
<p>Yes the error is because here the operation <code>t @ a</code> is reused multiple times. I am not sure what you mean by " <code>loss.backward()</code> should detach the graph". backward does not change the graph, it just traverses it (and free un necessary buffers if retain_graph is not set).<br>
In you case, the graph up to <code>y</code> is built once. Then each iteration extend this graph. The problem is that the first backward will free even the common part of the graph and so the second one will fail.</p>
<p>“I would expect the whole graph to be rebuilt on every iteration”: keep in mind that the computational graph is built ONLY buy doing forward operations in your python script. The backend will never change/built it.<br>
In you case you indeed can use <code>retain_graph=True</code> to keep the whole graph during the backward. And the “lower” part (that was created inside the loop) will be freed when the loop exit. The upper part (t @ a) will still remain as the <code>y</code> variable still refers to it.<br>
To free the upper part after the loop, simply delete everything that references it: <code>del y</code> in your case.</p>
<p>The graph is created every time your perform an operation on tensors (when gradient mode is enabled).<br>
The graph contains both the functions that need to be applied to perform the backward pass and the buffers and temporary variable they need.<br>
When you call backward, the graph is traversed in reverse order and each function is applied one after the other. After each function execution, all its buffers and temporary variables are deleted (if <code>retain_graph=False</code>).<br>
If during the backward, a buffer does not exist, then the above error is raised as the only way this buffer does not exist anymore is because your already backproped.</p>

username: Dominik
cooked: <p>Hi,</p>
<p>thanks for the prompt and thorough reply, it’s a lot clearer now <img src="https://discuss.pytorch.org/images/emoji/apple/slight_smile.png?v=12" title=":slight_smile:" class="emoji" alt=":slight_smile:" loading="lazy" width="20" height="20"> I have a few follow-up questions though:</p>
<ol>
<li>
<p>So that basically means that <code>y = t @ a</code> creates a graph and each iteration in the loop extends this graph by attaching to it? Consequently when the variables in the loop are re-assigned (<code>x_out</code> and <code>loss</code>) then the previously attached part is removed again, since nothing refers to it anymore? Is that interpretation correct?</p>
</li>
<li>
<p>Then the keyword argument <code>retain_graph</code> actually <em>only</em> refers to the buffers (of the graph’s vertices) that are needed for performing the backpropagation? But the actual graph (i.e. the relations between tensors) are retained in any way (no matter the value of the <code>retain_graph</code> argument)? In other topics I read that it was called <code>retain_variables</code> before, why the change to <code>retain_graph</code> (<code>retain_buffers</code> would be clearer maybe)? At least to me it was confusing until I read your reply.</p>
</li>
<li>
<p>The following statements are not completely clear to me:</p>
</li>
</ol>
<blockquote>
<p>The graph contains both the functions that need to be applied to perform the backward pass […]<br>
[…] each function is applied one after the other</p>
</blockquote>
<p>What are these functions actually (are they related to the <code>.grad_fn</code> attribute)? And how are the backprop buffers related to them?</p>

username: albanD
cooked: <ol>
<li>Yes, here is a small sample. I use <code>y = a*2</code> here because that way the op has a single input and single output and it is easier to show the graph.</li>
</ol>
<pre><code class="lang-auto">a = torch.rand(10, requires_grad=True)
# no graph at this point

y = a * 2
# The backward graph linked to y is: y -&gt; a

## Iterations 0
x_out0 = 2 * y
# The backward graph linked to x_out0 is: x_out0 -&gt; y -&gt; a
# Note that the backward graph linked to y is still: y -&gt; a (the arrow here is the same as the one between y and a above, meaning that deleting the buffers in one will delete them in the other)

loss0 = measure(x_out0)
# The backward graph linked to loss0 is: loss0 -&gt; x_out0 -&gt; y -&gt; a
loss0.backward()

## Iteration 1
x_out1 = 2 * y
# The backward graph linked to x_out1 is: x_out1 -&gt; y -&gt; a (the arrow between y and a here is the same as the one between y and a in iteration 0, meaning that deleting the buffers in one will delete them in the other)

loss1 = measure(x_out1)
# The backward graph linked to loss1 is: loss1 -&gt; x_out1 -&gt; y -&gt; a
loss1.backward()
# This one will fail as the buffers for the array between y and a are already deleted.

# If you were printing the all the graphs linked to both loss0 and loss1, you would get:
# loss1 -&gt; x_out1 -&gt; y -&gt; a
#    loss0 -&gt; x_out0 ↑
# As you can see some part of the graph is shared.
</code></pre>
<ol start="2">
<li>
<p>It refers to both buffers and intermediary results. Without these, the “graph” cannot be used for anything and so it does not really exist anymore. We only use it to detect double usage.</p>
</li>
<li>
<p>These functions are <code>autograd.Function</code> that contain both the code to run for the backward pass and some intermediate variables needed to perform these computations. Each function handle it’s buffers and temporary variables in the way it wants.</p>
</li>
</ol>
<p>Does that make things clearer?<br>
Let me know if you have other doubts.</p>

username: Dominik
cooked: <p>Your 2. point is still confusing me. You say that</p>
<blockquote>
<p>[…] and intermediary results. Without these, the “graph” cannot be used for anything […]</p>
</blockquote>
<p>To what parts of the graph does this refer? Does it refer to the entire graph that was tracked through backpropagation? And what does “anything” mean in that context? What else than gradient computation would / could you use a graph for?</p>
<p>I tried the following snippet where a graph is constructed (up to <code>c</code>), then backproped and then the graph’s upper part (by <code>d</code>, or even the whole graph by <code>e</code>) is reused for construction of another graph. Based on the above statement that <code>.backward()</code> frees any resources / buffers / intermediary results of the graph, I would expect the computation of <code>d</code> and <code>e</code> not to work (i.e. not only backprop), but apparently it does:</p>
<pre data-code-wrap="python"><code class="lang-python">a = torch.tensor(1, requires_grad=True)
b = a * torch.tensor(2)
c = b * torch.tensor(3)

c.backward()

d = b * torch.tensor(4)
e = c * torch.tensor(5)
print('d = ', d)
print('e = ', e)
</code></pre>
<p>So it still remains unclear to me what things, <em>after</em> performing <code>.backward()</code>, the graph (or parts of it) <em>can</em> be used for and what things it <em>cannot</em> be used for anymore (another <code>.backward()</code> for example). Like a list of <em>do</em>’s and <em>don’t</em>’s <em>after</em> a graph has been backproped (considering operations involving that graph).</p>

username: albanD
cooked: <aside class="quote no-group" data-username="Dominik" data-post="5" data-topic="24554">
<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/dominik/48/12990_2.png" class="avatar"> Dominik:</div>
<blockquote>
<p>To what parts of the graph does this refer?</p>
</blockquote>
</aside>
<p>This refers to every part of the graph that were visited during the backward pass.</p>
<aside class="quote no-group" data-username="Dominik" data-post="5" data-topic="24554">
<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/dominik/48/12990_2.png" class="avatar"> Dominik:</div>
<blockquote>
<p>And what does “anything” mean in that context? What else than gradient computation would / could you use a graph for?</p>
</blockquote>
</aside>
<p>Yes only gradient computation in this case.<br>
Be careful if playing with super simple example, you can create simple graphs that don’t have any buffer or intermediary result and so you will be able to backprop through them multiple times. But this is an artefact of the fact that these graphs are super simple.</p>
<aside class="quote no-group" data-username="Dominik" data-post="5" data-topic="24554">
<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/dominik/48/12990_2.png" class="avatar"> Dominik:</div>
<blockquote>
<p>Based on the above statement that <code>.backward()</code> frees any resources / buffers / intermediary results of the graph, I would expect the computation of <code>d</code> and <code>e</code> not to work</p>
</blockquote>
</aside>
<p>It does free ressources of the graph. Not the Tensors that the user created during the forward.<br>
You don’t have a strong link between Tensors from the forward pass and nodes in the graph. The only thing is that computing a new tensor creates a new node in the graph. But you can remove the Tensor without impacting the graph and you can remove the graph’s buffers (by doing backward) without impacting the Tensor that created it.</p>
<p>In your example, <code>b</code> and <code>c</code> are not part of the graph.<br>
So even after calling backprop, you can still use them.<br>
The same way, you could <code>del b</code> and the <code>c.backward()</code> call will still work without any problem.</p>

username: two_Two
cooked: <pre><code class="lang-auto">In your example, b and c are not part of the graph.
</code></pre>
<p>HI,I have a question that how to know if the b and c are not part of graph?</p>

username: albanD
cooked: <p>Because the graph we were talking about above is the graph to compute gradients. Which is composed only of backward Nodes and their buffers, not the user Tensors.</p>

username: two_Two
cooked: <blockquote>
<p>Because the graph we were talking about above is the graph to compute gradients.</p>
</blockquote>
<p>I still have a hard time getting my head around this … So I write a easy example as below and hope can get some feedback from you!</p>
<pre><code class="lang-auto">a = torch.tensor(1., requires_grad=True)
b = torch.tensor(2.,requires_grad= True)
c = a*b 
</code></pre>
<p>To my understanding , the graph would be created since <code>c =a*b </code></p>
<pre><code class="lang-auto">for _ in range(5):
    print(c.backward(retain_graph=True))
    print(a.grad,b.grad)
</code></pre>
<p>The result</p>
<pre><code class="lang-auto">None
tensor(2.) tensor(1.)
None
tensor(4.) tensor(2.)
None
tensor(6.) tensor(3.)
None
tensor(8.) tensor(4.)
None
tensor(10.) tensor(5.)
</code></pre>
<p>Q1:<br>
Why does <code>print(c.backward(retain_graph=True))</code>gives the <code>None</code>??</p>
<p>As for the explanation you give above:<br>
If the tensor is not part of computing gradient graph ,then we can delete it and backward should work fine  .So,here’s what I do:</p>
<pre><code class="lang-auto">del b 
for _ in range(3):
     c.backward(retain_graph = True)
     print(a.grad)
</code></pre>
<p>And the result gives ：</p>
<pre><code class="lang-auto">tensor(12.)
tensor(14.)
tensor(16.)
</code></pre>
<p>The result does’t make sense to me since to my understanding, <code>c =a*b</code><br>
What I expect is that the c.backward(retain_graph = True) should fail because the b has already been deleted ,what do I miss here?</p>
<p>I think the problem is that I do not know which tensor or function would be considered as the graph to compute gradients,Maybe b here is not ,but I think it should be part of it…</p>
<p>Two questions for you ,I am a beginner of Pytorch and thanks in advance!</p>

username: Upgrade_Yourself
cooked: <p>Hi, I read this blog here: <a href="https://blog.paperspace.com/pytorch-101-understanding-graphs-and-automatic-differentiation/" rel="nofollow noopener">https://blog.paperspace.com/pytorch-101-understanding-graphs-and-automatic-differentiation/</a></p>
<p>What I got is:<br>
1/ when you want a tensor to be part of the graph, you need to specify: requires_grad  =True<br>
So, for your first  example, x,t,a, y and x_out (requires_grad being contagious) are all going to be in the dynamic computation graph <strong>once you do the forward pass</strong> (ie y = t @ a also x_out=t @ (x + y) and loss = measure())<br>
If we define a leaf node as a tensor you create without the need of a function( say add, multiply etc) then t and a are leaf nodes<br>
2/All the non-leafs nodes will be erased once you do the backward pass. So, y and x_out’s values will be erased from the graph as well as the other gradients say dy/dt , dy/da, dx_out/dt, dx_out/dy etc<br>
3/For there to not be an error, one has to do forward() then backward(). But since you only recalculated x_out and loss but not y again in the loop, you didn’t do a complete forward(). Thus the error happened.<br>
Hope this helps!</p>

username: albanD
cooked: <p>Hi,</p>
<ul>
<li>
<code>.backward()</code> does not return anything. So it prints None. You can check the doc for more details.</li>
<li>I mention <code>ackward Nodes and their buffers</code>. In your case, the content of <code>b</code> becomes one of the buffers needed to backward the multiplication. So even if you delete <code>b</code> itself. The corresponding buffer will still be there.</li>
</ul>

username: two_Two
cooked: <p>Ok,Thanks for your clear explanation !</p>