Nan Loss coming after some time

Vijay_Dubey: <p>The loss function is a combination of Mean Sqaured error loss and cross-entropy loss.<br>
When i am training my model, there is a finite loss but after some time, the loss is NaN and continues to be so.<br>
When I am training my model just on a single batch of 10 images, the loss is finite most of the times, but sometimes that is also NaN.<br>
Please suggest a possible solution.</p>
<p>Thanks in advance</p>

tom: <p>Usually, the gradients become NaN first. The first two things to look at are a reduced learning rate and possibly gradient clipping.</p>
<p>Best regards</p>
<p>Thomas</p>

richard: <p><a class="mention" href="/u/tom">@tom</a>’s suggestions are great. Normalizing the data may help as well.</p>

Vijay_Dubey: <p>Hi <a class="mention" href="/u/tom">@tom</a><br>
Thanks for your reply.<br>
Can you also suggest how can I check if the gradients are becoming NaN first and also how can I ensure gradient clipping with a SGD or AdaGrad Optimizer.</p>
<p>Thanks</p>

Vijay_Dubey: <p>I tried doing it. But how should I decide the mean and standard deviation for the operation?</p>
<p>Thanks</p>

richard: <p>You could use a <a href="http://pytorch.org/docs/master/nn.html#torch.nn.functional.normalize" rel="nofollow noopener">normalization layer</a>. Alternatively, you can try dividing by some constant first (perhaps equal to the max value of your data?) The idea is to get the values low enough that they don’t cause really large gradients.</p>

AliSh: <p>Hi, I am facing the same issue, I am wondering if you have solved it please?</p>

ptrblck: <p>Have you tried the suggestions from this thread and is nothing working?<br>
If so, when do you see the first NaN value?<br>
Could you additionally check out input for NaN values?</p>

AliSh: <p>Thanks for reply, none of the suggestion in this thread worked for me.<br>
Finally, I have solved my issue by your suggestion in another thread <a href="https://discuss.pytorch.org/t/getting-nan-after-first-iteration-with-custom-loss/25929/7" class="inline-onebox">Getting Nan after first iteration with custom loss</a> .</p>

t.ouyang: <p>Here is a way of debuging the nan problem.<br>
First, print your model gradients because there are likely to be nan in the first place.<br>
And then check the loss, and then check the input of your loss…Just follow the clue and you will find the bug resulting in nan problem.</p>
<p>There are some useful infomation about why nan problem could happen:<br>
1.the learning rate<br>
2.sqrt(0)<br>
3.ReLU-&gt;LeakyReLU</p>

BikashgG: <p>Why is <code>sqrt(0)</code> a <code>Nan</code>? Should it not be equal to <code>0</code>?</p>

monster: <p>I have 100 folders of different class images and I am getting nan loss value in some folders, I already checked gray scale,truncated,missing labels etc everything is fine but still getting ‘nan’ loss. What could be the possible reason ?</p>

ptrblck: <p>Do you get a NaN output from your model if you are using samples from certain folders or what do you mean by:</p>
<aside class="quote no-group" data-username="monster" data-post="12" data-topic="11568">
<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/monster/48/24299_2.png" class="avatar"> monster:</div>
<blockquote>
<p>I am getting nan loss value in some folders</p>
</blockquote>
</aside>
<p>If your model is returning NaNs, you could set <code>torch.autograd.detect_anomaly(True)</code> at the beginning of your script to get a stack trace, which would hopefully point to the operation, which is creating the NaNs.</p>

monster: <p>I am getting ‘nan’ loss after 1st epoch on a large dataset, please tell me all possible reasons for ‘nan’ loss value.<br>
check this :</p>
<pre><code class="lang-auto">dict_values([tensor(5.5172, device='cuda:0', grad_fn=&lt;NllLossBackward&gt;), tensor(nan, device='cuda:0', grad_fn=&lt;DivBackward0&gt;), tensor(3.7665, device='cuda:0', grad_fn=&lt;BinaryCrossEntropyWithLogitsBackward&gt;), tensor(inf, device='cuda:0', grad_fn=&lt;DivBackward0&gt;)])

</code></pre>

ptrblck: <p>NaN values can be created by invalid operations, such as <code>torch.log(torch.tensor(-1.))</code>, by operations executed on Infs (created through over-/underflows) etc.<br>
To isolate it, use <code>torch.autograd.set_detect_anomaly(True)</code>.</p>

monster: <p>Thanks for reply.<br>
Can I just use gradient clipping? If yes,how can I choose clip value ?</p>

ptrblck: <p>If larger gradient magnitudes are expected and would thus create invalid values, you might clip the gradients. You could start with a max norm value of 1 or refer to any paper, which uses a similar approach.</p>
<p>Note however, that <code>FloatTensor</code>s have a maximal value of:</p>
<pre><code class="lang-python">print(torch.finfo().max)
&gt; 3.4028234663852886e+38
</code></pre>
<p>so you should make sure that the NaNs are not created by an invalid operation.</p>

monster: <p>by using torch.autograd.set_detect_anomaly(True) I found this error. My dataset seems ok so to resolve this issue should I use gradient clipping or just ignore ‘nan’ values using torch.isnan(x) ?</p>
<pre><code class="lang-auto">RuntimeError: Function 'SmoothL1LossBackward' returned nan values in its 0th output
</code></pre>

ptrblck: <p>I would recommend to try to figure out what is causing the NaNs instead of ignoring them.<br>
Based on the raised error, the loss function might either have created the NaNs or might have gotten them through their input.</p>
<p>To isolate it, you could try to make the script deterministic following the <a href="https://pytorch.org/docs/stable/notes/randomness.html">reproducibility docs</a>. Once it’s deterministic and you could trigger the NaNs in a single step, you could check the parameters, inputs, gradients etc. for the iteration which causes the NaNs.</p>

malisit: <p>I don’t know if this applies to this case and I made sure nothing’s wrong with my data, but I see nans after some time when I use RMSProp but not with Adam. Try changing your optimizer maybe? A similar experience is shared for <a href="https://github.com/keras-team/keras/issues/2134#issuecomment-284937761" rel="nofollow noopener">Keras as well</a>.</p>