Skip to content
ImagineWorld

Training Stability

node_idnode-book_building-frontier-llm-from-scratch_chapter-21-training-stability
node_typechapter-node
schema_profileworld.chapter_node.v1
statusactive
entropyhigh
manifoldworld
domainimagineworld.net
authorityinforms
layercorpus
chapter_num21
chapter_titleTraining Stability
governed_byCORPUS
constitutional_citationCONSTITUTION
local graph

No amount of infrastructure guarantees that a training run will converge. Large models are delicate: a single bad batch, a learning rate a touch too high, or a numerical overflow can send the loss soaring and, if unhandled, ruin weeks of compute. Keeping a frontier run alive is a discipline of its own — part vigilance, part fast intervention, part architectural insurance bought in earlier chapters. This short closing chapter of Part V covers the failure modes, the remedies, and what to watch.

The signature instability is the loss spike: a training loss that has been falling steadily suddenly jumps, sometimes by a large factor, in a single step or a handful of steps (Figure 21.1). Often the model recovers on its own; sometimes it diverges irrecoverably, the loss climbing to nonsense and never returning. The causes are a short list — an anomalous batch of data (a long run of repeated or corrupted tokens), a learning rate too high for the current phase, an attention-score or activation magnitude that grew until it overflowed, or simple numerical overflow in low precision. The larger and lower-precision the model, the more frequent and more dangerous spikes become, which is why the FP8 training of Chapter 18 demands such care.

Figure 21.1. A loss spike. After a steady decline, the loss jumps sharply in a few steps. Many spikes recover on their own; the danger is the spike that does not, which can corrupt the run if not caught and rolled back.

The interventions form a ladder from cheap and automatic to expensive and manual. Gradient clipping (Chapter 17) is the first line of defense, bounding any single update. Skipping anomalous batches — detecting a loss far above the recent average and discarding that step’s gradient rather than applying it — prevents one bad batch from propagating, and is a few lines:

if loss.item() > spike_factor * running_mean_loss:
opt.zero_grad(set_to_none=True) # discard this step's gradient
skipped += 1
continue # do not update on a bad batch

Python — skip a batch whose loss spikes far above the running average

When a spike does not self-correct, the heavier remedy is to roll back to a recent checkpoint and resume past the offending data, often with a temporarily lowered learning rate — which is why the frequent checkpointing of Chapter 17 is not optional.

Architectural choices also buy stability in advance: QK-norm (Chapter 15) bounds attention scores so they cannot explode; an auxiliary z-loss gently penalizes the logits’ magnitude to keep the softmax well-conditioned; careful weight initialization and the auxiliary-loss-free MoE balancing of Chapter 11 prevent other slow divergences. Table 21.1 maps symptoms to remedies.

SymptomLikely causeRemedy
Sudden loss spikebad batch, LR too highskip batch; clip; roll back + lower LR
Slow divergencepeak LR too high, weak warmuplower peak LR; lengthen warmup
Attention logits explodeunbounded scoresQK-norm; logit soft-cap; z-loss
NaN / Inf appearsoverflow (esp. FP8 / FP16)loss scaling; FP32 for sensitive ops
Dead / overloaded expertsrouting collapseload balancing (Chapter 11)

Table 21.1 — Instability symptoms and remedies

Stability problems announce themselves before they become fatal, if you are watching the right signals. The gradient norm is the most informative single number — a sudden growth precedes most spikes, giving an early warning. Beyond it: the training and validation loss curves (the obvious one), the magnitudes of activations and logits (creeping growth signals an impending overflow), and, for MoE models, the expert load distribution (to catch routing collapse). Good monitoring turns a mysterious 3 a.m. divergence into a logged, diagnosable event — and the difference between a run you can rescue and one you must restart from scratch.

Part V complete The model can now be trained at scale: the loop scheduled over trillions of tokens, the arithmetic in FP8, the model split across thousands of GPUs, the infrastructure feeding and measuring it, and the run kept stable. What you have at the end of pretraining is a base model — fluent, knowledgeable, and almost unusable as an assistant, because it only continues text rather than following instructions. Turning it into something helpful, harmless, and able to reason is the work of Part VI.

That transformation — from a raw next-token predictor into an aligned, instruction-following, reasoning model — is where some of the most consequential recent advances live, including the reinforcement-learning recipe behind DeepSeek-R1. Part VI begins with the first and simplest step: supervised fine-tuning.

21.4 Worked Example: Detecting and Surviving a Loss Spike

Section titled “21.4 Worked Example: Detecting and Surviving a Loss Spike”

