What the difference between detach(), detach_(),and with torch.no_grad() in our training phase?

Eric_K: <p>When I don’t need a network to update their parameters, I will not put this network’s paramters into optimizer’s parameter argument. And when I run forward，I will warp “with torch.no_grad():” for my “model(input)”.</p>
<p>Are there some wrongs in my operations?</p>
<p>Thanks…</p>

ptrblck: <p>Your assumptions are correct.<br>
<code>with torch.no_grad()</code> won’t track the wrapped operations by Autograd, so that intermediate tensors won’t be stored, which would be needed for the backward pass.<br>
That being said, you should not wrap the complete forward pass in this block during training, as you won’t be able to calculate the gradients.</p>
<p><code>detach()</code> operates on a tensor and returns the same tensor, which will be detached from the computation graph at this point, so that the backward pass will stop at this point.<br>
<code>detach_()</code> is the inplace operation of <code>detach()</code>.</p>

Eric_K: <p>Thanks for your reply~</p>
<p>If I just want to freeze part of a single network. "detach“ method is more convenient for me.<br>
If I want to freeze one separated network from others network. These three method are equivalent to me. Is that right?</p>
<p>Thank you~ ^^</p>

ptrblck: <p>They might yield the same result, but in specific edge cases you might get different and unexpected results:</p>
<ul>
<li>An optimizer, which doesn’t hold certain parameters, won’t update them. However other optimizers could still update these parameters, if they are passed.</li>
<li>If you are using weight decay, have updated some parameters in the past and are now freezing them, these parameters could still be updated, if they were passed to the optimizer.</li>
<li>
<code>detach()</code> could act in the same way as the second point.</li>
</ul>
<p>That being said, I would prefer the explicit way instead of relying implicitly that no side effects can occur. <img src="https://discuss.pytorch.org/images/emoji/apple/wink.png?v=9" title=":wink:" class="emoji" alt=":wink:"></p>

Kevin96: <p>I still don’t understand the difference between <code>detach()</code> and <code>detach_()</code>. They both do not create a copy and thus I don’t quite understand why we need an <strong>in-place</strong> version of <code>detach()</code>. Can you clarify the difference between them?</p>
<p>Also, can you clarify why “Views cannot be detached in-place”?<br>
<a href="https://pytorch.org/docs/stable/generated/torch.Tensor.detach_.html#torch.Tensor.detach_" class="onebox" target="_blank" rel="noopener nofollow ugc">https://pytorch.org/docs/stable/generated/torch.Tensor.detach_.html#torch.Tensor.detach_</a></p>
<p>Thanks!</p>

ptrblck: <p>The inplace version would also detach the source tensor as seen here:</p>
<pre><code class="lang-python"># inplace, non-view
a = torch.randn(1, 1, requires_grad=False)
b = torch.randn(1, 1, requires_grad=True)
c = a * b
d = c

d.detach_() # detaches d and c since inplace
d[0, 0] = 1.

(c + a).sum().backward()
# &gt; RuntimeError: element 0 of tensors does not require grad and does not have a grad_fn
</code></pre>
<p>“Views cannot be detached in-place” refers to e.g. this code snippet:</p>
<pre><code class="lang-python"># inplace, view
a = torch.randn(1, 1, requires_grad=False)
b = torch.randn(1, 1, requires_grad=True)
c = a * b
d = c.view(1, 1)

d.detach_() 
# &gt; RuntimeError: Can't detach views in-place. Use detach() instead.
</code></pre>
<p>Detaching <code>d</code> not inplace works if you want to use <code>c</code> for the backward pass:</p>
<pre><code class="lang-python"># not inplace
a = torch.randn(1, 1, requires_grad=False)
b = torch.randn(1, 1, requires_grad=True)
c = a * b
d = c.detach()

d[0, 0] = 1.

(c + a).sum().backward()
</code></pre>

zhiyuanpeng: <p>Thanks for your elaboration, and I’d like to confirm my understanding is right or not: the best practice is to use one of (detach, detach_, no_grad) and do not pass the parameters of the freezed network to optimizer? Thanks.</p>

ptrblck: <p>Yes, I would recommend to be as explicit as possible. I.e. if you don’t want the optimizer to update the parameters, don’t pass these parameters to it. Otherwise, you might hit edge cases, which might be hard to debug.</p>

zhiyuanpeng: <p>Got it. Thank you very much!</p>