P4.12 showed that the size of the starting weights decides what happens to a signal in a deep network: too small and it vanishes, too large and it explodes, and only a rule such as He initialization keeps it steady, and only at the start of training.
There is another way to keep the scale steady: measure it and fix it at every layer. After each linear layer, subtract the mean of the numbers and divide by their spread. Whatever the weights did, the next layer receives numbers of a standard size. On the same kind of ten-layer ReLU network (the first code cell below), the standard deviation of the last layer’s output is:
- Without normalization, weights with standard deviation give , and with standard deviation they give .
- With normalization after every linear layer, every weight scale from to gives about (BatchNorm) or (LayerNorm).
That is a normalization layer. This lesson explains the recipe, and then the five common versions: BatchNorm, LayerNorm, GroupNorm, InstanceNorm and RMSNorm. They share one recipe and differ in a single choice, which numbers are standardized together.
The recipe: standardize, then rescale
You met the operation in P1.D2 and P1.D4: standardizing subtracts the mean and divides by the standard deviation. For the seven values of P1.D2, dividing by (with ) gave , , , , , , . A normalization layer divides by (with ), which gives , , , , , , .
For a set of numbers that share one statistic, a normalization layer computes
Three details:
- is a tiny constant, in PyTorch’s BatchNorm, LayerNorm and GroupNorm (
nn.RMSNormdefaults to the machine epsilon of the data type, about in float32). If all the numbers are equal, , and without the division would fail. With it, the output is , not NaN. - and are learned parameters, one pair per feature (or channel). Without them, every layer would be forced to output mean and variance , which may be the wrong thing for the next layer. With them, the layer can choose any mean and spread, including the original ones: setting and gives back . Training decides.
- Gradients flow through and . They are computed from the numbers, so they are part of the computation graph (P4.8).
A hand-worked example, four ways
Take a batch of examples with features each. This is the matrix of pre-activations that a linear layer produces, in the row-batch convention of P4.5: one row per example, one column per feature.
| ex. | ||||
|---|---|---|---|---|
| 1 | 2 | 10 | 1 | 12 |
| 2 | 4 | 20 | 3 | 4 |
| 3 | 6 | 30 | 3 | 8 |
| 4 | 8 | 40 | 1 | 0 |
Features have different units, as they do inside a network: the second feature is five times the first.
BatchNorm: one statistic per column. Each feature is standardized across the 4 examples. Feature 1 is , which is the example of P1.D4: mean , variance , output . The four columns have means and variances . In NumPy the axis to average over is axis=0, and keepdims=True keeps the result shaped so that it broadcasts back over the rows (P1.B14).
- Example 1: −1.342, −1.342, −1.000, 1.342
- Example 2: −0.447, −0.447, 1.000, −0.447
- Example 3: 0.447, 0.447, 1.000, 0.447
- Example 4: 1.342, 1.342, −1.000, −1.342
Features 1 and 2 are now identical: standardizing removed the unit of each feature, whatever its scale. Every column now has mean and variance (nearly) .
LayerNorm: one statistic per row. Each example is standardized across its 4 features (axis=1). Example 1 is with mean and variance . The four rows have means and variances .
- Example 1: −0.883, 0.779, −1.090, 1.194
- Example 2: −0.529, 1.729, −0.670, −0.529
- Example 3: −0.538, 1.708, −0.819, −0.351
- Example 4: −0.260, 1.701, −0.690, −0.751
Now each row has mean and variance (nearly) , but the columns do not: feature 2 is the biggest number in examples 2, 3 and 4, and its column now averages . LayerNorm does not look at the other examples at all, so row 1 would be the same in a batch of one.
GroupNorm with 2 groups: one statistic per row and half-row. Split the 4 features into groups and , and standardize each group of each example. Example 1 has group means and and variances and . A group of only two numbers always becomes and , so example 1 gives . Real groups hold many channels and positions, so they keep much more information.
RMSNorm: one number per row, and no mean. Divide each example by its root mean square, , without subtracting anything. Example 1 has , so the divisor is and the row becomes . It is not centred: the mean of the output row is , but the mean of its squares is .
Running the PyTorch layers on this matrix (the first static block below) reproduces these numbers.
Which numbers share a statistic
Real tensors have more than two axes. An image batch has shape : examples, channels, and positions. A batch of token sequences has shape : sequences, tokens, features per token. In both, the three kinds of axis are the same: examples, channels (features) and positions (pixels or tokens). The widget draws a tensor with examples, channels and positions as a cube, so you can see which cells are grouped.
What to see, for this tensor:
- BatchNorm: the box is one channel across all examples and positions: statistics, each over numbers.
- LayerNorm: the box is one example and one position across the channels: statistics, each over numbers. This is the transformer form, where each token’s feature vector is normalized on its own.
- GroupNorm: one example, a group of channels, all positions. With 2 groups: statistics over numbers. With 1 group: statistics over , which is LayerNorm over channels and positions, the original image form.
- InstanceNorm: one example and one channel: statistics over numbers. It is GroupNorm with one channel per group (4 groups here), and was first used for image style transfer.
- RMSNorm: the same boxes as LayerNorm, but the mean is not removed.
The same rules for an image batch
For a batch of shape , the number of statistics and the size of each set:
| Layer | Statistics | Numbers each |
|---|---|---|
| BatchNorm | ||
| LayerNorm (image form) | ||
| GroupNorm, groups | ||
| InstanceNorm |
The learned and are one pair per channel (or one per element of the normalized shape in LayerNorm), not per statistic.
What the layers do not do
None of these layers removes the correlations between features. They standardize with one mean and one variance per set, not with a covariance matrix. In the BatchNorm example, features 1 and 2 are perfectly correlated before and still perfectly correlated after. Removing correlations is whitening (P1.D7), and BatchNorm standardizes each feature separately using batch statistics, which is not whitening.
BatchNorm in detail
BatchNorm (Ioffe and Szegedy, ICML 2015) standardizes each feature using the other examples in the batch. For a layer output of shape :
For images the sum also runs over the positions, so there is one pair per channel.
Training and inference differ. In training the statistics come from the current batch. At inference you may predict one example at a time, and a single example has no useful batch statistics (with one value, the variance is ). So BatchNorm also keeps running averages of the batch means and variances during training, and uses those fixed numbers at inference. The output for an example then does not depend on the other examples.
PyTorch updates the running averages after every training batch with a parameter called momentum, whose default is :
Note that this is the reverse of the usual meaning of momentum (P4.13), where a value such as is the weight kept on the old value. In PyTorch’s BatchNorm, is the weight of the new batch, so keeps percent of the old average. The running mean starts at and the running variance at . After one batch of a feature with true mean , the running mean is only (the PyTorch run below shows for feature 1). It takes a few dozen batches to get close: the second code cell shows after 1 batch, after 10 and after 50, for a feature with true mean . One more detail: PyTorch normalizes a training batch with the variance that divides by , but stores the unbiased variance (dividing by ) in the running average. The run below shows a running variance of for feature 1, which is .
Why model.eval() matters. model.train() and model.eval() (P2.7) switch BatchNorm between the two behaviours. If you forget model.eval() when predicting, each prediction depends on the other examples in the test batch (and the running averages are updated by test data). In training mode, PyTorch’s BatchNorm refuses a batch with a single value per channel.
Train and inference are close, not equal. In the PyTorch run below, feature 1 gives for the first example in training mode and in eval mode after the running averages have settled: the divisor uses the batch variance in one case and the stored unbiased variance in the other. With realistic batch sizes the two are much closer.
Batch size. BatchNorm’s statistics are estimated from the batch, and a small batch estimates them badly. The standard deviation of a batch mean of values with spread is (P1.D8): for , for , for and for (second code cell). With the “mean” is mostly noise, and every example is standardized with a different, noisy yardstick. This is why BatchNorm networks degrade at very small batch sizes, and why GroupNorm was proposed for them. The noise is also a mild regularizer, a side effect that some people value.
Gradient accumulation. P4.15 showed that accumulating the gradients of 4 micro-batches of 64 matches one batch of 256 for ordinary layers. BatchNorm breaks this: each micro-batch is standardized with its own 64 examples, not with all 256. In the second code cell, the first of 256 values becomes with batch-256 statistics and with 64-example statistics, and the largest difference over the 256 values is . The result is not the big-batch result, however carefully you divide the loss.
LayerNorm
LayerNorm (Ba, Kiros and Hinton, 2016) standardizes one example at a time, over its features. It has no batch in it: the output for an example is the same whether the batch holds 1 or 1000 examples, and the layer computes the same thing in training and in inference. The paper’s experiments are mostly on recurrent networks, where batch statistics are awkward because sequences have different lengths.
In a transformer (P7.7) each token is a vector of features, and LayerNorm standardizes each token’s vector separately, which is the LayerNorm box of the widget. and have one entry per feature. This is why transformers use LayerNorm (or RMSNorm), and not BatchNorm: the statistics do not depend on the other sequences in the batch, on the length of the sequence, or on padding. In the cube, this form has statistics. For images, the original form averages over together, which the cube shows as GroupNorm with one group.
GroupNorm and InstanceNorm
GroupNorm (Wu and He, 2018) was designed for vision with small batches. It splits the channels into groups and standardizes each group of each example over its channels and positions. Like LayerNorm, it uses no other examples, so its accuracy stays much steadier at small batch sizes, and it computes the same thing in training and inference. The two extremes are known layers: is LayerNorm over , and (one channel per group) is InstanceNorm (Ulyanov, Vedaldi and Lempitsky, 2016), which was introduced for fast image stylization. The widget’s “4 groups” is exactly InstanceNorm. A common choice for is 32, when allows it; the best value depends on the network.
RMSNorm
RMSNorm (Zhang and Sennrich, NeurIPS 2019) asks whether the mean subtraction in LayerNorm is needed. It drops it. For a vector with entries,
It has no , and it is cheaper because it computes one statistic and not two. It is also the “divide by the length” of P1.B4 with one change: the RMS is , so RMSNorm divides by its length and multiplies by (ignoring ), so the result always has length . For the length is , the RMS is , and the output is with length .
The LLaMA paper (Touvron et al., 2023) states that it uses RMSNorm on the input of each transformer sub-layer, and P10.C1 shows it in a modern decoder block. Check a model’s published architecture before assuming it uses RMSNorm: closed models do not publish theirs.
Where does the layer go?
Conventions vary, and none is a law. The original BatchNorm paper normalizes the pre-activation (linear, BatchNorm, ReLU), a common order in convolutional networks, and some architectures normalize after the activation instead. Because normalization subtracts the mean of each feature, the bias of the linear layer before it has no effect, so such layers often have no bias (a Go-deeper box shows why).
In a transformer block, the original transformer (Vaswani et al., 2017) normalizes after adding each sub-layer’s output to its input, called post-norm. GPT-2 moved the LayerNorm to the input of each sub-block, called pre-norm, and many large models since then do the same. P7.7 compares them.
What it does for training
The ten-layer experiment of the opening shows the first effect: the scale of the signal no longer depends on the scale of the weights. P4.12 gave rules for choosing the starting weights, and these layers make training much less sensitive to the choice (not independent of it: the learning rate, the first steps and the choice of still matter).
A second effect is on how fast the network trains. A short training run on a toy problem shows it (the second static block below, with 5 seeds each): 8 hidden layers of 32 ReLU units, 200 full-batch steps of plain gradient descent, and the accuracy on the 512 training points.
At learning rates , and the accuracy was: without normalization , , ; with BatchNorm , , ; with LayerNorm , , .
This is one small problem, not a benchmark. It shows that the unnormalized network, at a small learning rate, had not learned anything after 200 steps ( is chance), while BatchNorm reached at every learning rate tried. The run does not test whether normalization lets you use larger learning rates: the unnormalized network never diverged here. LayerNorm helped at the small rates, and at it was no better than no normalization ( against , with the seeds overlapping).
Why it helps is partly debated. The BatchNorm paper explained the benefit as reducing internal covariate shift: the distribution of each layer’s inputs keeps changing as the earlier layers learn, and normalizing keeps it steady. A later study (Santurkar et al., NeurIPS 2018) found that stabilizing the input distributions contributes little, and argued that the main effect is a smoother loss landscape, with gradients that predict better what happens after a step. Other explanations exist, and “it reduces internal covariate shift” is best treated as the original motivation, not a settled explanation.
Depth: three ways to see it
Intuition
A normalization layer is a thermostat between layers. The weights before it may push the numbers up or down, but the thermostat reads the temperature of a group of numbers and brings it back to a standard. The choice among BatchNorm, LayerNorm and the others is the choice of which numbers are in the room whose temperature is read. The analogy breaks in one place: a thermostat only holds a fixed target, whereas and let the network move the target.
Math
Scaling the numbers of a set by leaves unchanged up to , so the layer is scale-invariant: that is why the weight scale of the layer before it stops mattering. Adding a constant to the set also leaves unchanged for the layers that subtract the mean, but not for RMSNorm.
Code
import torch
import torch.nn as nn
X = torch.tensor([[2., 10., 1., 12.],
[4., 20., 3., 4.],
[6., 30., 3., 8.],
[8., 40., 1., 0.]])
bn, ln = nn.BatchNorm1d(4), nn.LayerNorm(4)
gn, rn = nn.GroupNorm(2, 4), nn.RMSNorm(4)
print("parameters:", [sum(p.numel() for p in m.parameters())
for m in (bn, ln, gn, rn)])
print("BN col 0:", bn(X)[:, 0].detach().numpy().round(3))
print("LN row 0:", ln(X)[0].detach().numpy().round(3))
print("GN row 0:", gn(X)[0].detach().numpy().round(3))
print("RMS row 0:", rn(X)[0].detach().numpy().round(3))
print("running_mean after 1 batch:", bn.running_mean.numpy().round(2))
for _ in range(100):
bn(X) # more batches, same data
print("running_mean after 101 :", bn.running_mean.numpy().round(2))
print("running_var after 101 :", bn.running_var.numpy().round(2))
bn.eval()
print("BN eval col 0:", bn(X)[:, 0].detach().numpy().round(3))
print("eval, one example:", tuple(bn(X[:1]).shape))
bn.train()
try:
bn(X[:1])
except ValueError as e:
print("train, one example:", str(e)[:24], "...")Output from a local run with PyTorch 2.9.1:
parameters: [8, 8, 8, 4]
BN col 0: [-1.342 -0.447 0.447 1.342]
LN row 0: [-0.883 0.779 -1.09 1.194]
GN row 0: [-1. 1. -1. 1.]
RMS row 0: [0.253 1.267 0.127 1.521]
running_mean after 1 batch: [0.5 2.5 0.2 0.6]
running_mean after 101 : [ 5. 25. 2. 6.]
running_var after 101 : [ 6.67 166.66 1.33 26.67]
BN eval col 0: [-1.162 -0.387 0.387 1.162]
eval, one example: (1, 4)
train, one example: Expected more than 1 val ...The parameter counts are and () for BatchNorm, LayerNorm and GroupNorm, and only () for RMSNorm. The running mean and variance of BatchNorm are stored in the layer but are buffers, not parameters: the optimizer does not train them. They match the hand-worked tables above.
A short training comparison (this takes a few seconds on a CPU):
import torch
import torch.nn as nn
from sklearn.datasets import make_moons
X, y = make_moons(512, noise=0.15, random_state=0)
X, y = torch.tensor(X).float(), torch.tensor(y)
def make(norm, depth=8, width=32):
layers, d = [], 2
for _ in range(depth):
layers.append(nn.Linear(d, width)); d = width
if norm == "batch": layers.append(nn.BatchNorm1d(width))
if norm == "layer": layers.append(nn.LayerNorm(width))
layers.append(nn.ReLU())
return nn.Sequential(*layers, nn.Linear(d, 2))
def accuracy(norm, lr, seed):
torch.manual_seed(seed)
model = make(norm)
opt = torch.optim.SGD(model.parameters(), lr=lr)
for _ in range(200): # full-batch steps
opt.zero_grad()
nn.functional.cross_entropy(model(X), y).backward()
opt.step()
model.eval()
return (model(X).argmax(1) == y).float().mean().item()
for lr in (0.01, 0.1, 0.5):
row = {n: sum(accuracy(n, lr, s) for s in range(5)) / 5
for n in ("none", "batch", "layer")}
print(f"lr {lr:<4} none {row['none']:.2f}"
f" BN {row['batch']:.2f} LN {row['layer']:.2f}")lr 0.01 none 0.50 BN 1.00 LN 0.99
lr 0.1 none 0.75 BN 1.00 LN 0.95
lr 0.5 none 0.85 BN 1.00 LN 0.80The numbers are the accuracy on the 512 training points, averaged over 5 seeds. They need scikit-learn and PyTorch, so they are not run in the browser.
Go deeper Why a bias before BatchNorm does nothing
A linear layer computes . For one feature across the batch, adding the constant to every value shifts the batch mean by and leaves the variance alone, so the subtraction of the mean removes it: is the same with or without . The shift is then supplied by . For this reason layers directly followed by BatchNorm are often built without a bias, which saves a few parameters. This argument needs every number of the set to be shifted by the same constant. In LayerNorm over features the biases differ from feature to feature, so there the bias is not removed.
Go deeper Folding BatchNorm into the layer before it at inference
In inference mode BatchNorm uses fixed numbers , , and , so it is an affine map of each feature. A linear layer followed by such a map is again a linear layer: scale each row of by and adjust the bias to . Deployment tools often fold BatchNorm into the previous layer this way, which removes the layer at no cost in accuracy. LayerNorm cannot be folded, because its statistics depend on each input.
Go deeper Normalization, weight scale and the effective learning rate
If a weight matrix is followed by a layer that is scale-invariant, multiplying the weights by does not change the output. Then the length of the weights does not matter to the loss, only their direction, and the gradient with respect to the weights is perpendicular to the weights and shrinks like . Gradient steps then increase the length of the weights, which lowers the effective learning rate over time. This is one of the explanations for how normalization interacts with the learning rate and with weight decay (P4.17). It is a result about the scale-invariant case, and real networks only approximate it.
Try it in Python
The first cell is the experiment of the opening: 10 ReLU layers of 64 units, 128 made-up inputs, the same weights with and without normalization, and four weight scales. It prints the standard deviation of the last layer’s output. (Its random numbers are not those of the P4.12 widget, so the figures differ slightly from that lesson’s.) The second cell shows the running averages with the PyTorch momentum convention, how noisy a batch mean is for small batches, and what micro-batches do to BatchNorm.
Runs real Python in your browser. First run downloads about 9 MB (once; your browser keeps it).
Running the cell gives, for weight standard deviations , , and : without normalization , , and , and with BatchNorm or LayerNorm about to for every scale. The value is the standard deviation of a ReLU applied to standardized numbers: in theory.
Runs real Python in your browser. First run downloads about 9 MB (once; your browser keeps it).
The running mean reaches , and after 1, 10 and 50 batches, and the running variance (true value ) is , and . The batch mean has standard deviation , , and for , , , . The standardized first value is with 256 values and with 64.
Common mistakes
Quiz
Check your understanding
A linear layer produces of shape : 32 examples, 64 features. BatchNorm takes its mean over which axis, and how many means does it compute?
BatchNorm standardizes each feature using the other examples in the batch, so it averages down each column and gets one mean per feature, 64 of them. Averaging over the 64 features of each example, giving 32 means, is LayerNorm. One mean for the whole matrix would mix features with different units. Averaging over the examples cannot give a mean for each example, because the examples are what is averaged.
Why does BatchNorm keep running averages of the means and variances during training?
Inference needs statistics that do not depend on which examples happen to be in the batch, including a batch of one, so the layer uses the stored running averages. The learned parameters are and , and the running averages are buffers that the optimizer does not touch. Training still divides by the batch standard deviation. The statistics of the raw numbers are not and : it is the output that has those values.
In PyTorch's BatchNorm with the default
momentum=0.1, a feature has running mean and then two batches in a row each have mean . What is the running mean after the second batch?The update is . After one batch it is and after the second it is . The value would add twice without letting the earlier value decay. The values and would follow if the new batch got the weight , which is the opposite of PyTorch's convention.
Why do transformers normalize with LayerNorm or RMSNorm and not with BatchNorm?
LayerNorm and RMSNorm use only the numbers of one token vector, so the result does not depend on the other sequences, on the batch size or on padding, and training and inference compute the same thing. LayerNorm has learned parameters, and . BatchNorm has no limit of 64 features. Standardizing each feature across the batch is exactly what BatchNorm does, not LayerNorm.
What does RMSNorm change compared with LayerNorm?
RMSNorm only rescales, dividing each vector by its root mean square, which makes it cheaper than LayerNorm, and it usually has no . It still works on one vector at a time, so it does not use the batch. The root mean square is not the largest absolute value, and nothing is subtracted, so the output keeps its mean.
Exercises
- Apply LayerNorm (ignore ) to the single example .
Show answer
The mean is and the variance is , so the output is , the same numbers as in P1.D4. In the lesson’s example this was a column (BatchNorm); here it is a row (LayerNorm). The arithmetic is the same, only the axis differs. - Apply RMSNorm (ignore ) to . What is the length of the result?
Show answer
The mean of squares is , so the RMS is , and the result is . Its length is , which is with . - A batch of images has shape : 8 examples, 6 channels, positions. How many statistics does each layer compute, and over how many numbers each: BatchNorm, LayerNorm over , GroupNorm with 2 groups, InstanceNorm?
Show answer
BatchNorm: statistics, each over numbers. LayerNorm: statistics, each over . GroupNorm with 2 groups: statistics, each over . InstanceNorm: statistics, each over . - A BatchNorm layer is applied to 64 features. How many learnable parameters does it have, and how many numbers does it store that are not learned?
Show answer
and give learnable parameters. It also stores a running mean and a running variance, numbers, which are buffers and not trained (PyTorch also keeps a counter of batches). - After normalizing feature 4 of the lesson’s example (values , mean , variance ), what and restore the original values?
Show answer
, so . Setting and gives back . This is why and let the layer undo the normalization.
Next: P4.20 covers residual connections, the other idea that lets very deep networks train, and P7.7 puts LayerNorm, attention and a residual path together in one transformer block. P4.16 treats the vanishing and exploding gradients that normalization helps to prevent, and P10.C1 shows RMSNorm in a modern decoder block.