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, for small logits, and use it and a prior-matching output bias as checks.
- Bound the error of central finite differences by , derive the optimal step , 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:
| Bug | Symptom | Test that catches it |
|---|---|---|
| shapes broadcast wrongly, e.g. in a hand-written loss | loss falls, predictions collapse toward the mean target | assert shapes at the loss; compare with the library loss |
| labels misaligned: inputs and labels shuffled separately, targets off by one position in a sequence | training accuracy near chance, loss stuck near | overfit one small batch; print input–label pairs just before the model |
| wrong input preprocessing: statistics of another dataset, RGB versus BGR, normalized twice | worse accuracy, no error | inspect the exact tensor that enters the model: its range, mean and a rendered example |
softmax applied before F.cross_entropy | loss cannot fall below , slow training | check that the loss takes logits; a 10-class loss stuck above 1.46 is a tell |
model.eval() forgotten, or model.train() not restored | evaluation depends on the batch size; training silently loses dropout | assert model.training where it matters |
| loss reduction changed from mean to sum, or the reverse | the effective learning rate scales with the batch size | recompute the loss by hand on one batch |
| data leakage: duplicates across splits, preprocessing fitted on all data, future information in a time series | validation results too good to be true | deduplicate; fit preprocessing on the training split only |
examples mixed within a batch, e.g. a view that should have been a permute | subtle accuracy loss; predictions depend on batch neighbors | the batch-independence gradient test below |
| augmentation that changes the label: flipping text, rotating a 6 into a 9 | an accuracy ceiling on the affected classes | view augmented samples with their labels |
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 0The 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.
Factor out inside the logarithm and write the rest as , with an average of :
The Gaussian moment generating function gives the first moment of , and its second moment is dominated by the variance of an average of independent terms, :
Expand . By symmetry of the Gaussian, odd powers of the have mean zero, so ; and :
A Monte Carlo check with : at the expansion gives against a simulated ; at it overshoots ( against ), as a second-order expansion should. Either way the lesson holds: a loss well above 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 (plus any constant) with near-zero weights makes the initial prediction equal the class frequencies , so the initial loss is the entropy rather than . 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).
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 . What is the expected initial binary cross-entropy?
Show the answer
0.305
The expected loss is the entropy of the prior, , against for a network that starts at . With a 1:99 imbalance the prior's entropy is only .
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.
Truncation. Taylor's theorem with the Lagrange remainder at points between and : the even terms cancel in the difference, leaving a remainder of order .
Rounding. The computed values are with , so the numerator carries an error of at most , and dividing by amplifies it as shrinks:
Balance. Set the derivative of to zero. At the optimum, , twice the truncation term:
With : in float64 (), and the error is about ; in float32 (), and the error is about . The one-sided difference only reaches order , about in float64.
| Step | ||||||
|---|---|---|---|---|---|---|
| float32 error | ||||||
| float64 error |
In practice. Compare with a relative error, . In double precision, values around or below indicate a correct gradient, and above 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 at , , 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 , or evaluate where no pre-activation lies within of zero.
You must run a central-difference gradient check in float32 () on a function with . What step minimizes the error bound?
Show the answer
0.007
. Even there the error is about , so float32 checks can only detect gross errors. The usual advice, double precision with near to , follows from the same formula with .
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: per step and per layer. "Somewhere around " 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.
A gradient check of a custom layer in float32 with reports relative errors around . What should you conclude?
- The backward pass is certainly wrong
- Nothing yet: rounding error dominates at this in float32; rerun in float64 with around to
- The step is too large; use
- The layer has too many kinks to be checked at all
Show the answer
B. Nothing yet: rounding error dominates at this in float32; rerun in float64 with around to
The rounding term with and is already about , 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 , and all produce NaN. Find the first non-finite value, not the last:
| Source | Example | Fix |
|---|---|---|
| logarithm of zero | torch.log(torch.softmax(z, -1)) when a probability underflows to 0 | compute log_softmax or pass logits to F.cross_entropy; clamp inside logarithms |
| exponential overflow | overflows for in float32 and bfloat16, and for in float16 | subtract the maximum before exponentiating (log-sum-exp) |
| division by zero | standardizing a constant feature, or a normalization layer whose input has zero variance | add inside the square root, as normalization layers do |
| negative variance from cancellation | computed in low precision comes out slightly negative, and its square root is NaN | two-pass or Welford algorithms; clamp at zero |
| float16 overflow | activations or gradients above 65,504 become | bfloat16 or float32 for sensitive operations; loss scaling skips such steps (Number Formats & Mixed Precision) |
| divergence | a learning rate too large lets weights grow until something overflows | lower the rate, clip gradients, warm up |
| bad data | a NaN in an input or label, a logarithm of a negative target | assert torch.isfinite on every batch |
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 ; with imbalanced classes, an output bias of starts the loss at the prior's entropy .
- The central difference has error at most , minimized at with error of order : about in float64 and 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 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.
A freshly initialized 10-class classifier reports a cross-entropy of 4.6 on its first batch. What is the most likely explanation?
- Everything is fine:
- The learning rate is too high
- The training set is too small
- 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 , rising only by about for logit scale . A loss twice as large means the logits are far from zero: scale down the last layer's initialization or check the input normalization.
Why is the best step for a central-difference gradient check proportional to ?
- It balances a truncation error growing like against a rounding error growing like
- Smaller steps are always better, and is as small as floating point allows
- It makes the truncation error exactly zero
- It balances a truncation error growing like against a rounding error growing like
Show the answer
A. It balances a truncation error growing like against a rounding error growing like
is minimized where , so and the error is of order . For the one-sided difference the truncation error is linear in , giving .
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?
- A label outside the vocabulary
- Attention scores large enough that their exponentials overflow float16's maximum of 65,504
- Gradients that underflow to zero in float16
- A missing call to
model.eval()
Show the answer
B. Attention scores large enough that their exponentials overflow float16's maximum of 65,504
exceeds float16's range once , and an infinity in a sum turns into NaN after or . 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.
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?
- Nothing unusual: gradients always spread across a batch
- The learning rate is too high
- An operation mixes examples across the batch axis, a bug for a model meant to treat examples independently
- 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).