AI Logic

Normalization

Batch Normalization

Updated:

The range over which batch normalization computes the mean and variance. Top left: in a convolutional layer, the values of one channel are pooled over all samples in the mini-batch and all positions. Top right: in a fully connected layer, the values of one unit are pooled over the whole mini-batch. Bottom: the computation flow at training time (mini-batch mean and variance) and at inference time (mean and variance collected during training)

What Is Batch Normalization?

Batch Normalization is a normalization method that rescales a layer's inputs to zero mean and unit variance using the mean and variance of the values in the mini-batch, then applies a learned scale γ\gamma and shift β\beta. Ioffe and Szegedy proposed it in 2015. With it, training is less likely to diverge even with a large learning rate, and much less care is needed with weight initialization.

In a deep network, every time the weights of an earlier layer are updated, the distribution of the values that later layers receive changes. Later layers must keep readjusting to the shifted distribution, like aiming at a moving target. The paper calls this phenomenon "internal covariate shift" and reasoned that fixing the mean and variance of each layer's inputs would speed up training.

In the paper, adding batch normalization to an image classification model (Inception) and tuning it, for example by raising the learning rate, reached the accuracy of the original model in 1/14 of the training steps. Today it is a standard component of convolutional networks (CNNs), starting with ResNet.

For a quick definition of the term, see batch normalization in the glossary. This article covers the computation steps, the difference between training and inference, and how it compares with other normalization methods.

Computation Steps

Batch normalization is computed separately for each feature (a unit in a fully connected layer, a channel in a convolutional layer) in the following order (Algorithm 1 in the paper). Let the mm values in the mini-batch be x1,…,xmx_1, \dots, x_m.

  1. Compute the mini-batch mean. μB=1m∑i=1mxi\mu_\mathcal{B} = \frac{1}{m} \sum_{i=1}^{m} x_i
  2. Compute the mini-batch variance. σB2=1m∑i=1m(xi−μB)2\sigma_\mathcal{B}^2 = \frac{1}{m} \sum_{i=1}^{m} (x_i - \mu_\mathcal{B})^2
  3. Subtract the mean and divide by the standard deviation. ϵ\epsilon is a small constant that prevents division by zero. x^i=xi−μBσB2+ϵ\hat{x}_i = \frac{x_i - \mu_\mathcal{B}}{\sqrt{\sigma_\mathcal{B}^2 + \epsilon}}
  4. Apply the learned scale and shift. yi=γx^i+βy_i = \gamma \hat{x}_i + \beta

The γ\gamma and β\beta in step 4 are parameters learned together with the other weights. Normalization alone would, for example, push the inputs of a sigmoid toward 0, so only the nearly linear part of the function would be used. Because setting γ=Var[x]\gamma = \sqrt{\mathrm{Var}[x]} and β=E[x]\beta = \mathrm{E}[x] recovers the original values, normalization does not reduce the layer's representational power.

In convolutional layers, positions are pooled per channel too

The left side of the figure at the top of the article shows the convolutional case. In a convolutional layer, the values of the same feature map (channel) should be normalized the same way at every position in the image, so the values of one channel are pooled over all samples in the mini-batch and all positions to compute the mean and variance (Section 3.2 of the paper). With mm images in the mini-batch and p×qp \times q feature maps, one pair of μB\mu_\mathcal{B} and σB2\sigma_\mathcal{B}^2 is computed from m⋅p⋅qm \cdot p \cdot q values. γ\gamma and β\beta are also one pair per channel. For the fully connected layer on the right of the figure, the computation uses the mm values of one unit.

Where to place it

The paper places it after the linear transform Wu+bWu + b and before the activation function. The values of WuWu tend to have a nearly symmetric distribution, so aligning their mean and variance tends to stabilize the distribution. In this case, the effect of the bias bb is canceled by subtracting the mean, so bb is dropped and its role is taken over by β\beta.

z=g(Wu+b)⟶z=g(BN(Wu))z = g(Wu + b) \quad \longrightarrow \quad z = g\bigl(\mathrm{BN}(Wu)\bigr)

Computation at inference

During training the mini-batch mean and variance are used, but at inference the output should depend only on the input, so the mean E[x]\mathrm{E}[x] and variance Var[x]\mathrm{Var}[x] over the whole training set are used (Section 3.1 of the paper).

x^=x−E[x]Var[x]+ϵ\hat{x} = \frac{x - \mathrm{E}[x]}{\sqrt{\mathrm{Var}[x] + \epsilon}}

