# Nan Loss coming after some time

**URL:** <https://discuss.pytorch.org/t/nan-loss-coming-after-some-time/11568>\
**Category:** Uncategorized\
**Created:** [December 26, 2017, 5:23pm UTC](https://discuss.pytorch.org/t/nan-loss-coming-after-some-time/11568 "2017-12-26T17:23:10Z")\
**Posts on this page:** 20\
**Page:** 1

<div class="post-metadata">

**Author:** ![Vijay\_Dubey](https://discuss.pytorch.org/user_avatar/discuss.pytorch.org/vijay_dubey/32/2719_2.png) [@Vijay\_Dubey](https://discuss.pytorch.org/u/Vijay_Dubey)\
**Post date:** [December 26, 2017, 5:23pm UTC](https://discuss.pytorch.org/t/nan-loss-coming-after-some-time/11568/1 "2017-12-26T17:23:10Z")

</div>

The loss function is a combination of Mean Sqaured error loss and cross-entropy loss.  
When i am training my model, there is a finite loss but after some time, the loss is NaN and continues to be so.  
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.  
Please suggest a possible solution.

Thanks in advance

---

<div class="post-metadata">

**Author:** ![tom](https://discuss.pytorch.org/user_avatar/discuss.pytorch.org/tom/32/3162_2.png) [@tom](https://discuss.pytorch.org/u/tom)\
**Post date:** [December 26, 2017, 8:34pm UTC](https://discuss.pytorch.org/t/nan-loss-coming-after-some-time/11568/2 "2017-12-26T20:34:07Z")

</div>

Usually, the gradients become NaN first. The first two things to look at are a reduced learning rate and possibly gradient clipping.

Best regards

Thomas

---

<div class="post-metadata">

**Author:** ![richard](https://discuss.pytorch.org/user_avatar/discuss.pytorch.org/richard/32/1861_2.png) [@richard](https://discuss.pytorch.org/u/richard)\
**Post date:** [December 27, 2017, 12:41am UTC](https://discuss.pytorch.org/t/nan-loss-coming-after-some-time/11568/3 "2017-12-27T00:41:33Z")

</div>

@tom’s suggestions are great. Normalizing the data may help as well.

---

<div class="post-metadata">

**Author:** ![Vijay\_Dubey](https://discuss.pytorch.org/user_avatar/discuss.pytorch.org/vijay_dubey/32/2719_2.png) [@Vijay\_Dubey](https://discuss.pytorch.org/u/Vijay_Dubey)\
**Post date:** [December 27, 2017, 9:58am UTC](https://discuss.pytorch.org/t/nan-loss-coming-after-some-time/11568/4 "2017-12-27T09:58:42Z")

</div>

Hi @tom  
Thanks for your reply.  
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.

Thanks

---

<div class="post-metadata">

**Author:** ![Vijay\_Dubey](https://discuss.pytorch.org/user_avatar/discuss.pytorch.org/vijay_dubey/32/2719_2.png) [@Vijay\_Dubey](https://discuss.pytorch.org/u/Vijay_Dubey)\
**Post date:** [December 27, 2017, 8:59pm UTC](https://discuss.pytorch.org/t/nan-loss-coming-after-some-time/11568/5 "2017-12-27T20:59:37Z")

</div>

I tried doing it. But how should I decide the mean and standard deviation for the operation?

Thanks

---

<div class="post-metadata">

**Author:** ![richard](https://discuss.pytorch.org/user_avatar/discuss.pytorch.org/richard/32/1861_2.png) [@richard](https://discuss.pytorch.org/u/richard)\
**Post date:** [December 28, 2017, 1:38am UTC](https://discuss.pytorch.org/t/nan-loss-coming-after-some-time/11568/6 "2017-12-28T01:38:24Z")

</div>

You could use a [normalization layer](http://pytorch.org/docs/master/nn.html#torch.nn.functional.normalize). 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.

---

<div class="post-metadata">

**Author:** ![AliSh](https://discuss.pytorch.org/user_avatar/discuss.pytorch.org/alish/32/39425_2.png) [@AliSh](https://discuss.pytorch.org/u/AliSh)\
**Post date:** [September 15, 2019, 9:44am UTC](https://discuss.pytorch.org/t/nan-loss-coming-after-some-time/11568/7 "2019-09-15T09:44:58Z")

</div>

Hi, I am facing the same issue, I am wondering if you have solved it please?

---

<div class="post-metadata">

**Author:** ![ptrblck](https://discuss.pytorch.org/user_avatar/discuss.pytorch.org/ptrblck/32/1823_2.png) [@ptrblck](https://discuss.pytorch.org/u/ptrblck)\
**Post date:** [September 15, 2019, 11:00pm UTC](https://discuss.pytorch.org/t/nan-loss-coming-after-some-time/11568/8 "2019-09-15T23:00:01Z")

</div>

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

---

<div class="post-metadata">

**Author:** ![AliSh](https://discuss.pytorch.org/user_avatar/discuss.pytorch.org/alish/32/39425_2.png) [@AliSh](https://discuss.pytorch.org/u/AliSh)\
**Post date:** [September 17, 2019, 2:40pm UTC](https://discuss.pytorch.org/t/nan-loss-coming-after-some-time/11568/9 "2019-09-17T14:40:21Z")

</div>

Thanks for reply, none of the suggestion in this thread worked for me.  
Finally, I have solved my issue by your suggestion in another thread [Getting Nan after first iteration with custom loss](https://discuss.pytorch.org/t/getting-nan-after-first-iteration-with-custom-loss/25929/7) .

---

<div class="post-metadata">

**Author:** ![t.ouyang](https://discuss.pytorch.org/user_avatar/discuss.pytorch.org/t.ouyang/32/14275_2.png) [@t.ouyang](https://discuss.pytorch.org/u/t.ouyang)\
**Post date:** [December 17, 2019, 1:49pm UTC](https://discuss.pytorch.org/t/nan-loss-coming-after-some-time/11568/10 "2019-12-17T13:49:45Z")

</div>

Here is a way of debuging the nan problem.  
First, print your model gradients because there are likely to be nan in the first place.  
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.

There are some useful infomation about why nan problem could happen:  
1.the learning rate  
2.sqrt(0)  
3.ReLU-\>LeakyReLU

---

<div class="post-metadata">

**Author:** ![BikashgG](https://discuss.pytorch.org/user_avatar/discuss.pytorch.org/bikashgg/32/1116_2.png) [@BikashgG](https://discuss.pytorch.org/u/BikashgG)\
**Post date:** [December 27, 2019, 8:16pm UTC](https://discuss.pytorch.org/t/nan-loss-coming-after-some-time/11568/11 "2019-12-27T20:16:10Z")

</div>

Why is `sqrt(0)` a `Nan`? Should it not be equal to `0`?

---

<div class="post-metadata">

**Author:** ![monster](https://discuss.pytorch.org/user_avatar/discuss.pytorch.org/monster/32/24299_2.png) [@monster](https://discuss.pytorch.org/u/monster)\
**Post date:** [June 25, 2020, 11:05am UTC](https://discuss.pytorch.org/t/nan-loss-coming-after-some-time/11568/12 "2020-06-25T11:05:51Z")

</div>

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 ?

---

<div class="post-metadata">

**Author:** ![ptrblck](https://discuss.pytorch.org/user_avatar/discuss.pytorch.org/ptrblck/32/1823_2.png) [@ptrblck](https://discuss.pytorch.org/u/ptrblck)\
**Post date:** [June 26, 2020, 3:17am UTC](https://discuss.pytorch.org/t/nan-loss-coming-after-some-time/11568/13 "2020-06-26T03:17:43Z")

</div>

Do you get a NaN output from your model if you are using samples from certain folders or what do you mean by:

> [@monster](#):
>
> I am getting nan loss value in some folders

If your model is returning NaNs, you could set `torch.autograd.detect_anomaly(True)` at the beginning of your script to get a stack trace, which would hopefully point to the operation, which is creating the NaNs.

---

<div class="post-metadata">

**Author:** ![monster](https://discuss.pytorch.org/user_avatar/discuss.pytorch.org/monster/32/24299_2.png) [@monster](https://discuss.pytorch.org/u/monster)\
**Post date:** [June 27, 2020, 4:32am UTC](https://discuss.pytorch.org/t/nan-loss-coming-after-some-time/11568/14 "2020-06-27T04:32:24Z")

</div>

I am getting ‘nan’ loss after 1st epoch on a large dataset, please tell me all possible reasons for ‘nan’ loss value.  
check this :

```auto
dict_values([tensor(5.5172, device='cuda:0', grad_fn=<NllLossBackward>), tensor(nan, device='cuda:0', grad_fn=<DivBackward0>), tensor(3.7665, device='cuda:0', grad_fn=<BinaryCrossEntropyWithLogitsBackward>), tensor(inf, device='cuda:0', grad_fn=<DivBackward0>)])

```

---

<div class="post-metadata">

**Author:** ![ptrblck](https://discuss.pytorch.org/user_avatar/discuss.pytorch.org/ptrblck/32/1823_2.png) [@ptrblck](https://discuss.pytorch.org/u/ptrblck)\
**Post date:** [June 29, 2020, 7:30am UTC](https://discuss.pytorch.org/t/nan-loss-coming-after-some-time/11568/15 "2020-06-29T07:30:16Z")

</div>

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

---

<div class="post-metadata">

**Author:** ![monster](https://discuss.pytorch.org/user_avatar/discuss.pytorch.org/monster/32/24299_2.png) [@monster](https://discuss.pytorch.org/u/monster)\
**Post date:** [June 30, 2020, 4:44pm UTC](https://discuss.pytorch.org/t/nan-loss-coming-after-some-time/11568/16 "2020-06-30T16:44:34Z")

</div>

Thanks for reply.  
Can I just use gradient clipping? If yes,how can I choose clip value ?

---

<div class="post-metadata">

**Author:** ![ptrblck](https://discuss.pytorch.org/user_avatar/discuss.pytorch.org/ptrblck/32/1823_2.png) [@ptrblck](https://discuss.pytorch.org/u/ptrblck)\
**Post date:** [June 30, 2020, 9:31pm UTC](https://discuss.pytorch.org/t/nan-loss-coming-after-some-time/11568/17 "2020-06-30T21:31:08Z")

</div>

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.

Note however, that `FloatTensor`s have a maximal value of:

```python
print(torch.finfo().max)
> 3.4028234663852886e+38

```

so you should make sure that the NaNs are not created by an invalid operation.

---

<div class="post-metadata">

**Author:** ![monster](https://discuss.pytorch.org/user_avatar/discuss.pytorch.org/monster/32/24299_2.png) [@monster](https://discuss.pytorch.org/u/monster)\
**Post date:** [July 1, 2020, 11:50am UTC](https://discuss.pytorch.org/t/nan-loss-coming-after-some-time/11568/18 "2020-07-01T11:50:50Z")

</div>

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) ?

```auto
RuntimeError: Function 'SmoothL1LossBackward' returned nan values in its 0th output

```

---

<div class="post-metadata">

**Author:** ![ptrblck](https://discuss.pytorch.org/user_avatar/discuss.pytorch.org/ptrblck/32/1823_2.png) [@ptrblck](https://discuss.pytorch.org/u/ptrblck)\
**Post date:** [July 1, 2020, 5:02pm UTC](https://discuss.pytorch.org/t/nan-loss-coming-after-some-time/11568/19 "2020-07-01T17:02:52Z")

</div>

I would recommend to try to figure out what is causing the NaNs instead of ignoring them.  
Based on the raised error, the loss function might either have created the NaNs or might have gotten them through their input.

To isolate it, you could try to make the script deterministic following the [reproducibility docs](https://pytorch.org/docs/stable/notes/randomness.html). 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.

---

<div class="post-metadata">

**Author:** ![malisit](https://discuss.pytorch.org/user_avatar/discuss.pytorch.org/malisit/32/27307_2.png) [@malisit](https://discuss.pytorch.org/u/malisit)\
**Post date:** [July 30, 2020, 1:42pm UTC](https://discuss.pytorch.org/t/nan-loss-coming-after-some-time/11568/20 "2020-07-30T13:42:11Z")

</div>

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 [Keras as well](https://github.com/keras-team/keras/issues/2134#issuecomment-284937761).

[Next page](https://discuss.pytorch.org/t/nan-loss-coming-after-some-time/11568.md?page=2)
