Foundations to Frontier
Tests

Training Stability: Loss Spikes, z-Loss and QK-Norm

Large training runs often hit loss spikes or diverge, wasting weeks of compute. Common causes are attention logits growing without bound (attention entropy collapse), output logits drifting, too-high learning rates, bad data batches, and low-precision overflow. Standard defences are learning-rate warm-up and decay, gradient clipping, careful initialisation, and normalisation placement (pre-norm). Two targeted fixes are QK-norm, which normalises queries and keys before their dot product so attention logits stay bounded, and z-loss, which penalises the squared log-normaliser of the output softmax so output logits stay near zero. Operationally, teams checkpoint often and roll back past spikes. This page covers these failure modes and remedies. In the exercises you implement QK-norm scores, z-loss and gradient clipping, then train the one-layer GPT with Adam at a safe and an aggressive learning rate. At lr 0.01 all variants trained alike. At lr 0.3 the baseline's attention logits exploded to about 5 × 10⁵ with 43 loss spikes, and its loss stalled at 2.32. With QK-norm, logits stayed at 7.4 and loss reached 1.94 (1.47 in the other two seeds). z-loss shrank the output log-normaliser (3.44 to 2.72 at lr 0.01) but did not stop attention logits exploding.

Level 0: Foundation

★☆☆☆☆ Introductory⏱ 5 minGeneral audience. No mathematics required.

Keeping a huge training run from blowing up

Training a large language model takes weeks, and sometimes the error suddenly shoots up and never recovers, like a rocket wobbling out of control. Often some numbers inside the model grow too large: the scores that decide what each word pays attention to can get so extreme that the model stops learning. Simple safeguards keep them in check: start with small steps and grow them (warm-up), limit how big each update can be (clipping), and normalise the attention inputs (QK-norm). The demo shows how sharply a softmax responds as its inputs grow.

LLM lab
Kept tokens: 10 of 10; entropy 1.57 nats; top probability 0.40. Low temperature or small k/p make output more deterministic; high temperature makes it more diverse.
Why engineers care

Stability engineering decides whether a training budget produces a model or a crashed run. The same ideas (bounded internal signals, clipping, rollback) apply to any long, expensive training of models for flight or robotics.

📝 Quick check (Level 0)
0/3 answered
  1. 1. A loss spike is…
  2. 2. QK-norm keeps ___ bounded:
  3. 3. Warm-up means the learning rate…

Level 1: Beginner

★★☆☆☆ Basic⏱ 20 minSecondary-school mathematics: arithmetic and elementary algebra.

By hand

  • Attention logit growth: if ‖q‖ and ‖k‖ grow, the logits q·k/√d grow, softmax saturates (attention entropy collapses to one key), gradients vanish or explode, and training stalls or diverges (Dehghani et al., 2023; Wortsman et al., 2023).
  • QK-norm: q̂ = q/‖q‖, k̂ = k/‖k‖ (often with RMSNorm and a learned scale g); logits g·q̂·k̂ lie in [−g, g].
  • z-loss: add c · (log Z)² with log Z the log-sum-exp of output logits (PaLM uses c = 10⁻⁴). This keeps the softmax normaliser near 1 and output logits from drifting, which matters especially in bf16.
  • Learning-rate schedule: linear warm-up (thousands of steps) then cosine decay to about 10% of peak; lower the peak if spikes appear.
  • Gradient clipping: rescale all gradients so their global norm is at most about 1.0.
  • Other measures: pre-norm blocks, small initialisation of output projections, Adam ε and β₂ choices, removing bad data, and rollback: restart from the last checkpoint before a spike and skip the offending batches.
📝 Quick check (Level 1)
0/3 answered
  1. 1. With QK-norm and scale g, logits lie in…
  2. 2. PaLM's z-loss coefficient:
  3. 3. A typical gradient-clipping norm:

Level 2: Intermediate

★★★☆☆ Intermediate⏱ 25 minUndergraduate students and practising engineers.

Stability tools in code

Exercise 1.

  • Compute QK-norm attention scores, bounded whatever the scale of Q and K.
  • Compute z-loss (coef · (ln V)² for uniform logits).
  • Clip the global gradient norm.

Practice.

  • Log per step: loss, gradient norm, maximum attention logit, attention entropy, output log Z and the learning rate; alert on spikes.
  • Use torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0) and a warm-up + cosine scheduler.
  • QK-norm is a small change in the attention module (normalise Q and K after projection, before RoPE in many implementations); z-loss is one line added to the loss.
  • Save checkpoints frequently enough that a rollback loses little; keep data order reproducible so bad batches can be skipped.
def attention(q, k, v, qk_norm=True, g=None):
    if qk_norm:
        q, k = F.normalize(q, dim=-1), F.normalize(k, dim=-1)       # or RMSNorm with learned gain
        scale = g if g is not None else math.sqrt(q.size(-1))
    else:
        scale = 1 / math.sqrt(q.size(-1))
    return F.scaled_dot_product_attention(q, k, v, is_causal=True, scale=scale)
