What is batch normalization?
Batch Normalization standardizes each layer's pre-activations or activations across the current mini-batch to zero mean and unit variance, then applies learned per-channel scale (gamma) and shift (beta) parameters. Originally proposed to reduce internal covariate shift, subsequent research showed its main benefit comes from smoothing the optimization landscape so higher learning rates train reliably. During inference, it uses fixed exponential moving averages of training mean and variance rather than batch statistics.
Study Card: What is Batch Normalization?
Direct Answer
Batch Normalization (BatchNorm) normalizes the activations of a layer across each mini-batch during training and rescales them with learned affine parameters. Given a mini-batch for a feature or channel, BatchNorm computes:
where and are learnable scale and shift parameters preserving representational capacity, and ensures numerical stability. While Ioffe and Szegedy (2015) motivated BatchNorm as reducing internal covariate shift, later analysis (Santurkar et al., 2018) demonstrated that it accelerates training primarily by smoothing the loss and gradient landscape (improving Lipschitzness), allowing larger learning rates and reducing sensitivity to initialization. During inference, BatchNorm replaces mini-batch statistics with running estimates accumulated during training so predictions are deterministic for single samples.
Key Terms
- Internal Covariate Shift: Changes in the distribution of layer inputs caused by parameter updates in earlier layers during training.
- Mini-Batch Statistics: Sample mean and variance computed across the batch dimension (and spatial dimensions in 2D CNNs).
- Learnable Scale and Shift (): Per-feature affine parameters restoring any linear transformation the network needs after standardization.
- Running Mean and Variance: Exponential moving averages tracked during training and frozen for deterministic inference.
- Regularization Effect: Mini-batch noise in and acts as mild stochastic regularization during training.
Example
Suppose a neuron produces activations [1.0, 2.0, 3.0, 4.0] over a mini-batch of 4 examples. BatchNorm computes mean and variance (standard deviation ). Standardizing gives with zero mean and unit variance. If the layer has learned and , the output becomes . Note that BatchNorm works poorly with very small batch sizes (noisy statistics) and variable-length sequences, which is why LayerNorm and RMSNorm are preferred in Transformers.
Code Implementation
import numpy as np
def batch_norm_forward(x, gamma, beta, eps, momentum, running_mean, running_var, training=True):
"""
Forward pass for Batch Normalization (TensorFlow momentum convention:
running = momentum * running + (1 - momentum) * batch_stat).
"""
if training:
mu = np.mean(x, axis=0)
var = np.var(x, axis=0)
running_mean = momentum * running_mean + (1.0 - momentum) * mu
running_var = momentum * running_var + (1.0 - momentum) * var
else:
mu = running_mean
var = running_var
x_normalized = (x - mu) / np.sqrt(var + eps)
out = gamma * x_normalized + beta
cache = (x, mu, var, x_normalized, gamma, eps)
return out, running_mean, running_var, cache
def batch_norm_backward(dout, cache):
"""Exact backward pass for Batch Normalization."""
x, mu, var, x_normalized, gamma, eps = cache
N = x.shape[0]
inv_std = 1.0 / np.sqrt(var + eps)
dbeta = np.sum(dout, axis=0)
dgamma = np.sum(dout * x_normalized, axis=0)
dx_normalized = dout * gamma
dvar = np.sum(dx_normalized * (x - mu) * -0.5 * (var + eps) ** (-1.5), axis=0)
dmu = np.sum(-dx_normalized * inv_std, axis=0) + dvar * np.mean(-2.0 * (x - mu), axis=0)
dx = (dx_normalized * inv_std) + (dvar * 2.0 * (x - mu) / N) + (dmu / N)
return dx, dgamma, dbeta
# Sample data and finite-difference gradient check
rng = np.random.default_rng(42)
N, D = 4, 3
x = rng.normal(loc=5.0, scale=2.0, size=(N, D))
gamma = rng.uniform(0.5, 1.5, size=D)
beta = rng.normal(size=D)
eps = 1e-5
momentum = 0.9
running_mean = np.zeros(D)
running_var = np.ones(D)
out_train, running_mean, running_var, cache = batch_norm_forward(
x, gamma, beta, eps, momentum, running_mean, running_var, training=True
)
out_infer, _, _, _ = batch_norm_forward(
x, gamma, beta, eps, momentum, running_mean, running_var, training=False
)
dout = rng.normal(size=(N, D))
dx, dgamma, dbeta = batch_norm_backward(dout, cache)
# Finite-difference check for dx
h = 1e-6
dx_num = np.zeros_like(x)
for idx in np.ndindex(x.shape):
x_pos = x.copy(); x_pos[idx] += h
x_neg = x.copy(); x_neg[idx] -= h
y_pos, _, _, _ = batch_norm_forward(x_pos, gamma, beta, eps, momentum, running_mean.copy(), running_var.copy(), True)
y_neg, _, _, _ = batch_norm_forward(x_neg, gamma, beta, eps, momentum, running_mean.copy(), running_var.copy(), True)
dx_num[idx] = np.sum((y_pos - y_neg) * dout) / (2.0 * h)
print("Training output mean (approx beta):", np.mean(out_train, axis=0))
print("Max gradient error vs finite diff:", np.max(np.abs(dx - dx_num)))
Related Concepts
- Layer Normalization / RMSNorm: Normalizes across features within each individual example rather than across the batch, making it independent of batch size and standard in RNNs and Transformers.
- Instance Normalization: Normalizes each channel of each single sample independently across spatial dimensions, widely used in style transfer.
- Group Normalization: Normalizes across groups of channels per example, providing a batch-size-independent middle ground between LayerNorm and InstanceNorm for small-batch vision training.
- Weight Normalization: Reparameterizes weight vectors into magnitude and direction instead of normalizing activations.
- Optimization Landscape Smoothness: BatchNorm improves the Lipschitz continuity of the loss and gradients, enabling faster convergence with higher learning rates.