In the paper, E[x]\mathrm{E}[x] is the average of μB\mu_\mathcal{B} over many mini-batches, and Var[x]\mathrm{Var}[x] is the average of σB2\sigma_\mathcal{B}^2 multiplied by mm−1\frac{m}{m-1} (the unbiased variance). The paper also notes that using moving averages instead makes it possible to track inference accuracy while training. Since the mean and variance are constants at inference, batch normalization becomes a single linear transform, y=γVar[x]+ϵx+(β−γ E[x]Var[x]+ϵ)y = \frac{\gamma}{\sqrt{\mathrm{Var}[x]+\epsilon}} x + \bigl(\beta - \frac{\gamma\,\mathrm{E}[x]}{\sqrt{\mathrm{Var}[x]+\epsilon}}\bigr), which can also be folded into the weights of the preceding layer.

Why Training Becomes Faster and More Stable

The paper gives the following three reasons why batch normalization helps training.

  • The distribution of layer inputs stabilizes. In the MNIST experiment, the distribution of the inputs to the sigmoid in the last hidden layer shifted greatly in both mean and variance during training without batch normalization, but barely moved with it. Later layers are no longer thrown off by changes in the distribution.
  • Large learning rates can be used. Scaling the weights WW by any factor does not change the normalized values (BN(Wu)=BN((aW)u)\mathrm{BN}(Wu) = \mathrm{BN}((aW)u)). As a result, larger weights do not amplify the gradients; in fact, the larger the weights, the smaller the gradients with respect to them. This prevents weights from growing until training diverges (exploding gradients), which tends to happen when the learning rate is raised, as well as vanishing gradients caused by saturating activation functions.
  • It has a regularization effect. During training, the output for the same sample changes slightly depending on which other samples share its mini-batch. This jitter suppresses overfitting, and in the paper the models did not overfit even when Dropout was removed or weakened.

The explanation "it works because it reduces internal covariate shift" is the paper's hypothesis. Later, Santurkar et al. (2018) argued that stabilizing the distribution of layer inputs has little to do with it, and that the main reason is that it smooths the loss landscape and stabilizes the behavior of the gradients. Why it works is still under debate. The effects themselves (faster training, the ability to use large learning rates) have been widely confirmed.

Experimental Results

The paper compared Inception (an improved version of GoogLeNet) with and without batch normalization on ImageNet image classification. The mini-batch size was 32, and evaluation used single-crop accuracy (top-1) on the validation data.

ModelSteps to reach the original model's best accuracy of 72.2%Best accuracy
Inception (no batch normalization)31.0×10631.0 \times 10^672.2%
BN-Baseline (batch normalization added only)13.3×10613.3 \times 10^672.7%
BN-x5 (5× learning rate and other adjustments)2.1×1062.1 \times 10^673.0%
BN-x30 (30× learning rate)2.7×1062.7 \times 10^674.8%
BN-x5-Sigmoid (sigmoid activation)—69.8%

(From Figure 3 of the paper)

  • Just adding batch normalization reached the original accuracy in fewer than half the steps.
  • With adjustments such as a 5× learning rate, removing Dropout, and reducing the L2 weight regularization to one fifth, it reached the original accuracy in 1/14 of the steps. Applying the same learning-rate increase to the original model made the parameters diverge.
  • Even with sigmoids, the model trained to 69.8%. Inception with sigmoids and no batch normalization never rose above chance accuracy (1/1000).

An ensemble of six models based on BN-x30 achieved a top-5 error of 4.9% on the validation data and 4.82% on the test data, surpassing the best results at the time.

Practical Considerations

The computation differs between training and inference. PyTorch's nn.BatchNorm2d normalizes with the mini-batch mean and variance while updating the running averages (running_mean, running_var) under model.train(), and normalizes with the running averages under model.eval(). If you forget to call model.eval() before inference or validation, the output depends on the contents of the mini-batch, and inference on one example at a time breaks down badly. Conversely, if you forget to switch back to model.train() after validation, the running averages stop being updated.

Performance drops with small mini-batches. A mean and variance computed from just a few values fluctuate widely. In experiments from the Group Normalization paper (ResNet-50, ImageNet), reducing the batch size per GPU from 32 to 2 raised the error rate of batch normalization from 23.6% to 34.7%. When images are large and only 1–2 fit on a GPU, as in object detection, consider a method that does not depend on batch size, such as Group Normalization, or computing the mean and variance jointly across multiple GPUs (synchronized batch normalization).

Also keep the following points in mind.

  • With data parallelism, the mean and variance are computed per GPU. By default, even with a total batch of 256, eight GPUs yield statistics over 32 examples each. In PyTorch, replacing the layer with nn.SyncBatchNorm computes them across GPUs.
  • It works better when the samples in a mini-batch are weakly related to one another. In the paper, shuffling the training data thoroughly so that the same samples did not always land in the same mini-batch raised validation accuracy by about 1%.
  • Biases are unnecessary. The bias of a convolutional or fully connected layer right before batch normalization is canceled out, so it is fine to set bias=False.
  • When only small batches are available for fine-tuning, the running averages are often frozen. Layers in model.eval() do not update their statistics, so a common approach is to put only the batch normalization layers in evaluation mode while training the other layers.

Comparison with Other Normalization Methods

