◆ AI All-in-One

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
↗ Plan a path here

Read first

Backpropagation

This leads to

The Transformer
The full path from zero — 16 concepts before this one
  1. What Is AI?
  2. Vectors
  3. Derivatives and Slopes
  4. Probability Basics
  5. How Machines Learn
  6. Partial Derivatives and Gradients
  7. Matrices and Matrix Multiplication
  8. The Chain Rule
  9. Supervised, Unsupervised and Reinforcement Learning
  10. Gradient Descent
  11. Supervised Learning
  12. Linear Regression
  13. The Perceptron
  14. Logistic Regression
  15. Neural Networks
  16. Backpropagation
  17. 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.

BatchNorm one feature, across the batch 2 1 0 4 2 1 6 3 0 8 6 3 example 1 example 2 example 3 example 4 f₁ f₂ f₃ f₁: mean 5, std 2.24 → −1.34, −0.45, 0.45, 1.34 LayerNorm one example, across its features 2 1 0 4 2 1 6 3 0 8 6 3 example 1 example 2 example 3 example 4 f₁ f₂ f₃ example 4: mean 5.67, std 2.05 → 1.14, 0.16, −1.30 Same 4 × 3 batch (4 examples, 3 features). The orange cells share one mean and one standard deviation. BatchNorm depends on the other examples in the batch; LayerNorm uses only the example itself.
Fig. 1 The same batch of 4 examples with 3 features each. BatchNorm computes one mean and spread per feature, down a column, across the examples in the batch. LayerNorm computes one mean and spread per example, along a row, across its own features.

Key idea A normalization layer subtracts a mean, divides by a standard deviation, then applies a learned scale γ\gamma and shift β\beta. 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 x1,…,xmx_1, \dots, x_m, compute their mean μ\mu ("mu") and variance σ2\sigma^2 ("sigma squared"):

μ=1m∑i=1mxi,σ2=1m∑i=1m(xi−μ)2\mu = \frac{1}{m}\sum_{i=1}^{m} x_i, \qquad \sigma^2 = \frac{1}{m}\sum_{i=1}^{m} (x_i - \mu)^2

Then normalise each number, and finally scale and shift it with two learned parameters, γ\gamma ("gamma") and β\beta ("beta"):

x^i=xi−μσ2+ϵ,yi=γ x^i+β\hat{x}_i = \frac{x_i - \mu}{\sqrt{\sigma^2 + \epsilon}}, \qquad y_i = \gamma\, \hat{x}_i + \beta

The small constant ϵ\epsilon (typically 10−510^{-5}) prevents division by zero when all the numbers happen to be equal. After the first step, x^\hat{x} has mean 0 and variance 1. The scale γ\gamma starts at 1 and the shift β\beta 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 γ=σ\gamma = \sigma and β=μ\beta = \mu recovers the original numbers.

A worked example

Take the first feature of a batch of 4 examples: (2,4,6,8)(2, 4, 6, 8).

  1. Mean: μ=(2+4+6+8)/4=5\mu = (2 + 4 + 6 + 8) / 4 = 5.
  2. Variance: the differences from the mean are (−3,−1,1,3)(-3, -1, 1, 3), their squares are (9,1,1,9)(9, 1, 1, 9), and the average is 20/4=520 / 4 = 5. So σ=5=2.236\sigma = \sqrt{5} = 2.236.
  3. Normalise: (−3,−1,1,3)/2.236=(−1.342,−0.447,0.447,1.342)(-3, -1, 1, 3) / 2.236 = (-1.342, -0.447, 0.447, 1.342).
  4. Scale and shift with, say, γ=2\gamma = 2 and β=0.5\beta = 0.5: (−2.183,−0.394,1.394,3.183)(-2.183, -0.394, 1.394, 3.183).
