TExcelTAD
Home › Math for Deep Learning & LLMs › Batch Normalization

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 BB values x1,…,xBx_1, \ldots, x_B of one feature (one channel in a CNN):

μB=1B∑ixi,σB2=1B∑i(xi−μB)2,x^i=xi−μBσB2+ϵ,yi=γx^i+β\mu_{\mathcal{B}} = \frac{1}{B}\sum_i x_i, \qquad \sigma^2_{\mathcal{B}} = \frac{1}{B}\sum_i (x_i - \mu_{\mathcal{B}})^2, \qquad \hat{x}_i = \frac{x_i - \mu_{\mathcal{B}}}{\sqrt{\sigma^2_{\mathcal{B}} + \epsilon}}, \qquad y_i = \gamma\hat{x}_i + \beta

γ\gamma and β\beta are learned per feature; with γ=σB\gamma = \sigma_{\mathcal{B}} and β=μB\beta = \mu_{\mathcal{B}} the layer could even undo the normalization. ϵ\epsilon (about 10−510^{-5}) 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 μB\mu_{\mathcal{B}} and σB2\sigma^2_{\mathcal{B}}, 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.

python · try it yourself
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 μB\mu_{\mathcal{B}} and σB\sigma_{\mathcal{B}}, so the gradient is not elementwise. With g=∂L/∂x^\mathbf{g} = \partial\mathcal{L}/\partial\hat{\mathbf{x}} (that is, upstream gradient times γ\gamma), the result simplifies to

∂L∂xi=1σB2+ϵ(gi−1B∑jgj−x^i1B∑jgjx^j)\frac{\partial\mathcal{L}}{\partial x_i} = \frac{1}{\sqrt{\sigma^2_{\mathcal{B}} + \epsilon}}\left(g_i - \frac{1}{B}\sum_j g_j - \hat{x}_i\frac{1}{B}\sum_j g_j\hat{x}_j\right)

The gradient is projected to be orthogonal to 1\mathbf{1} and to x^\hat{\mathbf{x}}: shifting or scaling the inputs cannot change the normalized output, so the gradient has no component in those directions.

python · try it yourself
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. Forgetting eval() 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 (1,2,3,6)(1, 2, 3, 6) with γ=1\gamma = 1, β=0\beta = 0, ϵ=0\epsilon = 0.

Answer

About (−1.069,−0.535,0,1.604)(-1.069, -0.535, 0, 1.604).

Solution

Mean 3; deviations (−2,−1,0,3)(-2, -1, 0, 3); variance (4+1+0+9)/4=3.5(4 + 1 + 0 + 9)/4 = 3.5, std 1.8711.871. Result (−1.069,−0.535,0,1.604)(-1.069, -0.535, 0, 1.604).

Exercise 2: Scale invariance

Show that batch norm's output does not change if the preceding layer's weights are multiplied by c>0c > 0.

Answer

Both the mean and the standard deviation scale by cc and cancel.

Solution

xi→cxix_i \to cx_i gives μ→cμ\mu \to c\mu, σ→cσ\sigma \to c\sigma (ignoring ϵ\epsilon), so x^i=cxi−cμcσ\hat{x}_i = \frac{cx_i - c\mu}{c\sigma} is unchanged.

Exercise 3: Folding into a linear layer (code)

Fold inference-mode batch norm (running mean m\mathbf{m}, variance v\mathbf{v}, γ\gamma, β\beta) into WW and b\mathbf{b} of the previous layer and check the outputs agree.

Answer

W′=diag⁡(s)WW' = \operatorname{diag}(s)W, b′=s⊙(b−m)+β\mathbf{b}' = s \odot (\mathbf{b} - \mathbf{m}) + \beta with s=γ/v+ϵs = \gamma/\sqrt{\mathbf{v} + \epsilon}.

Solution
python · try it yourself
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…

  1. the statistics of the current batch
  2. running averages of mean and variance collected during training
  3. mean 0 and variance 1 always
  4. no normalization

What are γ\gamma and β\beta in batch norm?

  1. Fixed constants
  2. Learned per-feature scale and shift
  3. The batch mean and variance
  4. Learning rates

Why is batch norm a poor fit for small batches?

  1. It needs more parameters
  2. The batch statistics become noisy estimates
  3. It cannot be differentiated
  4. It only works for images