Normalisation and initialisation

Feature scaling, initialisation schemes (Xavier, He, LeCun, orthogonal, μP) and normalisation layers (BatchNorm, LayerNorm, RMSNorm, GroupNorm, weight standardisation), computed in your browser and checked against torch.nn. Part of Topic: ml-fundamentals. Data as of October 2026. Reading: 23 min, plus 14 in closed details.

The idea in one sentence

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.

  1. The network. 1,024 random inputs, mean square 1.00, enter 20 linear layers of width 512, each followed by ReLU, with no bias (built in PyTorch). Each glass plate is one layer's output, its side the root mean square; the dashed squares are the size the signal should keep.
  2. PyTorch's default: ×0.162 per layer. 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.
  3. Xavier: ×0.495. Derived for tanh, which is roughly linear near 0, it loses half the second moment at every ReLU: 7.8 × 10⁻⁷ after 20 layers.
  4. He: ×0.990. Twice Xavier's variance, to pay for ReLU's halving: the signal holds, 0.82 after 20 layers.
  5. Twice He: ×1.980. Var(w) = 4/nin, a scale chosen to show the other failure illustrative, run on the same network: the mean square doubles at every layer, 8.6 × 10⁵ after 20 (plates wider than 2.4 times the input's are drawn at that size).
  6. The default plus a LayerNorm before every ReLU. The same shrinking weights, but each LayerNorm (the thin teal plates) resets the scale to 1 and ReLU halves it: 0.51 at every layer, whatever came before. That is the whole page in one picture: get the scale right once, or reset it every layer.

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).

second moment
E[x²], the mean square of a layer's numbers; equal to the variance when the mean is 0. The quantity every scheme on this page keeps near 1.
fan-in, fan-out
nin, nout: how many inputs a unit sums, and how many units read its output.
γ, β
the learned gain and shift a norm applies after normalising, one per feature.
running statistics
BatchNorm's moving averages of the mean and variance, used at inference instead of batch statistics.
residual stream
the vector x in x → x + F(x) that every block of a residual network adds into.
Every tool on one table
ToolAverages overLearnedTraining against inferenceWhere it lives
Standardisation (z-score)each input feature, over the training setnothingstatistics fixed from the training setinputs of distance-based and gradient-trained models
Min-max scalingeach feature's range, over the training setnothingas aboveinputs that need a bounded range
BatchNorm (2015)each feature (channel), over the batch (and positions)γ, β per featuredifferent: batch statistics in training, running averages at inferenceCNNs
LayerNorm (2016)each example (token), over its featuresγ, β per featureidenticalthe 2017 transformer, BERT, GPT-2
RMSNorm (2019)as LayerNorm, without subtracting the meanγ onlyidenticalessentially every current LLM
GroupNorm, InstanceNorm (2018, 2016)each example, over a group of channels (or one channel) and the pixelsγ, β per channelidenticaldetection and segmentation with small batches; style transfer
QK-normeach query and key head vectorγidenticalattention in many 2024 to 2026 LLMs
InitialisationVar(w)Keeps the variance for
Xavier (Glorot)2 / (nin + nout)tanh and sigmoid, roughly linear near 0
He (Kaiming)2 / ninReLU and its family
LeCun1 / ninlinear units; SELU (self-normalising networks)
Orthogonalrows orthonormal, times a gainevery 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.

Same wines, same neighbours rule: in raw units proline decides alone

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.

1 · Feature scaling: the inputs, once

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.

  1. Raw units, drawn to the same scale on both axes. Proline spans about 1,400 mg/L, hue about 1.2, so on equal axes every wine sits on a flat line: hue is invisible to anything that measures distance.
  2. 20 nearest neighbours, raw. The ringed test wine collects its 20 nearest training wines. Most of the distance is proline, so the neighbours are a vertical stripe of wines with similar proline, whatever their hue, and the vote goes to the wrong cultivar.
  3. Standardise: subtract each feature's mean, divide by its standard deviation. Both features now have mean 0 and standard deviation 1 on the training wines (or, with min-max, the range 0 to 1). Nothing about the wines changed; only the units.
  4. 20 nearest neighbours, scaled. Hue now counts as much as proline, the neighbourhood is a round patch, and the vote goes to the right cultivar.
  5. Every test wine. Each of the 54 test wines votes with its 20 neighbours; crosses mark the wrong votes in the current units. Raw units get 75.93% right; standardised and min-max scaled, 94.44%.
