Normalisation
Last updated
Good starting weights keep the signal the right size at the start of training, but the weights change with every step, and the signal drifts with them. Normalisation layers fix the size during training too: they rescale each layer's inputs to mean 0 and spread 1, every time. This lesson builds batch norm, which averages over the batch, finds out why it behaves differently in training and evaluation, and meets layer norm, which averages over one example and is what transformers use.
By the end of this lesson you can
- Say what batch normalisation computes, and what γ and β are for
- Explain why batch norm behaves differently in model.train() and model.eval()
- Say which axis batch norm and layer norm each average over, and when to use each
Batch normalisation
Batch normalisation (Ioffe and Szegedy, 2015) is a layer that takes a batch, and for each feature (each column) subtracts that feature's mean over the batch and divides by its standard deviation. Then it lets the network rescale and shift the result with two learned numbers per feature, and :
In words: and are the mean and variance of this feature over the batch . Subtracting and dividing gives , with mean 0 and variance 1. The tiny (PyTorch uses ) stops a division by zero. Then and , learned like weights, start at 1 and 0, so at first nothing changes; if a different scale or centre works better, training finds it.
So every layer's inputs start each step at a sensible size, however the weights below have moved. In PyTorch, nn.BatchNorm1d(n) goes after a Linear layer with n outputs, before the activation. Here it is in the deep sigmoid network that defeated lesson 7.5, now 10 layers:
"""Batch norm: a 10-layer sigmoid network with and without it, and train mode against eval mode.""" import torch from sklearn.datasets import load_digits from torch import nn from torch.utils.data import DataLoader, TensorDataset X, y = load_digits(return_X_y=True) data = TensorDataset(torch.tensor(X / 16, dtype=torch.float32), torch.tensor(y)) def deep(norm, depth=10, width=64): layers, n_in = [], 64 for _ in range(depth - 1): layers += [nn.Linear(n_in, width)] + ([nn.BatchNorm1d(width)] if norm else []) + [nn.Sigmoid()] n_in = width return nn.Sequential(*layers, nn.Linear(width, 10)) for norm in (False, True): torch.manual_seed(0) model = deep(norm) optimizer = torch.optim.SGD(model.parameters(), lr=0.1, momentum=0.9) for epoch in range(10): model.train() for xb, yb in DataLoader(data, batch_size=32, shuffle=True): loss = nn.functional.cross_entropy(model(xb), yb) optimizer.zero_grad() loss.backward() optimizer.step() model.eval() with torch.no_grad(): accuracy = (model(data.tensors[0]).argmax(dim=1) == data.tensors[1]).float().mean().item() print(f"{'with' if norm else 'without':7} batch norm: accuracy after 10 epochs {accuracy:.3f}") # the last model has batch norm: compare its two modes on the same four images bn = model[1] print("running mean of the first batch norm's first 3 units:", [round(v, 3) for v in bn.running_mean[:3].tolist()]) x = data.tensors[0][:4] with torch.no_grad(): model.train() a = model(x)[0, :3] model.eval() b = model(x)[0, :3] print("first image, 3 logits, train mode:", [round(v, 2) for v in a.tolist()]) print("first image, 3 logits, eval mode: ", [round(v, 2) for v in b.tolist()])
(.venv) $ python batchnorm.py without batch norm: accuracy after 10 epochs 0.101 with batch norm: accuracy after 10 epochs 0.974 running mean of the first batch norm's first 3 units: [-0.721, -0.13, -0.103] first image, 3 logits, train mode: [8.61, -4.78, -3.18] first image, 3 logits, eval mode: [8.08, -3.94, -0.67]
Without batch norm, 10.1%: always the same answer. With it, 97.4%, from the same network, optimiser and 10 epochs. Each sigmoid now gets inputs centred on 0, its steepest part, instead of drifting out to where it's flat. Batch norm also rescales the gradients on the way back by , which keeps them from fading layer by layer.
One small saving: the shift does the job of the Linear layer's bias, so before batch norm you can write nn.Linear(n_in, n, bias=False).
Train and eval behave differently
Batch statistics need a batch. When the trained model classifies one image, there's no batch to average over, and an answer shouldn't depend on which other images happened to come with it. So batch norm keeps running averages during training:
and the same for the variance. In words: after every training batch, move the running mean a tenth of the way towards this batch's mean. (PyTorch calls the 0.1 momentum, a different use of the word from lesson 7.3.) After many batches it's an average over the whole training set. The script printed the first three: −0.721, −0.13 and −0.103.
model.train() uses the batch's own statistics and updates the running averages; model.eval() uses the running averages and changes nothing. The script's last lines run the same 4 images through the trained model both ways. For the first image, the first three outputs (the scores for 0, 1 and 2) are:
| mode | score for 0 | score for 1 | score for 2 |
|---|---|---|---|
model.train(), this batch of 4 | 8.61 | −4.78 | −3.18 |
model.eval(), running averages | 8.08 | −3.94 | −0.67 |
Same weights, same image, different numbers. In training mode the image's scores depend on the other 3 images; the score for 2 differs by 2.5. Lesson 7.2's habit now matters: model.eval() before measuring, model.train() before training again. Forget it, and validation accuracy depends on the batch size you happen to use.
Layer normalisation
Layer normalisation (Ba, Kiros and Hinton, 2016) uses the same formula along the other axis: for each example, the mean and standard deviation over its own features. Nothing depends on the other examples in the batch, so it works the same in training and evaluation, and with a batch of any size, even 1.
This script normalises one small batch both ways and checks which averages come out as 0:
"""Batch norm averages each feature over the batch; layer norm averages each example over its features.""" import torch from torch import nn torch.manual_seed(0) x = torch.randn(4, 6) * 3 + 5 # a batch of 4 examples (rows), 6 features (columns) b = nn.BatchNorm1d(6)(x) # a new layer is in training mode: it uses this batch's statistics l = nn.LayerNorm(6)(x) def show(title, t): print(title) for row in t.tolist(): print(" " + " ".join(f"{v:6.2f}" for v in row)) show("x:", x) show("after batch norm:", b.detach()) show("after layer norm:", l.detach()) print("batch norm, mean of each feature (column):", [round(v, 3) + 0.0 for v in b.mean(dim=0).tolist()]) print("layer norm, mean of each example (row): ", [round(v, 3) + 0.0 for v in l.mean(dim=1).tolist()]) print("layer norm, std of each example (row): ", [round(v, 3) for v in l.std(dim=1, unbiased=False).tolist()])
(.venv) $ python layernorm.py x: 1.62 1.54 4.25 3.70 7.55 7.08 4.05 -1.35 6.40 4.53 9.33 5.80 5.50 7.62 4.57 4.67 7.80 8.78 11.01 5.16 6.85 3.76 2.48 -1.95 after batch norm: -1.14 -0.50 -1.13 -1.06 0.29 0.52 -0.43 -1.34 0.79 0.83 0.99 0.21 -0.01 1.28 -0.84 1.15 0.39 0.94 1.59 0.56 1.18 -0.92 -1.67 -1.67 after layer norm: -1.13 -1.16 -0.02 -0.25 1.38 1.18 -0.23 -1.90 0.50 -0.08 1.41 0.31 -0.60 0.69 -1.17 -1.11 0.80 1.39 1.63 0.15 0.58 -0.20 -0.52 -1.64 batch norm, mean of each feature (column): [0.0, 0.0, 0.0, 0.0, 0.0, 0.0] layer norm, mean of each example (row): [0.0, 0.0, 0.0, 0.0] layer norm, std of each example (row): [1.0, 1.0, 1.0, 1.0]
After batch norm, each column has mean 0; after layer norm, each row does, with standard deviation 1. Pick a method in the figure to see which numbers are averaged together:
Feature 1, over the 4 examples: before normalising, mean 5.54 and standard deviation 3.45. Each of these numbers becomes (value − 5.54) ÷ 3.45, so the highlighted group ends up with mean 0 and standard deviation 1.
Which to use:
- Batch norm for networks of images (Stage 8's convolutional networks), trained with batches of 32 or more. It's the classic choice there.
- Layer norm when batches are small or examples differ in length, as sentences do. Every transformer (Stage 10) has a layer norm in every block.
Wrong way: batch norm with a batch of one
A model with batch norm, still in training mode, gets one example:
"""The wrong way: batch norm, in training mode, with a batch of one example.""" import torch from torch import nn model = nn.Sequential(nn.Linear(64, 32), nn.BatchNorm1d(32), nn.ReLU(), nn.Linear(32, 10)) model.train() x = torch.randn(1, 64) # one example print(model(x))
(.venv) $ python batch_of_one.py ValueError: Expected more than 1 value per channel when training, got input size torch.Size([1, 32])
With a single example, each feature's batch mean is the example itself, so and the variance is 0: every output of the batch norm layer would be just , whatever the input. PyTorch refuses rather than return that.
You meet this in two ways:
- Predicting one example with a model left in training mode. Call
model.eval()first; then the running averages are used, and any batch size works. - A last batch of one during training. 1,797 digits in batches of 32 leaves a last batch of 5, which is fine; but a dataset of 1,793 would leave a last batch of 1 and crash at the end of the first epoch.
DataLoader(..., drop_last=True)skips the short last batch.
Batches of 2 or 3 don't crash, but their statistics are so noisy that batch norm works badly. If memory forces tiny batches, use layer norm.
Check what you learned
Sources
Every example on this page was run with Python 3.14, and its output and error messages are copied from it. These pages cover the same ground in more depth.
- Ioffe and Szegedy, Batch Normalization, 2015: the batch norm transform, γ and β, and the running averages used at inference
- Ba, Kiros and Hinton, Layer Normalization, 2016: normalising over the features of each example, independent of the batch
- PyTorch: torch.nn.BatchNorm1d: momentum 0.1 for the running averages, and training against evaluation mode
- PyTorch: torch.nn.LayerNorm: statistics over the last dimensions of each example