1. raw values mean 5, std 2.24 −4 −2 0 2 4 6 8 2, 4, 6, 8 2. subtract the mean now centred on 0 −4 −2 0 2 4 6 8 −3, −1, 1, 3 3. divide by the std spread 1 −4 −2 0 2 4 6 8 −1.342, −0.447, 0.447, 1.342 4. × γ = 2, then + β = 0.5 learned scale and shift −4 −2 0 2 4 6 8 −2.183, −0.394, 1.394, 3.183
Fig. 2 The four steps on a number line. Raw values 2, 4, 6, 8 are centred by subtracting their mean of 5, squeezed to a spread of 1 by dividing by 2.24, then stretched by γ = 2 and shifted by β = 0.5.

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 =0.9×= 0.9 \times running +0.1×+ 0.1 \times 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 (7.0−4.87)/3.85=1.087(7.0 - 4.87)/\sqrt{3.85} = 1.087. 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, (8,6,3)(8, 6, 3). Its mean is 17/3=5.66717/3 = 5.667. The differences are (2.333,0.333,−2.667)(2.333, 0.333, -2.667), their squares average to 4.2224.222, so σ=2.055\sigma = 2.055. The normalised values are (1.136,0.162,−1.298)(1.136, 0.162, -1.298). No other example is involved, so there are no running statistics, it works with a batch of one, and training and evaluation behave identically. γ\gamma and β\beta 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:

yi=γi xi1n∑j=1nxj2+ϵy_i = \gamma_i \, \frac{x_i}{\sqrt{\frac{1}{n}\sum_{j=1}^{n} x_j^2 + \epsilon}}

For (8,6,3)(8, 6, 3): the squares are (64,36,9)(64, 36, 9), their mean is 36.3336.33, the RMS is 6.0286.028, and the output (with γ=1\gamma = 1) is (1.327,0.995,0.498)(1.327, 0.995, 0.498). Removing the mean computation and the β\beta 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: LayerNorm(x+F(x))\text{LayerNorm}(\mathbf{x} + F(\mathbf{x})). This is post-norm. GPT-2 and almost all large models since normalise only the input to each branch: x+F(LayerNorm(x))\mathbf{x} + F(\text{LayerNorm}(\mathbf{x})). This is pre-norm.

Post-norm (original 2017 Transformer) normalise after adding the residual input x attention / MLP + LayerNorm output gradient must pass through every norm Pre-norm (GPT-2 onwards, most LLMs) normalise only the branch input input x LayerNorm attention / MLP + output clean residual path: x passes straight up
Fig. 3 Post-norm puts LayerNorm on the main path after each residual addition, so the gradient must pass through every normalization layer. Pre-norm normalises only the input to the attention or MLP branch, leaving a clean residual path straight from input to output.

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 call model.eval() before evaluating and model.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 β\beta does the same job. Use bias=False in layers followed by BatchNorm.
  • Weight decay on γ\gamma and β\beta. 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

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

  1. Compute by hand the BatchNorm output of the second feature column, (1,2,3,6)(1, 2, 3, 6), with γ=1\gamma = 1 and β=0\beta = 0. Check it with the NumPy code.
  2. In the training experiment, replace nn.BatchNorm1d(width) with nn.LayerNorm(width). Does it help as much?
  3. 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.

Check your understanding

5 quick questions. Pick an answer to see whether you were right and why. Your best score is saved on this device.

  1. A batch has the feature values (2, 4, 6, 8). With γ = 1 and β = 0, what does BatchNorm output for the value 8?

  2. Your model with BatchNorm scores well during training, but its test accuracy changes when you change the evaluation batch size. What is the most likely cause?

  3. Why do Transformers use LayerNorm rather than BatchNorm?

  4. You must train an object detector where only 2 images fit in each GPU batch. Which normalisation is the better choice for its convolutional layers?

  5. What is the difference between pre-norm and post-norm in a Transformer block?

Finished this chapter?

Learn more

Hand-picked courses, books, videos and tutorials for going deeper. See all resources →

Book

Dive into Deep Learning

Zhang, Lipton, Li & Smola · Intermediate · Free

An interactive book with maths, figures and runnable PyTorch code for every chapter. Many universities use it.

Paper

Batch Normalization

Ioffe & Szegedy · 2015 · Advanced · Free

Normalising activations to speed up and stabilise training.

Paper

Layer Normalization

Ba, Kiros & Hinton · 2016 · Advanced · Free

Normalising across features instead of the batch. Transformers use it.

Paper

Root Mean Square Layer Normalization

Zhang & Sennrich · 2019 · Advanced · Free

Introduces RMSNorm, a cheaper LayerNorm without mean subtraction, now standard in large language models such as Llama.

Paper

How Does Batch Normalization Help Optimization?

Santurkar, Tsipras, Ilyas & Madry · 2018 · Advanced · Free

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