DL0018 NaN Values

What are the common causes for a deep learning model to output NaN values?

Answer

NaN outputs almost always trace back to numerical instability somewhere in the pipeline: unstable math operations, exploding gradients, an oversized learning rate, bad weight initialization, or corrupted input data. Once any parameter becomes NaN or Inf, the poisoning propagates through every subsequent layer, so the model’s outputs quickly become NaN everywhere.

(1) Exploding Gradients: Gradients grow without bound through many layers, producing weight updates so large that parameters overflow to Inf/NaN.
(2) Unstable Math Operations: \log(0), division by zero, or square roots of negative numbers yield Inf/NaN. For example, batch normalization divides by zero variance if a batch is constant and no \epsilon is used.
(3) Improper Learning Rate: A learning rate that is too high makes parameter updates diverge, pushing weights to extreme values that overflow.
(4) Incorrect Weight Initialization: Initializing weights to very large values can overflow activations on the very first forward pass.
(5) Data Issues: Inputs containing NaN, Inf, or extreme unnormalized values inject invalid numbers directly into the computation graph.

Training loss curve where unclipped gradients explode and the loss becomes NaN, compared with stable training using gradient clipping.

Figure 1: Unclipped gradients can explode within a few steps until the loss itself becomes NaN/Inf; gradient clipping keeps training on track.

NaN Loss vs NaN Outputs: The two are stages of the same instability. A NaN loss can even appear while model outputs are still finite. For example, cross-entropy computes \log(\hat{y}), and a prediction extremely close to zero yields -\infty, which turns into NaN after the backward pass.

Diagram of five common NaN causes with their standard fixes all feeding into NaN parameters and therefore NaN outputs.

Figure 2: The five common causes and their standard fixes: every path ends at NaN parameters, hence NaN outputs.

Mathematical Formulation:
\mathcal{L} = -\log(\hat{y} + \epsilon)
\hat{y} \to 0 \ \Rightarrow\ \mathcal{L} \to \infty \ \Rightarrow\ \text{NaN in backprop}
g \leftarrow g \cdot \min\left(1,\ \frac{\tau}{\lVert g \rVert}\right)

Where:

  • \hat{y} is the predicted probability of the true class; without the \epsilon clamp the loss diverges as \hat{y} approaches 0 and turns NaN in backprop.
  • g is the gradient vector and \tau the clipping threshold; the second rule (norm clipping) caps update magnitude before gradients can overflow the parameters.

Login to view more content


Log in to track your progress

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *