How Computation Graph in PyTorch is created and freed?

dkdo: <p>Hi all,</p>
<p>I have some questions that prevent me from understanding PyTorch completely. They relate to how a Computation Graph is created and freed? For example, if I have this following piece of code:</p>
<pre><code>import torch

for i in range(100):
    a = torch.autograd.Variable(torch.randn(2, 3).cuda(), requires_grad=True)
    y = torch.sum(a)
    y.backward()
</code></pre>
<ol>
<li>Does it mean that each time I run the code in a loop, it will create a completely new computation graph and the graph from the previous loop is freed from buffer?</li>
<li>If I call <code>y.backward()</code> like above, will the computation graph within that loop be freed from buffer?</li>
<li>If the graph is not freed, can I treat it as a static computation graph and do something like the code below?</li>
</ol>
<p>Code:</p>
<pre><code>import torch

# a like a placeholder
a = torch.autograd.Variable(torch.randn(2, 3).cuda(), requires_grad=True)
y = torch.sum(a)

for i in range(100):
    a.data = torch.randn(2, 3).cuda()  # Only modify its data
    y.forward()  # Call a forward over y (computed using pre-built graph)
    y.backward()  # Backward on built graph</code></pre>

smth: <ol>
<li>yes</li>
<li>yes. you can keep it around if you want with <code>y.backward(retain_variables=True)</code> (on 0.1.12) and <code>y.backward(retain_graph=True)</code> (on master)</li>
<li>no you cannot, though that’s an interesting idea.</li>
</ol>

dkdo: <p>Thank you very much! It is clear now.</p>

zakizhou: <p><a class="mention" href="/u/smth">@smth</a><br>
Thanks for your explanation, I have one more question, if I add retain_graph=True in the following code, will all intermediary results in 100 graph exist in memory, or previous 99 graphs are freed and only the last graph exist in memory?<br>
import torch</p>
<pre><code>for i in range(100):
    a = torch.autograd.Variable(torch.randn(2, 3).cuda(), requires_grad=True)
    y = torch.sum(a)
    y.backward(retain_graph=True)</code></pre>

jdhao: <p>In your example, there is no need to  use <code>retain_graph=True</code>. In each loop, a new graph is created.</p>

peterlau123: <p>I think only the last graph exist after the loop</p>

Brando_Miranda: <aside class="quote no-group" data-username="dkdo" data-post="1" data-topic="3515">
<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/dkdo/48/641_2.png" class="avatar"> dkdo:</div>
<blockquote>
<p>Does it mean that each time I run the code in a loop, it will create a completely new computation graph and the graph from the previous loop is freed from buffer?</p>
</blockquote>
</aside>
<p>Im confused, what exactly is the operation that frees up the graph? Is it because we create a new variable with <code>requires_grad=True</code> or what is it that creates a new computation graph? <a class="mention" href="/u/smth">@smth</a></p>

smth: <p>the operation that frees up the graph is variable scoping in python. The variables in the <code>for loop</code> scope go out of scope in the next iteration of the loop</p>

simonada: <p>Hi, I think that if a variable is being updated within the loop with a value, for which the computational graph was retained before, then the computational graph is expanding on each iterations. E.g. for some A, b and u = tensors which require grad:</p>
<pre><code class="lang-auto">def f(A, b, u):
    r = A@u - b
    return (r**2).sum()

for k in range(5):
    f_eval = f(A, input_b, y)
    grad = torch.autograd.grad(f_eval, y, create_graph=True)[0]
    y.grad = grad
    y = y - 0.001*y.grad
make_dot(grad)
</code></pre>
<p>See below for after 2 iterations:<br>
<div class="lightbox-wrapper"><a class="lightbox" href="https://discuss.pytorch.org/uploads/default/original/3X/c/0/c077863fcc845eb75ccbe9ddef0f8d1a36063ca5.png" data-download-href="https://discuss.pytorch.org/uploads/default/c077863fcc845eb75ccbe9ddef0f8d1a36063ca5" title="test_depth"><img src="https://discuss.pytorch.org/uploads/default/optimized/3X/c/0/c077863fcc845eb75ccbe9ddef0f8d1a36063ca5_2_180x500.png" alt="test_depth" data-base62-sha1="rsDKL7XJBUb2lNc0lktji1JW0UR" width="180" height="500" srcset="https://discuss.pytorch.org/uploads/default/optimized/3X/c/0/c077863fcc845eb75ccbe9ddef0f8d1a36063ca5_2_180x500.png, https://discuss.pytorch.org/uploads/default/optimized/3X/c/0/c077863fcc845eb75ccbe9ddef0f8d1a36063ca5_2_270x750.png 1.5x, https://discuss.pytorch.org/uploads/default/optimized/3X/c/0/c077863fcc845eb75ccbe9ddef0f8d1a36063ca5_2_360x1000.png 2x" data-dominant-color="EFF0F0"><div class="meta"><svg class="fa d-icon d-icon-far-image svg-icon" aria-hidden="true"><use href="#far-image"></use></svg><span class="filename">test_depth</span><span class="informations">415×1152 53.1 KB</span><svg class="fa d-icon d-icon-discourse-expand svg-icon" aria-hidden="true"><use href="#discourse-expand"></use></svg></div></a></div></p>

riley: <p>In general, what percentage of forward-backward combined time is spent reforming the computation graph? It seems like a trivial optimization to simply save whatever graph object is formed between forward passes if the underlying computation graph is in fact static. If this is possible, there’s no reason why static computation graph approaches need lazy execution (which is what makes Tensorflow a pain). For a static graph, the computation graph could be formed on the first forward pass (no lazy execution) and then simply saved. I feel like few applications actually use dynamic computation graphs (i.e. where different functions are run in different situations) and instead are all essentially static graphs that could benefit from this.</p>

ptrblck: <aside class="quote no-group" data-username="riley" data-post="10" data-topic="3515">
<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/riley/48/12678_2.png" class="avatar"> riley:</div>
<blockquote>
<p>It seems like a trivial optimization to simply save whatever graph object is formed between forward passes if the underlying computation graph is in fact static.</p>
</blockquote>
</aside>
<p>This was basically done using tracing. However, the current way is to use <code>torch.jit.script</code>, as it will also track the control flow.</p>
<aside class="quote no-group" data-username="riley" data-post="10" data-topic="3515">
<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/riley/48/12678_2.png" class="avatar"> riley:</div>
<blockquote>
<p>I feel like few applications actually use dynamic computation graphs (i.e. where different functions are run in different situations) and instead are all essentially static graphs that could benefit from this.</p>
</blockquote>
</aside>
<p>Really? I have the feeling that especially due to the growth of NLP models the control flow capturing is getting even more important.<br>
Which models have you compared from which domain?</p>

riley: <p>I’m just referring to most typical feedforward ML models (like many models in computer vision, e.g. AlexNet, ResNet) where the computation graphs are set by the architecture. I see your point though (although I feel like even recurrent models don’t necessarily require full dynamic computation graph tracking and could just “copy-and-paste” whatever computation graph building operation occurs for one recursion for each recursion). Full disclosure, I’m not terribly familiar with the implementation of autograd.</p>
<p>The big question is how much of a performance hit is given by dynamic graph construction.</p>