Skip to content
E
Educatum

What is batch normalization?

Curated by Educatum AI teamLast updated:
Basic Concepts
Direct Answer

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 B={x1,…,xm}B = \{x_1, \dots, x_m\} for a feature or channel, BatchNorm computes:

μB=1m∑i=1mxi,σB2=1m∑i=1m(xi−μB)2,x^i=xi−μBσB2+ϵ,yi=γx^i+β\mu_B = \frac{1}{m}\sum_{i=1}^{m} x_i, \qquad \sigma_B^2 = \frac{1}{m}\sum_{i=1}^{m} (x_i - \mu_B)^2, \qquad \hat{x}_i = \frac{x_i - \mu_B}{\sqrt{\sigma_B^2 + \epsilon}}, \qquad y_i = \gamma \hat{x}_i + \beta

where γ\gamma and β\beta are learnable scale and shift parameters preserving representational capacity, and ϵ\epsilon 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 μB\mu_B and variance σB2\sigma_B^2 computed across the batch dimension (and spatial dimensions in 2D CNNs).
  • Learnable Scale and Shift (γ,β\gamma, \beta): 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 μB\mu_B and σB2\sigma_B^2 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 μB=2.5\mu_B = 2.5 and variance σB2=1.25\sigma_B^2 = 1.25 (standard deviation ≈1.118\approx 1.118). Standardizing gives x^≈[−1.34,−0.45,0.45,1.34]\hat{x} \approx [-1.34, -0.45, 0.45, 1.34] with zero mean and unit variance. If the layer has learned γ=2.0\gamma = 2.0 and β=1.0\beta = 1.0, the output becomes y=2.0x^+1.0≈[−1.68,0.11,1.89,3.68]y = 2.0\hat{x} + 1.0 \approx [-1.68, 0.11, 1.89, 3.68]. 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)))
  • 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.
View all →

Try keywords like RoPE, FlashAttention, DPO, or Blind 75.