Normalization: BatchNorm, LayerNorm, GroupNorm
After this lesson, you will be able to:
- Explain why deep networks need normalization layers — activations drift across the layer stack and the optimizer ends up chasing a moving target instead of fitting your data
- Pick between BatchNorm, LayerNorm, GroupNorm, InstanceNorm, and RMSNorm based on which dimension you reduce over and what your batch size and architecture look like
- Use BN correctly in production: switch to model.eval() at inference so you use running statistics, not batch statistics from a single test sample
- Read the per-token normalization in a transformer block, recognize pre-norm vs post-norm placement, and explain why LayerNorm (or RMSNorm), never BatchNorm, became the transformer default
Before you start
#Why Normalize Inside the Network at All?
#The General Recipe
Every normalization layer does the same four things:
- Pick a subset of the activation tensor (a "normalization group").
- Compute the mean and variance over that subset.
- Subtract the mean, divide by sqrt(variance + epsilon) so the subset has mean 0 and variance 1.
- Apply a learnable scale (γ) and shift (β) so the network can recover any distribution it actually wants.
S. Get that one detail right and everything else falls out.Why does subtracting the mean and dividing by the spread give mean 0 and variance 1, and why can the learnable pair still undo all of it? Open the derivation. It is the same standardising step as the z-score in Descriptive Statistics & Distributions, followed by one scale and shift.
#The Four Cuts of an Activation Tensor
(N, C, H, W): N samples in the batch, C channels, height H, width W. A typical transformer activation has shape (N, T, D): N sequences, T tokens, D feature dimensions.#BatchNorm: reduce over (N, H, W) per channel
(N, C, H, W), BatchNorm computes C separate (μ, σ²) pairs, one per channel, averaging across the batch dimension and spatial dimensions for each channel.The backward pass is the part people copy without understanding. The statistics mu and sigma squared depend on every x in the batch, so each x_i affects every output. The derivation follows the chain rule (derived in Vector & Matrix Calculus: Jacobian, Hessian & Backprop Rules) one dependency at a time and ends in a compact three-term formula.
model.eval()), it uses running averages of mean and variance accumulated during training (with exponential decay controlled by momentum, typically 0.1). This is necessary because at inference you might serve one sample at a time — you cannot compute a meaningful batch statistic from N=1.Two more questions about inference. How does the running average that eval mode uses come about, why does the variance need a correction, and why can the whole layer be fused into the one before it? Each has a short derivation.
Why does the running variance carry a factor m over m minus 1? The variance of one batch is on average a little too small, and the derivation shows exactly by how much. It uses E[x squared] = sigma squared + mu squared and the variance of a mean, sigma squared over m, both from Random Variables, Expectation & Variance.
At deploy time the means and variances are frozen, so batch norm is a fixed affine map and can be merged into the layer before it.
Try it! Open the Python REPL and verify the train-vs-eval split:import torch; bn = torch.nn.BatchNorm2d(3); x = torch.randn(8, 3, 4, 4); bn.train(); print(bn(x).mean().item()); bn.eval(); print(bn(x).mean().item())— the train output is exactly 0 (batch mean was subtracted), the eval output is small but nonzero (running mean was used).
The next result explains why batch norm makes the size of the weights almost irrelevant, and why larger learning rates stay safe.
#LayerNorm: reduce over the feature dimension per sample
(N, T, D), LayerNorm computes N · T separate (μ, σ²) pairs, one per token, averaging across the D feature dimension for each individual token. The batch and time dimensions are not part of the reduction.The reason layer norm uses the feature axis is a property you can prove: each token is normalized using only its own numbers.
#GroupNorm: reduce over (H, W) within a channel group
(N, C, H, W), GroupNorm splits the C channels into G groups (typically 32) and computes N · G separate (μ, σ²) pairs — averaging across the spatial dimensions and the channels within each group for each sample.G = C, GroupNorm becomes InstanceNorm. When G = 1, GroupNorm becomes LayerNorm (almost — applied over channel and spatial axes). This makes it a flexible knob: high G if your batch is small, low G if you have plenty of channels per group.The three norms differ only in the set S. Writing the set down shows both limit cases exactly.
#InstanceNorm and RMSNorm: the edge cases
(H, W) per sample per channel — one statistic per (N, C) slot. Used in style transfer (Ulyanov 2016) where you want to wipe out per-image contrast and color bias, leaving only structural content.#Why Transformers Picked LayerNorm and Stuck
Your CNN trains beautifully on ImageNet with batch size 32 per GPU. You move to a higher-resolution dataset that only fits batch size 2 per GPU, and your validation accuracy collapses while training loss looks fine. Most likely cause and fix?
#Pre-norm vs post-norm
LayerNorm(x + Attention(x))). This is post-norm. Modern transformers (GPT-2 onward) put LayerNorm before the sublayer: x + Attention(LayerNorm(x)). This is pre-norm.Post-norm has slightly higher final accuracy on small models but blows up at large depth without careful warmup. Pre-norm is more stable during training (gradients flow cleanly through the residual connection) and won out as transformers scaled past 24 layers. All large LLMs use pre-norm: GPT-2, GPT-3, GPT-4, LLaMA, Mistral.
#When to Use Which
The decision rubric:
| Situation | Use |
|---|---|
| CNN, batch ≥ 16 | BatchNorm (default) |
| CNN, batch ≤ 4 (object detection, segmentation, 3D) | GroupNorm with G=32 |
| Transformer / RNN / variable-length sequences | LayerNorm |
| LLM-scale transformer where compute matters | RMSNorm |
| Style transfer / generative image models | InstanceNorm or GroupNorm |
| Mixed precision training, very deep nets | LayerNorm is most numerically stable |
#Try It Yourself
This code needs PyTorch, and in places a GPU, so it cannot run on this page. Copy it to Google Colab to run it.
# Copy to Colab: needs torch, so it cannot run on this page.
# Implement BatchNorm and LayerNorm from scratch, then expose
# the train/eval mode bug live.
import torch
import torch.nn as nn
# --- Manual BatchNorm2d ---
class MyBatchNorm2d(nn.Module):
def __init__(self, num_features, eps=1e-5, momentum=0.1):
super().__init__()
self.eps, self.momentum = eps, momentum
self.gamma = nn.Parameter(torch.ones(num_features))
self.beta = nn.Parameter(torch.zeros(num_features))
self.register_buffer('running_mean', torch.zeros(num_features))
self.register_buffer('running_var', torch.ones(num_features))
def forward(self, x):
if self.training:
mu = x.mean(dim=(0, 2, 3))
var = x.var(dim=(0, 2, 3), unbiased=False)
self.running_mean = (1 - self.momentum) * self.running_mean + self.momentum * mu.detach()
self.running_var = (1 - self.momentum) * self.running_var + self.momentum * var.detach()
else:
mu, var = self.running_mean, self.running_var
x_hat = (x - mu[None, :, None, None]) / torch.sqrt(var[None, :, None, None] + self.eps)
return self.gamma[None, :, None, None] * x_hat + self.beta[None, :, None, None]
# --- Manual LayerNorm ---
class MyLayerNorm(nn.Module):
def __init__(self, normalized_shape, eps=1e-5):
super().__init__()
self.eps = eps
self.gamma = nn.Parameter(torch.ones(normalized_shape))
self.beta = nn.Parameter(torch.zeros(normalized_shape))
def forward(self, x):
mu = x.mean(dim=-1, keepdim=True)
var = x.var(dim=-1, keepdim=True, unbiased=False)
x_hat = (x - mu) / torch.sqrt(var + self.eps)
return self.gamma * x_hat + self.beta
# === Verify against PyTorch built-ins ===
torch.manual_seed(0)
x = torch.randn(8, 16, 4, 4)
mine_bn = MyBatchNorm2d(16); ref_bn = nn.BatchNorm2d(16)
mine_bn.train(); ref_bn.train()
out_mine = mine_bn(x); out_ref = ref_bn(x)
print(f"Manual BN matches torch.BatchNorm2d: {torch.allclose(out_mine, out_ref, atol=1e-5)}")
# Transformer-shaped tensor for LayerNorm
y = torch.randn(2, 10, 64)
mine_ln = MyLayerNorm(64); ref_ln = nn.LayerNorm(64)
out_mine = mine_ln(y); out_ref = ref_ln(y)
print(f"Manual LN matches torch.LayerNorm: {torch.allclose(out_mine, out_ref, atol=1e-5)}")
# === Demo the train-vs-eval bug ===
print("\n--- BatchNorm train-vs-eval mode ---")
bn = nn.BatchNorm2d(3)
single = torch.randn(1, 3, 4, 4) * 5 + 10 # sample with mean ~10, std ~5
bn.train()
out_train = bn(single)
print(f"train mode output mean: {out_train.mean().item():+.3f} (≈ 0, batch stats subtracted)")
bn.eval()
out_eval = bn(single)
print(f"eval mode output mean: {out_eval.mean().item():+.3f} (≈ 10, running mean = 0 was used)")
print("\nCHALLENGE: implement GroupNorm with num_groups=4 on the same x,")
print("then verify against torch.nn.GroupNorm(4, 16).")Notes for going further:
# GroupNorm sketch:
# class MyGroupNorm(nn.Module):
# def __init__(self, num_groups, num_channels, eps=1e-5):
# super().__init__()
# self.G, self.eps = num_groups, eps
# self.gamma = nn.Parameter(torch.ones(num_channels))
# self.beta = nn.Parameter(torch.zeros(num_channels))
# def forward(self, x):
# N, C, H, W = x.shape
# x = x.view(N, self.G, C // self.G, H, W)
# mu = x.mean(dim=(2, 3, 4), keepdim=True)
# var = x.var(dim=(2, 3, 4), keepdim=True, unbiased=False)
# x = (x - mu) / torch.sqrt(var + self.eps)
# x = x.view(N, C, H, W)
# return self.gamma[None, :, None, None] * x + self.beta[None, :, None, None]What to check: Manual BN should match torch.BatchNorm2d in train mode. Manual LN should match torch.LayerNorm. The train-vs-eval demo should show ≈0 train output and ≈10 eval output for a single-sample input.
#Key Takeaways
- All four normalizations are the same recipe with a different reduction axis. Subtract a mean, divide by a standard deviation, learnable scale and shift; the only choice is which slice of the activation tensor counts as "the same group"
- BatchNorm fights you at small batch sizes. Below batch 8 it loses accuracy, below batch 4 it stops working, and at batch 1 it produces zeros; switch to GroupNorm or LayerNorm in those regimes
- LayerNorm is the transformer default for a reason. It has no batch dependence and no train/eval mode split, so it works identically at training time and at single-token autoregressive inference
- RMSNorm is LayerNorm minus the mean-centering. Saves 7-30% compute at LLM scale with no measurable accuracy loss; LLaMA, PaLM, Mistral, and most modern open LLMs use it
- Forgetting
model.eval()before inference is the silent BN bug that costs production teams weeks — always switch modes explicitly, and prefer frameworks (Lightning, Hugging Face) that do it for you
#Quick Check
Why do transformers use LayerNorm instead of BatchNorm?