Level 3 In-Depth AI · Deep Learning
Normalization Layers: BatchNorm and LayerNorm
Layers that rescale the numbers flowing through a network so they keep a steady mean and spread. BatchNorm made deep image networks easy to train; LayerNorm and RMSNorm do the same job inside every Transformer. They also behave differently in training and evaluation, a classic source of bugs.
- Level
- ●●●●● Intermediate
- Reading
- 14 min
- To learn it well
- 1 hour to read, an hour to practise
- Builds on
- 16 concepts →
- Quiz
- 5 questions ↓
Read first
BackpropagationThis leads to
The TransformerThe full path from zero — 16 concepts before this one
- What Is AI?
- Vectors
- Derivatives and Slopes
- Probability Basics
- How Machines Learn
- Partial Derivatives and Gradients
- Matrices and Matrix Multiplication
- The Chain Rule
- Supervised, Unsupervised and Reinforcement Learning
- Gradient Descent
- Supervised Learning
- Linear Regression
- The Perceptron
- Logistic Regression
- Neural Networks
- Backpropagation
- Normalization Layers: BatchNorm and LayerNorm
Read them roughly in this order. See it on the concept map →
Why it matters
Deep networks are touchy. As data flows through dozens of layers, the numbers can drift: their average creeps up, their spread grows or shrinks, and each layer has to keep adapting to a moving target from the layer below. Gradients follow suit and vanish or explode. Careful initialisation sets things up well at the start, but nothing keeps them that way once training starts changing the weights.
A normalization layer fixes this directly. It measures the mean and spread of the numbers passing through it and rescales them to a standard size, at every step of training. The effect can be dramatic. In the experiment below, a 10-layer network that doesn't learn at all reaches 96.7% accuracy once normalization is added, with nothing else changed.
Normalization layers are everywhere. BatchNorm (2015) is part of almost every convolutional image network since ResNet. LayerNorm (2016) sits in every The Transformer, including all GPT-style language models, and its cheaper cousin RMSNorm is used in most open language models as of late 2026, such as the Llama family. Understanding them also saves you from one of the most common bugs in deep learning: forgetting that BatchNorm behaves differently during training and evaluation.
The intuition
Think of a relay team passing a baton, where each runner has to adjust to the speed of the one before. If the earlier runners keep changing pace, every later runner is constantly readjusting. Now put a coach at each handover who makes sure the baton always arrives at the same steady speed. Each runner can focus on their own job.
A normalization layer is that coach. Whatever the previous layer produces, it subtracts the average and divides by the spread, so the next layer always receives numbers centred on zero with a spread of about one. Then it applies a learned scale and shift, so the network can still choose a different size if that's genuinely useful. It just isn't forced into one by accident.
The main difference between the normalization layers is which numbers they average over. BatchNorm takes one feature and averages it across the examples in the batch. LayerNorm takes one example and averages across all of its features.
Key idea A normalization layer subtracts a mean, divides by a standard deviation, then applies a learned scale and shift . BatchNorm computes the statistics per feature across the batch; LayerNorm and RMSNorm compute them per example across features. BatchNorm needs
model.eval()at test time; LayerNorm doesn't.
How it works
The core operation
For a group of numbers , compute their mean ("mu") and variance ("sigma squared"):
Then normalise each number, and finally scale and shift it with two learned parameters, ("gamma") and ("beta"):
The small constant (typically ) prevents division by zero when all the numbers happen to be equal. After the first step, has mean 0 and variance 1. The scale starts at 1 and the shift at 0, and both are learned by Backpropagation like any other weight. If the best thing for the network is to undo the normalisation, it can learn to: setting and recovers the original numbers.
A worked example
Take the first feature of a batch of 4 examples: .
- Mean: .
- Variance: the differences from the mean are , their squares are , and the average is . So .
- Normalise: .
- Scale and shift with, say, and : .
Batch normalization
Batch normalization applies this to each feature separately, using the examples in the current mini-batch as the group. For a fully connected layer with 128 outputs, there are 128 means, 128 variances, 128 $\gamma$s and 128 $\beta$s. In a convolutional network, each channel is a feature, and the statistics are taken over the batch and over every pixel position in that channel. BatchNorm is usually placed right after a linear or convolutional layer and before the activation function.
Why does it help so much? The original paper argued that it reduces internal covariate shift, the drift in each layer's input distribution as earlier layers change. Later work, notably by Shibani Santurkar and colleagues in 2018, found that explanation doubtful and showed instead that BatchNorm makes the loss landscape smoother, so gradients are more predictive and larger learning rates are safe. In practice, the benefits are:
- Much higher learning rates without divergence, so faster training. The original paper matched an image classifier's accuracy with 14 times fewer training steps.
- Less sensitivity to initialisation, since each layer's output is rescaled anyway.
- A mild regularising effect, because each example's normalisation depends on the random other examples in its batch, which adds noise.
Training versus evaluation
That last point hints at a problem. At test time you might predict one example at a time, and then there is no batch to compute statistics from. Even with a batch, you don't want a prediction to depend on which other examples happen to be in it.
So BatchNorm keeps running statistics: during training, it maintains an exponential moving average of the batch means and variances it has seen. In PyTorch, each training batch updates them as running running batch (the momentum=0.1 setting). At evaluation time it uses these stored averages instead of the batch's own statistics. The layer behaves like a fixed linear function.
You switch between the two behaviours with model.train() and model.eval(). In the code below, a BatchNorm layer sees 100 training batches with mean 5 and standard deviation 2. Its running statistics end at mean 4.87 and variance 3.85, close to the true 5 and 4. In evaluation mode, the input 7.0 becomes . In training mode, a batch of one example can't be normalised at all, and PyTorch raises an error.
Layer normalization
BatchNorm has awkward properties: it needs reasonably large batches (statistics from 2 examples are very noisy), it behaves differently in training and evaluation, and it fits poorly with sequences of different lengths and with recurrent networks.
Layer normalization avoids all of this by normalising each example on its own, across its features. Take the fourth example from the figure, . Its mean is . The differences are , their squares average to , so . The normalised values are . No other example is involved, so there are no running statistics, it works with a batch of one, and training and evaluation behave identically. and are still learned, one per feature.
In a Transformer, each token's vector (say 768 or 4,096 numbers) is normalised across its own features. That's why Transformers use LayerNorm: sequences vary in length, batches can be small, and at generation time the model processes one token at a time.
RMSNorm
RMSNorm simplifies LayerNorm further. It skips subtracting the mean and just divides by the root mean square (RMS) of the features, then multiplies by a learned scale:
For : the squares are , their mean is , the RMS is , and the output (with ) is . Removing the mean computation and the shift makes it a little cheaper. Biao Zhang and Rico Sennrich showed in 2019 that it works about as well, and it has since become the standard in large language models.
Other variants
- Group normalization splits a convolutional layer's channels into groups and normalises within each group, per example. It doesn't depend on the batch, so it is used when batches are tiny, such as in object detection and in the U-Nets of Diffusion Models.
- Instance normalization normalises each channel of each image separately. It's used in style transfer.
Where the norm goes: pre-norm and post-norm
In a Transformer block, the original 2017 design normalised after adding the residual connection: . This is post-norm. GPT-2 and almost all large models since normalise only the input to each branch: . This is pre-norm.
With pre-norm, the residual path runs from the bottom of the network to the top untouched, which keeps gradients healthy in very deep stacks. Ruibin Xiong and colleagues showed in 2020 that pre-norm Transformers train stably and can even do without learning-rate warmup, which post-norm ones need. Pre-norm models usually add one final LayerNorm before the output layer.
In code
All three normalisations by hand in NumPy, checked against PyTorch's layers:
import numpy as np
import torch
from torch import nn
x = np.array([[2.0, 1.0, 0.0],
[4.0, 2.0, 1.0],
[6.0, 3.0, 0.0],
[8.0, 6.0, 3.0]]) # a batch of 4 examples, 3 features each
eps = 1e-5
# BatchNorm: statistics per feature, over the batch (down each column)
bn = (x - x.mean(0)) / np.sqrt(x.var(0) + eps)
# LayerNorm: statistics per example, over its features (along each row)
ln = (x - x.mean(1, keepdims=True)) / np.sqrt(x.var(1, keepdims=True) + eps)
# RMSNorm: no mean subtraction, divide by the root mean square of each row
rms = x / np.sqrt((x ** 2).mean(1, keepdims=True) + eps)
np.set_printoptions(precision=3, suppress=True)
print("BatchNorm, first column:", bn[:, 0])
print("LayerNorm, last row: ", ln[3])
print("RMSNorm, last row: ", rms[3])
t = torch.tensor(x, dtype=torch.float32)
print(np.allclose(nn.BatchNorm1d(3)(t).detach(), bn, atol=1e-4),
np.allclose(nn.LayerNorm(3)(t).detach(), ln, atol=1e-4),
np.allclose(nn.RMSNorm(3, eps=eps)(t).detach(), rms, atol=1e-4))
# BatchNorm, first column: [-1.342 -0.447 0.447 1.342]
# LayerNorm, last row: [ 1.136 0.162 -1.298]
# RMSNorm, last row: [1.327 0.995 0.498]
# True True True
(nn.RMSNorm needs PyTorch 2.4 or later.) Training versus evaluation mode:
import torch
from torch import nn
torch.manual_seed(0)
bn = nn.BatchNorm1d(1, momentum=0.1) # running stats: 90% old + 10% new each batch
for _ in range(100): # "training": batches with mean 5, std 2
bn(5 + 2 * torch.randn(32, 1))
print(f"running mean {bn.running_mean.item():.2f}, running var {bn.running_var.item():.2f}")
x = torch.tensor([[7.0]]) # one new example
bn.eval()
print(f"eval mode: 7.0 -> {bn(x).item():.3f}") # uses the running statistics
bn.train()
try:
bn(x) # a batch of one has no spread to measure
except ValueError as e:
print("train mode, batch of 1:", e)
# running mean 4.87, running var 3.85
# eval mode: 7.0 -> 1.087
# train mode, batch of 1: Expected more than 1 value per channel when training, got input size torch.Size([1, 1])
And the effect on training. A 10-layer ReLU network, 128 neurons wide, is trained on the digits dataset from Neural Networks for 300 steps with SGD and momentum, with and without a BatchNorm layer after each linear layer:
import torch
from torch import nn
from sklearn.datasets import load_digits
from sklearn.model_selection import train_test_split
digits = load_digits()
X = torch.tensor(digits.data, dtype=torch.float32) / 16
y = torch.tensor(digits.target)
X_tr, X_te, y_tr, y_te = train_test_split(X, y, test_size=0.25, random_state=0)
def make(norm, depth=10, width=128):
layers, n_in = [], 64
for _ in range(depth):
layers += [nn.Linear(n_in, width)] + ([nn.BatchNorm1d(width)] if norm else []) + [nn.ReLU()]
n_in = width
return nn.Sequential(*layers, nn.Linear(width, 10))
for norm in [False, True]:
for lr in [0.01, 0.1, 1.0]:
torch.manual_seed(0)
model = make(norm)
opt = torch.optim.SGD(model.parameters(), lr=lr, momentum=0.9)
for step in range(300):
idx = torch.randint(0, len(X_tr), (64,))
loss = nn.functional.cross_entropy(model(X_tr[idx]), y_tr[idx])
opt.zero_grad(); loss.backward(); opt.step()
model.eval() # use running statistics
with torch.no_grad():
acc = (model(X_te).argmax(1) == y_te).float().mean().item()
print(f"{'with' if norm else 'without'} BatchNorm, lr {lr:<4}: test accuracy {acc:.3f}")
# without BatchNorm, lr 0.01: test accuracy 0.096
# without BatchNorm, lr 0.1 : test accuracy 0.098
# without BatchNorm, lr 1.0 : test accuracy 0.104
# with BatchNorm, lr 0.01: test accuracy 0.967
# with BatchNorm, lr 0.1 : test accuracy 0.953
# with BatchNorm, lr 1.0 : test accuracy 0.749
Without normalisation, the deep network stays at chance (about 10% for 10 classes) at every learning rate: PyTorch's default initialisation is too small for 10 plain ReLU layers, and the signal fades. With BatchNorm it trains well across a hundredfold range of learning rates.
Common pitfalls
- Forgetting
model.eval(). In training mode, BatchNorm normalises each test batch with its own statistics and updates the running averages with test data. Predictions change depending on what else is in the batch. Always callmodel.eval()before evaluating andmodel.train()before training again. - Tiny batches with BatchNorm. With 2 to 4 examples per batch, the batch statistics are too noisy. Use GroupNorm or LayerNorm instead, or synchronise BatchNorm statistics across GPUs.
- Fine-tuning with BatchNorm on a small dataset. Running statistics adapt to the new data, which can wreck a pretrained network. A common fix is to keep BatchNorm layers in eval mode (frozen statistics) while fine-tuning.
- Bias before BatchNorm. A linear layer's bias is cancelled out when BatchNorm subtracts the mean, and does the same job. Use
bias=Falsein layers followed by BatchNorm. - Weight decay on and . Usually they are excluded from weight decay. See Optimizers: SGD, Momentum and Adam.
- Train/eval mismatch in data. If test inputs are scaled differently from training inputs, the running statistics no longer fit and accuracy falls quietly.
Watch out If a model's accuracy is fine during training but much worse when you evaluate it, or changes when you change the evaluation batch size, suspect BatchNorm in the wrong mode first.
Where it leads
- Residual Connections: normalization and skip connections together made 100-layer networks routine.
- The Transformer: LayerNorm or RMSNorm appears twice in every block.
- Classic CNN Architectures: LeNet to ResNet: BatchNorm is part of the standard convolution, BatchNorm, ReLU building block.
- Dropout and Regularizing Neural Networks: another layer that behaves differently in training and evaluation.
- Training Neural Networks in Practice: checking train and eval modes is part of the debugging checklist.
A bit of history
Sergey Ioffe and Christian Szegedy at Google introduced batch normalization in 2015, training an image classifier to the same accuracy as before in 14 times fewer steps. It immediately became standard, and the ResNets of late 2015 used it after every convolution. Jimmy Lei Ba, Jamie Ryan Kiros and Geoffrey Hinton proposed layer normalization in 2016 for recurrent networks, and the 2017 Transformer adopted it. Yuxin Wu and Kaiming He proposed group normalization in 2018 for small-batch vision tasks.
In 2018, Shibani Santurkar and colleagues challenged the original "internal covariate shift" explanation, arguing that BatchNorm works by smoothing the optimisation landscape. Biao Zhang and Rico Sennrich introduced RMSNorm in 2019. GPT-2 (2019) moved LayerNorm to the start of each block, and the pre-norm design, now usually with RMSNorm, became the standard for large language models.
Try it
- Compute by hand the BatchNorm output of the second feature column, , with and . Check it with the NumPy code.
- In the training experiment, replace
nn.BatchNorm1d(width)withnn.LayerNorm(width). Does it help as much?- In the train/eval example, call
bn.train()and pass a batch of two examples,[[7.0], [9.0]]. What comes out, and why doesn't it depend on the running statistics?Hint for 3: in training mode BatchNorm uses the batch's own mean (8) and standard deviation (1), so the outputs are always about −1 and +1 for any two different numbers.
Learn more
Hand-picked courses, books, videos and tutorials for going deeper. See all resources →
Dive into Deep Learning
An interactive book with maths, figures and runnable PyTorch code for every chapter. Many universities use it.
Batch Normalization
Normalising activations to speed up and stabilise training.
Layer Normalization
Normalising across features instead of the batch. Transformers use it.
Root Mean Square Layer Normalization
Introduces RMSNorm, a cheaper LayerNorm without mean subtraction, now standard in large language models such as Llama.
On Layer Normalization in the Transformer Architecture
Explains why putting layer norm before each sub-layer (pre-LN) trains more stably than the original post-LN design.
How Does Batch Normalization Help Optimization?
Argues that BatchNorm works by smoothing the loss landscape rather than by reducing internal covariate shift, with clear experiments.
Facts checked as of 30 November 2026. Fast-moving details (products, prices, laws) change often. · Source: content/entries/dl/batch-normalization.md