TExcelTAD

Batch Normalisation

Weight initialisation sets the scale of every layer's activations at step 0. After a few hundred updates the weights have changed and that careful scale is gone: some layers' outputs grow, others shrink, and each layer has to keep adapting to the moving distribution of its inputs. Batch normalisation (BN, Ioffe and Szegedy, 2015) fixes the scale during training, too: after a linear or convolution layer it standardises every feature with the mean and variance of the current mini-batch, then lets the network rescale it with two learned parameters. In practice the effect is large: deeper networks train, much higher learning rates are stable, and the initialisation matters less.

The transform, its backward pass and the reasons it helps are derived in Batch Normalization. This lesson implements the layer, checks it against nn.BatchNorm1d number for number, measures what it buys on Digits, and covers the details that cause bugs: running statistics, train versus eval mode and small batches.

The layer

For a mini-batch x∈RN×dx \in \mathbb{R}^{N \times d} and each feature jj:

μj=1N∑ixij,σj2=1N∑i(xij−μj)2x^ij=xij−μjσj2+ϵ,yij=γjx^ij+βj\begin{aligned} \mu_j &= \frac{1}{N} \sum_{i} x_{ij}, \qquad \sigma_j^2 = \frac{1}{N} \sum_{i} (x_{ij} - \mu_j)^2 \\ \hat{x}_{ij} &= \frac{x_{ij} - \mu_j}{\sqrt{\sigma_j^2 + \epsilon}}, \qquad y_{ij} = \gamma_j \hat{x}_{ij} + \beta_j \end{aligned}

