Autograd python userspace code relies on internal state

username: remidebette
cooked: <p>Hi,</p>
<p>I have a simple beginer question about autograd.<br>
Thanks for the nice library.<br>
I really like the functionality and I understand that it simplifies a lot of code by packaging the derivative against a variable directly in the variable.</p>
<p>What I am fearing is that the .backward() =&gt; .grad mechanic relies on the user keeping in mind that there is a mutable internal state, .grad, that is linked with what previous code was executed, which tends to hurt readability.</p>
<p>Let’s assume I write this:</p>
<pre><code class="lang-python">&gt;&gt;&gt; w = torch.tensor([1., 1., 1.], requires_grad=True)
&gt;&gt;&gt; func = w[0] ** 2 + 2 * w[1] + w[2]   # The loss function AST is computed
&gt;&gt;&gt; func.backward()   # the derivatives of func against each tensor that was declared with required_true is computed and stored in the respective .grad internal states
&gt;&gt;&gt; w.grad   # I can get the derivatives, handy
tensor([2., 2., 1.])
</code></pre>
<p>Now this means I should not write too much code between the .backward() and the .grad, because it is unclear which function it is the derivative of.<br>
When I look in a codebase at a .grad, I do not know immediately what function was used to generate it.</p>
<pre><code class="lang-python">&gt;&gt;&gt; w = torch.tensor([1., 1., 1.], requires_grad=True)
&gt;&gt;&gt; func = w[0] ** 2 + 2 * w[1] + w[2]
&gt;&gt;&gt; func.backward()
&gt;&gt;&gt; oups_had_forgotten = func + 3 * w[1]
&gt;&gt;&gt; ... some code ...
&gt;&gt;&gt; w.grad
tensor([2., 2., 1.])
</code></pre>
<p>If I have not been cautious about my backward, am I using the function func or oups here?<br>
Also, if I wanted to compute another derivative, I need to .zero_() the tensor, which is another hard to read step.</p>
<p>I feel a more functional approach (in appearance, the backend could still behave like now) could be beneficial to try and learn users.<br>
Consider something like:</p>
<pre><code class="lang-python">&gt;&gt;&gt; w.grad(func)
tensor([2., 2., 1.])
&gt;&gt;&gt; w.grad(oups_had_forgotten)
tensor([2., 5., 1.])
</code></pre>
<p>This functional .grad would have the advantage of explicity and would not store the data in the tensor in place.<br>
So, no need for .backward() and no need for .zero_() to clean the user exposed state.<br>
Is there a function exposing such a behavior today? Would there be big downturns in terms of usability/performance?</p>
<p>Thank you</p>

username: albanD
cooked: <p>Hi,</p>
<p>The <code>.backward()</code> and <code>.grad</code> fields are built to work nicely with the <code>torch.nn</code> and <code>torch.optim</code> libraries.<br>
It allows you to handle computing the gradients and updating all the parameters without the user having to handle passing all the gradients by themselves.</p>
<p>If you are not working with these libraries, I would recommend using <code>torch.autograd.grad(out, inp)</code> that will return the gradient for each input you give.<br>
This will do what you want here right?</p>

username: remidebette
cooked: <p>Thanks for your reply <a class="mention" href="/u/alband">@albanD</a>!<br>
Indeed you are correct this is the function I had in mind.<br>
From reading the documentation I did not understand clearly its puprose (maybe an example would have helped)</p>
<p>I just tried to apply my mental flow with it and it works. The defaults do not allow for an easy try and learn though since they do not retain the graph:</p>
<pre><code class="lang-python">&gt;&gt;&gt; w = torch.tensor([1., 1., 1.], requires_grad=True)
&gt;&gt;&gt; func = w[0] ** 2 + 2 * w[1] + w[2]
&gt;&gt;&gt; oups_had_forgotten = func + 3 * w[1]
&gt;&gt;&gt; torch.autograd.grad(oups_had_forgotten, w)
(tensor([2., 5., 1.]),)
&gt;&gt;&gt; torch.autograd.grad(func, w)
Traceback (most recent call last):
  File "&lt;input&gt;", line 1, in &lt;module&gt;
  File "C:\Users\remi\.virtualenvs\zerotogan--y2dYRx8\lib\site-packages\torch\autograd\__init__.py", line 158, in grad
    inputs, allow_unused)
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>Is the aggressive freeing of buffers a performance tweek?</p>
<p>But if I choose to retain the graph at each step then I can at least do some retry:</p>
<pre><code class="lang-python">&gt;&gt;&gt; w = torch.tensor([1., 1., 1.], requires_grad=True)
&gt;&gt;&gt; func = w[0] ** 2 + 2 * w[1] + w[2]
&gt;&gt;&gt; oups_had_forgotten = func + 3 * w[1]
&gt;&gt;&gt; torch.autograd.grad(func, w, retain_graph=True)
(tensor([2., 2., 1.]),)
&gt;&gt;&gt; torch.autograd.grad(oups_had_forgotten, w, retain_graph=True)
(tensor([2., 5., 1.]),)
</code></pre>
<p>Thanks !</p>

username: albanD
cooked: <blockquote>
<p>Indeed you are correct this is the function I had in mind.</p>
</blockquote>
<p>Perfect!</p>
<blockquote>
<p>Is the aggressive freeing of buffers a performance tweek?</p>
</blockquote>
<p>It is a very important memory improvement yes.<br>
In a neural network, most of the memory usage comes from the buffer. So freeing the buffers as you do the backward allows you to significantly reduce the peak memory usage.</p>