Simple Algorithm
Deep Learning · Emergence · 24 min

Diagnosing Training Failures

Loss curves, gradient statistics, NaNs and the tests that catch silent bugs.

The worst bugs in deep learning do not crash. The loss goes down, the accuracy is merely disappointing, and weeks pass before anyone notices that the labels were shifted by one. The defense is a set of instruments with known readings: an initial loss you can compute in advance, a gradient check whose error you can bound, statistics that should stay within known ranges, and tests that a correct network must pass.

What you’ll learn

  • Derive the expected cross-entropy at initialization, log⁡K+(1−1K)s22+O(s4)\log K+(1-\tfrac1K)\tfrac{s^2}{2}+\order{s^4} for small logits, and use it and a prior-matching output bias as checks.
  • Bound the error of central finite differences by Mh2/6+ε∣f∣/hMh^2/6+\varepsilon\abs f/h, derive the optimal step h∗≈(3ε∣f∣/M)1/3h^*\approx(3\varepsilon\abs f/M)^{1/3}, and explain why gradient checks need double precision and must avoid kinks.
  • Read per-layer activation and gradient statistics, dead-unit fractions and update-to-weight ratios, run a learning-rate range test, and design tests (overfitting one batch, batch independence) that catch silent bugs.
  • Trace NaNs and infinities to their sources (logarithms of zero, overflow, zero variance, low-precision formats) and describe how large runs handle loss spikes.

A catalogue of silent bugs

A network is a differentiable program that tries to minimize whatever loss it is given, so it routes around many bugs and simply learns something worse. These are the common ones, each with the symptom it leaves and a test that exposes it:

BugSymptomTest that catches it
shapes broadcast wrongly, e.g. (B,1)−(B)(B,1)-(B) in a hand-written lossloss falls, predictions collapse toward the mean targetassert shapes at the loss; compare with the library loss
labels misaligned: inputs and labels shuffled separately, targets off by one position in a sequencetraining accuracy near chance, loss stuck near log⁡K\log Koverfit one small batch; print input–label pairs just before the model
wrong input preprocessing: statistics of another dataset, RGB versus BGR, normalized twiceworse accuracy, no errorinspect the exact tensor that enters the model: its range, mean and a rendered example
softmax applied before F.cross_entropyloss cannot fall below log⁡(1+(K−1)/e)\log(1+(K-1)/e), slow trainingcheck that the loss takes logits; a 10-class loss stuck above 1.46 is a tell
model.eval() forgotten, or model.train() not restoredevaluation depends on the batch size; training silently loses dropoutassert model.training where it matters
loss reduction changed from mean to sum, or the reversethe effective learning rate scales with the batch sizerecompute the loss by hand on one batch
data leakage: duplicates across splits, preprocessing fitted on all data, future information in a time seriesvalidation results too good to be truededuplicate; fit preprocessing on the training split only
examples mixed within a batch, e.g. a view that should have been a permutesubtle accuracy loss; predictions depend on batch neighborsthe batch-independence gradient test below
augmentation that changes the label: flipping text, rotating a 6 into a 9an accuracy ceiling on the affected classesview augmented samples with their labels
Most of these are invisible in the loss curve alone. They show up only in tests with known correct answers.
python
import torch

def batch_independence_test(model, x, i=3):
    """Output i of a correct model must not depend on any other example's input."""
    model.eval()                      # batchnorm in train mode mixes examples legitimately
    x = x.clone().requires_grad_(True)
    model(x)[i].sum().backward()      # gradient of example i's outputs only
    mass = x.grad.flatten(1).abs().sum(dim=1)
    others = torch.arange(len(x)) != i
    assert torch.all(mass[others] == 0), f"example {i} depends on others: {mass}"

def overfit_one_batch(model, loss_fn, x, y, opt, steps=500):
    model.train()
    for _ in range(steps):
        opt.zero_grad()
        loss = loss_fn(model(x), y)
        loss.backward()
        opt.step()
    return loss.item()                # should be close to its minimum, often 0