loss = ce_loss + 1e-4 * torch.logsumexp(logits, dim=-1).pow(2).mean()   # z-loss
🐍 Exercise 1: QK-norm, z-loss and clipping
Implement QK-norm attention scores, the z-loss and global gradient-norm clipping.
📝 Quick check (Level 2)
0/3 answered
  1. 1. PyTorch gradient clipping function:
  2. 2. A key metric to log for attention stability:
  3. 3. After a spike, teams often…

Level 3: Advanced

★★★★☆ Advanced⏱ 25 minGraduate level, with full derivations and proofs.

Theory

Why attention logits run away. The logit q·k = (xW_q)·(xW_k) grows quadratically in the weight scale. With a large learning rate, Adam’s normalised updates enlarge W_q and W_k quickly. Once one key dominates, the softmax gradient (A ∘ (dA − ⟨dA, A⟩)) vanishes for all other keys and the attention pattern freezes, while updates through the dominant key can be huge.

Why QK-norm works. Normalising q and k removes their scale entirely; only directions matter, and the logit range is set by a single bounded scale. The softmax can still be sharp (e^(2g) ratio between keys) but cannot become numerically extreme.

What z-loss does and does not do. z-loss controls the output softmax’s normaliser. It prevents a different failure, logits drifting to large magnitudes, which causes instability and round-off in low precision. It does not constrain the attention logits, so it cannot prevent attention entropy collapse, which is why the two fixes are used together.

📝 Quick check (Level 3)
0/3 answered
  1. 1. Attention logits grow ___ in the weight scale:
  2. 2. When one key dominates, gradients to other keys…
  3. 3. z-loss constrains…

Level 4: Expert

★★★★★ Expert⏱ 30 minResearchers: original papers and open problems.

Which stability fix prevents training collapse at high learning rates?

History.

  • A. Chowdhery et al., “PaLM: scaling language modeling with pathways” (2022), z-loss and rollbacks.
  • M. Dehghani et al., “Scaling vision transformers to 22 billion parameters” (ICML 2023), QK-norm.
  • M. Wortsman et al., “Small-scale proxies for large-scale Transformer training instabilities” (ICLR 2024).
  • S. Zhai et al., “Stabilizing transformer training by preventing attention entropy collapse” (ICML 2023).

Exercise 2.

  • Task and model: copy-8-back with the one-layer GPT (16 tokens, d = 32). Loss is averaged over all positions, where 7 of 16 are unpredictable, so the best possible is about 1.29.
  • Training: Adam with no warm-up and no clipping, 300 steps, at a safe (0.01) and an aggressive (0.3) learning rate. Three variants:
    • baseline;
    • QK-norm (scale g = 8);
    • z-loss (10⁻³).
  • Measures: final loss (mean of the last 20 steps), largest attention logit, number of loss spikes (jumps above 0.5) and mean output log Z.
learning rate variant final loss max attention logit spikes mean log Z
0.01 baseline 1.375 16.3 0 3.44
0.01 QK-norm 1.379 7.6 0 3.42
0.01 z-loss 1.376 16.3 0 2.72
0.3 baseline 2.318 544,711 43 3.92
0.3 QK-norm 1.939 7.4 17 3.83
0.3 z-loss 24.9 (diverged) 7.5 × 10⁶ 83 602.9
  • At a safe learning rate the fixes cost nothing: all variants reach the same loss.
  • At an aggressive rate the baseline collapses: attention logits reach half a million and loss stalls near the uniform 2.3.
  • QK-norm keeps attention bounded and keeps learning. Seeds 1 and 2 gave 1.476 and 1.467 against 2.307 and 2.319 for the baseline.
  • z-loss addresses a different problem: it lowers log Z at the safe rate, but cannot stop attention logits exploding. In this seed it diverged completely at lr 0.3. In seeds 1 and 2 it ended at 2.87 and 2.34, no better than the baseline.
  • Spikes still occur with QK-norm at lr 0.3 (17), because a learning rate this high is too aggressive anyway; warm-up and clipping remain necessary.
🐍 Exercise 2 (research): which stability fix prevents training collapse at high learning rates?
Train the GPT at a safe and an aggressive learning rate with no fix, QK-norm and z-loss; compare final loss, attention logits, spikes and log Z.

Training stability in AI, robotics and aerospace

  • Large in-house training runs: monitoring and rollback procedures save weeks of cluster time.
  • Low-precision onboard fine-tuning: bounded logits (QK-norm) and z-loss help in bf16 and fp8.
  • Design lesson: keep every internal signal bounded, and log the signals that precede a blow-up.

References

  1. A. Chowdhery et al. (2022). “PaLM: scaling language modeling with pathways.” arXiv:2204.02311.
  2. M. Dehghani et al. (2023). “Scaling vision transformers to 22 billion parameters.” Proc. ICML.
  3. M. Wortsman et al. (2024). “Small-scale proxies for large-scale Transformer training instabilities.” Proc. ICLR.
  4. S. Zhai et al. (2023). “Stabilizing transformer training by preventing attention entropy collapse.” Proc. ICML.