Loss spikes are normal in large runs (Chapter 21); the discipline is to detect them against a running average and recover rather than let a single bad batch derail the run. A spike beyond a multiple of the moving average triggers a rollback:

ema = beta * ema + (1 - beta) * loss.item() # smooth running loss
f loss.item() > spike_factor * ema: # a real spike, not noise
load_checkpoint(last_good) # roll back (Chapter 17)
skip_batches(n=100) # step over the bad data
log.Warning(f"spike at {step}: {loss:.2f} vs ema {ema:.2f}")
pair with grad clipping (Section 17.6), grad-norm monitoring, and
keeping several recent checkpoints so a rollback target always exists
*Python — spike detection and rollback*
21.5 NaNs, Infs, and Where They Come From
A non-finite value — a NaN or an infinity — is the most abrupt
failure a run can suffer: once one appears, the next optimizer step
smears it across every parameter and the model is dead. They
come from three places. Overflow, when an unstabilized
exponential in softmax or attention exceeds the float range.
Division by zero, when RMSNorm meets a zero-variance row or a
log meets a zero probability. And bad inputs, a corrupt token id
indexing out of the embedding table, or an infinity that rode in
with the data. The defense is to detect them early and cheaply:
def assert_finite(name, t):
if not torch.isfinite(t).all():
bad = (~torch.isfinite(t)).sum().item()
raise FloatingPointError(f"{name}: {bad} non-finite values")
if step % 50 == 0:
assert_finite("loss", loss) # cheap periodic check
for n, p in model.named_parameters():
if p.grad is not None:
assert_finite(f"grad/{n}", p.grad)
*Python — train/guards.py: catch non-finite values at the source*
Checking every step is wasteful; never checking means a NaN can
corrupt thousands of steps before you notice in the loss curve. A
periodic guard catches the problem within a few dozen steps and,
crucially, names the tensor where it first appeared — turning “the
loss went to NaN somewhere” into “the gradient of layer 53's gate
exploded,” which is a debuggable statement.
21.6 The Practitioner's Monitoring Dashboard
Stability is mostly a matter of watching a handful of scalars and
knowing their healthy ranges. A spike or drift in any one of them is
an early warning, often visible long before the loss itself moves:
SignalHealthy rangeWhat a deviation means
Training losssmooth decayspike → bad batch or LR too high
Gradient normstable, 0(0.1–1)climbing → instability building
Learning ratefollows schedulemismatch → scheduler bug
Activation RMSroughly constantgrowing → residual-stream blowup
Router entropy (MoE)high, stablecollapse → experts unused
Tokens/sec (MFU)flatdrop → stragglers or I/O stall

Table 21.1 — Signals to monitor and their healthy ranges

The two most predictive signals are the gradient norm and the activation RMS. A gradient norm that begins to climb — even while the loss still looks fine — is the classic precursor to a spike (Section 21.1), and is exactly what your clipping threshold (Section 17.8) is sized against. A steadily growing activation RMS signals a residual stream that is not being held in check by normalization, the failure mode that motivated the placement choices of Chapter 15. Watch these two and you will see most trouble coming.

The loss is a lagging indicator By the time the loss curve visibly breaks, the cause is several steps in the past. Gradient norm and activation statistics move first; a dashboard that surfaces them turns most blow-ups from post-mortems into near-misses you quietly recovered from.

21.7 Recovering from a Loss Spike: A Runbook

Section titled “21.7 Recovering from a Loss Spike: A Runbook”

When the monitoring of Section 21.6 catches a spike, the response should be a procedure, not a panic. The same situation arises on nearly every large run, and the recovery is well-rehearsed. The sequence, in order, is this.

First, stop before the damage spreads — a NaN left to propagate through one optimizer step corrupts every parameter, so halting promptly is what makes recovery possible at all. Second, roll back to the last good checkpoint (Section 20.5), discarding the poisoned state. Third, skip the offending data: spikes are very often caused by a single pathological batch — a corrupted document, an extreme outlier — so advancing the data loader past the batch that triggered the spike frequently resolves it outright. Fourth, if spikes recur, lower the learning rate briefly through the unstable region and let it return to schedule afterward (Section 17.2). Finally, resume and watch the gradient norm closely to confirm the run has stabilized.

What makes this routine rather than catastrophic is everything built earlier: frequent checkpoints give a clean state to return to, the monitoring dashboard provides early warning and a named culprit, and gradient clipping (Section 17.8) often prevents the spike from becoming fatal in the first place. A large run is not one that never spikes — it is one engineered so that spikes are survivable.