The first test backpropagates from one example's output and checks that no other input receives gradient, catching any operation that mixes the batch axis (Karpathy, 2019). The second runs a handful of examples for many steps: a correct model with enough capacity drives the loss nearly to zero; if it cannot, look for a bug before tuning anything.

The loss you should see at step zero

Before training, the loss is predictable. If it is not what you predicted, something is wrong with the data, the labels, the loss or the initialization, and you have learned it in one forward pass.

DerivationProof
  1. L=−zy+log⁡K+log⁡(1+u),u=1K∑k=1K(ezk−1)L=-z_y+\log K+\log(1+u),\qquad u=\frac1K\sum_{k=1}^K\big(e^{z_k}-1\big)

    Factor out KK inside the logarithm and write the rest as log⁡(1+u)\log(1+u), with uu an average of ezk−1e^{z_k}-1:

  2. E[u]=es2/2−1=s22+O(s4),E[u2]=s2K+O(s4)\E[u]=e^{s^2/2}-1=\frac{s^2}2+\order{s^4},\qquad \E[u^2]=\frac{s^2}{K}+\order{s^4}

    The Gaussian moment generating function gives the first moment of uu, and its second moment is dominated by the variance of an average of KK independent terms, Var⁡(ez)=s2+O(s4)\Var(e^{z})=s^2+\order{s^4}:

  3. E[L]=log⁡K+s22−s22K+O(s4)=log⁡K+(1−1K)s22+O(s4)\E[L]=\log K+\frac{s^2}{2}-\frac{s^2}{2K}+\order{s^4}=\log K+\Big(1-\frac1K\Big)\frac{s^2}{2}+\order{s^4}

    Expand log⁡(1+u)=u−u2/2+u3/3−⋯\log(1+u)=u-u^2/2+u^3/3-\cdots. By symmetry of the Gaussian, odd powers of the zkz_k have mean zero, so E[u3]=O(s4)\E[u^3]=\order{s^4}; and E[zy]=0\E[z_y]=0:

  4. K=10:log⁡K=2.303,s=0.5: 2.415 (simulated 2.414)K=10:\quad\log K=2.303,\qquad s=0.5:\ 2.415\ (\text{simulated }2.414)

    A Monte Carlo check with K=10K=10: at s=0.5s=0.5 the expansion gives 2.4152.415 against a simulated 2.4142.414; at s=2s=2 it overshoots (4.104.10 against 3.773.77), as a second-order expansion should. Either way the lesson holds: a loss well above log⁡K\log K at step zero means the logits start out large and the network is confidently wrong.

With imbalanced classes, start from the prior instead. Setting the output biases to bk=log⁡πkb_k=\log\pi_k (plus any constant) with near-zero weights makes the initial prediction equal the class frequencies π\pi, so the initial loss is the entropy H(π)H(\pi) rather than log⁡K\log K. The network then does not spend its first steps learning the class frequencies, which otherwise shows as a "hockey stick" at the start of the loss curve (Karpathy, 2019).

Predict before you look

A binary classifier sees one positive example for every ten negatives. Its output bias is set so the initial predicted probability of a positive is exactly 1/111/11. What is the expected initial binary cross-entropy?

Show the answer

0.305

The expected loss is the entropy of the prior, −111log⁡111−1011log⁡1011≈0.218+0.087=0.305-\tfrac1{11}\log\tfrac1{11}-\tfrac{10}{11}\log\tfrac{10}{11}\approx0.218+0.087=0.305, against ln⁡2≈0.693\ln2\approx0.693 for a network that starts at 12\tfrac12. With a 1:99 imbalance the prior's entropy is only 0.0560.056.

Checking gradients with finite differences

Frameworks compute gradients correctly; custom layers, custom backward functions and hand-written losses may not. A gradient check compares the analytic gradient with a finite difference. Its error has two sources pulling in opposite directions, and the best step size follows from balancing them.

