Simple Algorithm
Deep Learning · Representation · 24 min

BatchNorm, LayerNorm & RMSNorm

What each one normalizes over, and why it makes training faster and more stable.

In 2015 one new layer let an ImageNet network reach its old accuracy in 14 times fewer training steps. Batch normalization standardizes every unit with statistics of the current mini-batch; its descendants LayerNorm and RMSNorm standardize each example on its own and now sit in every transformer. Here you write down what each one computes and over which axes, how they behave at test time, what they do to gradients, and what is (and is not) known about why they make training faster and more stable.

What you’ll learn

  • Write the forward pass of BatchNorm, LayerNorm, GroupNorm and RMSNorm, and name the axes of an activation tensor that each one averages over.
  • Explain BatchNorm's training and inference modes, its running statistics, and the bugs that come from mixing them up.
  • Derive the scale invariance that normalization creates and its consequences for gradients: orthogonality to the weights and the effective learning rate η/∥w∥2\eta/\norm{\mathbf w}^2.
  • Weigh the explanations of why normalization helps (internal covariate shift, smoother landscapes, larger learning rates, automatic rate tuning, near-identity residual blocks, batch noise) against the experiments that test them.
  • Place normalization layers in an architecture, before or after the activation and as Pre-LN or Post-LN, and use the PyTorch modules.

Standardize every layer, on the fly

Standardizing the inputs is one of the oldest tricks for training faster. For a linear model with squared loss, the curvature of the loss is the input second-moment matrix E[xx⊤]=Σ+μμ⊤\E[\mathbf x\mathbf x^\top] = \Sigma + \boldsymbol\mu\boldsymbol\mu^\top: features on very different scales, or a large shared mean μ\boldsymbol\mu, make some directions far steeper than others, and gradient descent zigzags. LeCun, Bottou, Orr and Müller (1998) recommended shifting every input to zero mean and scaling it to unit variance.

In a deep network every layer is a model whose inputs are the previous layer's outputs, and their means and scales drift as the earlier weights change. Ioffe and Szegedy (2015) called this drift internal covariate shift and proposed to standardize inside the network, with statistics computed on the current mini-batch.

z^i=zi−μBσB2+ϵ,yi=γ z^i+β,i=1,…,B\hat z_i = \frac{z_i - \mu_B}{\sqrt{\sigma_B^2 + \epsilon}},\qquad y_i = \gamma\,\hat z_i + \beta,\qquad i = 1,\dots,B
The statistics, and therefore every output, depend on the whole batch: during training, example ii's output changes if its batchmates change.

Standardizing alone would restrict what a layer can represent: a sigmoid fed standardized inputs would stay in its nearly linear middle. The learned γ\gamma and β\beta give that freedom back; with γ=σ2+ϵ\gamma = \sqrt{\sigma^2 + \epsilon} and β=μ\beta = \mu the layer can even undo itself. Two practical consequences follow. A bias added just before batch normalization is wasted, because the mean subtraction cancels it and β\beta takes over its role, so such layers are built without one. And in a convolutional layer a channel's statistics are pooled over the batch and over all spatial positions, so that every position is normalized the same way, with one γ\gamma and one β\beta per channel.

The effect on training was dramatic. On an Inception network for ImageNet, batch normalization with a five times larger learning rate, and other changes it allowed such as removing dropout, reached the original model's accuracy in 14 times fewer training steps (Ioffe & Szegedy, 2015).

Check your understanding

A layer computes z=Wh+b\mathbf z = W\mathbf h + \mathbf b and feeds z\mathbf z to batch normalization in training mode. What is ∂L/∂b\partial L/\partial\mathbf b?

  1. Exactly zero: adding bkb_k to every example's zkz_k raises the batch mean by bkb_k, and the mean subtraction removes it
  2. The same as ∂L/∂β\partial L/\partial\boldsymbol\beta, since both are shifts
  3. The batch sum of ∂L/∂z\partial L/\partial\mathbf z, as for any bias, which is generally nonzero
  4. Zero only at initialization, while γ=1\boldsymbol\gamma = \mathbf 1
Show the answer

