The idea in one sentence. A deep transformer trains because every block adds to a residual stream instead of replacing it and a norm fixes the size of what each block reads; every other stability tool bounds one more quantity that would otherwise grow: the stream (norm placement, initialisation), the attention logits (QK-norm, soft-capping), the output logits (z-loss), or the step (warmup, clipping).
Fig. 1: One block, and the five places a stability fix acts. The running example's decoder block as a structure, no measured numbers: the stream runs along the front from the embedding to the LM head, each sub-layer's branch runs behind it and adds back at a +. Blue plates are norms, green plates the matrices that write into the stream, dashed outlines the places other placements put a norm. Loss spikes (section 8) are what you see when one of them fails.
You need the decoder block (The transformer from zero) and the maths of LayerNorm, BatchNorm and init schemes (Xavier, He, μP), which the ML-fundamentals page Normalisation and initialisation derives; its parent's When training goes wrong tab maps training symptoms to causes for any model. This page is the transformer-specific depth.
New terms. Residual stream: the running vector per token that blocks add to. Branch: what one sub-layer adds. Pre-norm / post-norm / sandwich / output norm: the norm before the branch, on the stream after the add, around the branch, after the branch. QK-norm: a norm on each head's query and key. log Z: the log of the output softmax's normaliser; z-loss penalises it. Attention entropy: how spread a head's weights are (0 nats is one-hot). Massive activation: one stream entry thousands of times the median. Spike score: the share of steps far outside a rolling average.
The running example. The root's tiny GPT (6 blocks, d_model 256, 8 heads of 32, LayerNorm, 5.8M parameters) on TinyStories: batches of 32 × 256 tokens, AdamW, lr 3e-3 with 100 warmup steps and cosine decay, clipping at 1.0, 1,500 steps. Every run changes one thing and keeps the same batches and seed (Apple M1 Pro, MPS, about 5.5 minutes each). The unigram floor, a model that ignores context and predicts token frequencies, is 6.006 nats.
Full configuration: learned positions, tied embeddings, a 4,096-token BPE, AdamW (0.9, 0.95). This page's training loop is the root's train.py with a probe added (src/runs/ns_train.py: every-step loss and gradient norm, and every 10 steps the per-layer largest attention logit, entropy, q and k norms and the output log Z on 8 fixed held-out windows). It reproduces the Block lab's pre-norm run (2.2788 here against 2.2811; MPS reruns differ in the third decimal). The eight pre- and post-norm runs at five learning rates are the root's Block lab runs, reused, and were logged without the probe. The output norm and the logit cap are added by patching the shared model at import (src/runs/ns_model.py), because the shared code is read-only for child pages.
Measured first. The transformer from zero child trained the tiny GPT with one piece removed at a time, at an equal budget: without the residual connection it learns nothing (held-out 6.011, the unigram floor); without the norms it trains, but worse (2.546 against 2.276; at lr 1e-3, 3.061 against 2.464). The residual path makes depth trainable; the norm lets it train at a useful learning rate.
Two ways depth goes wrong. Forward, the stream's size drifts: every add can make it bigger, or a norm after every add forces it flat. Backward, the gradient to block 1 passes through every block above it; a factor a little under one per step vanishes over depth, a little over one explodes. Where the norm sits relative to the add decides which of these happens (section 2).
How to check it on a real run. Log the stream's RMS after each block on a fixed batch every few hundred steps (forward hooks, or output_hidden_states=True, whose last entry is already after the final norm, as the root's Inside lab found). Steady growth under pre-norm is normal; one channel hundreds of times larger than the rest is a massive activation (section 7).
The norm can sit before the branch, on the stream after the add, or around the branch. Each choice trades the size of the stream against the path the gradient takes.
Fig. 2: The same sub-layer four ways. One row per placement; in each the stream runs left (input) to right (output) along the front, and the branch F runs behind it and adds back at the +. The blue plate is the norm. The gradient's thinning in step 5 is drawn, not measured.
x = Norm(x + F(x)). The norm stands on the main path after the add, so the stream is renormalised after every sub-layer and its size is fixed at RMS 1 (times the gain). The 2017 Transformer and BERT.x = x + F(Norm(x)). The norm moves onto the branch: the main path is a clean identity and the stream grows with depth, so a final norm before the unembedding is needed. GPT-2 onward.x = x + Norm(F(Norm(x))). A second norm on the branch output: every add is a unit-RMS vector times the learned gains. Gemma 2, 3 and 4.x = x + Norm(F(x)). Only the branch output is normalised; the branch reads the raw stream. OLMo 2 and OLMo 3.| Placement | One sub-layer | Stream | Gradient path | Used by (checked in configs and code) |
|---|---|---|---|---|
| Post-norm | x = Norm(x + F(x)) | fixed at RMS 1 (times the gain) | through every norm on the way down | 2017 Transformer, BERT |
| Pre-norm | x = x + F(Norm(x)), final norm before the unembedding | grows with depth | clean identity path | GPT-2 onward, Llama 1 to 4, Mistral, Qwen 2 and 3, DeepSeek-V2, V3 and V3.2 (V4 adds four mixed streams, below), Kimi K2, gpt-oss, SmolLM2 |
| Sandwich (peri-norm) | x = x + Norm(F(Norm(x))) | grows like √(sub-layers) times the learned gains | clean | Gemma 2, 3 and 4 (four norms per block) |
| Output norm ("reordered") | x = x + Norm(F(x)) | grows like √(sub-layers) | clean | OLMo 2 and OLMo 3 |
| DeepNorm | x = Norm(αx + F(x)), branch init × β | fixed (post-norm) | through every norm, but the residual is up-weighted | MiniMax-M1 (α = 3.5566 in its config) |
Fig. 3: The stream's size through 12 sub-layers: post-norm pins it, the others let it grow. The median token's L2 norm over 256 channels (RMS 1 is norm 16), log scale, on the 256-token running sequence (the Roxy story, never seen in training), same seed and initial weights. Trained: pre-norm is the root's reference run (lr 3e-3), post-norm lr 1e-3, the others lr 3e-3.
measured In a matched pair (the root's Block lab, both at lr 1e-3) token "o" grows from 0.9 to 14.8 under pre-norm and stays between 16.0 and 16.4 under post-norm until the last norm's gain takes it to 24.6; the reference model (lr 3e-3) grows from 1.3 to 65.8, most of it in block 1's FFN (a branch of norm 53.0). That growth is pre-norm's cost: later blocks add updates small next to the stream, and the final norm (ln_f, self.norm in transformers' Llama) is mandatory.
CPU forward of the recorded checkpoints (src/analysis/inspect_runs.py, which steps each block by hand for its placement and checks the logits equal the model's own forward; largest difference 0 on every run). Same seed and the same initial weights where the shapes allow.
| At initialisation | after the embedding | after the last sub-layer | why |
|---|---|---|---|
| Pre-norm, GPT-2 init | 0.449 | 1.42 | each branch starts small (output matrices ÷ √(2L), section 6), so 12 adds barely move the stream |
| Pre-norm, flat init | 0.449 | 5.18 | without the √(2L) shrink the branches are 3.46× larger at the start |
| Post-norm | 0.449 | 16.0 | the stream is normalised after every add: norm √256 = 16 by construction |
| Sandwich (peri-norm) | 0.449 | 56.0 | every branch output is normalised before the add: about 16 √12 |
| Output norm (OLMo 2) | 0.449 | 53.2 | the same: the branch reads the raw stream, its output is normalised |
Xiong et al. 2020 show that at initialisation post-norm's gradients near the output are large, so a large early learning rate is unstable and warmup (ramping the rate up from near zero) is what makes it train; pre-norm's gradients are "well-behaved at initialization" (the theorem and a toy that reproduces it are on the ML-fundamentals Normalisation page).
measured Pre-norm trains at every rate tried (2.464 at 1e-3 to 4.361 at 3e-2, where its gradient norm before clipping spikes to 40.8, with 2.734 at 1e-2); post-norm only below 3e-3 (2.534 at 1e-3, 3.215 at 3e-4) or with the long warmup. The two placements that normalise the branch output train worse than pre-norm at this scale, and the attention logits say why: with the output norm nothing normalises what attention reads, so the largest logit reaches 5,693 at lr 3e-3 (pre-norm: 58.2) and the loss stalls at 3.405; the sandwich's logits still reach 241 at 3e-3 and 7,239 at 1e-2. Neither ships alone: OLMo 2 adds QK-norm to its output norm (its paper: "in isolation, neither of these changes yield good results, but together" they help), Gemma 2 adds soft-capping to its sandwich and Gemma 3 QK-norm; with QK-norm added, output norm reaches 2.506 (largest logit 15.3) and the sandwich 2.396 (largest logit 12.5). QK-norm does not rescue post-norm, whose failure is the gradient, not the logits (6.011 at 3e-3, largest logit 5.70). Pre-norm + QK-norm is the most robust: 2.273, 2.302 and 2.476 across a tenfold range of rates.
Held-out loss after 1,500 steps (20 fixed validation windows), one point per run, measured on Apple M1 Pro (MPS). Pre- and post-norm points are the root's Block lab runs; the others are this page's. The square is post-norm at lr 3e-3 with 500 warmup steps. Dashed: the unigram floor.
Norm of the gradient of all of a block's parameters, one backward pass on 8 fixed held-out windows of 256 tokens, log scale (the root's src/block/gradnorm.py, CPU). After training, the gradient reaching block 1 of the post-norm model at lr 3e-3 is 5.1e-7, against 0.027 at block 6, a factor of about 50,000: its lower blocks stopped learning. The runs that trained have block gradients between 0.27 and 0.92, roughly even across depth.
Held-out loss after 1,500 steps; the full grid with curves is the Stability explorer tab.
| Placement | lr 3e-3 | lr 1e-2 | lr 3e-2 |
|---|---|---|---|
| Pre-norm | 2.281 | 2.734 | 4.361 |
| Post-norm | 5.943 | not run | not run |
| Sandwich | 2.501 | 3.324 | 3.389 |
| Output norm | 3.405 | 3.763 | 3.605 |
| Pre-norm + QK-norm | 2.273 | 2.302 | 2.476 |
Kim et al. 2025 (Peri-LN) trained the three placements at 400M, 1.5B and 3.2B parameters (their Table 1, five seeds each, diverged runs excluded, which they say "mostly occurs in Pre-LN"); published by the authors, not run here (hundreds of GPU-days):
| Size | Post-LN loss | Pre-LN loss | Peri-LN loss | Post / Pre / Peri benchmark average |
|---|---|---|---|---|
| 400M | 7.46 | 3.43 | 3.34 | 42.45 / 49.69 / 51.57 |
| 1.5B | 5.38 | 3.29 | 3.18 | 45.49 / 53.71 / 56.55 |
| 3.2B | 4.43 | 3.20 | 3.11 | 46.45 / 56.69 / 58.56 |
Their Post-LN losses are those of runs that trained badly at the shared learning rate, like the Block lab's post-norm at 3e-3; the paper also reports that Pre-LN hidden states pass the float16 maximum "as early as 0.5B training tokens" (section 7.2). Read 2026-10-19 from arXiv 2502.02732 v3. Their Peri-LN advantage does not reproduce at 6 layers and 12M tokens (the sandwich trains worse here, above); their runs are 400M to 3.2B parameters.
The tiny GPT's block, which this page's runs use (the output norm is added by src/runs/ns_model.py):
OLMo 2 normalises the branch output and adds it to the raw stream; Gemma 3 does the same after a normalised input as well (both quoted from the pinned transformers source):
Wang et al. 2022 keep post-norm but scale the residual by α = (2N)1/4 for an N-layer decoder (and shrink some branch initialisations by β = (8N)−1/4), reporting stable training "up to 1,000 layers". MiniMax-M1's config sets postnorm: true and layernorm_*_alpha = 3.5565588 with 80 layers, which is exactly (2 × 80)1/4 = 3.5566 (calculated); its transformers code normalises the input, keeps the normalised vector as the residual, and adds α × residual + β × branch:
Hyper-connections keep n = 4 copies of the stream and learn an n × n matrix per sub-layer that mixes them in place of the identity add; over depth the stream carries the product of those matrices, whose gain reached "peaks of 3000" in DeepSeek's unconstrained 27B run. mHC projects each matrix onto the doubly stochastic matrices (rows and columns sum to 1), which are closed under products and can only average, so the gain stays 1; DeepSeek-V4 ships it (hc_mult 4) with ordinary pre-norm RMSNorm inside each branch.
Every placement above keeps one stream of width D per token. Hyper-connections (Zhu et al. 2024) keep n copies (n = 4) and learn, per sub-layer, how to collapse them into the branch input, how to spread the branch output back, and an n × n matrix Hres that mixes the streams in place of the identity add: xl+1 = Hresl xl + Hpost⊤l F(Hprel xl) (mHC paper, Eq. 3). The price is the identity path: after L sub-layers the stream carries the product of L mixing matrices. DeepSeek report that in a 27B run the composite's largest gain reached "peaks of 3000, a stark divergence from 1", with "an unexpected loss surge around the 12k step" (section 3.1, figures 2 and 3; published, not run here).
The fix. Manifold-constrained hyper-connections project each Hres onto the doubly stochastic matrices (non-negative, every row and every column sums to 1) with 20 iterations of Sinkhorn-Knopp (alternately dividing by row and column sums; DeepSeek steps it on a 4 × 4 matrix). A product of doubly stochastic matrices is doubly stochastic, so the composite can only average streams, never amplify them. The authors report a 6.7% time overhead at n = 4 and a final loss 0.021 below the baseline at 27B (sections 1 and 5.2); DeepSeek-V4's released code does exactly this (config hc_mult 4, hc_sinkhorn_iters 20), with ordinary pre-norm RMSNorm inside each branch.
The arithmetic, on random matrices (calculated, illustrative; src/analysis/hc_toy.py): 120 sub-layers (60 blocks), 4 streams, each mixing matrix the identity plus Gaussian noise of standard deviation σ, 20 seeds. The largest row sum of the product:
| σ | unconstrained (median, max) | doubly stochastic (max) |
|---|---|---|
| 0.05 | 3.24, 7.03 | 1.0000 |
| 0.1 | 12.1, 35.5 | 1.0000 |
| 0.2 | 268, 11,678 | 1.0000 |
| 0.3 | 136,917, 13,111,633 | 1.0000 |
Small per-layer deviations compound geometrically when nothing constrains them; the projection pins the gain at 1 whatever the noise. Random matrices, not trained ones: they show the mechanism, not the paper's 3,000. Not run here: a hyper-connection model on MPS would not show the instability, which appears at 27B after 12k steps.
The code:
When placement matters, and how to check. At 6 layers pre-norm and a well-warmed post-norm differ by about a tenth of a nat, while the output placements without a logit control lose much more. Placement matters more when the learning rate is pushed, when depth grows (post-norm's window narrows) and in low precision, where pre-norm's growing stream is the one that overflows. Sweep three or four learning rates on a short run; the placement with the widest flat region is the robust one (Wortsman et al.'s "LR sensitivity", section 8).
A norm runs twice per block on every token, in training and at inference. LayerNorm subtracts the mean and divides by the standard deviation; RMSNorm (Zhang and Sennrich 2019) drops the mean and divides by the root mean square, on the hypothesis that "re-centering invariance in LayerNorm is dispensable". Every model in section 9 after GPT-2 uses RMSNorm.
measured |μ| / RMS has a median of at most 0.015 at any of the 13 points and a maximum of 0.069. Replacing every trained LayerNorm by an RMSNorm with the same gains, at inference and without retraining, moves the loss on the running sequence by 0.000012 nats (1.956310 to 1.956322), and the greedy continuation is identical: the RMSNorm paper's hypothesis, seen from inside. Trained from scratch (same batches, schedule, lr 3e-3): LayerNorm 2.279 (seed 0) and 2.260 (seed 1); RMSNorm 2.275 and 2.256. The gap between the two norms, 0.004 on the two-seed means, is smaller than the spread between seeds (0.019 for LayerNorm, 0.018 for RMSNorm): no measurable difference at this scale, as the paper reports. Wall time per run: 323 s against 383 s (rough, shared laptop).
bias=False)The cost. The paper reports RMSNorm "reduces the running time by 7%~64% on different models" (published, 2019 GPUs): one fewer reduction and no bias. The saving depends on kernel fusion; on this Mac it does not reproduce (RMSNorm made the whole run 19% slower, below). Real implementations keep the statistics in float32, and Gemma 1 to 3 and Qwen3-Next multiply by (1 + w) where others use w, so a checkpoint loaded into the other convention is wrong by exactly 1 in every gain (the mistakes at the end).
The root's reference tiny GPT (LayerNorm, pre-norm, trained), the running sequence's 256 tokens: mean of each token's stream row over its RMS, after the embedding and each sub-layer. Bars: the median token; ticks: the largest. Measured on the CPU (src/analysis/mistakes.py).
The operation alone, forward plus backward, median of 30 repeats on MPS and 15 on the CPU (rough, measured on a shared Apple M1 Pro; read the ratio, not the milliseconds):
| Device | Input (B × T × D) | dtype | LayerNorm ms | nn.RMSNorm ms | hand RMSNorm (Llama) ms | RMS / LN |
|---|---|---|---|---|---|---|
| CPU | 32 × 256 × 256 | float32 | 0.93 | 4.00 | 4.04 | 4.28 |
| CPU | 4 × 2,048 × 4,096 | float32 | 15.82 | 38.07 | 38.03 | 2.41 |
| CPU | 1 × 8,192 × 8,192 | float32 | 36.96 | 75.08 | 75.94 | 2.03 |
| MPS | 32 × 256 × 256 | float32 | 1.79 | 4.05 | 4.01 | 2.26 |
| MPS | 32 × 256 × 256 | bfloat16 | 0.91 | 4.40 | 4.23 | 4.86 |
| MPS | 4 × 2,048 × 4,096 | float32 | 15.11 | 59.44 | 59.41 | 3.93 |
| MPS | 4 × 2,048 × 4,096 | bfloat16 | 8.27 | 64.95 | 62.66 | 7.86 |
| MPS | 1 × 8,192 × 8,192 | float32 | 25.24 | 100.73 | 100.48 | 3.99 |
| MPS | 1 × 8,192 × 8,192 | bfloat16 | 12.22 | 111.52 | 106.64 | 9.12 |
Does not reproduce on this Mac. On MPS with torch 2.14.1, RMSNorm is 2.3 to 9.1 times slower than LayerNorm, and PyTorch's own nn.RMSNorm is no faster than the hand-written Llama version: LayerNorm has a fused MPS kernel, RMSNorm runs as separate elementwise and reduction ops. Whole training runs show it too: 383 s for RMSNorm against 323 s for LayerNorm (rough). On the CPU: 4.28x at 32 x 256 x 256, 2.41x at 4 x 2048 x 4096, 2.03x at 1 x 8192 x 8192 (RMS time over LN time). With fused kernels the norms are a small share of a training step.
transformers' Llama RMSNorm computes the statistics in float32 whatever the input dtype, then casts back before the gain. Gemma 1 to 3 and Qwen3-Next store the gain as an offset from 1; Gemma 4 went back to a plain w.
nn.RMSNorm has a different default ε (measured)torch.nn.RMSNorm(dim) without eps uses the machine epsilon of float32, 1.19e-7, not the 1e-5 or 1e-6 of model configs (torch 2.14.1 docstring: "If not specified, uses the machine epsilon of the computation (opmath) type"). On a row of 256 entries all equal to 0.001 (RMS 0.001) the output entry is 0.9452 with the default, 0.3015 with 1e-5 and 0.7071 with 1e-6. Ordinary rows have an RMS near 1, where the three agree to many digits, so the difference only bites on near-zero rows; but a reimplementation that leaves eps unset does not reproduce the reference model bit for bit. The tiny GPT passes eps=cfg.norm_eps (1e-5) explicitly.
The problem. An attention logit is the score before the softmax, s = q · k / √dh = |q| |k| cos θ / √dh (dh = 32 in the tiny GPT). The norm before attention fixes the size of x, but q = Wq Norm(x) and k = Wk Norm(x), and nothing stops Wq and Wk from growing. When a few logits get large the softmax goes one-hot: its entropy (about 4.58 nats for uniform attention over this sequence) collapses, the gradient to every other key vanishes, and the head stops learning (attention entropy collapse). It broke ViT-22B at about 8B parameters, whose attention logits, without normalisation, "grow to over 50000 in magnitude" (Dehghani et al. 2023, appendix B; near float16's largest value, 65,504, which Numerical computing explains), and Wortsman et al. 2023 showed it in small models at high learning rates: in their sweeps "all points with attention logits above 1e4 diverged" (section 3.3).
The fix. QK-norm normalises each head's query and key before the dot product, so |q| and |k| are set by the norm's learned gains instead of by the projection weights. In the tiny GPT (RMSNorm per head, before RoPE, as in Qwen3):
Fig. 4: The same batches at ten times the learning rate: logits run away without a fix and stay bounded with QK-norm. The pre-norm tiny GPT at lr 3e-2 with gradient clipping switched off (back row) against the same model, seed and batches with one change (front row; pick it below). Towers: the largest attention logit in each layer on a fixed probe batch (8 held-out windows), log scale against the wall, one band per decade from 1 to 100,000; measured on Apple M1 Pro (MPS) every 10 steps, each step of the figure plays one stretch of training. Predict before it plays: which layer passes 1,000 first?
Measured. Without a fix the largest logit passes 1,000 by step 100 and peaks at 20,865 (step 510); the lowest layer entropy falls to 0.004 nats, one-hot attention. The loss never becomes non-finite: the run stalls at a held-out 4.295, between the bigram floor (3.616) and the unigram floor. With QK-norm and everything else identical the largest logit peaks at 69.9 and the run reaches 2.432. For scale, at the default lr 3e-3 the same model without QK-norm peaks at 58.2 and reaches 2.279; with QK-norm at 3e-3, 2.273.
ViT-22B's team saw "divergent training loss after a few thousand steps" at about 8B parameters, "caused by extremely large values in attention logits" that gave "(almost one-hot) attention weights with near-zero entropy" (Dehghani et al. 2023, section 2). Zhai et al. 2023 name it attention entropy collapse. Wortsman et al. showed it "also appear[s] in small models when training at high learning rates". Entropy here is −Σ p log p over the keys, averaged over the sequence's positions; 0 is one-hot.
Mixed-modal training makes it worse. Chameleon shares every weight between text and image tokens, and "each modality will try to 'compete' with the other by increasing its norms slightly"; with image generation disabled it trained without instability. Its fixes were QK-norm ("essential" at both 7B and 34B) and z-loss, and its lesson was that "monitoring uncontrolled growth of output norms is strongly correlated with predicting future loss divergence" (Chameleon, section 2.3; the whole story is on Native multimodal and any-to-any models, section 6).
QK-norm does not cap the logit at a small number. With unit gains an RMS-normalised head vector has length √dh, so s ≤ √dh = 5.66 here. But the gains are learned: in this page's QK-norm run at lr 3e-2 the mean |q| after the norm is 3.6 to 11.6 per layer and |k| 3.1 to 11.9 at the end (unit gains would give 5.66 for both), and the largest logit is 67.1, about 12 times the unit-gain ceiling. The ML-fundamentals page measures the same on Qwen3-0.6B (ceilings 184 to 12,897 from its trained gains, real largest logits 12.5 to 48) (Normalisation and initialisation, section 5, closed block "Measured: does QK-norm cap attention logits in Qwen3-0.6B?"). What QK-norm removes is growth through the projection weights and the stream; the gain vector is small and moves slowly.
Qwen3 normalises per head before RoPE; OLMo 2 normalises the whole query projection (all heads at once) before splitting into heads; Llama 4 Scout uses a weightless L2 norm, only in its RoPE layers, and Maverick turns it off (use_qk_norm false in its config; the code comment says "the 128E model does not use qk_norm").
Gemma 2 squashes the logits themselves: s ← c · tanh(s / c), "50.0 for the self-attention layers and 30.0 for the final layer" (Gemma 2 report, section 2): logits well under c pass unchanged and none can exceed c. Gemma 3 "replace[d] the soft-capping of Gemma 2 with QK-norm" (Gemma 3 report); Gemma 4 keeps only the final-layer cap of 30 (configs read 2026-10-19). Measured (same high-rate run, a cap of 50 on the attention logits): held-out 2.845 against 4.295 uncapped and 2.432 with QK-norm; the largest raw logit before the cap reached 6,296. The cap helps but less than QK-norm: logits keep growing behind it (raw 6,296), but because no capped logit can exceed 50 no head goes fully one-hot (lowest layer entropy 1.371 nats against 0.004 uncapped). That is one reason Gemma 3 switched to QK-norm, which removes the growth instead of hiding it.
Without QK-norm: MLA and qk-clip. Multi-head latent attention never materialises per-head keys at decode (they are absorbed into the query, see Attention variants), so a per-head key norm has nowhere to go. DeepSeek-V3 instead "employs additional RMSNorm layers after the compressed latent vectors" (DeepSeek-V3 report, section 4.2). Kimi K2 keeps the forward pass untouched and, after each optimiser step, rescales a head's query and key weights when that head's largest logit passes a threshold (qk-clip, part of MuonClip); the Moonshot AI: Kimi page animates it.
How to check. Log the largest attention logit per layer on a fixed batch every few hundred steps (one extra forward with explicit scores; fused kernels never return them). Steady growth past a few hundred with falling entropy predicts trouble before the loss shows it: Wortsman et al. predicted this way that a 4.8B model "will be unstable at LR 1e-2", and it was.
The problem. The last layer's softmax has the same weakness at the other end of the model. Cross-entropy depends only on differences between the output logits yj, so the whole vector can drift up or down for free; Z = Σj eyj is the softmax's normaliser and log Z measures that drift. Wortsman et al. 2023 (section 3.1.2) describe an instability where the logits "diverge and become very negative", far from the log-probabilities, which in low precision loses the small differences that matter.
measured Mean log Z on the probe batch starts at 8.37 (a uniform guess over 4,096 tokens has log Z = ln 4096 = 8.32 when the logits are near 0) and ends at 11.46 in the healthy run at lr 3e-3, at 8.67 in the high-rate run without a fix and at 8.52 with z-loss 1e-4. So at this scale z-loss 1e-4 barely moves log Z (8.52 against 8.67). In the healthy run log Z drifts up to 11.46, where the penalty is 1e-4 × 11.462 = 0.013 nats, under 1% of the loss: the pull is weak by design; the drift it prevents shows up over long runs, at scale and in low precision (published), none of which a 1,500-step float32 run has.
Released models sit far from log Z = 0 too: GPT-2 averages −42.6, SmolLM2-135M +25.2 and Qwen2.5-0.5B +22.4 on one sentence, and storing GPT-2's logits in bf16 already moves 2.4% of its probability mass. The measurement, with a slider that shifts every logit, is the closed block "Real logits from three small models" on Loss functions ("The level of the logits").
Mean log Z of the output softmax on the fixed probe batch, every 10 steps, measured on Apple M1 Pro (MPS).
How to check. Log mean log Z on a fixed batch; a value drifting steadily away from 0 is the symptom z-loss treats, and it costs one logsumexp you already pay for in the cross-entropy. Do not switch the z-loss implementation mid-run (OLMo 2's trap, in the mistakes at the end).
The problem. The stream after L blocks is a sum of 2L branch outputs. If each branch starts with variance v, the sum starts with variance about 2L · v (independent terms add their variances), so a deeper model starts with a larger, noisier stream (the general schemes, Xavier and He, are on the ML-fundamentals Normalisation and initialisation page).
GPT-2's fix. Scale the weights of the layers that write into the stream (attention's output projection and the FFN's down projection) by 1/√N, N the number of residual layers (Radford et al. 2019, section 2.3). With N = 2L the sum of 2L branches starts with the variance of one. In practice: N(0, 0.02) everywhere and 0.02/√(2L) for those two matrices; for the tiny GPT (L = 6) that is 0.02/√12 = 0.00577. The tiny GPT and transformers' GPT-2 do exactly this:
measured At initialisation the median token's stream grows from 0.449 to 1.42 with the scaled init and to 5.18 without it (the stepper in section 2, "flat" switch). Trained from scratch on the same batches at lr 3e-3: 2.267 without the shrink against 2.279 with it. The difference is smaller than the spread between two seeds of the default init (2.279 and 2.260): with 12 branches the √12 shrink does not measurably matter. It is a depth effect: the papers above report it at hundreds of millions of parameters and dozens of layers, where this page cannot run.
Embeddings are part of the init. The tiny GPT's token and position tables start at N(0, 0.02) each, so a token enters the stream with a norm of 0.449 (0.02 × √(2 × 256) = 0.45, calculated). A tiny embedding makes the first norm's Jacobian large (it divides by the input's size), which is Takase et al.'s argument for scaling it up and the OLMo 2 team's argument for not weight-decaying it (spike score 0.16 to 0.092 without decay on embeddings).
| Scheme | What it does | Evidence (published, not run here) |
|---|---|---|
| OLMo 2: plain N(0, 0.02), no depth scaling | dropped OLMo-0424's 1/√d input and 1/√(2 · d · layer) output scaling | in a run made to spike, gradient-norm spike score 0.40 to 0.03 (OLMo 2 §3.2; recounted on the OLMo 2 paper page) |
| DeepSeek-V3: σ = 0.006 | "All learnable parameters are randomly initialized with a standard deviation of 0.006" | DeepSeek-V3 report, section 4.2; its config.json still says initializer_range 0.02, the library default, so the config is not evidence of the training init |
| "Spike No More": small sub-layers, large shortcut | initialise branches small and keep the embedding large: scale embeddings by √d or put a norm on them | Takase et al., COLM 2025: the usual init spiked at 350M and 1.7B ("its loss value exploded at about 13000 steps" at 1.7B) |
| DeepNorm | post-norm with residual × α = (2N)1/4, some branches × β = (8N)−1/4 | Wang et al. 2022; MiniMax-M1 (section 2) |
| μP | init and per-layer learning rates scaled with width so the best hyperparameters transfer from a small model | Yang et al. 2022: "by transferring from 40M parameters, we outperform published numbers of the 6.7B GPT-3 model, with tuning cost only 7% of total pretraining cost"; the rules (Table 3) are on the ML-fundamentals page |
How to check. Init decides the first thousand steps, more so with depth and width. Before training, run one forward and backward pass at step 0 and log the stream's RMS and the gradient norm by layer (the stepper in section 2 is that check on the tiny GPT); a 2× change in the last layer's stream between two inits is worth a short learning-rate sweep on each.
What they are. In trained LLMs a handful of stream entries, at fixed channels and mostly on the first token, are thousands of times larger than the rest. Sun et al. 2024 found in LLaMA2-7B a largest activation "about 2,000" (2,622 in their Table 1) "approximately 10,000 times larger than the median magnitude (about 0.2)", appearing "in layer 2" and staying "nearly constant values until layer 30", on the starting token and the first period or newline, in two channels (1415 and 2533). They act as fixed biases: setting them to zero makes perplexity infinite and drops mean zero-shot accuracy from 68.95% to 36.75%, while setting them to their mean value changes almost nothing (their Table 3; published, not run here).
Fig. 5: In SmolLM2-135M one entry of the stream is about 12,900 times the median, from layer 12 to the end. The root's Inside a real model lab (Apple M1 Pro), the running text: per layer, the median |entry| of the stream (front), its largest |entry| (middle) and the attention weight on token 0 (back, 0 to 1); log scale against the wall, one band per decade, until the last step.
measured In the tiny GPT: none. In the root's reference tiny GPT the largest single stream entry anywhere is 35.8 (token 132, f6) against a median |entry| of 2.69 at that point, a ratio of 13; the Inside lab's own measurement (35.8) agrees, and its verdict was no massive activation. Every trained model of this page is in the table below the figure.
Why they belong on this page. Under pre-norm the stream is never normalised in place, so a huge entry rides the residual path to the last layer and dominates the RMS of every norm that reads that token. Sun et al. link them to the attention sink (Attention variants); how the norm takes part is our reading, not their claim. They set the range low-precision formats must hold (Pre-LN hidden states pass the float16 maximum "as early as 0.5B training tokens", Kim et al. 2025, section 7.2), so quantisation keeps these channels apart (Quantization and Precision).
The largest single entry in every trained model of this page (the running sequence, the same CPU forward as Fig. 3):
12M tokens and 6 layers are far too little for the phenomenon, which the Inside lab saw only in pretrained models; in the reference model the largest entry after every sub-layer from block 2's attention to block 5's FFN sits on token 0, a hint of the same first-token specialisation (from the same CPU forward as Fig. 3).
Sun et al.: "in GPT-2 with explicit attention biases, massive activations disappear" (section 4.3). Gated attention (an elementwise sigmoid gate on each head's output, Qwen3-Next) cut the largest activation from 1,053 to 94 and first-token attention from 0.467 to 0.048 in Qiu et al.'s 15B MoE (Table 4); the Attention variants child trained that gate on the tiny GPT, where there is no sink to remove: largest stream entry 35.1 with the gate against 37.5 without, first-token attention at most 0.016 against 0.016.
How to check. Per layer, the largest |entry| of the stream with its token and channel, against the median |entry|, on a few real prompts. A ratio in the thousands at a fixed channel on token 0 is a massive activation: normal in a pretrained model, a design input for quantisation, not a bug.
What a spike is. A loss spike is a sudden jump of the training loss after a healthy stretch; sometimes it recovers in a few hundred steps, sometimes the run never comes back (divergence). PaLM's 540B run "observed spikes in the loss roughly 20 times during training, despite the fact that gradient clipping was enabled"; restarting "roughly 100 steps before the spike" and skipping "roughly 200-500 data batches" stopped each one, and replaying the same batches from an earlier checkpoint did not spike, so "spikes only occur due to the combination of specific data batches with a particular model parameter state" (PaLM, section 5.1; "not observed when training the smaller models"). OLMo 2 found gradient-norm spikes more frequent than loss spikes and earlier, and counts them with a spike score: the share of values at least seven standard deviations from a rolling average of the last 1,000 (the OLMo 2 paper page replays every ablation).
measured OLMo 2's score run on this page's every-step logs (7 standard deviations; a 100-step window, as on the ML-fundamentals root, because these runs have 1,500 steps, not hundreds of thousands): count of spiking steps out of the 1,400 after the first window.
| Run | loss spikes | gradient-norm spikes | gradient-norm score |
|---|---|---|---|
| lr 3e-3 (default) | 0 | 1 | 0.07% |
| lr 3e-2, no clipping | 0 | 9 | 0.64% |
| + QK-norm | 0 | 0 | 0.00% |
| + z-loss | 0 | 9 | 0.64% |
| + logit cap 50 | 0 | 5 | 0.36% |
| lr 3e-2, clipping, QK-norm | 0 | 0 | 0.00% |
No run has a loss spike by this definition: at a 1,500-step scale the loss changes too smoothly. The gradient norm separates them: 9 spikes without a fix, 9 with z-loss, 5 with the cap, 0 with QK-norm, against 1 at the default rate; the ML-fundamentals root found the same ordering on a character-level model (QK-norm 0, z-loss no better than nothing).
Gradient norm before clipping at every step (log scale), measured on Apple M1 Pro (MPS); red marks are the steps OLMo 2's score flags (7 standard deviations from the mean of the previous 100 steps; a 100-step window because these runs have 1,500 steps, as on the ML-fundamentals root).
The causes and their fixes, in the order to check them:
| Symptom before the spike | Likely cause | Fix | Evidence |
|---|---|---|---|
| largest attention logit climbing, entropy falling in some layers | attention-logit growth | QK-norm (or a logit cap, or qk-clip); lower peak learning rate | section 4; measured here 4.295 to 2.432 |
| mean log Z drifting away from 0 | output-logit divergence | z-loss 1e-4 | section 5; Wortsman et al. §3.1.2 |
| spike at the very start, before or during warmup | learning rate too high for the placement or init | longer warmup; pre-norm; smaller branch init | post-norm 5.943 to 2.138 with 500 warmup steps (Block lab); "a longer warm-up period reduces LR sensitivity" (Wortsman et al. §3.2.1) |
| gradient norm growing slowly over the whole run | optimiser and init settings (AdamW ε too large, embeddings decayed) | AdamW ε 1e-8 (not 1e-5), no weight decay on embeddings, OLMo 2's init | OLMo 2 §3 to §3.4; Wortsman et al. §3.4 (ε 1e-15 helped at 4.8B) |
| spike tied to particular batches | data plus parameter state (repeated n-grams in OLMo 2's case) | roll back about 100 steps and skip the batches; filter repeated n-grams | PaLM §5.1; OLMo 2 §3.1 |
| spikes in an MoE traced to outliers that routing amplifies | the router's updates feeding back into the backbone's | DeepSeek-V4's anticipatory routing: features use the current parameters, routing indices are computed with the parameters of step t − Δt; a detector switches it on only around a spike, at about 20% extra wall-clock time while active | V4 report; DeepSeek |
| loss becomes non-finite (not a number, or infinite) in one step | numerics: an overflow in low precision, a norm on an all-zero row | find the first non-finite tensor (anomaly detection), keep norms and softmax statistics in float32 | the Numerical computing page; transformers' RMSNorm upcasts (section 3) |
What does not transfer. The tiny GPT shows these mechanisms only at ten times its default learning rate; real runs show them at their own default rates, because instability grows with model size (Wortsman et al.'s central finding). Absolute thresholds (a logit of 1e4, a spike score of 0.1%) do not transfer; the direction of each fix does.
A run log that makes a spike diagnosable (all cheap): loss and global gradient norm every step; per-layer largest attention logit, attention entropy and stream RMS on a fixed batch every few hundred steps; mean log Z; the learning rate actually applied; the batch indices of every step, so the batches around a spike can be replayed; checkpoints frequent enough to roll back about 100 steps.
The pattern. RMSNorm everywhere; pre-norm as the base; since 2024 a second control on the attention logits in most new families (QK-norm in Qwen3, Gemma 3 and 4, OLMo 2 and 3, GLM-4.5, MiniMax-M2, Llama 4 Scout; qk-clip in Kimi K2; a cap in Gemma 2), and a few departures from the plain identity residual (Gemma's and OLMo's normalised branch outputs, MiniMax-M1's DeepNorm, DeepSeek-V4's four mixed streams). The ML-fundamentals page measures the residual streams of six released models (Normalisation and initialisation, section 6, closed block "Measured: the residual stream in six released models"); the root's Architecture map places these choices on the 2017 to 2026 timeline.
Read from the released config.json files in the root's src/data/configs and src/map/inputs/configs and from the modeling code in transformers 5.20.1 (read 2026-10-19). "Code" means the choice is fixed in the model class with no config switch.
| Model | Norm | Placement | Attention-logit control | Output cap | ε | Other |
|---|---|---|---|---|---|---|
| GPT-2 (2019) | LayerNorm | pre + final | none | none | 1e-5 | residual outputs ÷ √(2L) |
| Llama 3.1 8B / 70B / 405B | RMSNorm | pre | none | none | 1e-5 | statistics in float32 (code) |
| Llama 4 Scout / Maverick | RMSNorm | pre | weightless L2 norm on RoPE layers (Scout use_qk_norm true; Maverick false) | none | 1e-5 | |
| Mistral 7B, Mixtral, Mistral Small 3.1 | RMSNorm | pre | none | none | 1e-5 | |
| Qwen3 dense and MoE | RMSNorm | pre | QK-norm per head, before RoPE (code) | none | 1e-6 | |
| Qwen3-Next | RMSNorm, gain 1 + w (code) | pre | QK-norm per head (code) | none | 1e-6 | sigmoid output gate on attention |
| Gemma 2 (9B, 27B) | RMSNorm, gain 1 + w | sandwich | soft-cap 50 | soft-cap 30 | 1e-6 | |
| Gemma 3 | RMSNorm, gain 1 + w | sandwich | QK-norm (replaced the cap) | none | 1e-6 | |
| Gemma 4 31B | RMSNorm, plain gain w (code; back from 1 + w) | sandwich | QK-norm per head (code) | soft-cap 30 | 1e-6 | |
| OLMo 2, OLMo 3 | RMSNorm | output norm | QK-norm over all heads at once (code) | none | 1e-6 | z-loss and N(0, 0.02) init in training (OLMo 2 report) |
| DeepSeek-V3, V3.2 | RMSNorm | pre | none (MLA); RMSNorm on the compressed latents | none | 1e-6 | init σ 0.006 (report; config says 0.02) |
| DeepSeek-V4 | RMSNorm | pre inside each branch | its own compressed attention (the Attention variants child) | none | 1e-6 | mHC: 4 streams, Sinkhorn-projected mixing (hc_mult 4) |
| Kimi K2 | RMSNorm | pre | qk-clip in the optimiser (MuonClip), not in the model | none | 1e-6 | MLA (DeepSeek-V3 layout) |
| GLM-4.5 / GLM-4.5-Air | RMSNorm | pre | use_qk_norm true / false | none | 1e-5 | |
| MiniMax-M1 | RMSNorm | DeepNorm (postnorm true, α 3.5566) | none | none | 1e-5 | α = (2 × 80)1/4 |
| MiniMax-M2 | RMSNorm | pre | QK-norm over all heads at once | none | 1e-6 | |
| gpt-oss 20b / 120b | RMSNorm | pre | none; a learned sink logit per head | none | 1e-5 |
Each one ran here unless marked; the losses are on the 256-token running sequence (the trained reference model scores 1.956) or held-out windows, from src/analysis/mistakes.py and the runs above.
nn.RMSNorm without eps (section 3).q_norm and k_norm)initializer_range in a config as the training initEvery cell is a real training run of the running example's tiny GPT (6 blocks, d_model 256, LayerNorm, learned positions, 1,500 steps of 32 × 256 tokens, seed 0, AdamW, 100 warmup steps then cosine, gradient clipping at 1.0 unless the row says otherwise), measured on Apple M1 Pro (MPS). The number is the held-out loss at the end (20 fixed validation windows); the unigram floor, the loss of a model that ignores context, is 6.006. Runs from the root's Block lab (on Topic: llm-architecture) are marked Block lab and were logged every 10 steps without the attention probe; this page's runs record the largest attention logit and the output log Z every 10 steps on a fixed probe batch.
Try: click up to three cells to overlay them; the first click on a selected cell removes it. Start with pre-norm at 3e-2 against pre-norm + QK-norm at 3e-2, then post-norm at 3e-3 against post-norm with 500 warmup steps.
Logit and log Z panels are empty for Block lab runs (not recorded). Log scales on the logit and gradient panels. Timings are not shown: each run took about 5.5 minutes on a shared laptop, which says nothing about a datacenter GPU; the losses and logits are deterministic up to MPS's last-digit reruns (this page's rerun of the Block lab's pre-norm lr 3e-3 run ended at 2.2788, the Block lab's at 2.2811, the root's reference run at 2.278).
Links checked 2026-10-19; times of the root and Attention variants updated 2026-10-23. Times are rough reading times. "Maker" means written by the lab that built the model or method; "third-party" means independent.
The map of the topic: it defines pre-norm in one line and links here. 26 min, plus 13 in closed details
One token through one block, every vector and its FLOPs; its eight pre- and post-norm runs are the ones section 2 reuses (their charts moved here on 2026-10-23). 15 min, plus 4 in closed details
SmolLM2's massive activation and attention sink, measured. 15 min
The block written from an empty file; the no-residual and no-norm ablations. 40 min, plus 22 in closed details
MLA (why it cannot take QK-norm), sinks and the output gate trained on the tiny GPT. 37 min, plus 28 in closed details
RoPE, which QK-norm sits in front of. 40 min, plus 21 in closed details
Router logits, the other softmax that needs watching. 35 min, plus 21 in closed details
The basics: every norm from zero, Xiong et al.'s theorem in a toy, init schemes, μP, six released models' streams. 23 min, plus 14 in closed details
The symptom map for any training run; a char-level transformer swept with and without QK-norm and z-loss. 28 min
Every stability ablation of a real 7B to 13B run, re-drawn from the paper's vector figures, spike score live. 29 min
qk-clip and MuonClip, animated. 38 min
What massive activations do to low-precision formats. 34 min
Floating point, stable softmax, why norms keep statistics in float32. 40 min
Warmup, AdamW's ε and βs. 34 min
Where a stable recipe sits in a whole pretraining run. 30 min
Third-party. Why post-norm needs warmup. 40 min
Maker (of RMSNorm). 30 min
Third-party (Google DeepMind). Attention-logit growth and output-logit divergence reproduced in small models; the most useful paper for this page. 60 min
Maker. QK normalisation, section 2. 15 min for section 2
Third-party (Apple). σReparam. 40 min
Third-party (NAVER). Pre, post and peri-norm at 400M to 3.2B. 45 min
Third-party. Small sub-layers, large shortcut. 40 min
Third-party. 40 min
Maker (DeepSeek); Zhu et al. 2024, Hyper-Connections is the method it constrains. 45 min
Maker (Microsoft). DeepNorm. 30 min
Maker. z-loss and the rollback-and-skip recipe. 10 min for those sections
Maker. Soft-capping, then QK-norm. 10 min each
Third-party for these models (Microsoft). Hyperparameter transfer across width. 60 min
modeling_llama, qwen3, qwen3_next, olmo2, olmo3, gemma2, gemma3, gemma4, minimax, llama4, deepseek_v4, gpt2: every quoted line located by pattern in src/code/code_refs.py. as needed