Proper way to do gradient clipping?

kim.seonghyeon: <p>Is there a proper way to do gradient clipping, for example, with Adam? It seems like that the value of Variable.data.grad should be manipulated (clipped) before calling optimizer.step() method. I think the value of Variable.data.grad can be modified in-place to do gradient clipping. Is it safe to do?</p>
<p>Also, Is there a reason that Autograd RNN cells have separated biases for input-to-hidden and hidden-to-hidden? I think this is redundant and has a some overhead.</p>

apaszke: <p>You can safely modify <code>Variable.grad.data</code> in-place after the backward pass finishes. For example see how it’s done in the <a href="https://github.com/pytorch/examples/blob/master/word_language_model/main.py#L84-L91">language modelling example</a>.</p>
<p>The reason for that is that it has a nice user facing API where you have both weight tensors exposed. Also, it opens up a possibility of doing batched matrix multiply on the inputs for all steps, and then only applying the hidden-to-hidden weights (it’s not yet added there). If you measure the overhead and prove us that it can be implemented in a clean and fast way, we’ll happily accept a PR or change it.</p>

kim.seonghyeon: <p>I have tested nn.LSTM against simple LSTM implementation and found almost no difference in the performance. Maybe I overestimated the overhead of the additional addition with simple guess. Thank you!</p>

apaszke: <p>If you’re running on GPU you’ll also likely see great speedups from using cuDNN LSTM implementation.</p>

kim.seonghyeon: <p>I have tested in CPU and got no better results than just few milliseconds. (for someone who may try to implement LSTM for benchmarking <img src="//discuss.pytorch.org/images/emoji/apple/slight_smile.png?v=5" title=":slight_smile:" class="emoji" alt=":slight_smile:"> ) I think some more addition is insignificant than another expensive computations, like multiplication of weight matrices, nonlinear activation functions, or even python loop itself.</p>

dmadeka1: <p>Quick question about this <a class="mention" href="/u/apaszke">@apaszke</a> , are the <code>Variable.grad.data</code> that we should pass to our clip function a part of the model object or (if we use a different optimizer) - the optimizer object?</p>
<p>In the sense, does optimizer itself call backward? In which case, the code below should pass optimizer to the clip function right?</p>
<pre><code class="lang-python">        optimizer.zero_grad()
        output, hidden = model(data, hidden)
        loss = criterion(output.view(-1, ntokens), targets)
        loss.backward()
        clipped_lr = lr * clip_gradient(model, clip)
        for p in model.parameters():
            p.data.add_(-clipped_lr, p.grad.data)
            
        optimizer.step()
</code></pre>

apaszke: <p>I’m sorry but I don’t understand the question. Optimizer never calls <code>backward()</code> itself, unless you give it a callable argument (see <code>torch.optim</code> docs for more details on that). BTW you might want to use <code>torch.nn.utils.clip_grad_norm</code> now.</p>

mcleonard: <p>Maybe I’m doing something wrong here, but using gradient clipping like</p>
<pre><code class="lang-auto">nn.utils.clip_grad_norm(model.parameters(), clip)
for p in model.parameters():
    p.data.add_(-lr, p.grad.data)