A. Exactly zero: adding bkb_k to every example's zkz_k raises the batch mean by bkb_k, and the mean subtraction removes it

Since b\mathbf b is added to every example, the batch mean absorbs it and z^\hat z does not depend on it at all, so neither does the loss. In backward-pass terms, the mean subtraction makes the gradients ∂L/∂zik\partial L/\partial z_{ik} sum to zero over the batch, and the bias gradient is exactly that sum. In evaluation mode, with fixed running statistics, the bias does matter again.

Predict before you look

A convolutional layer feeds BatchNorm2d a batch of 32 images, each producing feature maps of 56×5656\times56 positions. How many numbers, in thousands, are averaged into each channel's batch mean?

Show the answer

100.4 thousand

32×56×56=100,35232\times56\times56 = 100{,}352: in a convolutional network, a channel's "batch" is every position of every image. That sounds like plenty, but positions within one image are strongly correlated, so the statistics still fluctuate with the number of images. With only 2 to 4 images per device, batch normalization degrades sharply (Batch Normalization's Hidden Costs).

Which numbers share a mean? The normalizer family

Every normalizer computes the same standardization; what differs is which set of numbers shares one mean and one variance. Take an image activation tensor of shape (B,C,H,W)(B, C, H, W) (batch, channels, height, width) and a transformer activation of shape (B,T,d)(B, T, d) (batch, tokens, width):

NormalizerOne mean and variance perAveraged over, for (B,C,H,W)(B, C, H, W)For (B,T,d)(B, T, d)Uses other examples?
BatchNorm (Ioffe & Szegedy, 2015)channelB,H,WB, H, WBB (and TT); rarely usedyes, in training
LayerNorm (Ba, Kiros & Hinton, 2016)example (or token)C,H,WC, H, Wdd, per tokenno
Instance norm (Ulyanov, Vedaldi & Lempitsky, 2016)example and channelH,WH, W–no
GroupNorm (Wu & He, 2018)example and group of C/GC/G channelsC/G,H,WC/G, H, W–no
RMSNorm (Zhang & Sennrich, 2019)token; no mean is subtracted–dd, root mean square onlyno
Each also learns a gain for every channel or feature, and every one except RMSNorm usually learns a shift too. GroupNorm with one group is LayerNorm over (C,H,W)(C, H, W); with one channel per group it is instance norm.
LN⁡(x)=γ⊙x−μ1σ2+ϵ+β,RMSNorm⁡(x)=γ⊙x1d∑i=1dxi2+ϵ\operatorname{LN}(\mathbf x) = \boldsymbol\gamma\odot\frac{\mathbf x - \mu\mathbf 1}{\sqrt{\sigma^2 + \epsilon}} + \boldsymbol\beta,\qquad\operatorname{RMSNorm}(\mathbf x) = \boldsymbol\gamma\odot\frac{\mathbf x}{\sqrt{\frac1d\sum_{i=1}^dx_i^2 + \epsilon}}
For one token x∈Rd\mathbf x\in\R^d, with μ\mu and σ2\sigma^2 the mean and variance of its own dd entries. Nothing here refers to other tokens or other sequences.

For images, Wu and He (2018) found GroupNorm with 32 groups a good compromise. On ResNet-50 trained on ImageNet with 32 images per GPU, their validation errors were 23.6% with BatchNorm, 24.1% with GroupNorm, 25.3% with LayerNorm and 28.4% with instance norm. With 2 images per GPU, BatchNorm's error rose to 34.7% while GroupNorm's stayed at 24.1%.

RMSNorm drops LayerNorm's mean subtraction, on the hypothesis that re-centering is dispensable and re-scaling is what matters. In Zhang and Sennrich's experiments it matched LayerNorm while cutting running time by 7% to 64%, and many language models of the 2020s use it; LLaMA, for example, normalizes the input of each sublayer with RMSNorm (Touvron et al., 2023).

Check your understanding

You need a normalizer for a language model. A token's output must not depend on the other sequences in the batch, and must not change if the same constant is added to every coordinate of that token's vector. Which normalizer satisfies both?

  1. BatchNorm
  2. LayerNorm
  3. RMSNorm
  4. Both LayerNorm and RMSNorm
