torch.nn. Part of Topic: ml-fundamentals. Data as of October 2026. Reading: 23 min, plus 14 in closed details.Training works when the scale of the signal stays about 1 at every layer: feature scaling fixes the inputs once, initialisation picks weights that neither shrink nor grow the signal at step zero, and normalisation layers reset the scale at every layer on every step, which is why a normalised network barely cares about its initialisation.
nn.Linear's own initialisation shrinks the mean square about six times at every layer: after 20 layers it is 1.7 × 10⁻¹⁶, so almost nothing reaches the output, and the gradient on the way back shrinks the same way.Fig. 1 is measured (src/recompute.py, src/signal_prop.py, torch 2.14.1); section 2 derives each factor and draws all of them, with orthogonal weights and N(0, 0.02), on one log-scale chart.
You need the training step (forward, backward, update) from the parent's Reading tab, Topic: ml-fundamentals, and what ReLU does to its input (Activation functions).
| Tool | Averages over | Learned | Training against inference | Where it lives |
|---|---|---|---|---|
| Standardisation (z-score) | each input feature, over the training set | nothing | statistics fixed from the training set | inputs of distance-based and gradient-trained models |
| Min-max scaling | each feature's range, over the training set | nothing | as above | inputs that need a bounded range |
| BatchNorm (2015) | each feature (channel), over the batch (and positions) | γ, β per feature | different: batch statistics in training, running averages at inference | CNNs |
| LayerNorm (2016) | each example (token), over its features | γ, β per feature | identical | the 2017 transformer, BERT, GPT-2 |
| RMSNorm (2019) | as LayerNorm, without subtracting the mean | γ only | identical | essentially every current LLM |
| GroupNorm, InstanceNorm (2018, 2016) | each example, over a group of channels (or one channel) and the pixels | γ, β per channel | identical | detection and segmentation with small batches; style transfer |
| QK-norm | each query and key head vector | γ | identical | attention in many 2024 to 2026 LLMs |
| Initialisation | Var(w) | Keeps the variance for |
|---|---|---|
| Xavier (Glorot) | 2 / (nin + nout) | tanh and sigmoid, roughly linear near 0 |
| He (Kaiming) | 2 / nin | ReLU and its family |
| LeCun | 1 / nin | linear units; SELU (self-normalising networks) |
| Orthogonal | rows orthonormal, times a gain | every direction, not only the average (section 2) |
| Small fixed, residual-scaled | σ = 0.02; residual output layers ÷ √(2L) | transformers, which lean on their norms |
Labels used on this page: derived computed here from a stated formula; measured computed here on real data or a real released model; illustrative seeded toy inputs; reported the authors' own figure. Everything else carries its source link.
Fig. 2 · k-nearest neighbours with k = 20, a 70/30 split with random_state=42, scaler fitted on the 124 training wines, as in scikit-learn's Importance of Feature Scaling example. Test accuracy over the 54 test wines, computed in your browser; src/scaling.py gets the same from scikit-learn 1.9.1: 75.93% raw, 94.44% standardised, 94.44% min-max measured.
A model that measures distance (k-nearest neighbours, SVMs with an RBF kernel, k-means), projects variance (PCA) or penalises all weights alike (ridge, lasso) treats one unit of every feature the same, so a feature measured in thousands outvotes one measured in fractions. Tree models split one feature at a time and do not care.
Predict how much of kNN's accuracy on two wine features is lost to units alone, then watch Fig. 2. The 178 wines of the UCI Wine data are plotted on proline (278 to 1,680 mg/L) and hue (0.48 to 1.71); one test wine asks its 20 nearest training wines to vote on its cultivar. Switch to min-max to compare.
| Method | Formula | Result | Note |
|---|---|---|---|
| Standardisation (z-score) | z = (x − μ) / σ | mean 0, standard deviation 1 | the default; scikit-learn's StandardScaler uses the population σ (no n − 1) |
| Min-max normalisation | x′ = (x − xmin) / (xmax − xmin) | range [0, 1] | one outlier squeezes every other value into a sliver |
| Robust scaling | (x − median) / IQR | median 0, interquartile range 1 | for features with outliers (RobustScaler) |
The statistics (μ, σ, minimum, maximum) are fitted on the training set only and applied unchanged to validation and test data; fitting them on all the data leaks the test set into training (scikit-learn, common pitfalls). A pipeline object does this for you. On all 13 features measured (src/scaling.py): kNN with k = 20 scores 77.78% raw, 96.30% standardised and 98.15% min-max scaled.
Gradient descent suffers too: unequal scales stretch the loss surface into a narrow ravine, so the step that is safe along the steep feature is tiny along the flat one. Fig. 3 fits the smallest model that shows it on the same training wines, hue = w · proline + b, by gradient descent on the mean squared error, from w = b = 0, with the same rule each time: a learning rate of 1.2/λmax, 60% of the largest stable step (2/λmax, where λmax is the steepest curvature). Both axes are drawn to the same scale, as gradient descent sees them derived, computed in your browser.
On all 13 Wine features, for least squares (alcohol from the other 12 features), the condition number of the Hessian XTX/n, roughly how many more steps gradient descent needs, is 1.6 × 108 raw, 690 min-max scaled and 45 standardised measured (src/scaling.py).
PCA object to both pipelines, so fitting the standardised pipeline refits the PCA that the unscaled pipeline then uses on raw data. With a PCA of its own, the unscaled pipeline scores 74.07% (log-loss 0.497, against 1.18) measured. Scaling still wins (96.30%, log-loss 0.0739); the gap is 22 points, not 61 (src/scaling.py).Why random, and why the scale matters. A constant initialisation gives every neuron in a layer the same input and the same gradient, so they stay copies of each other for ever (the symmetry problem; the parent's Training lab preset "All-zero init never breaks symmetry"). Random weights break the symmetry, but their scale decides Fig. 1: too small and the signal shrinks layer by layer (vanishing gradients), too large and it grows exponentially (exploding gradients).
The factor per layer, in three lines. A unit computes y = Σi wixi over nin inputs. With zero-mean weights independent of the inputs, each of the nin terms contributes Var(w) · E[x²]. In the hero network, nin = 512 and He's Var(w) = 2/512, so Var(y) = 2 E[x²]; ReLU then zeroes the negative half, and E[relu(y)²] = ½ Var(y) = E[x²]: factor 1 derived.
So Xavier, derived for tanh and sigmoid (roughly linear near 0), gives ReLU a factor of ½ per layer; He (Kaiming) doubles the variance to 2/nin for ReLU; LeCun's 1/nin keeps a linear unit and pairs with SELU. Which activation pairs with which scheme is also drawn as one batch through five networks in the parent's Reading tab (step 2) and thread 2, "Keep the variance constant"; activations themselves are on Activation functions.
Fig. 4 · the same 1,024 inputs through the same 20-layer ReLU network of width 512, built in PyTorch, with no bias; only the initialisation changes, or a LayerNorm is added before every ReLU. Each layer multiplies the mean square (the second moment, E[x²]) by a fixed factor: 0.162 with nn.Linear's own default (1.7 × 10−16 after 20 layers), 0.495 with Xavier (7.8 × 10−7), 0.990 with He (0.82), 0.101 with a fixed N(0, 0.02) (1.3 × 10−20), 1.015 with orthogonal weights (1.32), 1.98 with twice He's variance, an illustrative scale (8.6 × 105), and the LayerNorm line stays at 0.51 whatever came before measured (src/recompute.py, src/signal_prop.py, torch 2.14.1). The text beside it derives the factors; sections 3 onwards are the norm line.
Predict the factor after 20 layers for Xavier with ReLU, then read the row. Set the fan-in and fan-out, the depth and the activation. The per-layer factor is how much one layer multiplies the second moment of the signal (forward) or of the gradient (backward). Green: within a factor 10 after L layers.
nn.Linear and the convolutions initialise with kaiming_uniform_(a=√5), which the source comment explains "is the same as initializing with uniform(−1/sqrt(in_features), 1/sqrt(in_features))" (PyTorch 2.14, torch/nn/modules/linear.py): Var = 1/(3nin), a third of LeCun's and a sixth of He's. That is the "commonly used heuristic" Glorot and Bengio set out to replace (their Eq. 1). In a deep ReLU stack with no normalisation it shrinks the second moment about 6 times per layer, to 1.7 × 10−16 after 20 layers (Fig. 1, step 2, and the bottom lines of Fig. 4). Norm layers hide this, so it rarely bites; a plain deep MLP needs kaiming_normal_ explicitly. Embeddings default to N(0, 1).| Scheme | Var(w) | forward factor | after L layers | backward factor | std | uniform bound |
|---|
Closed forms: factor = n · Var(w) · c; after L layers, factorL; uniform bound = √(3 Var). Defaults reproduce PyTorch, independently: every Var(w) matches torch.nn.init on a 1,024 × 1,024 tensor to within sampling error, and the hero's network multiplies the second moment per layer by 0.990 with He (theory 1), 0.495 with Xavier or LeCun (theory 0.5) and 0.162 with nn.Linear's default (theory 1/6) measured (src/recompute.py). The σ = 0.02, GPT-2 and μP rows are section 6.
Orthogonal initialisation: every direction, not only the average. Variance scaling preserves the mean square; a random Gaussian matrix still stretches some directions and crushes others, and a product of 20 of them spreads those factors apart. An orthogonal matrix (orthonormal rows, torch.nn.init.orthogonal_) has every singular value equal to 1, so a product of orthogonal layers preserves the length of every input exactly. In a 20-layer linear network of width 512 at initialisation, Gaussian weights with Var = 1/n keep the mean square at 0.94, yet half the singular values of the whole map are below 9.2 × 10−4 and the largest is 6.4; with orthogonal weights all 512 are 1.000 measured (src/signal_prop.py, float64). With ReLU, a gain of √2 plays He's role: the hero's orthogonal line multiplies the second moment by 1.015 per layer. Saxe, McClelland and Ganguli 2013 solve the learning dynamics of deep linear networks exactly and show that random orthogonal initialisation gives learning times that do not grow with depth, where scaled Gaussian initialisation does not (paraphrase of their abstract). It is the standard init for recurrent weight matrices, which multiply the same matrix at every time step.
Xavier: Glorot and Bengio 2010, derived for activations assumed linear near 0; uniform and normal flavours. He: He, Zhang, Ren and Sun 2015 (§2.2), who note "it is sufficient to use either" the forward or the backward condition, because a single layer's mismatch does not compound, and show it lets a 30-layer ReLU model converge where Xavier stalls. LeCun: LeCun, Bottou, Orr and Müller 1998 (standard deviation m−1/2 for m inputs), which SELU networks adopt as "LeCun normal" so that their activations converge to mean 0 and variance 1 by themselves (Klambauer et al. 2017). He's derivation keeps the non-zero mean of ReLU's output in view: what is preserved is the second moment, not the variance.
Every normalisation layer picks a set of numbers, computes their mean μ and variance σ², and replaces each number x in the set with
The kinds differ only in which numbers share one μ and σ, and that choice decides the rest: whether an example's output depends on the other examples in its batch, and whether training and inference compute the same thing. Fig. 5 is Figure 2 of the GroupNorm paper (Wu and He 2018) in 3D, on numbers computed in your browser: an activation tensor as a block, each norm lighting the set that shares one μ and σ.
For token sequences, BatchNorm would average one feature over every token of every sequence in the batch, padding included, and its statistics would change with sequence length; LayerNorm and RMSNorm average each token over its own D features, so a token's output depends on nothing else. That independence is why transformers use them.
Try: pick a layout and a norm, then click any number: everything outlined shares its statistics. Then press "Change example 1": example 1 is multiplied by 3, and every output that changes in another example is ringed in orange.
For images: BatchNorm shares statistics across the N examples and H × W pixels of one channel; LayerNorm across all channels and pixels of one example; InstanceNorm across the pixels of one channel of one example; GroupNorm across a group of channels of one example (one group is LayerNorm, one channel per group is InstanceNorm). Inputs are seeded random numbers with an offset and scale per channel and a scale per example illustrative; outputs with γ = 1, β = 0, ε = 10−5 match torch.nn.BatchNorm2d, BatchNorm1d, LayerNorm, RMSNorm, GroupNorm and InstanceNorm2d to 10−14 (src/checks/norms_ref.py).
| Norm | Set sharing μ, σ (image) | Set (tokens) | Depends on the batch | Paper |
|---|---|---|---|---|
| BatchNorm | one channel, all N examples and pixels | one feature, all B × T tokens | yes | Ioffe and Szegedy 2015 |
| LayerNorm | one example, all C channels and pixels | one token, its D features | no | Ba, Kiros and Hinton 2016 |
| InstanceNorm | one channel of one example | (not used) | no | Ulyanov, Vedaldi and Lempitsky 2016, for style transfer |
| GroupNorm | a group of C/G channels of one example (G = 32 in the paper) | (not used) | no | Wu and He 2018 |
| RMSNorm | as LayerNorm, no mean | one token, its D features, no mean | no | Zhang and Sennrich 2019 |
Fig. 6 · four features with true means 5, −1, 0, 2 and standard deviations 2, 0.5, 3, 1; batches from a seeded generator illustrative. PyTorch conventions: momentum 0.1, running mean starting at 0 and running variance at 1, ε = 10−5, γ = 1, β = 0. Training outputs, running statistics and inference outputs match torch.nn.BatchNorm1d to 10−14 (src/checks/norms_ref.py).
BatchNorm is feature scaling per layer, over the batch. In training, for every feature (channel): compute the batch mean μB and variance σB² (in a CNN, across the pixels too); normalise, x̂ = (x − μB) / √(σB² + ε); apply y = γx̂ + β, one γ and one β per feature; and update running averages of μ and σ² with a momentum. At inference a single input has no batch, so the layer uses the running averages. The original paper averages the mini-batch statistics over the training data once training is done (§3.1, Algorithm 2), but those change every time the weights do, so frameworks keep a moving average instead. With frozen statistics the layer is a fixed affine map, which can be folded into the preceding convolution or linear layer at deployment.
Predict what BatchNorm outputs with a batch of 2, then watch Fig. 6: it normalises each column (feature) of a batch, updates its running statistics, then meets one test batch at inference. Switch to batch size 2, then to LayerNorm, the method that replaced BatchNorm in transformers, on the same numbers.
Batch 8
Why ±1. With two values per feature, subtracting their mean leaves ±d/2 and their biased standard deviation is d/2, so every training output is ±1 (up to ε) derived, whatever the inputs: the layer passes on only which value was larger. Under a shifted test distribution (a recalibrated sensor, a new camera) the frozen running statistics no longer centre the data either, while LayerNorm re-centres each example on its own. GroupNorm's ResNet-50 on ImageNet has "10.6% lower error than its BN counterpart when using a batch size of 2" reported (Wu and He 2018).
What it buys, and costs. Centred, unit-scale inputs to every layer allow higher learning rates and make deep plain networks trainable (the parent's Training lab preset "BatchNorm rescues the deep sigmoid net"); each example also carries the noise of its batch partners, a mild regulariser. The costs: noisy statistics at small batches; awkward for RNNs and variable-length sequences (statistics per time step, padding inside the batch); running averages that go stale under distribution shift and must be recomputed after fine-tuning; and across devices each GPU's batch is small unless statistics are synchronised (SyncBatchNorm), which costs communication. In evaluation, call model.eval(), or outputs depend on the rest of the batch.
Small batches: change where the statistics come from. Batch Renormalization corrects the batch statistics towards the running ones (Ioffe 2017); SyncBatchNorm pools them across devices; GroupNorm abandons the batch axis (Fig. 5), which is why detection and segmentation models, trained with one or two images per GPU, moved to it. Weight standardisation normalises the weights instead of the activations: each convolution filter's weights are re-centred and re-scaled to mean 0 and variance 1 over its fan-in before every forward pass, ŵ = (w − mean(w)) / std(w), and the authors pair it with GroupNorm for micro-batch training of one or two images per GPU, reporting that it matches or beats large-batch BatchNorm on several tasks (Qiao, Wang, Liu, Shen and Yuille 2019, paraphrase of their abstract; they argue it smooths the loss landscape). It is a per-filter z-score with no batch statistics, so it, too, computes the same thing at training and inference.
LayerNorm normalises each example (each token, in a transformer) over its own features, with one γ, β vector per layer (Ba, Kiros and Hinton 2016). That fixes BatchNorm's three weaknesses at once: no dependence on batch size, fine for RNNs and variable-length inputs, and the same computation at training and inference, with no running averages (the LayerNorm mode of Fig. 6). It gives up the mild regularising noise of batch statistics and a little inference compute, because the statistics are computed per token instead of being folded into the weights. It was the 2017 transformer's norm.
RMSNorm (Zhang and Sennrich 2019) is LayerNorm without the re-centring. Its argument: LayerNorm's benefit comes from re-scaling invariance (the output does not change when the input is multiplied by a constant), not from re-centring; it "achieves comparable performance against LayerNorm but reduces the running time by 7%~64% on different models" reported, and its abstract singles out RNNs as the networks LayerNorm's overhead "significantly slows". In Fig. 5 (step 6), RMSNorm leaves each token's mean in place and only fixes its scale. It is the default in essentially every open LLM since Llama (Llama, Mistral, Qwen, DeepSeek, Gemma and OLMo 2; their config files name rms_norm_eps; the parent's Defaults across models tab lists 21 landmark models).
ε is not a detail. It bounds the output when the input is nearly constant. Released configs use 10−5 (Llama 3.1, Mistral 7B v0.3, GPT-2, SmolLM2) or 10−6 (Qwen3, Gemma 3, OLMo 2), and BERT's LayerNorm uses 10−12 (src/inputs/configs_norm_init.json, read from each model's config.json). An ε below what the number format can resolve against the variance does nothing, so low-precision kernels usually compute the statistics in float32.
Where the norm sits in a transformer block (post, pre, sandwich, output norm), QK-norm and the other logit controls are taught on Normalisation, residuals and stability (Topic: llm-architecture). Two measurements of released models live here, and that page links to them:
QK-norm is an RMSNorm on each head's query and key vectors (ViT-22B, Qwen3, OLMo 2, Gemma 3). An attention logit is q · k / √dh. With unit gain, an RMS-normalised head vector has length √dh, so a logit is at most √dh. But the gain γ is learned: ‖q‖ ≤ √dh · max|γq| (RoPE only rotates), so the ceiling is √dh · max|γq| · max|γk| derived. The bars compare that ceiling, from the released weights, with the largest logit reached on a 145-token English passage.
Qwen3-0.6B, 28 layers, dh = 128; gains read from q_norm.weight and k_norm.weight; logits from the model's own eager attention in float32, causal mask, first token excluded as a query (src/recompute.py, src/real/real_streams.py) measured. Log scale.
The trained gains are far from 1 (the key gains reach 96 in layer 1), so the ceilings run from 184 to 12,897 while the real largest logits per layer stay between 12.5 and 48: QK-norm does not cap logits at a small number in a trained model, so do not assume a √dh bound. What it changes is where growth can come from: not the projection weights or the residual stream, only a dh-sized gain vector, which an optimiser with a bounded step changes slowly. That is our reading of the numbers, not a claim from the papers.
| Model | Norm | Placement | ε | Attention logit control | initializer_range |
|---|---|---|---|---|---|
| BERT base (2018) | LayerNorm | post | 10−12 | none | 0.02 |
| GPT-2 (2019) | LayerNorm | pre, plus final | 10−5 | none | 0.02 |
| Llama 3.1 8B, Mistral 7B v0.3 | RMSNorm | pre | 10−5 | none | 0.02 |
| SmolLM2-135M | RMSNorm | pre | 10−5 | none | 0.0417 |
| Qwen3-0.6B | RMSNorm | pre | 10−6 | QK-norm | 0.02 |
| Gemma 3 270M | RMSNorm (gain 1 + γ) | peri (pre and post) | 10−6 | QK-norm (Gemma 2: soft-cap) | 0.02 |
| OLMo 2 1B | RMSNorm | output norm | 10−6 | QK-norm | 0.02 |
Read from each config.json and the module types (src/inputs/configs_norm_init.json, src/real/real_streams.py). Kimi K2 keeps pre-norm and controls logits with qk-clip in the optimiser (Moonshot AI: Kimi animates it); DeepSeek-V3 initialises with σ = 0.006.
Zhu, Chen, He, LeCun and Liu 2025 observe that LayerNorm in trained transformers "often produces tanh-like, S-shaped input-output mappings" and replace every norm layer with Dynamic Tanh, DyT(x) = γ · tanh(αx) + β with a learned scalar α, reporting matched or better results across vision and language tasks reported. It computes no statistics at all: an element-wise squashing that bounds activations. Whether it holds at frontier scale is not yet shown.
A residual stack adds, so its variance grows. Section 2 treats one layer at a time. A residual network adds every block's output into one stream, x → x + F(x), so even if each block preserves variance the stream's variance grows with the number of additions. In Xiong et al.'s analysis of a pre-norm transformer at initialisation, the stream's expected squared size after l blocks lies between (1 + l/2)d and (1 + 3l/2)d (their Lemma 2): linear in depth, which the exact toy below reproduces. Depth-aware schemes therefore shrink the residual branches at initialisation: GPT-2 scales the weights that write into the stream by 1/√(2 · n_layer), 0.02/√24 = 0.00408 for GPT-2 small measured from Hugging Face's GPT2LMHeadModel init. The transformer schemes (GPT-2's, DeepNorm, OLMo 2 dropping OLMo-0424's depth scaling, DeepSeek-V3's σ = 0.006) and the norm placements are taught, and measured on a tiny GPT, on Normalisation, residuals and stability (sections 2 and 6).
Initialisation instead of normalisation. Fixup (Zhang, Dauphin and Ma 2019) drops normalisation altogether: it rescales the residual branches (the last layer of each branch starts at zero) and adds scalar multipliers and biases, and trains residual networks "with 10,000 layers" as stably as with normalisation. The point of the hero, from the other side: get the scale right at step zero and keep it right, and the norm is optional.
A small fixed scale only works with norms. σ = 0.02 is not variance-preserving on its own: a layer of width d multiplies the second moment by d · 0.02², which is 0.31 at d = 768 and 1.64 at d = 4,096 derived (the calculator in section 2; ReLU halves both). Transformers get away with it because every branch input is re-normalised. Configs record it as initializer_range = 0.02 (GPT-2, BERT, Llama 3.1, Mistral, Qwen3, Gemma 3, OLMo 2), the value Hugging Face uses when a model is initialised from scratch; SmolLM2-135M sets 0.0417 = 1/√576, LeCun's scale for its width (src/inputs/configs_norm_init.json). The config value is not proof of how the released weights were trained; the parent's Defaults across models tab gives each lab's stated scheme.
Xiong et al. 2020 analyse a simplified Transformer at initialisation and prove that in post-norm "the expected gradients of the parameters near the output layer are large", so a large learning rate on them is unstable and warmup is "practically helpful for avoiding this problem"; with pre-norm "the gradients are well-behaved at initialization". In their Theorem 1 the last layer's gradient is O(d√(ln d)) for post-norm whatever the depth, and O(d√(ln d / L)) for pre-norm, shrinking with the number of layers L. Lemma 2 (above) is the price of pre-norm; post-norm's pre-normalisation sum stays at 3d/2.
Try: press Play: the same input climbs the residual stream block by block (top: the stream's size; for post-norm, also the sum before each norm), then the gradient comes back down (bottom: the size of each block's second feed-forward matrix gradient). Pick the placement and what to compare it with; raise the depth.
Xiong et al.'s simplified Transformer: width d = 64, 16 tokens, attention with WQ = WK = 0 (every token attends uniformly), a ReLU feed-forward of width d, Xavier-initialised weights, LayerNorm without learned gain, a 10-class softmax output; inputs and labels seeded illustrative. Forward and backward passes are written by hand and match PyTorch autograd to 3 × 10−15 over 24 configurations (src/checks/toy_ref.py). Defaults reproduce Lemma 2 (Xiong et al. 2020) independently: averaged over 20 seeds, post-norm's squared sum before the norm is 1.42 to 1.53 times d at every layer (theory 3/2), and pre-norm's squared stream after layer l stays inside (1 + l/2)d to (1 + 3l/2)d at every l from 1 to 12 (13.1d at l = 12, bounds 7d and 19d) measured.
Post-norm keeps the stream at size 1, but its late blocks get the largest gradients and those do not shrink as L grows (5 seeds: the last block's is 2.7 at L = 6 and 3.2 at L = 48) measured, Theorem 1's warmup problem. Pre-norm lets the stream grow, so each block's contribution is a shrinking fraction of it and the late blocks' gradients fall: 1.04, 0.67, 0.53, 0.40 at L = 6, 12, 24, 48, close to Theorem 1's 1/√L (√8 = 2.8 against the measured 2.6) measured. Peri-norm and the output norm add a branch of fixed size each time, so their stream grows like the square root of the number of sub-layers (RMS 9.8 after 48 blocks, √97 = 9.8); the DeepNorm mode keeps post-norm but up-weights the residual and shrinks the branch init (Wang et al. 2022).
Try: switch the quantity; hover or tap a point for its value. The dashed line is 1/√L.
Computing in your browser…
Each point averages 5 seeds of the toy above at L = 3, 6, 12, 24 and 48 blocks; "gradient" is the Frobenius norm of the second feed-forward matrix's gradient. Log-log axes.
What the toy cannot show: instability in real runs appears later in training and at scale (attention logits, rare huge gradients), which a 64-wide toy at initialisation cannot reproduce. Normalisation, residuals and stability trains a small transformer under four placements, with and without QK-norm, in its Stability explorer tab; the parent's When training goes wrong tab maps the symptoms to fixes.
Try: switch the quantity, and hide models with their buttons. The horizontal axis is depth as a fraction of each model's layers.
| Model | Placement | layers | d | embedding RMS | last block RMS | growth | largest logit |
|---|
One passage, one forward pass per model: measurements of six trained checkpoints, not a controlled comparison of placements (the models differ in size, data and training) measured; the controlled comparison is the toy above.
μP: initialisation and learning rate as one choice. In the standard parametrisation the best learning rate and init shift as a model gets wider, so hyperparameters tuned on a small model do not transfer. The Maximal Update Parametrization (Yang et al. 2022) changes how both scale with width so that "each layer is updated on the same order during training regardless of width"; the μP row of the calculator is its output-layer init, Var = 1/nin². The payoff reported: "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" reported.
Yang et al.'s Table 3, for Adam: hidden weights keep Var = 1/fan_in but their learning rate scales as 1/fan_in; output weights are initialised with Var = 1/fan_in² (not 1/fan_in) and also get a 1/fan_in learning rate; input weights and biases keep both; attention uses 1/d instead of 1/√d. OLMo 2's init argument uses the same reasoning: its gradient norm at initialisation grows with √d, which by Yang et al.'s argument lets a width-independent learning rate transfer (OLMo 2 §3.2).
nn.Linear uses U(±1/√nin), a sixth of He's variance (section 2).Loss spikes, NaNs and their fixes (QK-norm, z-loss, OLMo 2's init change, clipping) are diagnosed in the parent's When training goes wrong tab (Topic: ml-fundamentals), which replaced the old "Debugging training" page.
Built from the old Notion page "Normalisation and initialisation" (last edited 22 September 2026, fetched 3 October 2026; saved verbatim in src/live.md), with every claim rechecked against the linked sources on 3 October 2026; rebuilt to the teaching contract on 24 October 2026. Every norm is checked against torch.nn (src/checks/norms_ref.py), the placement toy against PyTorch autograd (src/checks/toy_ref.py), the init numbers and QK-norm ceilings in src/recompute.py, orthogonal init, twice He and the LayerNorm line of Fig. 1 and Fig. 4 in src/signal_prop.py, the wine numbers in src/scaling.py, and the six released models in src/real/real_streams.py.
Reading, step 1 (data and initialisation) and step 2 (activations and normalisation): the comparison at the level of one training step, and "Watch the variance, layer by layer", one batch through five 16-layer networks with per-layer activation spread and gradient size. Thread 2, "Keep the variance constant": the pact between activation, initialisation and normalisation. Training lab: swap the init and the norm (and pre against post) in a network trained live. Defaults across models: norm type, placement, epsilon, init scheme and standard deviation for 21 models. When training goes wrong: loss spikes and their fixes (QK-norm, z-loss, OLMo 2's init change), which replaced the "Debugging training" page. (30 min, plus 1 in closed details)
Every activation's formula and failure, and why the activation dictates the init scheme. (25 min, plus 5 in closed details)
Warmup, Adam's early steps and why post-norm needs them; Muon, whose logit growth led to qk-clip. (34 min, plus 14 in closed details)
Weight decay, dropout and the mild regularising noise of BatchNorm's batch statistics. (32 min, plus 8 in closed details)
The distance-based and linear models for which feature scaling matters. (29 min, plus 8 in closed details)
The owner of the transformer side of this page (Topic: llm-architecture): the residual stream, norm placements with a four-placement stepper, DeepNorm and mHC, QK-norm, soft-capping and qk-clip with a before/after of runaway logits, z-loss, residual init, massive activations and loss spikes; its Stability explorer tab trains a tiny GPT across learning rates, placements and QK-norm. It links to this page's Qwen3 QK-norm measurement and six-model streams (sections 5 and 6). (27 min, plus 14 in closed details)
The output norm, QK-norm and the N(0, 0.02) init, each with its before-and-after curve replayed from the paper's figures. (29 min)
The post-norm block, and its Then and now tab morphing it into a 2026 block (pre-norm, RMSNorm). (14 min)
The LayerNorm placement change that let BERT scale, and the 1/√(2N) residual init. (23 min)
QK-Norm replacing the QKV bias, in a toy Qwen3 trained live. (27 min)
MuonClip and qk-clip, animated per head. (38 min, plus 10 in closed details)
How to read a released config, and where open models put their norms (pre-norm RMSNorm close to universal; QK-norm, sandwich and output norms as the recent deltas). (22 min, plus 8 in closed details)
The original, with training and inference algorithms. (45 min)
The batch-independent alternative. (45 min)
The LLM-era default norm. (45 min)
He initialisation, derived alongside PReLU. (45 min)
Xavier initialisation. (45 min)
Why post-norm needs warmup and pre-norm does not; the toy on this page is their model. (45 min)
The figure of the four norms' axes, and BatchNorm at small batches. (30 min)
The case against internal covariate shift. (40 min)
Initialisation and learning rate scaled together with width. (1h)
The wine example rerun on this page; mind the shared PCA object. (15 min)