γ\gamma (PyTorch's weight, starting at 1) and β\beta (bias, starting at 0) are learned, so the layer can undo the normalisation if that helps; ϵ=10−5\epsilon = 10^{-5} protects against division by zero. Because β\beta adds a constant per feature, the bias of the linear layer before BN is redundant (the mean subtraction removes it): build that layer with bias=False.

At inference there may be a single example, so the batch statistics are replaced by running statistics, exponential moving averages collected during training. PyTorch's convention, with momentum m=0.1m = 0.1 by default:

μ^←(1−m) μ^+m μbatch,σ^2←(1−m) σ^2+m NN−1 σbatch2\hat{\mu} \leftarrow (1 - m)\,\hat{\mu} + m\,\mu_{\text{batch}}, \qquad \hat{\sigma}^2 \leftarrow (1 - m)\,\hat{\sigma}^2 + m\,\frac{N}{N - 1}\,\sigma^2_{\text{batch}}

Two traps hide in that line. PyTorch's momentum is the weight of the new value (Keras and TensorFlow call 1−m1 - m the momentum, 0.99 by default), and the running variance uses the unbiased estimate (divisor N−1N - 1), while the normalisation in training mode uses the biased one (divisor NN).

The backward pass through the batch statistics couples every example of the batch. With g=γ⊙∂L/∂yg = \gamma \odot \partial L/\partial y, per feature:

∂L∂xij=1σj2+ϵ(gij−1N∑kgkj−x^ij 1N∑kgkjx^kj)\frac{\partial L}{\partial x_{ij}} = \frac{1}{\sqrt{\sigma_j^2 + \epsilon}} \left( g_{ij} - \frac{1}{N}\sum_k g_{kj} - \hat{x}_{ij} \, \frac{1}{N} \sum_k g_{kj} \hat{x}_{kj} \right)

The two subtracted terms remove the components of the gradient along "shift all examples" and "scale all examples", the directions the normalisation makes the output insensitive to. A consequence you can check: the gradient sums to zero over the batch, for every feature.

From scratch in NumPy

The class stores the running statistics like PyTorch's buffers, uses the batch statistics in training mode and the running ones in eval mode. The gradient is checked against central differences.

python · try it yourself
import numpy as np

class BatchNorm1d:
    def __init__(self, d, eps=1e-5, momentum=0.1):
        self.gamma, self.beta = np.ones(d), np.zeros(d)
        self.running_mean, self.running_var = np.zeros(d), np.ones(d)
        self.eps, self.momentum, self.training = eps, momentum, True

    def forward(self, x):
        if self.training:
            mu, var = x.mean(0), x.var(0)                  # biased variance (divide by N) to normalise
            n, m = len(x), self.momentum
            self.running_mean = (1 - m) * self.running_mean + m * mu
            self.running_var = (1 - m) * self.running_var + m * var * n / (n - 1)   # unbiased
        else:
            mu, var = self.running_mean, self.running_var
        self.xhat = (x - mu) / np.sqrt(var + self.eps)
        self.inv_std = 1 / np.sqrt(var + self.eps)
        return self.gamma * self.xhat + self.beta

    def backward(self, gy):                               # training mode only
        self.dgamma = (gy * self.xhat).sum(0)
        self.dbeta = gy.sum(0)
        g = gy * self.gamma                               # dL/dxhat
        return self.inv_std * (g - g.mean(0) - self.xhat * (g * self.xhat).mean(0))

rng = np.random.default_rng(0)
x = rng.normal(3.0, 2.0, (8, 4))                         # batch 8, 4 features, far from mean 0 / std 1
bn = BatchNorm1d(4)
bn.gamma, bn.beta = rng.normal(1, 0.1, 4), rng.normal(0, 0.1, 4)
y = bn.forward(x)
print("output mean per feature:", (np.round((y - bn.beta).mean(0), 6) + 0.0).tolist())
print("xhat std per feature:   ", np.round(bn.xhat.std(0), 4).tolist())

# gradient check of L = sum(y * w) for a fixed random w
w = rng.normal(size=y.shape)
dx = bn.backward(w)
num, h = np.zeros_like(x), 1e-6
for idx in np.ndindex(*x.shape):
    xp, xm = x.copy(), x.copy(); xp[idx] += h; xm[idx] -= h
    probe = BatchNorm1d(4); probe.gamma, probe.beta = bn.gamma, bn.beta
    lp = (probe.forward(xp) * w).sum(); lm = (probe.forward(xm) * w).sum()
    num[idx] = (lp - lm) / (2 * h)
rel = np.abs(dx - num).max() / np.abs(num).max()
print("gradient check, max relative error below 1e-6:", bool(rel < 1e-6))
print("sum of dL/dx per feature (always 0):", (np.round(dx.sum(0), 10) + 0.0).tolist())

print("running_mean after 1 batch:", np.round(bn.running_mean, 4).tolist())
for _ in range(49):
    bn.forward(rng.normal(3.0, 2.0, (8, 4)))
print("running_mean after 50:     ", np.round(bn.running_mean, 3).tolist())
print("running_var  after 50:     ", np.round(bn.running_var, 3).tolist())
bn.training = False
x1 = np.array([[3.0, 3.0, 3.0, 3.0]])
print("eval on one sample at the mean:", np.round(bn.forward(x1), 3).tolist())
output mean per feature: [0.0, 0.0, 0.0, 0.0]
xhat std per feature:    [1.0, 1.0, 1.0, 1.0]
gradient check, max relative error below 1e-6: True
sum of dL/dx per feature (always 0): [0.0, 0.0, 0.0, 0.0]
running_mean after 1 batch: [0.2084, 0.3027, 0.2517, 0.3156]
running_mean after 50:      [3.338, 2.749, 3.099, 3.096]
running_var  after 50:      [4.528, 3.484, 4.31, 4.048]
eval on one sample at the mean: [[-0.222, 0.129, 0.03, 0.1]]

The input has mean 3 and standard deviation 2; after the layer every feature has mean βj\beta_j and x^\hat{x} has standard deviation exactly 1. The analytic gradient agrees with the numerical one (relative error below 10−610^{-6}) and sums to 0 over the batch, as the formula says. After one batch the running mean is only about 0.3: it started at 0 and moved 10 % of the way. After 50 batches it is near 3 (3.338, 2.749, 3.099, 3.096: with batches of 8 the batch means are noisy, and the average remembers the last 10 or so) and the running variance near 4. In eval mode a sample exactly at the true mean 3 comes out near βj\beta_j, not exactly at it, because the running mean is an estimate.

The same layer in PyTorch, number for number

The recorded example (PyTorch 2.14.1, CPU) feeds five float64 batches through nn.BatchNorm1d and the same formulas in NumPy, compares outputs and running statistics after every step, then compares the input gradient with the NumPy backward pass:

python · try it yourself
import numpy as np
import torch
from torch import nn

def bn_numpy(x, gamma, beta, rm, rv, m=0.1, eps=1e-5):    # the NumPy layer, as one function
    mu, var = x.mean(0), x.var(0)
    xhat = (x - mu) / np.sqrt(var + eps)
    n = len(x)
    return gamma * xhat + beta, (1 - m) * rm + m * mu, (1 - m) * rv + m * var * n / (n - 1)

def bn_numpy_backward(x, gamma, gy, eps=1e-5):
    inv_std = 1 / np.sqrt(x.var(0) + eps)
    xhat = (x - x.mean(0)) * inv_std
    g = gy * gamma
    return inv_std * (g - g.mean(0) - xhat * (g * xhat).mean(0))

torch.manual_seed(0)
bn = nn.BatchNorm1d(4).double()
with torch.no_grad():
    bn.weight.uniform_(0.5, 1.5); bn.bias.uniform_(-0.5, 0.5)
print("buffers:", [name for name, _ in bn.named_buffers()])

rm, rv = np.zeros(4), np.ones(4)
g, b = bn.weight.detach().numpy(), bn.bias.detach().numpy()
worst = 0.0
for step in range(5):                                      # 5 training batches
    x = torch.randn(16, 4, dtype=torch.float64) * 2 + 3
    y_t = bn(x)                                            # train mode: batch stats + update buffers
    y_n, rm, rv = bn_numpy(x.numpy(), g, b, rm, rv)
    worst = max(worst, np.abs(y_t.detach().numpy() - y_n).max(),
                np.abs(bn.running_mean.numpy() - rm).max(), np.abs(bn.running_var.numpy() - rv).max())
print("max difference to NumPy over 5 steps (outputs, running stats) below 1e-12:", bool(worst < 1e-12))
x = (torch.randn(16, 4, dtype=torch.float64) * 2 + 3).requires_grad_()
gy = torch.randn(16, 4, dtype=torch.float64)
bn(x).backward(gy)
dx_n = bn_numpy_backward(x.detach().numpy(), g, gy.numpy())
print("input gradient equals NumPy backward:", bool(np.abs(x.grad.numpy() - dx_n).max() < 1e-12))
print("num_batches_tracked (5 + the gradient batch):", bn.num_batches_tracked.item())
print("running_mean:", [round(v, 4) for v in bn.running_mean.tolist()])

bn.eval()
x = torch.randn(3, 4, dtype=torch.float64)
y_eval = bn(x)
manual = (x - bn.running_mean) / torch.sqrt(bn.running_var + bn.eps) * bn.weight + bn.bias
print("eval uses the running stats:", torch.allclose(y_eval, manual))

bn.train()
try:
    bn(torch.randn(1, 4, dtype=torch.float64))
except ValueError as e:
    print("batch of 1 in train mode:", str(e).split(",")[0])

bn2d = nn.BatchNorm2d(3)                                   # images: one mean/var per channel
imgs = torch.randn(8, 3, 5, 5) * torch.tensor([1.0, 5.0, 0.1]).view(1, 3, 1, 1)
out = bn2d(imgs)
print("BatchNorm2d weight shape:", tuple(bn2d.weight.shape),
      " per-channel std after:", [round(v, 3) for v in out.std(dim=(0, 2, 3), unbiased=False).tolist()])
buffers: ['running_mean', 'running_var', 'num_batches_tracked']
max difference to NumPy over 5 steps (outputs, running stats) below 1e-12: True
input gradient equals NumPy backward: True
num_batches_tracked (5 + the gradient batch): 6
running_mean: [1.4451, 1.3983, 1.3555, 1.3842]
eval uses the running stats: True
batch of 1 in train mode: Expected more than 1 value per channel when training
BatchNorm2d weight shape: (3,)  per-channel std after: [1.0, 1.0, 0.999]

Everything agrees to better than 10−1210^{-12}: the outputs, the running mean, the running variance (so PyTorch does use the unbiased variance with weight 0.1 on the new batch) and the gradient. The running statistics and the counter num_batches_tracked are buffers: they are saved in the state_dict and moved by .to(device), but the optimiser never sees them. The counter is only used when you pass momentum=None, which replaces the moving average by a plain cumulative average of all batches so far. In eval mode the layer computes γ(x−μ^)/σ^2+ϵ+β\gamma (x - \hat{\mu}) / \sqrt{\hat{\sigma}^2 + \epsilon} + \beta, which is what allclose confirms. In train mode a batch of one example is refused by BatchNorm1d on an (N,d)(N, d) input: its variance is 0 and the output would be β\beta whatever the input. (BatchNorm2d accepts one image, because each channel still has H×WH \times W values.)

nn.BatchNorm2d for images of shape (N,C,H,W)(N, C, H, W) computes one mean and variance per channel, over the N×H×WN \times H \times W values of that channel, and has CC values of γ\gamma and β\beta. Each channel is standardised to standard deviation 1.0; the third, whose standard deviation was 0.1, ends at 0.999 because ϵ=10−5\epsilon = 10^{-5} is no longer negligible next to its variance of 0.01.

What it buys: a deep MLP on Digits

Ten hidden layers of width 64 with ReLU and He initialisation, with and without BN after each linear layer, trained with SGD (momentum 0.9, batch 64) at three learning rates on the course's Digits training split (1077 images). The numbers are validation accuracy after epochs 1, 3 and 10, computed in eval mode, so the BN network uses its running statistics.

python · try it yourself
import torch
from torch import nn
from sklearn.datasets import load_digits
from sklearn.model_selection import train_test_split

X, y = load_digits(return_X_y=True)
X = X / 16.0
X_tmp, X_te, y_tmp, y_te = train_test_split(X, y, test_size=0.2, random_state=0, stratify=y)
X_tr, X_va, y_tr, y_va = train_test_split(X_tmp, y_tmp, test_size=0.25, random_state=0, stratify=y_tmp)
X_tr, X_va = (torch.tensor(a, dtype=torch.float32) for a in (X_tr, X_va))
y_tr, y_va = (torch.tensor(a) for a in (y_tr, y_va))

def mlp(bn, depth=10, width=64):
    layers, d = [], 64
    for _ in range(depth):
        layers += [nn.Linear(d, width, bias=not bn)]       # BN's beta replaces the bias
        layers += [nn.BatchNorm1d(width)] if bn else []
        layers += [nn.ReLU()]
        d = width
    model = nn.Sequential(*layers, nn.Linear(width, 10))
    for m in model:
        if isinstance(m, nn.Linear):
            nn.init.kaiming_normal_(m.weight, nonlinearity="relu")
    return model

print("val accuracy at epoch      1      3     10")
for lr in (0.01, 0.1, 0.5):
    for bn in (False, True):
        torch.manual_seed(0)
        model = mlp(bn)
        opt = torch.optim.SGD(model.parameters(), lr=lr, momentum=0.9)
        gen, accs = torch.Generator().manual_seed(0), []
        for epoch in range(1, 11):
            model.train()
            for idx in torch.randperm(len(y_tr), generator=gen).split(64):
                loss = nn.functional.cross_entropy(model(X_tr[idx]), y_tr[idx])
                opt.zero_grad(); loss.backward(); opt.step()
            if epoch in (1, 3, 10):
                model.eval()
                with torch.no_grad():
                    accs.append((model(X_va).argmax(1) == y_va).float().mean().item())
        print(f"lr {lr:<4} {'with BN' if bn else 'no BN  '}       " + "  ".join(f"{a:.3f}" for a in accs))
val accuracy at epoch      1      3     10
lr 0.01 no BN         0.206  0.769  0.922
lr 0.01 with BN       0.472  0.819  0.939
lr 0.1  no BN         0.400  0.100  0.103
lr 0.1  with BN       0.592  0.906  0.967
lr 0.5  no BN         0.125  0.097  0.097
lr 0.5  with BN       0.319  0.747  0.964

At the careful learning rate 0.01 both networks train, and BN is ahead early (0.472 against 0.206 after one epoch) and ends a little higher (0.939 against 0.922). At 0.1 the plain network collapses after its first epoch to chance (0.103), while the BN network reaches 0.906 after three epochs and 0.967 after ten. At 0.5 the plain network never learns (0.097) and the BN network still ends at 0.964. That is the practical summary: BN mostly lets you use a learning rate 10 to 50 times larger, which then trains faster. Why it works is still debated (the original "internal covariate shift" story, a smoother loss surface, an automatic adjustment of the effective learning rate through scale invariance); the math lesson discusses the arguments.

Small batches

The statistics of a batch of NN examples are estimates, and their noise shrinks only like 1/N1/\sqrt{N}. For tiny batches it dominates:

python · try it yourself
import numpy as np

rng = np.random.default_rng(0)
pop = rng.normal(3.0, 2.0, 100_000)                 # one feature over the whole data set

x = rng.choice(pop, 2)
xhat = (x - x.mean()) / np.sqrt(x.var() + 1e-5)
print("batch of 2:", np.round(x, 3).tolist(), "-> normalised", np.round(xhat, 4).tolist())

print("batch size   spread of batch mean   spread of batch std   |train - eval| for one sample")
for n in (2, 4, 16, 64, 256):
    batches = rng.choice(pop, (2000, n))
    mu, sd = batches.mean(1), batches.std(1)
    z_train = (batches[:, 0] - mu) / np.sqrt(sd ** 2 + 1e-5)   # what the sample sees in training
    z_eval = (batches[:, 0] - pop.mean()) / pop.std()          # what it sees at inference
    print(f"{n:10d} {mu.std():18.3f} {sd.std():21.3f} {np.abs(z_train - z_eval).mean():24.3f}")
batch of 2: [5.392, 2.187] -> normalised [1.0, -1.0]
batch size   spread of batch mean   spread of batch std   |train - eval| for one sample
         2              1.418                 0.874                    0.758
         4              1.008                 0.686                    0.496
        16              0.489                 0.356                    0.244
        64              0.240                 0.176                    0.119
       256              0.127                 0.086                    0.058

With two examples per batch the normalised values are always exactly −1-1 and +1+1 (5.392 and 2.187 become 1.0 and -1.0): the layer throws away everything except which example is larger. The spread of the batch mean around the true mean 3 is 1.418 at N=2N = 2 and 0.127 at N=256N = 256. The last column is the real problem: the same example is normalised differently in training (batch statistics) and at inference (population statistics), by 0.758 standard deviations on average at N=2N = 2 and 0.058 at N=256N = 256. The network is trained on one transform and evaluated with another.

What to do with small batches:

  • Use batches of at least 16 to 32 per BN layer when you can.
  • Otherwise use a normalisation that does not look at the batch: LayerNorm or GroupNorm (GroupNorm is the usual choice for detection and segmentation, where a GPU holds only a few large images).
  • With several GPUs, each device sees only its share of the batch; nn.SyncBatchNorm.convert_sync_batchnorm(model) computes the statistics over all devices at the cost of a communication step per BN layer (Memory, Mixed Precision and Multiple Devices).

Pitfalls

  • Evaluating in train mode. Validation then uses batch statistics (results depend on the batch composition) and, worse, updates the running statistics with validation data. Always model.eval() before evaluation, model.train() after.
  • Predicting in train mode with batch size 1 raises the error above (for BatchNorm1d); with batch size 2 it silently returns ±1\pm 1 patterns.
  • Fine-tuning with tiny batches. The pretrained running statistics are good; a few small batches in train mode overwrite them with noise. Freeze BN layers (m.eval() for every BN module after model.train(), and requires_grad_(False) on γ,β\gamma, \beta) when the batch is small (Partial Fine-Tuning).
  • Mixing up momentum conventions when porting from Keras: Keras momentum=0.99 is PyTorch momentum=0.01.
  • A bias before BN wastes parameters and does nothing; use bias=False.
  • Different data at test time. The running statistics describe the training distribution. Under a shift (new camera, new sensor), recomputing them on unlabelled target data (train mode, no gradient, then eval) is a cheap and often effective fix.
  • Folding for deployment. In eval mode BN is an affine map, so it can be merged into the preceding linear or convolution layer; export tools do this. It only holds with fixed running statistics.

Practice

  1. With momentum=0.1, how many batches does it take until the initial value of the running mean (0) has a weight below 1 %?
Answer

After kk batches the initial value has weight 0.9k0.9^k. 0.944≈0.00970.9^{44} \approx 0.0097, so 44 batches. This is why a model evaluated after only a handful of steps has running statistics that are still biased towards 0 and 1.

  1. A model trained with batch size 256 gives 0.96 validation accuracy in eval mode and 0.91 when you forget model.eval() and evaluate with batches of 8. Explain the gap.
Answer

In train mode each validation batch of 8 is normalised with its own noisy mean and variance (the small-batch table: an error of 0.496 standard deviations per example at batch size 4 and 0.244 at 16, so somewhere in between at 8), so every example is transformed differently from what the network learned. In addition, each such forward pass updates the running statistics with validation data. In eval mode the stable running statistics are used.

  1. How many learnable parameters and how many buffer values does nn.BatchNorm2d(64) have?
Answer

128 learnable parameters (γ\gamma and β\beta, 64 each) and 129 buffer values: running_mean (64), running_var (64) and num_batches_tracked (1).

  1. Why does the gradient of BN with respect to its input sum to zero over the batch?
Answer

Adding the same constant to every example of a feature does not change x^\hat{x} (the mean subtraction removes it), so the loss is unchanged by that direction. The directional derivative along "all ones" is ∑i∂L/∂xij=0\sum_i \partial L / \partial x_{ij} = 0.

Test yourself

How does PyTorch update running_var in nn.BatchNorm1d with the default momentum=0.1?

  1. 0.9⋅running+0.1⋅0.9 \cdot \text{running} + 0.1 \cdot the biased batch variance
  2. 0.9⋅running+0.1⋅0.9 \cdot \text{running} + 0.1 \cdot the unbiased batch variance (divisor N−1N - 1)
  3. 0.1⋅running+0.9⋅0.1 \cdot \text{running} + 0.9 \cdot the batch variance
  4. It stores the variance of the last batch

What does a BatchNorm layer use in model.eval() mode?

  1. The statistics of the current batch
  2. The running mean and variance collected during training
  3. Mean 0 and variance 1
  4. The statistics of the test set

In the Digits experiment at learning rate 0.1, what happened?

  1. Both networks reached about 0.97
  2. The plain network fell to chance (0.103) while the BN network reached 0.967
  3. The BN network diverged
  4. Neither network learned

Over which values does nn.BatchNorm2d compute each mean for an input of shape (N,C,H,W)(N, C, H, W)?

  1. Over CC, for each pixel
  2. Over NN, HH and WW, one mean per channel
  3. Over HH and WW, for each image
  4. Over everything, one mean in total

With batches of 2, what does batch normalisation output for one feature (before γ\gamma and β\beta)?

  1. The original values
  2. Always −1-1 and +1+1 (up to ϵ\epsilon)
  3. Always 0
  4. Random values