Batch Normalization
Batch norm makes each activation depend on the rest of the batch. Why training and evaluation disagree, and when to use something else.
Jump to a section
One value, two normalised outputs
Put the value 2 in a batch with 0, and batch normalization turns it into +1. Put the same value in a batch with 4, and it becomes −1. Nothing about the example changed, only the examples it was batched with. That dependence is why the layer helps during training, and it is behind most of the bugs it causes.
Batch normalization standardises each feature with statistics computed across the mini-batch, then applies a learned scale and shift. For one feature over a batch :
is a small constant for numerical stability, and and are learned per feature. The batch has mean 1 and variance 1, so 2 normalises to . The batch has mean 3 and the same variance, so 2 normalises to (ignoring , with and ).
What gamma and beta give back
After the standardising step every feature has zero batch mean and variance close to one. Forcing that on every layer would limit what the network can represent, so and let it pick its own scale and offset. Setting and undoes the normalization for fixed statistics, but no single fixed pair can undo the statistics of every batch.
Subtracting the mean also makes a bias in the preceding layer pointless. Adding to every adds to , and the two cancel. That is why convolutions followed by batch norm are usually built with bias=False; does the bias's job.
Ioffe and Szegedy introduced the layer to reduce internal covariate shift, the drift in each layer's input distribution as earlier layers train. Applied to an Inception image classifier, it reached the same accuracy with 14 times fewer training steps, and it tolerated much higher learning rates. Santurkar et al. later argued that the gain has less to do with covariate shift than with a smoother loss surface. The practical effect is the same either way: larger learning rates and less sensitivity to initialisation.
Two modes in one layer
During training the layer normalises with the current batch's statistics and also keeps running estimates of them for later, as an exponential moving average:
PyTorch's default is . This momentum is the weight on the new value, the opposite convention from optimizer momentum. A batch seen 50 steps ago keeps a weight of , so the running estimates reflect roughly the last few dozen batches.
Two variances are in play. The normalization itself divides by , the population variance of the batch. The running variance is updated with the unbiased estimate, which divides by : a factor of for a batch of 32.
In evaluation mode, with PyTorch's default track_running_stats=True, the layer uses the stored running statistics. Each example's output then depends only on that example, a batch of one works, and the value 2 maps to the same output whichever batch it arrives in. If tracking is disabled, the layer uses batch statistics in evaluation too.
In code
A BatchNorm1d for (N, C) input that follows PyTorch's defaults: population variance for the training forward pass, unbiased variance for the running estimate. Training needs at least two examples.
1import torch
2from torch import Tensor, nn
3
4
5class BatchNorm1d(nn.Module):
6 def __init__(self, num_features: int, eps: float = 1e-5, momentum: float = 0.1) -> None:
7 super().__init__()
8 self.eps, self.momentum = eps, momentum
9 self.gamma = nn.Parameter(torch.ones(num_features)) # learnable scale
10 self.beta = nn.Parameter(torch.zeros(num_features)) # learnable shift
11 self.register_buffer("running_mean", torch.zeros(num_features))
12 self.register_buffer("running_var", torch.ones(num_features))
13
14 def forward(self, x: Tensor) -> Tensor: # x: (N, num_features)
15 if self.training:
16 if x.size(0) < 2:
17 raise ValueError("Training requires at least two examples")
18 mean = x.mean(dim=0)
19 var = x.var(dim=0, unbiased=False) # biased var, as in BN
20 with torch.no_grad(): # update running stats
21 self.running_mean.mul_(1 - self.momentum).add_(self.momentum * mean)
22 unbiased_var = var * x.size(0) / (x.size(0) - 1)
23 self.running_var.mul_(1 - self.momentum).add_(self.momentum * unbiased_var)
24 else:
25 mean, var = self.running_mean, self.running_var # frozen at inference
26 x_hat = (x - mean) / torch.sqrt(var + self.eps)
27 return self.gamma * x_hat + self.beta
28
29
30bn = BatchNorm1d(16)
31out = bn(torch.randn(32, 16))
32assert out.shape == (32, 16)
33bn.eval() # switch to running stats
34assert bn(torch.randn(1, 16)).shape == (1, 16) # works for batch size 1and are parameters that the optimizer updates. The running mean and variance are buffers: saved with the model, moved with it between devices, never touched by the optimizer.
Where it goes wrong
Serving in training mode. Forget model.eval() and predictions depend on whatever else was batched with them. Every forward pass in training mode also folds the serving batch into the running statistics.
Tiny batches. With the normalised values are always and (ignoring ), whatever the inputs: the layer keeps only which example is larger. Small batches give noisy statistics that no longer resemble the fixed ones used at evaluation. Group norm was designed for this case; Wu and He report 10.6% lower ImageNet error than batch norm for ResNet-50 at a batch size of 2.
Per-device batches. Under data parallelism each GPU normalises over its own slice of the batch unless the layer synchronises statistics across devices (nn.SyncBatchNorm in PyTorch). A global batch of 256 spread over 32 GPUs gives every layer statistics from 8 examples.
Stale running statistics. The stored mean and variance describe the activations the model produced the last time it ran in training mode. After a shift in the input data, or fine-tuning with the layers frozen, they can stop matching. Running forward passes over the new data in training mode, with gradients off, re-estimates them without changing any weight.
Sources and further reading
- Ioffe and Szegedy, Batch Normalization: normalization and learned affine parameters.
- PyTorch BatchNorm1d documentation: running statistics, variance estimators, and evaluation behavior.
- Ba, Kiros and Hinton, Layer Normalization (2016): per-example normalization without batch statistics.
- Wu and He, Group Normalization (2018): channel groups for small-batch training.
- Santurkar et al., How Does Batch Normalization Help Optimization? (2018): the loss-smoothness account of why it works.
Keep going
Ask your own question about Batch Normalization, or start a guided session on it: six short pages, from the big picture to code you can run.