DerivationProof
  1. f(x+h)−f(x−h)2h=f′(x)+h212(f′′′(ξ+)+f′′′(ξ−)),∣h212(⋯)∣≤Mh26\frac{f(x+h)-f(x-h)}{2h}=f'(x)+\frac{h^2}{12}\big(f'''(\xi_+)+f'''(\xi_-)\big),\qquad\Big|\frac{h^2}{12}\big(\cdots\big)\Big|\le\frac{Mh^2}{6}

    Truncation. Taylor's theorem with the Lagrange remainder at points ξ±\xi_\pm between xx and x±hx\pm h: the even terms cancel in the difference, leaving a remainder of order h2h^2.

  2. ∣f(x+h)δ+−f(x−h)δ−2h∣≤ε∣f∣h\Big|\frac{f(x+h)\delta_+-f(x-h)\delta_-}{2h}\Big|\le\frac{\varepsilon\abs f}{h}

    Rounding. The computed values are f(x±h)(1+δ±)f(x\pm h)(1+\delta_\pm) with ∣δ±∣≤ε\abs{\delta_\pm}\le\varepsilon, so the numerator carries an error of at most 2ε∣f∣2\varepsilon\abs f, and dividing by 2h2h amplifies it as hh shrinks:

  3. Mh3=ε∣f∣h2 ⟹ h∗=(3ε∣f∣M)1/3,E(h∗)=M2(h∗)2=32/32 (ε∣f∣)2/3M1/3\frac{Mh}{3}=\frac{\varepsilon\abs f}{h^2}\ \Longrightarrow\ h^*=\Big(\frac{3\varepsilon\abs f}{M}\Big)^{1/3},\qquad E(h^*)=\frac M2(h^*)^2=\frac{3^{2/3}}{2}\,(\varepsilon\abs f)^{2/3}M^{1/3}

    Balance. Set the derivative of E(h)=Mh2/6+ε∣f∣/hE(h)=Mh^2/6+\varepsilon\abs f/h to zero. At the optimum, ε∣f∣/h∗=M(h∗)2/3\varepsilon\abs f/h^*=M(h^*)^2/3, twice the truncation term:

  4. float64: h∗≈10−5, E≈10−11;float32: h∗≈10−2, E≈10−5\text{float64: }h^*\approx10^{-5},\ E\approx10^{-11};\qquad\text{float32: }h^*\approx10^{-2},\ E\approx10^{-5}

    With ∣f∣≈M≈1\abs f\approx M\approx1: in float64 (ε=2−52≈2.2×10−16\varepsilon=2^{-52}\approx2.2\times10^{-16}), h∗≈9×10−6h^*\approx9\times10^{-6} and the error is about 4×10−114\times10^{-11}; in float32 (ε=2−23≈1.2×10−7\varepsilon=2^{-23}\approx1.2\times10^{-7}), h∗≈7×10−3h^*\approx7\times10^{-3} and the error is about 2.5×10−52.5\times10^{-5}. The one-sided difference (f(x+h)−f(x))/h(f(x+h)-f(x))/h only reaches order ε1/2\varepsilon^{1/2}, about 3×10−83\times10^{-8} in float64.

Step hh10−110^{-1}10−210^{-2}10−310^{-3}10−410^{-4}10−510^{-5}10−610^{-6}
float32 error4.5×10−34.5\times10^{-3}3.6×10−53.6\times10^{-5}4.7×10−54.7\times10^{-5}8.8×10−48.8\times10^{-4}1.2×10−21.2\times10^{-2}9.6×10−29.6\times10^{-2}
float64 error4.5×10−34.5\times10^{-3}4.5×10−54.5\times10^{-5}4.5×10−74.5\times10^{-7}4.5×10−94.5\times10^{-9}5.9×10−115.9\times10^{-11}1.6×10−101.6\times10^{-10}
The central difference of f(x)=exf(x)=e^x at x=1x=1, computed in NumPy. Truncation dominates for large hh (the error falls 100-fold per decade, as h2h^2), rounding for small hh (the error grows as 1/h1/h). In float32 the best achievable error is near 10−510^{-5}, so a relative mismatch of 10−310^{-3} there says nothing about a bug.

In practice. Compare with a relative error, ∣ga−gn∣/max⁡(∣ga∣,∣gn∣)\abs{g_a-g_n}/\max(\abs{g_a},\abs{g_n}). In double precision, values around 10−710^{-7} or below indicate a correct gradient, and above 10−210^{-2} usually a wrong one (Stanford CS231n notes). PyTorch's torch.autograd.gradcheck uses eps=1e-6, atol=1e-5 and rtol=1e-3 by default, values designed for float64 inputs. Check a random subset of coordinates of every parameter tensor rather than one long vector, so a bug confined to one tensor is not averaged away.

Kinks. At a nondifferentiable point the difference straddles two slopes. For ReLU⁡\operatorname{ReLU} at z=h/2z=h/2, (ReLU⁡(z+h)−ReLU⁡(z−h))/(2h)=0.75(\operatorname{ReLU}(z+h)-\operatorname{ReLU}(z-h))/(2h)=0.75, while the analytic derivative is 1. A network has many kinks, so a few large mismatches among many good ones can be harmless; recheck them with a smaller hh, or evaluate where no pre-activation lies within hh of zero.

Predict before you look

You must run a central-difference gradient check in float32 (ε=2−23\varepsilon=2^{-23}) on a function with ∣f∣≈∣f′′′∣≈1\abs f\approx\abs{f'''}\approx1. What step h∗=(3ε∣f∣/M)1/3h^*=(3\varepsilon\abs f/M)^{1/3} minimizes the error bound?

