Adam+Half Precision = NaNs?

ajbrock: <p>Hi guys,</p>
<p>I’ve been running into the sudden appearance of NaNs when I attempt to train using Adam and Half (float16) precision; my nets train just fine on half precision with SGD+nesterov momentum, and they train just fine with single precision (float32) and Adam, but switching them over to half seems to cause numerical instability. I’ve fiddled with the hyperparams a bit; upping epsilon helps a <em>tiny</em> bit but doesn’t fix the issue.</p>
<p>Is this something anyone else has info on? If not I can throw together a reproduction script and dig into the issue.</p>
<p>Thanks again! Been a good while since I’ve had to post on account of hitting no issues otherwise.</p>

smth: <p>half precision is super finicky during training, so I’m not surprised.</p>
<p>One thing I recommend trying is to do the forward + backward in half precision, but the optimizer step in float precision.<br>
To do this, you might have to clone your parameters, and cast them to float32 and once forward+backward is over, you copy over the param .data and .grad into this float32 copy (and call optimizer.step on this float32 copy) and then copy back…</p>
<p>Other than that, I dont have a good idea of why adam + half is giving NaNs.</p>

ajbrock: <p>Thanks, that’s just the answer I was looking for–will try out the precision swaps and report back.</p>

ajbrock: <p>EDIT: see below, it looks like eps was the culprit after all, no need for this solution.</p>
<p>Alright, got this working by just hanging onto fp32 copies of the parameters and keeping all of the Adam values in fp32 as well, as shown in <a href="https://gist.github.com/ajbrock/075c0ca4036dc4d8581990a6e76e07a3" rel="nofollow noopener">This Gist</a>. I suspect you could get the desired stability and do this even more efficiently by just keeping the Adam values in fp32 (I think there’s a divide-by-0 happening somewhere) but this gives the desired memory reduction without any loss of speed over fp32.</p>

apaszke: <p>It’s probably a 0 division somewhere. Have you tried using a much larger eps (say 1e-4)? The default 1e-8 is rounded to 0 in half precision.</p>

ajbrock: <p>I had previously tried upping epsilon after tagging it as the culprit, but I can’t recall to exactly what values–as of right now I’m training with eps=1e-4 and it’s working just fine. Guess I should have dug into that further, thanks!</p>

michaelklachko: <p>You might want to look at this paper:<br>
<a href="https://arxiv.org/abs/1609.07061" class="onebox" target="_blank" rel="nofollow noopener">https://arxiv.org/abs/1609.07061</a><br>
if you’re willing to keep a copy of weights/gradients in FP32 you might be able to reduce the precision of forward/backward step much further than FP16.</p>

iidsample: <p>For anybody who arrives here through a google search -<br>
This is a paper by Nvidia which sheds more light on training in FP16.<br>
<a href="https://arxiv.org/abs/1710.03740" class="onebox" target="_blank" rel="nofollow noopener">https://arxiv.org/abs/1710.03740</a></p>
<p>Also they have been nice to provide implemented code -<br>
<aside class="onebox whitelistedgeneric">
  <header class="source">
      <img src="https://github.githubassets.com/favicon.ico" class="site-icon" width="16" height="16">
      <a href="https://github.com/NVIDIA/apex" target="_blank" rel="nofollow noopener">GitHub</a>
  </header>
  <article class="onebox-body">
    <img src="https://avatars0.githubusercontent.com/u/1728152?s=400&amp;v=4" class="thumbnail" width="" height="">

<h3><a href="https://github.com/NVIDIA/apex" target="_blank" rel="nofollow noopener">NVIDIA/apex</a></h3>

<p>A PyTorch Extension:  Tools for easy mixed precision and distributed training in Pytorch - NVIDIA/apex</p>


  </article>
  <div class="onebox-metadata">
    
    
  </div>
  <div style="clear: both"></div>
</aside>
</p>

Lin_Jia: <p>This is a very old post, and google search took me here. For future references, it seems Adam is now adapted to do half-precision training with tuning on hyperparameters:</p>
<aside class="onebox allowlistedgeneric">
  <header class="source">
      <a href="https://www.programmersought.com/article/22245145270/" target="_blank" rel="noopener nofollow ugc">programmersought.com</a>
  </header>
  <article class="onebox-body">
    <img src="" class="thumbnail" width="" height="">

<h3><a href="https://www.programmersought.com/article/22245145270/" target="_blank" rel="noopener nofollow ugc">pytorch1.1 half-precision training Adam RMSprop optimizer Nan problem -...</a></h3>



  </article>
  <div class="onebox-metadata">
    
    
  </div>
  <div style="clear: both"></div>
</aside>


alexmath: <p>I had a similar issue. Changing BCELoss to BCEWithLogitsLoss and Adam epsilon from 10**(-8) to 10**(-4) worked for me.</p>
<p>I found it useful to inspect the computed gradients when debugging.</p>
<pre><code class="lang-auto">print([p.grad for p in model.parameters()])
</code></pre>

gingsi: <p>For me the backward function died before the optimizer was even called. My loss was very high and dividing the loss by 1e5 as last step before the backward pass helped to get rid of the NaN. Of course, performance could suffer, learning rate may need to be tuned etc.</p>

m4ttr4ymond: <p>I had this problem with TensorFlow, but this is the only post I found discussing it, so I might as well share my solution. Float16s can only represent numbers as small as 10e-5, but the default adam epsilons for TensorFlow and PyTorch are lower than this (10e-7 and 10e-8 respectively). This seems to cause underflow errors when using float16s. Changing the epsilon to 10e-4 solved the problem for me.</p>

Zeratul: <p>Wow, thank you so much !!<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"> Your solution works really well !!!</p>

Mark_Hamazaspyan: <p>Another solution, use bitsandbytes. It has Adam8bit optimizer.</p>
<pre><code class="lang-auto">import bitsandbytes as bnb

# adam = torch.optim.Adam(model.parameters(), lr=0.001, betas=(0.9, 0.995)) # comment out old optimizer
adam = bnb.optim.Adam8bit(model.parameters(), lr=0.001, betas=(0.9, 0.995)) # add bnb optimizer
</code></pre>
<aside class="onebox allowlistedgeneric" data-onebox-src="https://github.com/TimDettmers/bitsandbytes">
  <header class="source">
      <img src="https://github.githubassets.com/favicons/favicon.svg" class="site-icon" width="32" height="32">

      <a href="https://github.com/TimDettmers/bitsandbytes" target="_blank" rel="noopener nofollow ugc">GitHub</a>
  </header>

  <article class="onebox-body">
    <div class="aspect-image" style="--aspect-ratio:690/344;"><img src="https://opengraph.githubassets.com/4bd24347f5962bdaea38eed0dc568f503e4d4372055cda966b576564c807a83a/TimDettmers/bitsandbytes" class="thumbnail" width="690" height="345"></div>

<h3><a href="https://github.com/TimDettmers/bitsandbytes" target="_blank" rel="noopener nofollow ugc">GitHub - TimDettmers/bitsandbytes: 8-bit CUDA functions for PyTorch</a></h3>

  <p>8-bit CUDA functions for PyTorch. Contribute to TimDettmers/bitsandbytes development by creating an account on GitHub.</p>


  </article>

  <div class="onebox-metadata">
    
    
  </div>

  <div style="clear: both"></div>
</aside>


Nth1: <p>Thank you very much <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"></p>