Show the answer

B. LayerNorm

LayerNorm uses only the token's own entries and subtracts their mean, so a constant added to all of them cancels. RMSNorm also ignores the batch, but it divides by the root mean square without centering, and a shift changes both its numerator and its denominator.

Training mode and inference mode

At test time a prediction should depend on its input alone, and a single example has no batch to take statistics from. So batch normalization runs in two modes. In training mode it normalizes with μB\mu_B and σB2\sigma_B^2 and updates its running statistics; in evaluation mode it normalizes with those running statistics μ^,σ^2\hat\mu,\hat\sigma^2 instead. It is then a fixed affine map per channel, y=γ(z−μ^)/σ^2+ϵ+βy = \gamma(z - \hat\mu)/\sqrt{\hat\sigma^2 + \epsilon} + \beta, which can be folded into the preceding layer's weights and bias for fast inference. Ioffe and Szegedy defined the population statistics as averages over many training batches, with the unbiased correction n/(n−1)n/(n - 1) on the variance; frameworks instead keep exponential moving averages while training:

μ^ ← (1−m) μ^+m μB,σ^2 ← (1−m) σ^2+m nn−1 σB2\hat\mu\ \leftarrow\ (1 - m)\,\hat\mu + m\,\mu_B,\qquad\hat\sigma^2\ \leftarrow\ (1 - m)\,\hat\sigma^2 + m\,\frac{n}{n - 1}\,\sigma_B^2
nn is the number of values pooled per channel (B⋅H⋅WB\cdot H\cdot W for images). PyTorch's momentum argument is this mm, the weight of the new batch, with default 0.10.1: the opposite of an optimizer's momentum. With momentum=None it keeps a plain cumulative average. LayerNorm, GroupNorm and RMSNorm need none of this: they compute the same function in both modes.
python
import torch
import torch.nn as nn

block = nn.Sequential(
    nn.Conv2d(64, 128, kernel_size=3, padding=1, bias=False),  # a bias would be cancelled
    nn.BatchNorm2d(128),   # gamma, beta and running stats per channel; eps=1e-5, momentum=0.1
    nn.ReLU(),
)
x = torch.randn(32, 64, 56, 56)

block.train()              # normalize with this batch's statistics; update the running averages
y_train = block(x)
block.eval()               # normalize with the running averages: each image independent of the rest
y_eval = block(x)
print((y_train - y_eval).abs().max())         # far from 0: the two modes compute different functions

ln = nn.LayerNorm(512)     # one mean and variance per token, over the last dimension
rms = nn.RMSNorm(512)      # no centering: x / sqrt(mean(x**2) + eps), times a learned gain
h = 3 + 2 * torch.randn(8, 128, 512)                     # (batch, tokens, width), mean 3
print(ln(h).mean(-1).abs().max(), ln(h).var(-1, unbiased=False).mean())   # about 0 and 1
print(rms(h).pow(2).mean(-1).mean(), rms(h).mean(-1).mean())             # about 1 and 0.83

After a single forward pass in training mode the running averages are still mostly their initial values (mean 0, variance 1), so the two modes disagree badly: evaluation mode is only as good as the statistics it has accumulated. The last line shows RMSNorm's missing centering: unit mean square, but the mean 3/13≈0.833/\sqrt{13}\approx0.83 survives. nn.RMSNorm exists in recent PyTorch versions.

Think first A model scores well when the test set is evaluated in shuffled batches of 256, but its accuracy drops when the same weights serve one request at a time. What is the most likely bug?

Evaluation ran in training mode. With 256 random test images, the batch statistics happen to be close to the population statistics, so the predictions looked fine. One request at a time, each image is normalized by statistics of itself alone (for a convolutional layer, its own spatial positions), which changes its features. Calling model.eval() makes every prediction use the running statistics, identical in both settings.

What normalization does to signals and gradients

