Batch Normalization’s Hidden Costs
Batch-size dependence, train–test mismatch, gradient explosion at initialization and the fixes.
Batch normalization made deep convolutional networks easy to train, and quietly made every example's output depend on its batchmates. That one design choice explains a whole catalogue of problems: accuracy that collapses at small batch sizes, models that compute one function in training and another at test time, contrastive learners that cheat, and, in deep networks without skip connections, gradients that provably explode at initialization. This lesson works through each cost and its fixes.
What you’ll learn
- Quantify the noise in batch statistics, and explain how the normalization batch size trades training noise and regularization against train–test inconsistency.
- Derive Batch Renormalization's correction, and choose between it, Ghost BatchNorm, synchronized BatchNorm, PreciseBN, FrozenBN and GroupNorm.
- Explain how batch statistics leak information between examples, in contrastive learning and in sequence models, and why transformers normalize each token on its own.
- State the mean-field theorem that batch normalization makes gradients explode with depth at initialization, with its conditions and rates, and the ways around it.
- Use test-time re-estimation of batch statistics under distribution shift, knowing what it requires.
Your output depends on your batchmates
Every other layer in a network maps one example's input to that example's output. In training mode, batch normalization does not: the output for example is , a function of the whole mini-batch. Four consequences follow, and the rest of this lesson takes them one at a time:
- Noise. The same input gives different outputs in different batches, because and are random estimates.
- Two functions. The network trained on batch statistics is evaluated with running statistics, a different function.
- Coupling. One example's loss depends on the others, and the backward pass mixes gradients across the batch (Deriving Backward Passes showed that it projects along the batch axis). Per-example gradients are no longer defined on their own, and the batch can carry information the task should not see.
- Gradient explosion. In deep plain networks, the coupling makes gradients grow exponentially with depth at initialization.
Start with the noise. For independent values with standard deviation , the batch mean has standard deviation , and for Gaussian values the sample variance has relative standard deviation . At the mean wanders by half a standard deviation from batch to batch, so the same input can land anywhere in a wide band after normalization.
How many independent examples must a normalization batch contain for the standard deviation of its batch mean to fall to 5% of ?
Show the answer
400
gives , so . Precise statistics need hundreds of examples, far more than the one or two images per device of a large detection model; pooling over the positions of one image helps less than its pixel count suggests, because those positions are strongly correlated.
| Images per GPU | 32 | 16 | 8 | 4 | 2 |
|---|---|---|---|---|---|
| BatchNorm | 23.6 | 23.7 | 24.8 | 27.3 | 34.7 |
| GroupNorm | 24.1 | 24.2 | 24.0 | 24.2 | 24.1 |
Wu and Johnson (2021) separated the effects by training ResNet-50 with a fixed total batch of 1,024 but normalization batches from 2 to 1,024, and evaluating three ways. Small normalization batches add training noise (higher training error), shrink the generalization gap (the noise regularizes), and create a large train–test inconsistency: the population statistics used at test time differ from anything the network saw in training. At 2 or 4 examples per normalization batch, the inconsistency was a major cause of the poor accuracy: evaluated with mini-batch statistics of the same size, the same model did decently. The best validation error came from normalization batches of 32 to 128, where noise and inconsistency regularize without hurting.
Repairing the batch
Batch Renormalization (Ioffe, 2017) attacks the train–test gap directly. Keep moving averages and during training as usual, but use them in the forward pass too, through a per-unit correction of the batch-normalized value:
When the clipping is inactive, substitute and : the batch statistics cancel and the training-time output is exactly the inference-time output.
Yet the gradient still flows through and as in BatchNorm, since and are frozen. If and , then and : the correction is the identity on average and only removes the batch-to-batch fluctuation. With microbatches of 4 examples, Batch Renormalization reached 76.5% ImageNet accuracy against 74.2% for BatchNorm, still below either method at 32 examples.
Think first Why not let the gradient flow through and as well?
Then the layer would simply be with the moving averages, in the backward pass as well as the forward pass: normalization by statistics computed outside the gradient step. Ioffe and Szegedy (2015) found that this blows up. The gradient ignores how the statistics depend on the weights, so it keeps pushing in directions the normalization later cancels; in their example a bias grows without bound while the loss stays fixed. Freezing and keeps BatchNorm's gradient, which projects out exactly the changes the normalization would cancel, while the forward pass already matches inference.
| Fix | What it changes | Typical use |
|---|---|---|
| Batch Renormalization (Ioffe, 2017) | Corrects batch statistics toward the moving averages, as above | small or non-i.i.d. batches |
| Ghost BatchNorm (Hoffer, Hubara & Soudry, 2017) | Computes statistics over small virtual sub-batches (128 examples in their experiments) of a large batch | large-batch training, to keep the regularizing noise |
| Synchronized BatchNorm (Peng et al., 2018) | Computes statistics across all devices | detection and segmentation with 1 or 2 images per device |
| PreciseBN (Wu & Johnson, 2021) | Recomputes population statistics with the final weights on to examples, all weighted equally, instead of trusting the moving average | large learning rates and batches, where the average lags the weights |
| FrozenBN | Freezes pretrained statistics: a fixed affine map | fine-tuning with tiny batches |
| GroupNorm (Wu & He, 2018) | Removes the batch from the statistics altogether | any batch size, at some loss of regularization |
import torch
import torch.nn as nn
BN_TYPES = (nn.BatchNorm1d, nn.BatchNorm2d, nn.BatchNorm3d)
@torch.no_grad()
def recompute_bn_stats(model, loader, num_batches=100):
"""Replace the running averages by statistics of the final weights (PreciseBN-style)."""
bns = [m for m in model.modules() if isinstance(m, BN_TYPES)]
saved = [bn.momentum for bn in bns]
for bn in bns:
bn.reset_running_stats() # running mean 0, running variance 1, counter 0
bn.momentum = None # None: equal-weight average over the batches below
model.train() # batch statistics are what we want to average
for i, (x, _) in enumerate(loader):
if i == num_batches:
break
model(x) # forward only: updates running stats, no weight changes
for bn, m in zip(bns, saved):
bn.momentum = m
model.eval()Run it after training (or before each evaluation). With batches of 32 to 128, a hundred batches give the to examples Wu and Johnson found sufficient.
Leakage: when batchmates carry the answer
Coupling examples is harmless when the batch is a random sample and the task concerns each example alone. It is not harmless when the batch itself carries information. The cleanest case is contrastive learning. In MoCo (He et al., 2020), a query encoder and a key encoder embed two views of each image, and the loss asks each query to pick out its own key among many. Both encoders were standard ResNets with BatchNorm, and training failed in a telling way: the accuracy on the pretext task quickly passed 99.9% while the representations got worse on downstream classification. Their ablations suggest that the statistics of each device's sub-batch acted as a signature telling which sub-batch a positive key came from, so the model could solve the task without learning good image features.
The fix, shuffling BN, permutes the samples across devices before the key encoder (and back afterwards), so that a query and its positive key are normalized with statistics of different subsets. SimCLR and BYOL instead synchronize BatchNorm across all devices, so that every example shares the same statistics (Wu & Johnson, 2021). For BYOL, which uses no negative pairs at all, it was even hypothesized that batch statistics secretly provide the contrast that prevents collapse; replacing BatchNorm by GroupNorm with weight standardization gave 73.9% against 74.3% linear-probe accuracy on ImageNet, which refuted the hypothesis (Richemond et al., 2020).
Why does MoCo shuffle the examples across devices before its key encoder?
- To increase the number of negatives each query sees
- So that a query and its positive key are normalized with statistics of different sub-batches, and the statistics cannot reveal which key is the positive
- To make the batch statistics more accurate
- To reduce communication between devices
Show the answer
B. So that a query and its positive key are normalized with statistics of different sub-batches, and the statistics cannot reveal which key is the positive
With per-device BatchNorm, a query and its positive key were normalized together, and the sub-batch statistics leaked which sub-batch the positive came from: the pretext accuracy rose above 99.9% while the features degraded. Shuffling breaks that link at no extra cost.
Sequence models add their own reasons to avoid batch statistics, which is why transformers normalize each token on its own with LayerNorm or RMSNorm:
- Causality. Statistics pooled over the tokens of a sequence would let a token's normalized value depend on later tokens, leaking the future into a causal language model.
- Variable lengths and padding. Padding positions would contaminate the statistics, and their number varies from batch to batch.
- Unstable statistics. In transformers for language, statistics across the batch fluctuate strongly during training, and naive BatchNorm performed clearly worse than LayerNorm (Shen et al., 2020).
- Scale. Large models are trained with few sequences per device and served one request at a time.
Gradient explosion at initialization
The coupling has a cost even with perfect statistics. Ioffe and Szegedy conjectured that batch normalization might keep the singular values of layer Jacobians close to , the ideal of dynamical isometry. A mean-field analysis of randomly initialized networks proved the opposite.
The contrast with plain networks is the point. Without normalization, the weight and bias variances can be tuned to criticality, where gradients neither explode nor vanish (Criticality & Finite-Width Effects); with batch normalization no tuning removes the explosion, because the normalization itself causes it. The explosion even appears for linear activations, although it fades there as grows.
It also predicts what can be trained. Yang et al. defined the depth scale and found that the deepest trainable network tracked it across their experiments: ReLU networks with batch normalization deeper than about 50 layers could not be trained on MNIST, whatever the batch size.
In a ReLU network with batch normalization and large batches, the squared gradient norm grows by per layer. By what factor does the gradient's norm grow across 30 layers?
Show the answer
313 ×
The norm grows by per layer, so by over 30 layers, and by about over 50. A per-layer factor that looks harmless compounds into an unusable gradient.
The standard way out is the one every modern network takes: skip connections, with normalization on the branches, where it downscales each branch at initialization and leaves the identity path to carry the gradient (Training Without Normalization). Without skips, Yang et al. found two levers that raise the trainable depth: making the activation more nearly linear at initialization (a small gain for tanh, a large shift for ReLU), and a much larger , with a transition near beyond which gradients no longer explode.
They also watched what happens next. After a single gradient step, the huge gradients inflate the lower layers' weights, and scale invariance then shrinks those layers' later gradients in proportion: the network reaches a rough equilibrium at once. In networks of moderate depth that is enough to train; in very deep ones the lower layers end up barely moving.
Shifted test data, and what remains open
Running statistics bake the training distribution into the network, a liability under distribution shift and an opportunity too. Schneider et al. (2020) re-estimated the BatchNorm statistics on unlabeled test images of a shifted distribution and changed nothing else. On ImageNet-C, a benchmark of corrupted images (noise, blur, weather, compression), ResNet-50's mean corruption error fell from 76.7% to 62.2%; treating the training statistics as a prior worth a fixed number of pseudo-samples made the adaptation useful even with very few test images. Tent (Wang et al., 2021) goes further: it also updates each channel's and at test time, by minimizing the entropy of the model's predictions.
The trick assumes a batch or stream of test inputs from one shifted distribution, and it is no panacea: Nado et al. (2020) found mixed results for prediction-time batch normalization alongside pretraining, and smaller gains under more natural shifts than synthetic corruptions. Robustness can cut the other way, too: a workshop paper reported that batch normalization made networks markedly less robust to small adversarial perturbations and to noise on several standard datasets (Galloway et al., 2019).
Schneider et al. (2020) made ResNet-50 far more accurate on corrupted ImageNet images without labels and without changing a single weight. What did they change?
- The learning rate of a short fine-tuning run
- The data augmentation used in training
- The BatchNorm statistics, re-estimated on the corrupted test images
- The last layer's bias, re-estimated by self-training
Show the answer
C. The BatchNorm statistics, re-estimated on the corrupted test images
The weights stay fixed; only the mean and variance used by each BatchNorm layer are recomputed from the shifted test data. The network then normalizes corrupted inputs the way it normalized clean ones in training.
Key takeaways
- In training mode BatchNorm computes : outputs are noisy (the batch mean wanders by ), training and inference compute different functions, and examples are coupled.
- The normalization batch size trades training noise and regularization against train–test inconsistency; 32 to 128 examples worked best for ResNet-50, and tiny batches fail largely through the inconsistency.
- Batch Renormalization, Ghost and synchronized BatchNorm, PreciseBN, FrozenBN and GroupNorm each repair a different part: the gap, the noise, the batch size, the lagging averages, fine-tuning, or the batch dependence itself.
- Batch statistics can leak information, as in MoCo's contrastive task, and they can let a model adapt to shifted test data: the same coupling is a bug or a tool depending on the task.
- At initialization, deep BatchNorm networks without skip connections have squared gradient norms growing like with for every nonlinearity (Yang et al., 2019); skip connections, near-linear activations or a large are the ways out.
Check yourself
In the interactive lesson these are scored with your confidence, and what you miss comes back for review.
In Batch Renormalization, with and treated as constants in the backward pass. What does this achieve when the clipping is inactive?
- The forward pass equals the inference-time transform , while the gradient is still computed as in BatchNorm
- The batch statistics are ignored in both passes, so the layer becomes a fixed affine map
- The output no longer depends on the moving averages
- It doubles the effective batch size by combining two batches
Show the answer
A. The forward pass equals the inference-time transform , while the gradient is still computed as in BatchNorm
Substituting and cancels and in the forward value, so training and inference compute the same normalization. Freezing and keeps BatchNorm's backward pass, which is what keeps the training stable.
Wu and Johnson (2021) trained ResNet-50 with a total batch of 1,024 but tiny normalization batches of 2 or 4 examples. What did they identify as a major cause of the poor accuracy?
- Too few gradient steps
- The inconsistency between the mini-batch statistics seen in training and the population statistics used at test time
- Overfitting caused by too little noise
- Numerical overflow in the variance
Show the answer
B. The inconsistency between the mini-batch statistics seen in training and the population statistics used at test time
Evaluated with mini-batch statistics of the same size, the models did decently; evaluated with population statistics, they did not. Small normalization batches also add training noise, but the gap between the two evaluations shows how much the train–test inconsistency alone cost.
Which of these is not a reason why transformer language models normalize each token with LayerNorm or RMSNorm instead of BatchNorm?
- Statistics pooled over a sequence's tokens would let a token depend on later tokens
- Padding and variable sequence lengths would contaminate batch statistics
- LayerNorm is the only normalizer whose loss is invariant to the scale of the preceding weights
- Batch statistics of language data fluctuate strongly during training
Show the answer
C. LayerNorm is the only normalizer whose loss is invariant to the scale of the preceding weights
BatchNorm creates scale invariance too, per unit rather than per layer. The real reasons are causality, padding, unstable statistics and the small per-device batches of large models.
According to the mean-field theory of Yang et al. (2019), what happens to gradients at initialization in a deep fully connected network with BatchNorm and no skip connections?
- They vanish, because each normalization divides by the batch standard deviation
- They stay at a constant size, because BatchNorm keeps the layer Jacobians close to isometries
- They explode only for ReLU; tanh networks avoid it at the right weight variance
- They explode exponentially with depth for every non-constant activation, and no weight variance prevents it; the rate is smallest for linear activations
Show the answer
D. They explode exponentially with depth for every non-constant activation, and no weight variance prevents it; the rate is smallest for linear activations
The squared gradient norm grows like with for every non-constant ; for linear , , which approaches only as the batch grows. The theorem disproves the conjecture that BatchNorm makes Jacobians near-isometric.
With a total batch of 4,096 spread over 8 devices, each device normalizes its own 512 examples. Which statement is right?
- BatchNorm uses all 4,096 examples, because the gradient is averaged over them
- The statistics come from 512 examples per device, which already acts like Ghost BatchNorm; synchronizing them would remove some regularizing noise
- Per-device statistics make the model's inference depend on the number of devices
- Each device must use a different learning rate to compensate
Show the answer
B. The statistics come from 512 examples per device, which already acts like Ghost BatchNorm; synchronizing them would remove some regularizing noise
Unless the statistics are synchronized, BatchNorm's batch is the per-device batch. Hoffer et al. (2017) made the same choice deliberately with Ghost BatchNorm, normalizing over small virtual batches inside a large one to keep the noise that helps generalization.
Further reading
- G. Yang, J. Pennington, V. Rao, J. Sohl-Dickstein & S. S. Schoenholz, "A mean field theory of batch normalization," ICLR (2019).
- S. Ioffe, "Batch renormalization: Towards reducing minibatch dependence in batch-normalized models," NeurIPS (2017).
- Y. Wu & J. Johnson, "Rethinking 'batch' in BatchNorm," arXiv:2105.07576 (2021).
- K. He, H. Fan, Y. Wu, S. Xie & R. Girshick, "Momentum contrast for unsupervised visual representation learning," CVPR (2020).
- S. Schneider, E. Rusak, L. Eck, O. Bringmann, W. Brendel & M. Bethge, "Improving robustness against common corruptions by covariate shift adaptation," NeurIPS (2020).