</code></pre>
<p>makes my network train much slower than with <code>optimizer.step()</code>.</p>
<p>Here’s what it looks like with gradient clipping, with <code>clip=5</code>:</p>
<pre><code class="lang-auto">Epoch: 1/10... Step: 10... Loss: 4.4288
Epoch: 1/10... Step: 20... Loss: 4.4274
Epoch: 1/10... Step: 30... Loss: 4.4259
Epoch: 1/10... Step: 40... Loss: 4.4250
Epoch: 1/10... Step: 50... Loss: 4.4237
Epoch: 1/10... Step: 60... Loss: 4.4223
Epoch: 1/10... Step: 70... Loss: 4.4209
Epoch: 1/10... Step: 80... Loss: 4.4193
Epoch: 1/10... Step: 90... Loss: 4.4188
Epoch: 1/10... Step: 100... Loss: 4.4174
</code></pre>
<p>And without gradient clipping, everything else equal:</p>
<pre><code class="lang-auto">Epoch: 1/10... Step: 10... Loss: 3.2837
Epoch: 1/10... Step: 20... Loss: 3.1901
Epoch: 1/10... Step: 30... Loss: 3.1512
Epoch: 1/10... Step: 40... Loss: 3.1296
Epoch: 1/10... Step: 50... Loss: 3.1170
Epoch: 1/10... Step: 60... Loss: 3.0758
Epoch: 1/10... Step: 70... Loss: 2.9787
Epoch: 1/10... Step: 80... Loss: 2.9104
Epoch: 1/10... Step: 90... Loss: 2.8271
Epoch: 1/10... Step: 100... Loss: 2.6813
</code></pre>
<p>There is probably something I don’t understand, but I’m just switching out those two bits of code.</p>

apaszke: <p>Maybe you’re clipping them to very small values. It’s a possible effect</p>

WendyShang: <p>The one comes with nn.util clips in proportional to the magnitude of the gradients. Thus you’d like to make sure it is not too small for your particular model as Adam said (I think :p). The old-fashioned way of clipping/clampping is</p>
<pre><code>def gradClamp(parameters, clip=5):
    for p in parameters:
        p.grad.data.clamp_(max=clip)</code></pre>

Brando_Miranda: <p>for people trying to just get an answer quickly:</p>
<pre><code>torch.nn.utils.clip_grad_norm(mdl_sgd.parameters(),clip)
</code></pre>
<p>or with in-place clamp:</p>
<pre><code>W.grad.data.clamp_(-clip,clip)
</code></pre>
<hr>
<p>also similar Q:</p>
<aside class="quote quote-modified" data-post="1" data-topic="2836">
  <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/osm3000/48/1749_2.png" class="avatar">
    <a href="https://discuss.pytorch.org/t/gradient-clipping/2836">Gradient clipping</a> 
  </div>
  <blockquote>
    Hi everyone, 
I am working on implementing Alex Graves model for handwriting synthesis (this is is the <a href="https://arxiv.org/pdf/1308.0850.pdf" rel="noopener nofollow ugc">link</a>) 
In page 23, he mentions the output derivatives and LSTM derivatives 
 <a class="lightbox" href="https://discuss.pytorch.org/uploads/default/original/1X/c8945faa55cdbc3f93a69a579cddacd6811560ee.png" data-download-href="https://discuss.pytorch.org/uploads/default/c8945faa55cdbc3f93a69a579cddacd6811560ee" title="Screenshot from 2017-05-10 14:53:50.png">[image]</a> 
How can I do this part in PyTorch? 
Thank you, 
Omar
  </blockquote>
</aside>


ntubertchen: <p>I thought nn.utils.clip_grad_norm(model.parameters(), clip) is supposed to finish the job.</p>
<p>What is:<br>
for p in model.parameters():<br>
p.data.add_(-lr, p.grad.data)<br>
for?</p>
<p>Can someone give a more explicit explain? Is it because after I use gradient clipping, I may not use adam optimizer?</p>

Neta_Zmora: <p><a class="mention" href="/u/ntubertchen">@ntubertchen</a><br>
Hi,<br>
Use <code>torch.nn.utils.clip_grad_norm</code> to keep the gradients within a specific range (clip).  In RNNs the gradients tend to grow very large (this is called ‘the exploding gradient problem’), and clipping them helps to prevent this from happening .  It is probably helpful to look at the <a href="https://pytorch.org/docs/master/_modules/torch/nn/utils/clip_grad.html" rel="nofollow noopener">implementation</a> because it teaches us that:</p>
<ol>
<li>“The norm is computed over all gradients together, as if they were concatenated into a single vector.”</li>
<li>You can control the norm type (<a href="https://en.wikipedia.org/wiki/Lp_space#The_p-norm_in_finite_dimensions" rel="nofollow noopener">lp-norm</a>, with p defaulting to 2; or the L-inf norm).</li>
<li>All of the gradient coefficients are multiplied by the same <code>clip_coef</code>.</li>
<li>clip_grad_norm is invoked after all of the gradients have been updated.  I.e. between loss.backward() and optimizer.step().  So during loss.backward(), the gradients that are propagated backwards are not clipped, until the backward pass completes and clip_grad_norm() is invoked.  optimizer.step() will then use the updated gradients.</li>
</ol>
<p>Regarding the code you ask about:</p>
<pre><code class="lang-auto">for p in model.parameters():
    p.data.add_(-lr, p.grad.data)