The most visible effect is on the forward signal. For any c>0c > 0, BN⁡(cWh)=BN⁡(Wh)\operatorname{BN}(cW\mathbf h) = \operatorname{BN}(W\mathbf h) (ignoring ϵ\epsilon), and likewise for LayerNorm and RMSNorm: the scale of the weights before a normalization layer no longer reaches the layers after it. A deep stack of normalized layers therefore keeps its activations at unit scale whatever the initialization, the problem that Initialization & Vanishing Gradients solved by choosing the scale carefully. The weights still matter through their direction, and that makes the loss scale-invariant in them:

DerivationProof, and what it does to a gradient step
  1. ddcL(cw)∣c=1=w⊤∇L(w)=0\frac{d}{dc}L(c\mathbf w)\Big|_{c=1} = \mathbf w^\top\nabla L(\mathbf w) = 0

    Differentiate L(cw)=L(w)L(c\mathbf w) = L(\mathbf w) with respect to cc and set c=1c = 1:

  2. c ∇L(cw)=∇L(w)⟹∇L(cw)=1c ∇L(w)c\,\nabla L(c\mathbf w) = \nabla L(\mathbf w)\quad\Longrightarrow\quad\nabla L(c\mathbf w) = \frac1c\,\nabla L(\mathbf w)

    Differentiate the same identity with respect to w\mathbf w instead; the chain rule puts a factor cc on the left:

  3. Δθ ≈ ∥Δw∥∥w∥=η∥w∥2 ∥∇L(w^)∥\Delta\theta\ \approx\ \frac{\norm{\Delta\mathbf w}}{\norm{\mathbf w}} = \frac{\eta}{\norm{\mathbf w}^2}\,\norm{\nabla L(\hat{\mathbf w})}

    Write w=∥w∥ w^\mathbf w = \norm{\mathbf w}\,\hat{\mathbf w} with ∥w^∥=1\norm{\hat{\mathbf w}} = 1. A gradient step Δw=−η∇L(w)=−η∇L(w^)/∥w∥\Delta\mathbf w = -\eta\nabla L(\mathbf w) = -\eta\nabla L(\hat{\mathbf w})/\norm{\mathbf w} is orthogonal to w\mathbf w, so it rotates the direction by an angle of roughly

  4. Only the direction affects the loss, so the step that matters is governed by the effective learning rate η/∥w∥2\eta/\norm{\mathbf w}^2, not by η\eta. And because every step is orthogonal to w\mathbf w, Pythagoras makes the norm grow, ∥wt+1∥2=∥wt∥2+∥Δwt∥2\norm{\mathbf w_{t+1}}^2 = \norm{\mathbf w_t}^2 + \norm{\Delta\mathbf w_t}^2, which slowly lowers the effective rate unless weight decay pushes back. What Weight Decay Really Does works out where the two forces balance.