MethodFormulaResultNote
Standardisation (z-score)z = (x − μ) / σmean 0, standard deviation 1the default; scikit-learn's StandardScaler uses the population σ (no n − 1)
Min-max normalisationx′ = (x − xmin) / (xmax − xmin)range [0, 1]one outlier squeezes every other value into a sliver
Robust scaling(x − median) / IQRmedian 0, interquartile range 1for 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: a ravine in raw units, a round bowl after standardising

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.

  1. Raw units: a crack, not a bowl. One unit of w multiplies proline, which is in the hundreds, so the loss is 4.4 × 10⁶ times more curved along w than along b (the condition number κ, the ratio of the steepest to the flattest curvature). At equal scale the ravine is a line; its bottom, b = 0.85, is at the far end.
  2. 30 steps in raw units. The first step drops onto the floor of the crack; after that the flat direction moves 1.2/κ of the remaining way per step. After 30 steps b is 8.3 × 10⁻⁶ and the loss 0.078, against 0.026 at the bottom: still 11% of the way from the bottom to the start, and at this rate it would take millions of steps to close.
  3. Min-max scaled: a stretched bowl, κ = 23. One way is 23 times more curved than the other, which is mild: the first steps drop to the valley floor and the rest slide down it, and after 30 steps the loss is 0.026, the bottom.
  4. Standardised: a round bowl, κ = 1.0. With mean 0 and variance 1, the two curvatures are equal (the Hessian is the identity), so every step points at the bottom: the loss is 0.026 within a few steps.

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).

Correction: scikit-learn's own example overstates the gap
It reports that PCA to two components then logistic regression scores 35.19% unscaled against 96.30% standardised. Rerunning its code reproduces both numbers, but the example passes one 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).

2 · Initialisation: the scale of step zero

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.

E[xnext²] = c · nin · Var(w) · E[x²]
c
½ after ReLU (it zeroes half of a symmetric input); 1 for a linear unit, or tanh near 0
forward
keep c · nin Var(w) = 1: Var(w) = 1/nin (linear, LeCun), 2/nin (ReLU, He)
backward
the gradient flows through the transposed weights, summing over nout units: c · nout Var(w) = 1
compromise
both cannot hold when nin ≠ nout; Glorot and Bengio average them: Var(w) = 2/(nin + nout), drawn as U[−√6/√(nin+nout), +√6/√(nin+nout)] (their Eq. 16)

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.

Twenty layers multiply a small error twenty times; a norm resets it each layer

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.

Anything but a factor of 1 compounds with depth

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.

PyTorch's default is not He initialisation
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).

Per-layer factor and after L layers, for every scheme

SchemeVar(w)forward factorafter L layersbackward factorstduniform 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.

Where each formula comes from

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.

3 · One recipe, five choices of axes

Every normalisation layer picks a set of numbers, computes their mean μ and variance σ², and replaces each number x in the set with

y = γ · (x − μ) / √(σ² + ε) + β
μ, σ²
mean and (biased, divide-by-n) variance over the set; RMSNorm skips μ and uses the mean square
ε
a small constant against division by zero (10−5 by default in PyTorch)
γ, β
learned per feature or channel, initialised to 1 and 0, so the layer can undo the normalisation if that helps; without them normalising would limit what a layer can represent (Ioffe and Szegedy 2015, §3)

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 σ.

  1. The tensor. One layer's activations for a batch of images: N = 4 examples across, C = 6 channels in depth, H × W = 2 × 2 positions stacked. Colour is the value, orange positive and blue negative; each channel has its own offset and scale and each example its own scale illustrative, so every norm has something to remove.
  2. BatchNorm: one channel, across the batch. The front slab, channel 1 in all 4 examples at all 4 positions: 16 numbers stream into one μ and σ, 6 sets in all, then every number becomes its z-score. Each output now depends on the other examples in the batch.
  3. LayerNorm: one example, every channel. 24 numbers per set, 4 sets. An example's output depends on nothing else, and training and inference compute the same thing.
  4. InstanceNorm: one channel of one example. 4 numbers per set, 24 sets. It removes each image's own contrast per channel, which is why it suits style transfer and hurts classification.
  5. GroupNorm: a group of channels of one example. With 3 groups of 2 channels, 8 numbers per set, 12 sets. G = 1 is LayerNorm, G = C is InstanceNorm; it never looks at the batch, so it works with a batch of 1 or 2.
  6. RMSNorm: LayerNorm's set, without the mean. Each example is divided by its root mean square; nothing is subtracted, so a set's mean survives and only its scale is fixed (compare the colours with step 3).
  7. Multiply example 1 by 3. Under BatchNorm, 72 outputs in the other three examples change (outlined); under LayerNorm, InstanceNorm, GroupNorm and RMSNorm, 0. Only BatchNorm couples the examples of a batch.

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.