Show the answer

0.007

(3×1.19×10−7)1/3≈7.1×10−3(3\times1.19\times10^{-7})^{1/3}\approx7.1\times10^{-3}. Even there the error is about 2.5×10−52.5\times10^{-5}, so float32 checks can only detect gross errors. The usual advice, double precision with hh near 10−510^{-5} to 10−610^{-6}, follows from the same formula with ε=2−52\varepsilon=2^{-52}.

Instruments during training

Log a few statistics per layer, not just the loss. Their healthy ranges come from the signal-propagation theory of Initialization & Vanishing Gradients:

  • Activation statistics: the mean and standard deviation of each layer's outputs. Steady shrinking or growth with depth means vanishing or exploding signals.
  • Dead and saturated units: the fraction of ReLUs that output zero on an entire batch, and of tanh or sigmoid units in their flat tails. A dead unit receives no gradient and rarely recovers.
  • Gradient norms per layer: a layer whose gradient is orders of magnitude smaller than its neighbors' is not learning. A sudden jump in the global norm often precedes a loss spike.
  • Update-to-weight ratio: ∥Δw∥/∥w∥\norm{\Delta\mathbf w}/\norm{\mathbf w} per step and per layer. "Somewhere around 10−310^{-3}" is a rough heuristic from the Stanford CS231n notes, not a law: much smaller suggests a learning rate too low, much larger one too high. With Adam, steps have roughly fixed size per coordinate, so the ratio mostly tracks the learning rate divided by the typical weight.

One more instrument belongs before a long run: the learning-rate range test (Smith, 2017). Train for a few epochs while the learning rate rises linearly from very small to very large, and plot accuracy against the rate. The rate where accuracy starts to improve and the rate where it slows, turns ragged or falls bracket the useful range. If no rate in a wide sweep makes progress, look for a bug before tuning anything.

Check your understanding

A gradient check of a custom layer in float32 with h=10−6h=10^{-6} reports relative errors around 10−110^{-1}. What should you conclude?

  1. The backward pass is certainly wrong
  2. Nothing yet: rounding error dominates at this hh in float32; rerun in float64 with hh around 10−510^{-5} to 10−610^{-6}
  3. The step is too large; use h=10−9h=10^{-9}
  4. The layer has too many kinks to be checked at all
Show the answer

B. Nothing yet: rounding error dominates at this hh in float32; rerun in float64 with hh around 10−510^{-5} to 10−610^{-6}