Spikes are survivable by design Stop, roll back, skip the bad batch, optionally ease the learning rate, resume. The procedure only works because checkpoints, monitoring, and clipping were in place beforehand — recovery is prepared, not improvised.

21.8 Why Weight Decay and z-loss Stabilize Training

Section titled “21.8 Why Weight Decay and z-loss Stabilize Training”

Two regularizers do quiet but essential work for stability, beyond their textbook role of reducing overfitting. The first is weight decay (Section 17.9), which pulls weights gently toward zero each step; left unchecked, weights can grow without bound over a long run, inflating activations and gradients until the training destabilizes. The second is less familiar but increasingly standard at scale — a z-loss that penalizes the softmax normalizer from drifting:

# z-loss penalizes a growing softmax normalizer (logsumexp)
z = torch.logsumexp(logits, dim=-1) # the softmax denominator
z_loss = 1e-4 * (z ** 2).mean() # add to the main objective
loss = cross_entropy + z_loss

Python — train/zloss.py: keeping the logits from drifting

The mechanism is preventive. The cross-entropy loss constrains the differences between logits but not their absolute scale, so the logits are free to drift upward together over training — and large logits make the softmax numerically fragile and the exponentials prone to overflow (Section 21.5). The z-loss adds a small penalty on the magnitude of the logsumexp, gently anchoring the overall logit scale without distorting the relative values that carry the model’s predictions. Together, weight decay bounds the parameters and z-loss bounds the outputs; both are cheap insurance against the slow drifts that turn into sudden spikes, and both are examples of the same principle — that stability at scale is bought by keeping quantities from growing where nothing else would stop them.

Bound what nothing else bounds Cross-entropy constrains logit differences but not their scale; weight decay constrains parameter growth. z-loss and weight decay each anchor a quantity that would otherwise drift unchecked — cheap regularizers that prevent the slow growth behind many late-run spikes.

The loss spikes of Section 21.4 are loud — they announce themselves and trigger the runbook. The more dangerous failures are silent: the run does not crash, the loss looks plausible, and yet something is subtly wrong — a slightly miscomputed gradient, a data bug that biases what the model learns, a precision issue that slowly erodes quality. These are insidious precisely because nothing alerts you; the run completes, the artifact looks fine, and the damage is discovered only later, after enormous compute has been spent.

Defending against silent failures is the deeper reason the monitoring discipline of Section 21.6 watches so many signals rather than the loss alone. A healthy loss curve can coexist with an unhealthy run, but the symptoms usually show somewhere — in gradient norms drifting where they should be stable, in weight or activation statistics moving oddly, in an evaluation metric that fails to improve even as the loss falls. Catching these requires three habits: instrument broadly, so that many indicators are visible and a divergence in any of them raises a flag; add explicit assertions, such as checks for NaN or infinity, that turn a silent corruption into a loud, locatable error; and compare against a known-good baseline run, so that “plausible” can be checked against “correct.” The governing principle is that at the scale of a real training run, the absence of a crash is not evidence of success — only a broad set of healthy signals is — and building the observability to tell the difference is as important as any single optimization.

No crash is not the same as no bug Silent failures pass the loss check while quietly corrupting a run, wasting compute before discovery. Watching gradient norms, weight statistics, and eval metrics — plus NaN assertions and a baseline to compare against — is what surfaces them early.

21.10 Initialization and Stability from Step One

Section titled “21.10 Initialization and Stability from Step One”

A training run’s stability is decided in part before the first gradient ever flows, by how the weights are initialized. Set the initial weights too large and activations grow as they pass through layer after layer, exploding by the top of a deep network; set them too small and the signal vanishes the same way. Either failure can doom a run from the very first step, regardless of how carefully the learning rate is later tuned.

The classical schemes — Xavier (Glorot) and He (Kaiming) initialization — address this by setting the initial weight scale based on each layer’s input and output dimensions, chosen so that the variance of activations is preserved as they propagate forward and gradients as they propagate backward. For the deep transformers this book builds, an additional refinement is common: scaling the weights of the residual branches down in proportion to depth, so that the contributions of many layers summed into the residual stream (Section 8.5) do not accumulate to an unstable magnitude. The deeper point connects to everything else in this chapter: initialization, normalization placement (Section 15.6), and the z-loss and weight decay of Section 21.8 are all answers to the same underlying question — how to keep the scale of activations and gradients under control so the network trains. Initialization is simply the first of these controls to act, setting the starting conditions from which a stable run, or an immediate divergence, follows.

Stability begins before the first step Initialize too large and activations explode through depth; too small and they vanish. Xavier and He scale the initial weights to preserve variance, and deep transformers scale residual branches down by depth — the first of the controls that keep a run stable.