</code></pre>
<p>This iterates across all of the model.parameters() and performs an in-place multiply-add on each of the parameter tensors §.<br>
p.data.add_ is functionally equal to:</p>
<pre><code class="lang-auto">p.data = p.data + (-lr * p.grad.data)
</code></pre>
<p>In other words, this performs a similar function as optimizer.step(), using the gradients to updates the model parameters, but without the extra sophistication of a torch.optim.Optimizer.  If you use the above code, then you should not use an optimizer (and vice-versa).</p>
<p>Cheers,<br>
Neta</p>

tom: <p>Note that <code>clip_grad_norm_</code> modifies the gradient <em>after the entire backpropagation has taken place</em>. In the RNN context it is common to restrict the gradient <em>that is being backpropagated</em> during the calculation. This is described e.g. in <a href="https://arxiv.org/abs/1308.0850" rel="nofollow noopener">Alex Graves’ famous RNN paper</a>.<br>
To do the latter, you typically use <code>register_hook</code> on the inputs or outputs of certain operations, e.g. with <code>lambda x: x.clamp(-10,10)</code> to do element-wise clipping.<br>
For a practical example, you could search for <code>register_hook</code> in <a href="https://github.com/t-vi/pytorch-tvmisc/blob/master/misc/graves_handwriting_generation.ipynb" rel="nofollow noopener">my Graves handwriting generation notebook</a>.</p>
<p>Best regards</p>
<p>Thomas</p>

hughperkins: <p><a class="mention" href="/u/tom">@tom</a> Awesome info. Thanks!</p>

Jared_77: <aside class="quote no-group" data-username="Brando_Miranda" data-post="13" data-topic="191">
<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/brando_miranda/48/14355_2.png" class="avatar"> Brando_Miranda:</div>
<blockquote>
<p>torch.nn.utils.clip_grad_norm(mdl_sgd.parameters(),clip)</p>
</blockquote>
</aside>
<p>Thanks. Where does this go in relation to forward and backward propagation?</p>

jukiewiczm: <aside class="quote no-group" data-username="Neta_Zmora" data-post="15" data-topic="191">
<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/neta_zmora/48/23393_2.png" class="avatar"> Neta_Zmora:</div>
<blockquote>
<p>In other words, this performs a similar function as optimizer.step(), using the gradients to updates the model parameters, but without the extra sophistication of a torch.optim.Optimizer. If you use the above code, then you should not use an optimizer (and vice-versa).</p>
</blockquote>
</aside>
<p>What’s the reason for not using the <code>optimizer.step</code> after clipping the gradients?</p>

Neta_Zmora: <p>No reason: you can certainly use <code>optimizer.step()</code> and it will most likely lead to a better solution since the optimizer will update the parameters in a more sophisticated way (e.g. using momentum).</p>

jukiewiczm: <p>My bad, I thought what you suggest is that if you do gradient clipping, then you should (for some reason) use custom updates instead of <code>optimizer.step()</code>. Now I got it, you meant that if you use custom updates, then you should not use <code>optimizer.step()</code> (to avoid mixing custom and auto updates). Makes sense!</p>

aaronlelevier: <p>You need to use both <code>optimizer.step</code> and clip right? Because <code>optimizer.step</code> calcultes the gradient and then you want to clip those gradients to prevent vanishing on the next training step?</p>