The rounding term ε∣f∣/h\varepsilon\abs f/h with ε≈1.2×10−7\varepsilon\approx1.2\times10^{-7} and h=10−6h=10^{-6} is already about 0.10.1, which explains the mismatch by itself. Only a check whose error floor is far below the mismatch can reveal a bug.

NaNs, infinities and loss spikes

A single NaN propagates through every operation it touches: within one step it reaches the loss, and after one update every weight. Infinities are almost as bad, since ∞−∞\infty-\infty, 0⋅∞0\cdot\infty and 0/00/0 all produce NaN. Find the first non-finite value, not the last:

SourceExampleFix
logarithm of zerotorch.log(torch.softmax(z, -1)) when a probability underflows to 0compute log_softmax or pass logits to F.cross_entropy; clamp inside logarithms
exponential overfloweze^z overflows for z>88.7z>88.7 in float32 and bfloat16, and for z>11.09z>11.09 in float16subtract the maximum before exponentiating (log-sum-exp)
division by zerostandardizing a constant feature, or a normalization layer whose input has zero varianceadd ϵ\epsilon inside the square root, as normalization layers do
negative variance from cancellationE[x2]−E[x]2\E[x^2]-\E[x]^2 computed in low precision comes out slightly negative, and its square root is NaNtwo-pass or Welford algorithms; clamp at zero
float16 overflowactivations or gradients above 65,504 become ∞\inftybfloat16 or float32 for sensitive operations; loss scaling skips such steps (Number Formats & Mixed Precision)
divergencea learning rate too large lets weights grow until something overflowslower the rate, clip gradients, warm up
bad dataa NaN in an input or label, a logarithm of a negative targetassert torch.isfinite on every batch
88.72=ln⁡(3.4×1038)88.72=\ln(3.4\times10^{38}) and 11.09=ln⁡65,50411.09=\ln65{,}504: the logarithms of the largest finite float32 and float16 numbers. Gradients that are too small are the opposite problem: in float16 they underflow to zero, silently, below about 6×10−86\times10^{-8}.

To locate the first bad operation, torch.autograd.set_detect_anomaly(True) makes the backward pass check each result and report the forward operation whose gradient produced a NaN, with its stack trace; it slows training, so use it only while debugging. Forward hooks that assert torch.isfinite on every layer's output find forward-pass infinities the same way.

Loss spikes at scale. Large models can fail without any bug. Training the 540-billion-parameter PaLM, Chowdhery et al. (2022) saw the loss spike about 20 times, at irregular intervals, despite gradient clipping. Restarting from a checkpoint about 100 steps before a spike and skipping roughly 200 to 500 data batches avoided the spike at that point. The same batches did not cause a spike when replayed from a different, earlier checkpoint, so the spikes came from the combination of particular data with a particular parameter state, not from bad data alone. Mechanisms and remedies such as growing attention logits, QK normalization and the z-loss are the subject of Normalization & Stability in Transformers.

Key takeaways

  • Check the loss at step zero: with small i.i.d. logits it is log⁡K+(1−1K)s2/2+O(s4)\log K+(1-\tfrac1K)s^2/2+\order{s^4}; with imbalanced classes, an output bias of log⁡πk\log\pi_k starts the loss at the prior's entropy H(π)H(\pi).
  • The central difference has error at most Mh2/6+ε∣f∣/hMh^2/6+\varepsilon\abs f/h, minimized at h∗=(3ε∣f∣/M)1/3h^*=(3\varepsilon\abs f/M)^{1/3} with error of order ε2/3\varepsilon^{2/3}: about 10−1110^{-11} in float64 and 10−510^{-5} in float32. Gradient checks belong in double precision, away from kinks.
  • Log per-layer activation and gradient sizes, dead-unit fractions and update-to-weight ratios; around 10−310^{-3} for the last is a heuristic, not a law.
  • Silent bugs need tests with known answers: overfitting one batch, the batch-independence gradient test, and inspecting the exact tensors that enter the model.
  • NaNs come from logarithms of zero, exponential overflow (above 88.7 in float32 and bfloat16, 11.09 in float16), zero variance and divergence; find the first non-finite value. Loss spikes at scale can arise without any bug.