Every number, clickable: inputs, outputs, and a token layout

Only BatchNorm lets one example change another's output

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).

The five norms, their sets and their papers
NormSet sharing μ, σ (image)Set (tokens)Depends on the batchPaper
BatchNormone channel, all N examples and pixelsone feature, all B × T tokensyesIoffe and Szegedy 2015
LayerNormone example, all C channels and pixelsone token, its D featuresnoBa, Kiros and Hinton 2016
InstanceNormone channel of one example(not used)noUlyanov, Vedaldi and Lempitsky 2016, for style transfer
GroupNorma group of C/G channels of one example (G = 32 in the paper)(not used)noWu and He 2018
RMSNormas LayerNorm, no meanone token, its D features, no meannoZhang and Sennrich 2019

At batch size 2 every training output is ±1; inference then sees a range it never trained on

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).

4 · BatchNorm: z-scores inside the network, and the batch it cannot do without

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

  1. Batch 1: normalise each column. Each feature (column) is normalised by the batch's own mean and standard deviation, written under the grid, then the running averages move 10% of the way towards this batch's statistics (PyTorch momentum 0.1), from their starting values 0 and 1.
  2. Batch 2: the running mean creeps. Same procedure; the running mean moves another 10% of the way towards the true feature means (5, −1, 0, 2).
  3. 200 batches later. The running averages are an exponential average over roughly the last 10 batches (1 / momentum), so they track the true statistics with some noise.
  4. Inference, with the running statistics. A test batch from the same distribution: inference uses the stored averages, training mode would have used the batch's own statistics. Close with batch 8, never identical.
  5. A shifted test batch: every feature +3. The running averages still describe the training data, so every output column is pushed off centre by about 3 / sd in expectation (1.5 for feature 1, 6 for feature 2; this batch's own means are under the grid). The fix is to recompute the statistics on new data, or adapt them at test time, which LayerNorm never needs.

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.

Correction: why BatchNorm works
The original paper's explanation is that BN reduces "internal covariate shift", the change in each layer's input distribution as earlier layers train. Santurkar et al. 2018 showed that "such distributional stability of layer inputs has little to do with the success of BatchNorm" and that BN instead "makes the optimization landscape significantly smoother", so gradients are more predictive and larger steps are safe. The old page listed the original claim as an advantage.

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.

Framework details: momentum, two variances, placement, the headline result
  • The two "momentum" conventions are opposite. PyTorch: running = (1 − momentum) · running + momentum · batch, default momentum 0.1, and its docs warn this "is different from one used in optimizer classes" (BatchNorm1d). Keras: moving = moving · momentum + batch · (1 − momentum), default momentum 0.99 and ε = 10−3 (BatchNormalization). Both mean "keep 90% (or 99%) of the old estimate"; porting 0.1 from PyTorch to Keras keeps only 10%.
  • Two variances. PyTorch normalises with the biased batch variance (divide by n) but stores the unbiased one (divide by n − 1) in the running average.
  • Placement. The original paper adds BN "immediately before the nonlinearity", normalising x = Wu, and drops the layer's bias because β replaces it (§3.2); after the activation also appears in practice.
  • Headline. On ImageNet, BN reached the same accuracy "with 14 times fewer training steps" and an ensemble reached 4.9% top-5 validation error reported.

5 · LayerNorm and RMSNorm: the same recipe on the other axis

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(x) = x / RMS(x) · γ,   RMS(x) = √( (1/d) Σ xi² + ε )
vs LayerNorm
no mean subtraction, no β: half the reductions and one fewer parameter vector

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:

Measured: does QK-norm cap attention logits in Qwen3-0.6B?

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.

Trained gains put the ceiling hundreds of times above the real logits

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.

The released models measured on this page: norm, ε, init scale
ModelNormPlacementεAttention logit controlinitializer_range
BERT base (2018)LayerNormpost10−12none0.02
GPT-2 (2019)LayerNormpre, plus final10−5none0.02
Llama 3.1 8B, Mistral 7B v0.3RMSNormpre10−5none0.02
SmolLM2-135MRMSNormpre10−5none0.0417
Qwen3-0.6BRMSNormpre10−6QK-norm0.02
Gemma 3 270MRMSNorm (gain 1 + γ)peri (pre and post)10−6QK-norm (Gemma 2: soft-cap)0.02
OLMo 2 1BRMSNormoutput norm10−6QK-norm0.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.

2025: normalisation without statistics (Dynamic Tanh)

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.

6 · Depth: residual stacks, initialisation instead of normalisation, and μP

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.'s theorem in an exact toy: why post-norm needs warmup

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.

Pre-norm's stream grows; post-norm's late gradients stay large

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).