Batch normalization and the normalization methods proposed after it differ in which axes' values are pooled to compute the mean and variance. Writing an image tensor as "batch NN × channels CC × height HH × width WW", they compare as follows (Section 3.1 of the Group Normalization paper).

MethodRange pooled for mean and varianceEffect of batch sizeTraining vs. inferenceMain uses
Batch normalizationN,H,WN, H, W of one channelAffected (worse when small)Computation differsCNNs
Layer NormalizationC,H,WC, H, W of one sampleNot affectedSame computationTransformers, RNNs
Instance NormalizationH,WH, W of one channel of one sampleNot affectedSame computationImage style transfer, generative models
Group NormalizationH,WH, W of a group of channels of one sampleNot affectedSame computationCNNs with small batches, such as object detection and video

In experiments from the Group Normalization paper (ResNet-50, ImageNet, 32 images per GPU), the validation error rates were 23.6% for batch normalization, 24.1% for Group Normalization, 25.3% for Layer Normalization, and 28.4% for Instance Normalization. For image classification with sufficiently large batches, batch normalization gave the best result.

Rough guidelines for choosing:

  • CNNs where enough samples fit on one GPU (roughly 16–32 or more per GPU): batch normalization.
  • CNNs where batches must be small, for example because images are large: Group Normalization (or synchronized batch normalization).
  • Transformers, RNNs, and data with variable sequence lengths: Layer Normalization or RMSNorm.
  • To ease the small-batch problem while keeping batch normalization: Batch Renormalization. However, accuracy still drops as batches get even smaller.

PyTorch example

Show code
python
import torch
import torch.nn as nn

# Place after the conv layer and before the activation. The preceding conv's bias is canceled out, so omit it
block = nn.Sequential(
    nn.Conv2d(3, 64, kernel_size=3, padding=1, bias=False),
    nn.BatchNorm2d(64),   # num_features = number of channels. Defaults: eps=1e-5, momentum=0.1
    nn.ReLU(),
)

x = torch.randn(32, 3, 28, 28)   # [batch N, channels C, height H, width W]

# Training: normalize with the mini-batch mean and variance, and update the running averages
block.train()
y = block[1](block[0](x))
print(y.mean(dim=(0, 2, 3))[:3])   # per-channel mean is nearly 0 (since γ=1, β=0)
print(block[1].running_mean[:3])   # running average: new = (1 - momentum) * old + momentum * mini-batch mean

# Inference: normalize with running_mean and running_var collected during training (independent of the mini-batch)
block.eval()
with torch.no_grad():
    one = block(x[:1])              # even a single image is normalized on the same basis as in training

# Written exactly as Algorithm 1 in the paper (each channel pooled over N, H, W)
def batch_norm_train(x, gamma, beta, eps=1e-5):
    mu = x.mean(dim=(0, 2, 3), keepdim=True)                    # mini-batch mean μ_B
    var = x.var(dim=(0, 2, 3), unbiased=False, keepdim=True)    # mini-batch variance σ²_B
    x_hat = (x - mu) / torch.sqrt(var + eps)
    return gamma.view(1, -1, 1, 1) * x_hat + beta.view(1, -1, 1, 1)

z = torch.randn(8, 4, 5, 5)
print(torch.allclose(batch_norm_train(z, torch.ones(4), torch.zeros(4)),
                     nn.BatchNorm2d(4).train()(z), atol=1e-5))   # True

FAQ

Q. What happens if model.eval() is not called during validation?
A.

The batch normalization layers normalize with the mean and variance of the current mini-batch, just as in training, and also update their running averages with the validation data. The output then depends on how the mini-batch is composed, and when inferring one example at a time, the mean and variance are computed from that single example, so the results break down badly. Always call model.eval() before validation or inference, and call model.train() when returning to training.

Q. Should batch normalization go before or after the activation function?
A.

The paper places it after the linear transform (fully connected or convolutional) and before the activation function, because the output of the linear transform has a nearly symmetric distribution that stabilizes easily once its mean and variance are aligned. Many models, including ResNet, use this order. Some place it after, but the safe starting point is the paper's order: "convolution → batch normalization → activation function".

Q. Can Dropout and batch normalization be used together?
A.

Yes. However, batch normalization has a regularizing effect of its own, and in the paper the models did not overfit even when Dropout was removed or weakened. When using both, keep the Dropout probability on the small side and tune it while watching validation accuracy.

References

  1. S. Ioffe and C. Szegedy, "Batch Normalization: Accelerating Deep Network Training by Reducing Internal Covariate Shift," ICML, 2015.
  2. S. Santurkar, D. Tsipras, A. Ilyas, and A. Madry, "How Does Batch Normalization Help Optimization?," NeurIPS, 2018.
  3. Y. Wu and K. He, "Group Normalization," ECCV, 2018.
  4. PyTorch Documentation, "torch.nn.BatchNorm2d."