Batch Normalization
Good initialization makes activations well scaled at step 0, but training changes the weights and the scales drift. Batch normalization (Ioffe and Szegedy, 2015) re-standardizes each feature over the mini-batch at every step, then lets the network learn the scale and shift it wants. It made deep convolutional networks much faster to train and tolerant of higher learning rates.
The transform
For a mini-batch of values of one feature (one channel in a CNN):
and are learned per feature; with and the layer could even undo the normalization. (about ) prevents division by zero.
Training versus inference
At inference there may be a single example, so batch statistics are unavailable. During training the layer keeps exponential running averages of and , and at inference it uses them. The layer then becomes a fixed affine map, which can be folded into the preceding linear or convolution layer.
import numpy as np
rng = np.random.default_rng(0)
X = rng.normal(5.0, 3.0, size=(64, 4)) # 4 features with mean 5, std 3
gamma, beta, eps = np.ones(4), np.zeros(4), 1e-5
mu, var = X.mean(0), X.var(0)
Y = gamma * (X - mu) / np.sqrt(var + eps) + beta
print("before: mean", np.round(X.mean(0), 2), " std", np.round(X.std(0), 2))
print("after: mean", np.round(Y.mean(0), 6) + 0, " std", np.round(Y.std(0), 4))
run_mu, run_var, m = np.zeros(4), np.ones(4), 0.1
for _ in range(200): # running averages over many batches
Xb = rng.normal(5.0, 3.0, size=(64, 4))
run_mu = (1 - m) * run_mu + m * Xb.mean(0); run_var = (1 - m) * run_var + m * Xb.var(0)
print("running mean", np.round(run_mu, 2), " running var", np.round(run_var, 2))before: mean [5.05 5.09 4.4 5.48] std [2.81 2.7 3.07 3.41]
after: mean [0. 0. 0. 0.] std [1. 1. 1. 1.]
running mean [5.02 4.9 5.06 4.88] running var [9.42 8.52 8.9 8.67]
The backward pass
Every output depends on every input of the batch through and , so the gradient is not elementwise. With (that is, upstream gradient times ), the result simplifies to
The gradient is projected to be orthogonal to and to : shifting or scaling the inputs cannot change the normalized output, so the gradient has no component in those directions.
import numpy as np
rng = np.random.default_rng(1)
x = rng.normal(2.0, 1.5, size=8); up = rng.normal(size=8); gamma, eps = 1.7, 1e-5
def bn(x):
return gamma * (x - x.mean()) / np.sqrt(x.var() + eps)
L = lambda x: np.sum(bn(x) * up)
xh = (x - x.mean()) / np.sqrt(x.var() + eps); g = up * gamma
dx = (g - g.mean() - xh * np.mean(g * xh)) / np.sqrt(x.var() + eps)
num = np.array([(L(x + e) - L(x - e)) / 2e-6 for e in np.eye(8) * 1e-6])
print("formula matches finite differences:", np.allclose(dx, num, atol=1e-6))
print("gradient sums to 0:", np.isclose(dx.sum(), 0), " orthogonal to x_hat (up to eps):", np.isclose(dx @ xh, 0, atol=1e-4))formula matches finite differences: True
gradient sums to 0: True orthogonal to x_hat (up to eps): True
Why it helps
The original motivation, reducing "internal covariate shift", has been questioned. Better-supported explanations: it makes the loss smoother (smaller gradient changes, so larger learning rates work), makes each layer invariant to the scale of its incoming weights, and adds a little regularizing noise because batch statistics vary. Its drawbacks: dependence on the batch size (small batches give noisy statistics), awkward use in RNNs, and a train/test discrepancy. Transformers use layer normalization instead.
In software
nn.BatchNorm1d/2d(num_features, momentum=0.1, eps=1e-5);model.train()uses batch statistics,model.eval()running ones. Forgettingeval()is a classic bug.- For CNNs the statistics are taken over batch, height and width for each channel.
- Folding BN into the previous convolution is a standard inference optimization.
Go further: Batch Normalisation writes the layer in NumPy, matches PyTorch number for number and measures what it buys on a deep MLP.
Exercises
Exercise 1: Normalize by hand
Batch-normalize with , , .
Answer
About .
Solution
Mean 3; deviations ; variance , std . Result .
Exercise 2: Scale invariance
Show that batch norm's output does not change if the preceding layer's weights are multiplied by .
Answer
Both the mean and the standard deviation scale by and cancel.
Solution
gives , (ignoring ), so is unchanged.
Exercise 3: Folding into a linear layer (code)
Fold inference-mode batch norm (running mean , variance , , ) into and of the previous layer and check the outputs agree.
Answer
, with .
Solution
import numpy as np
rng = np.random.default_rng(3)
W, b = rng.normal(size=(4, 3)), rng.normal(size=4)
m, v, g, be, eps = rng.normal(size=4), rng.uniform(0.5, 2, 4), rng.normal(size=4), rng.normal(size=4), 1e-5
x = rng.normal(size=(5, 3))
ref = g * (x @ W.T + b - m) / np.sqrt(v + eps) + be
s = g / np.sqrt(v + eps)
print(np.allclose(ref, x @ (s[:, None] * W).T + s * (b - m) + be))True
Test yourself
At inference time, batch normalization uses…
- the statistics of the current batch
- running averages of mean and variance collected during training
- mean 0 and variance 1 always
- no normalization
What are and in batch norm?
- Fixed constants
- Learned per-feature scale and shift
- The batch mean and variance
- Learning rates
Why is batch norm a poor fit for small batches?
- It needs more parameters
- The batch statistics become noisy estimates
- It cannot be differentiated
- It only works for images