Swept over depth: post-norm's last gradient does not fall, pre-norm's falls like 1/√L

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.

Measured: the residual stream in six released models

Every pre-norm stream grows a hundredfold or more; OLMo 2's output norm keeps it small

Try: switch the quantity, and hide models with their buttons. The horizontal axis is depth as a fraction of each model's layers.

ModelPlacementlayersdembedding RMSlast block RMSgrowthlargest logit

  • Post-norm (BERT) keeps the stream at a fixed size: each block ends with a LayerNorm, so the typical token's stream stays between 0.55 and 0.8 (the learned gain sets it, not 1), and the sum entering each norm is 0.94 to 1.62.
  • Every pre-norm model's stream grows with depth, as Lemma 2 says it must at initialisation, and training does not undo it: from embedding to last block, ×106 in GPT-2, ×289 in SmolLM2-135M and ×531 in Qwen3-0.6B. The final norm before the output head removes the scale.
  • Peri-norm does not stop the growth. Gemma 3 270M's stream grows ×1,041, to a typical RMS of 1,073: the sandwich fixes the size of each addition only up to the post-norm's learned gain, and those gains are large.
  • OLMo 2's output norm keeps the stream smallest of the five decoders: ×12.8, ending at RMS 0.88, and its first token shows no outsized values on this passage (largest first-token RMS 0.7).
  • The first token is different in the other decoders: its stream reaches RMS 111 (GPT-2), 193 (Qwen3), 832 (SmolLM2) and 4,119 (Gemma 3) against typical tokens' 14 to 1,073, the "massive activations" of Sun et al. 2024; that is why it is excluded from the medians and shown separately.
  • Largest attention logits stay below 50 in all six on this passage (BERT 31, GPT-2 42, Qwen3 48, with or without QK-norm); the instabilities QK-norm prevents appear during training at scale, not in a finished small model's forward pass.

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.

μP's rules for Adam, and OLMo 2's use of the argument

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).

Common mistakes, one line each
  • Fitting the scaler on all the data: leaks the test set; fit on the training set only (section 1).
  • Scaling inputs for a tree model, or not scaling them for kNN, SVM, PCA or a regularised linear model: trees are unaffected; the others are not (75.9% against 94.4% for kNN on two wine features).
  • Evaluating a BatchNorm network in training mode, or training it with tiny batches: outputs then depend on the batch, and at batch 2 every output is ±1; use GroupNorm or SyncBatchNorm for small per-device batches, and recompute running statistics after fine-tuning (section 4).
  • Copying BatchNorm's momentum between PyTorch and Keras: PyTorch's 0.1 and Keras's 0.99 mean the same thing from opposite sides.
  • Calling OLMo 2's or Gemma's norm "post-norm": both keep the residual stream unnormalised and normalise the branch output (Gemma also its input); the 2017 post-norm normalises the stream itself.
  • Assuming PyTorch layers are He-initialised: nn.Linear uses U(±1/√nin), a sixth of He's variance (section 2).
  • Using Xavier with ReLU, or He with tanh: Xavier halves the ReLU signal's second moment at every layer (7.8 × 10−7 after 20 layers, measured); He doubles a tanh signal near 0.
  • Reading σ = 0.02 as a variance-preserving init: at width 4,096 it grows the second moment by 1.64 per linear layer and at 768 shrinks it by 0.31; the norms rescue it.

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.

Provenance and checks

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.