The widget shows the other side of the invariance. LayerNorm's Jacobian has norm of order d/∥x∥\sqrt d/\norm{\mathbf x} (Xiong et al., 2020): a gradient passing back through a normalization layer is divided by the size of that layer's input, then multiplied by whatever the layer below does to it. In a plain stack nothing makes the two cancel, and for batch normalization Yang et al. (2019) proved that they never do: in deep fully connected networks without skip connections, at initialization and in the infinite-width limit, batch normalization makes gradients explode exponentially with depth for every non-constant nonlinearity, even the identity (Batch Normalization's Hidden Costs). Put the normalization on a residual branch and the identity path carries the gradient past it, which is the combination modern architectures use (Residual Connections).

Why does it help? Six explanations, weighed

Normalization layers were adopted for one reason and are now believed to work for several others. The original explanation has not survived testing; the others each have evidence, and none is the whole story:

ExplanationThe claimThe evidence
Internal covariate shift (Ioffe & Szegedy, 2015)Keeping each layer's input distribution stable speeds trainingSanturkar et al. (2018) injected random, time-varying noise with nonzero mean and non-unit variance after every BatchNorm layer: layer inputs became less stable than with no normalization at all, yet training was almost as fast as with plain BatchNorm
Smoother landscape (Santurkar et al., 2018)Normalization improves the Lipschitz constants of the loss and of its gradient, so gradients are more predictive and larger steps are safeMeasured along training trajectories; proved under assumptions for adding a single normalization layer; other normalizations they tried have the same effect
Larger learning rates (Bjorck et al., 2018)The main gain is that much larger learning rates become stable, speeding convergence and helping generalizationExperiments on CIFAR-10; but in residual networks the larger rates pay off only with large batches (De & Smith, 2020)
Automatic rate tuning (Arora, Li & Lyu, 2019)Through scale invariance, a fixed learning rate on normalized weights adapts itselfProved: gradient descent with a fixed rate (say 0.30.3) on scale-invariant weights reaches a stationary point at the T−1/2T^{-1/2} rate of a well-tuned one
Near-identity residual blocks (De & Smith, 2020)In a deep normalized ResNet each residual branch starts downscaled by about the square root of its depth, so blocks begin close to the identityDerived for the variances at initialization; SkipInit, a zero-initialized scalar on each branch, recovers the benefit without any normalization (Training Without Normalization)
Batch noise as regularization (Ioffe & Szegedy, 2015)An example's output depends on random batchmates, like noise injection, which can replace dropoutGroupNorm reaches lower training error but higher validation error than BatchNorm (Wu & He, 2018); normalizer-free networks need extra regularization to match it
Which effect dominates depends on the architecture (plain or residual), the optimizer and the batch size.
Check your understanding

Santurkar et al. (2018) injected noise after every BatchNorm layer of a network, drawn at each step from a new distribution whose mean was not zero and whose variance was not one. What did they find?

  1. Training became unstable, confirming that BatchNorm works by preventing internal covariate shift
  2. The next BatchNorm layer removed the noise, so nothing changed
  3. Training was almost as fast as with plain BatchNorm, although each layer's inputs shifted more than in a network without any normalization
  4. Training was faster than with plain BatchNorm, because the noise regularized it
Show the answer

C. Training was almost as fast as with plain BatchNorm, although each layer's inputs shifted more than in a network without any normalization

The "noisy BatchNorm" network had less stable layer-input distributions than even the unnormalized network, yet it trained almost exactly like the standard BatchNorm network and much better than the unnormalized one. Whatever BatchNorm does, it is not mainly stabilizing input distributions; Santurkar et al. pointed to a smoother loss landscape instead.

Where does the normalization go? Ioffe and Szegedy normalized pre-activations, ϕ(BN⁡(Wh))\phi(\operatorname{BN}(W\mathbf h)), which became the convolution, BatchNorm, ReLU pattern of ResNets; pre-activation ResNets reorder it to BatchNorm, ReLU, convolution inside each residual branch. Transformers face the same choice relative to the residual connection. The original transformer normalized after each addition, LN⁡(x+F(x))\operatorname{LN}(\mathbf x + F(\mathbf x)) (Post-LN); most large language models since, LLaMA among them, normalize the branch input instead, x+F(LN⁡(x))\mathbf x + F(\operatorname{LN}(\mathbf x)), with one more normalization before the output (Pre-LN). The choice matters at depth: Post-LN typically needs a learning-rate warmup to train well, Pre-LN does not, and the reason is the gradient arithmetic of the previous screen's widget applied to a transformer.

Key takeaways

  • Every normalizer standardizes a set of numbers, (z−μ)/σ2+ϵ(z - \mu)/\sqrt{\sigma^2 + \epsilon}, then applies a learned gain (and usually a shift); they differ in the set. BatchNorm pools a channel over the batch and positions, LayerNorm and RMSNorm a single example or token, GroupNorm groups of channels within an example.
  • BatchNorm uses batch statistics in training and running averages at inference; evaluating in training mode, tiny batches and per-device statistics are its classic pitfalls. LayerNorm, GroupNorm and RMSNorm compute the same function in both modes.
  • Normalization makes the loss invariant to the scale of the weights before it: gradients are orthogonal to the weights and shrink like 1/∥w∥1/\norm{\mathbf w}, so the effective learning rate is η/∥w∥2\eta/\norm{\mathbf w}^2.
  • Normalization pins the forward signal, but gradients through a deep plain stack of normalization layers can still explode; on residual branches (Pre-LN), both passes stay tame.
  • Internal covariate shift is not the explanation that survived testing. Smoother landscapes, larger stable learning rates, automatic rate tuning, near-identity residual blocks and batch noise each explain part of the benefit.

Check yourself

In the interactive lesson these are scored with your confidence, and what you miss comes back for review.

Question 1

For a convolutional activation tensor of shape (B,C,H,W)(B, C, H, W), over which axes does BatchNorm2d compute each mean and variance?

  1. (B,H,W)(B, H, W): one pair per channel
  2. (C,H,W)(C, H, W): one pair per example
  3. (H,W)(H, W): one pair per example and channel
  4. BB only: one pair per channel and position
Show the answer

A. (B,H,W)(B, H, W): one pair per channel

Each channel gets one mean and one variance from all of its values in the batch, at all positions, and one γ\gamma and β\beta. Its effective sample is B⋅H⋅WB\cdot H\cdot W numbers.

Question 2

After training, a BatchNorm layer in evaluation mode normalizes with what?

  1. The statistics of the current test batch
  2. The statistics of the last training batch
  3. The running averages of the mean and variance accumulated during training
  4. No statistics: normalization is switched off at test time
Show the answer

C. The running averages of the mean and variance accumulated during training

Evaluation mode turns BatchNorm into a fixed affine map built from the running statistics and the learned γ\gamma and β\beta, so each prediction depends on its input alone.

Question 3

Which change to a token's vector x\mathbf x leaves RMSNorm's output unchanged (ignoring ϵ\epsilon)?

  1. Adding 11 to every coordinate
  2. Multiplying x\mathbf x by 33
  3. Multiplying x\mathbf x by −1-1
  4. Doubling only its first coordinate
Show the answer

B. Multiplying x\mathbf x by 33

RMS⁡(3x)=3RMS⁡(x)\operatorname{RMS}(3\mathbf x) = 3\operatorname{RMS}(\mathbf x), so 3x/RMS⁡(3x)=x/RMS⁡(x)3\mathbf x/\operatorname{RMS}(3\mathbf x) = \mathbf x/\operatorname{RMS}(\mathbf x): positive rescalings cancel. That is the only invariance RMSNorm keeps from LayerNorm.

Question 4

A weight matrix feeds a LayerNorm, so the loss is invariant to its scale. During training its norm has doubled. With the same learning rate η\eta, how much does one gradient step now turn the weights' direction, compared with before (for the same direction)?

  1. The same
  2. Half as much
  3. A quarter as much
  4. Twice as much
Show the answer

C. A quarter as much

By ∇L(2w)=12∇L(w)\nabla L(2\mathbf w) = \tfrac12\nabla L(\mathbf w) the step is half as long, and it moves weights that are twice as long, so the angle shrinks fourfold: the effective learning rate is η/∥w∥2\eta/\norm{\mathbf w}^2.

Question 5

Which formula describes one sublayer of a Pre-LN transformer, with FF the attention or MLP sublayer?

  1. LN⁡(x+F(x))\operatorname{LN}(\mathbf x + F(\mathbf x))
  2. LN⁡(x)+F(x)\operatorname{LN}(\mathbf x) + F(\mathbf x)
  3. F(LN⁡(x))F(\operatorname{LN}(\mathbf x)), with no skip connection
  4. x+F(LN⁡(x))\mathbf x + F(\operatorname{LN}(\mathbf x))
Show the answer

D. x+F(LN⁡(x))\mathbf x + F(\operatorname{LN}(\mathbf x))

Pre-LN normalizes the input of each branch and leaves the residual stream itself unnormalized, so the identity path runs from the output back to the embeddings untouched; a final normalization precedes the output layer.

Go deeper

Further reading

  • S. Ioffe & C. Szegedy, "Batch normalization: Accelerating deep network training by reducing internal covariate shift," ICML (2015).
  • J. L. Ba, J. R. Kiros & G. E. Hinton, "Layer normalization," arXiv:1607.06450 (2016).
  • Y. Wu & K. He, "Group normalization," ECCV (2018).
  • B. Zhang & R. Sennrich, "Root mean square layer normalization," NeurIPS (2019).
  • S. Santurkar, D. Tsipras, A. Ilyas & A. Madry, "How does batch normalization help optimization?," NeurIPS (2018).