Check yourself

In the interactive lesson these are scored with your confidence, and what you miss comes back for review.

Question 1

A freshly initialized 10-class classifier reports a cross-entropy of 4.6 on its first batch. What is the most likely explanation?

  1. Everything is fine: ln⁡10≈4.6\ln10\approx4.6
  2. The learning rate is too high
  3. The training set is too small
  4. The logits are large at initialization, so the network starts out confidently wrong
Show the answer

D. The logits are large at initialization, so the network starts out confidently wrong

With small logits the loss would be about ln⁡10≈2.30\ln10\approx2.30, rising only by about (1−1K)s2/2(1-\tfrac1K)s^2/2 for logit scale ss. A loss twice as large means the logits are far from zero: scale down the last layer's initialization or check the input normalization.

Question 2

Why is the best step for a central-difference gradient check proportional to ε1/3\varepsilon^{1/3}?

  1. It balances a truncation error growing like h2h^2 against a rounding error growing like ε/h\varepsilon/h
  2. Smaller steps are always better, and ε1/3\varepsilon^{1/3} is as small as floating point allows
  3. It makes the truncation error exactly zero
  4. It balances a truncation error growing like hh against a rounding error growing like ε/h2\varepsilon/h^2
Show the answer

A. It balances a truncation error growing like h2h^2 against a rounding error growing like ε/h\varepsilon/h

E(h)=Mh2/6+ε∣f∣/hE(h)=Mh^2/6+\varepsilon\abs f/h is minimized where Mh/3=ε∣f∣/h2Mh/3=\varepsilon\abs f/h^2, so h∗∝ε1/3h^*\propto\varepsilon^{1/3} and the error is of order ε2/3\varepsilon^{2/3}. For the one-sided difference the truncation error is linear in hh, giving h∗∝ε1/2h^*\propto\varepsilon^{1/2}.

Question 3

A mixed-precision run starts producing NaNs, and anomaly detection points at the softmax over attention scores computed in float16. What is the most likely cause?

  1. A label outside the vocabulary
  2. Attention scores large enough that their exponentials overflow float16's maximum of 65,504
  3. Gradients that underflow to zero in float16
  4. A missing call to model.eval()
Show the answer

B. Attention scores large enough that their exponentials overflow float16's maximum of 65,504

eze^z exceeds float16's range once z>11.09z>11.09, and an infinity in a sum turns into NaN after ∞−∞\infty-\infty or ∞/∞\infty/\infty. Subtracting the maximum score first (or computing the softmax in float32 or bfloat16) removes the overflow; bounding the logits themselves, for example with QK normalization, addresses the cause.

Question 4

In evaluation mode you backpropagate from the output of example 3 in a batch and find nonzero gradients on the input of example 5. What does this tell you?

  1. Nothing unusual: gradients always spread across a batch
  2. The learning rate is too high
  3. An operation mixes examples across the batch axis, a bug for a model meant to treat examples independently
  4. The model is in evaluation mode, so the test is invalid
Show the answer

C. An operation mixes examples across the batch axis, a bug for a model meant to treat examples independently

For a model that processes examples independently, example 3's output cannot depend on example 5's input. A typical culprit is a reshape that interleaves the batch axis with another axis, such as view where permute was meant.

Further reading

  • A. Karpathy, "A recipe for training neural networks," blog post (2019).
  • J. Nocedal & S. J. Wright, Numerical Optimization, 2nd ed., ch. 8 "Calculating derivatives" (Springer, 2006).
  • Stanford CS231n course notes, "Neural networks part 3: learning and evaluation" (gradient checks and sanity checks).
  • I. Goodfellow, Y. Bengio & A. Courville, Deep Learning, §11.5 "Debugging strategies" (MIT Press, 2016).
  • A. Chowdhery et al., "PaLM: Scaling language modeling with Pathways," arXiv:2204.02311 (2022); Journal of Machine Learning Research 24 (2023).