AI State of the Art
Fundamentals/Machine Learning: The Basics/27 min
Section 15

Batch Normalization and Layer Normalization

Listen as a podcast →

Introduction: the chaos of dancing distributions

During the training of a neural network, the weights change constantly at each iteration. This means that the inputs to each layer also change: their mean, their variance, their entire distribution shifts over time.

This phenomenon has a name: internal covariate shift. The problem: each layer must constantly adapt to a moving distribution. It's like trying to aim at a target that moves every second, you spend your time adjusting instead of making progress.

Concretely, without normalization, activation values can drift toward extreme zones (very large or very small), creating unstable gradients. Activations saturate the non-linear functions (like tanh or sigmoid), gradients vanish, and training slows down drastically.

Normalization stabilizes all of this by forcing activations to stay within a consistent distribution (mean close to 0, variance close to 1). Layers can then focus on learning useful representations, instead of wasting time compensating for drifts.

The scientific debate

Why does normalization really work? It's surprisingly controversial. The original explanation (reducing internal covariate shift) has been questioned by subsequent work. Some researchers think normalization "smooths" the optimization landscape (loss landscape), making gradients more predictable and training more stable. Others point to an implicit regularizing effect. Regardless of the exact theoretical reason: empirically, normalization works incredibly well and has become indispensable.

BatchNorm: normalizing over the batch

Batch Normalization: Accelerating Deep Network Training

BatchNorm (Ioffe and Szegedy, 2015) is the normalization technique that started it all. The idea: for each channel (one of the dimensions of the representation), compute the mean and variance over all examples in the batch, then normalize.

Concrete example: you have a batch of 64 images passing through a convolutional layer with 128 channels. For channel 42, BatchNorm computes the mean and variance of channel 42 across all 64 images, then normalizes all values of that channel. Result: 128 pairs (mean, variance), one per channel.

The 4-step process:

  1. Compute the batch mean: μ=1N∑i=1Nxi\mu = \frac{1}{N} \sum_{i=1}^{N} x_i for each channel
  2. Compute the variance: σ2=1N∑i=1N(xi−μ)2\sigma^2 = \frac{1}{N} \sum_{i=1}^{N} (x_i - \mu)^2
  3. Normalize: x^=x−μσ2+ϵ\hat{x} = \frac{x - \mu}{\sqrt{\sigma^2 + \epsilon}}
  4. Rescale and shift: y=γ x^+βy = \gamma \, \hat{x} + \beta

Symbol by symbol: NN is the number of examples in the batch; xix_i the activation value for example ii; μ\mu ("mu") their mean; σ2\sigma^2 ("sigma squared") their variance, the average of the squared deviations, a measure of spread; σ2\sqrt{\sigma^2} is therefore the standard deviation, that spread expressed back in the original unit; x^\hat{x} ("x-hat") the normalized value; and ϵ\epsilon ("epsilon") a tiny number added only so that nothing is ever divided by zero should every value in the batch happen to be identical.

Step 3 in one sentence: subtract the mean, which recenters the values around zero, then divide by the standard deviation, which brings their spread to 1. This is exactly what statisticians do to compare quantities measured in different units.

Step 4 is subtle and important. The parameters γ\gamma ("gamma", a scale factor) and β\beta ("beta", an offset) are learned during training, unlike μ\mu and σ\sigma which are recomputed for every batch. Why? Because forcing all activations to have mean 0 and variance 1 could hurt the network's expressiveness. These parameters allow the network to "undo" the normalization partially if it's useful for a given layer. In theory, if γ=σ\gamma = \sigma and β=μ\beta = \mu, you recover the original values.

At inference

At inference, you often process a single image (batch size 1). No batch = no batch statistics. BatchNorm solves this by keeping, throughout training, a running mean and running variance, moving averages in which each new batch counts a little and the accumulated history counts a lot. These statistics are then used as constants at inference, making the behavior completely deterministic.

This is a frequent source of bugs: if you forget to switch the model into evaluation mode before inference (eval() in the usual libraries), BatchNorm keeps computing the current batch's statistics instead of using the accumulated running ones. The results will be different and often inconsistent.

BatchNorm changed deep learning's life

Before BatchNorm, training a deep network required meticulous tuning of the learning rate and of the weights' starting values. With BatchNorm you can take a markedly larger learning rate: in the original paper the authors train variants at 5 times and at 30 times the baseline network's rate, which would have diverged without normalization. It also reduces sensitivity to initialization and provides a mild regularizing effect, a mini-batch's statistics vary from batch to batch, and that small noise plays a role akin to dropout. It's thanks to BatchNorm that we could reliably train truly deep networks (50, 100, 150 layers).

Key limitations:

  • Batch dependency: with a batch of 2 or 4 examples, the mean and variance computed over so few values are erratic and represent nothing. The model suffers.
  • Variable-length sequences: when the sentences in a batch differ in length, later positions are filled in by only some of the examples, so the statistic there no longer rests on the same population
  • Distributed training: synchronizing batch statistics across multiple GPUs adds complexity and latency
  • Two different behaviors: the layer does not do the same thing at training time and at inference time, which is a reliable source of surprises

LayerNorm: normalizing over features

Layer Normalization

LayerNorm (Ba, Kiros, and Hinton, 2016) takes the opposite approach from BatchNorm: instead of normalizing each feature across the entire batch, it normalizes all features of a single example, independently of other examples in the batch.

Concrete example: same situation, 64 images, 128 channels. For image 17, LayerNorm computes the mean and variance across the 128 channels of that image. Result: 64 pairs (mean, variance), one per image.

For each example ii, with DD the number of channels and xijx_{ij} the value of channel jj of example ii:

μi=1D∑j=1Dxij\mu_i = \frac{1}{D} \sum_{j=1}^{D} x_{ij} σi2=1D∑j=1D(xij−μi)2\sigma_i^2 = \frac{1}{D} \sum_{j=1}^{D} (x_{ij} - \mu_i)^2 x^=x−μiσi2+ϵ\hat{x} = \frac{x - \mu_i}{\sqrt{\sigma_i^2 + \epsilon}} y=γ x^+βy = \gamma \, \hat{x} + \beta

The fundamental difference from BatchNorm: LayerNorm is identical during training and inference. No running statistics, no different behavior depending on the mode. This is a major simplification that eliminates an entire class of bugs.

Why LayerNorm is the natural choice for Transformers:

  • Batch-independent: works with any batch size, even batch = 1
  • Stable for sequences: each token is normalized independently, no issues with variable lengths
  • Deterministic: same behavior during training and inference
  • Parallelizable: no synchronization needed between batch examples
LayerNorm is the Transformer standard

All major transformers (BERT, GPT, T5, LLaMA) use LayerNorm, almost always in pre-normalization: it is applied before the attention layer and before the feedforward layer that follows, not after. That arrangement stabilizes very deep networks far better than post-normalization. The detail is in Pre-norm vs post-norm.

GroupNorm: the intelligent compromise

GroupNorm (Wu and He, 2018) sits between BatchNorm and LayerNorm. The idea: divide the channels into groups and normalize within each group, independently of the batch.

Example: 128 channels, we create 32 groups of 4 channels. For each image, each group of 4 channels is normalized separately. This gives a finer normalization than LayerNorm (which treats all channels together) but without BatchNorm's batch dependency.

Interesting extreme cases:

  • 1 single group = all channels together = LayerNorm
  • As many groups as channels: each channel normalized on its own, which is InstanceNorm, used in style transfer (repainting a photo in the manner of a painting)

GroupNorm is particularly useful in computer vision when the batch is small. If you train a U-Net to segment high-resolution medical images, your GPU memory may only allow 2 or 4 images per batch. Computing a mean and variance over 2 values means nothing, so BatchNorm is unusable; GroupNorm, which never looks at the batch, works identically.

That is why diffusion models for image generation commonly use GroupNorm in the U-shaped network that serves as their backbone, memory constraints force small batches there, exactly the case where BatchNorm fails.

RMSNorm: LayerNorm but faster

RMSNorm (Zhang and Sennrich, 2019) is a simplification of LayerNorm that removes the recentering (mean subtraction):

x^=xRMS(x)\hat{x} = \frac{x}{\text{RMS}(x)} RMS(x)=1D∑i=1Dxi2\text{RMS}(x) = \sqrt{\frac{1}{D} \sum_{i=1}^{D} x_i^2} y=γ x^y = \gamma \, \hat{x}

Symbol by symbol: DD is the number of values in the vector (the number of channels or dimensions); xix_i the ii-th of them; RMS stands for root mean square, square each value, average, take the root. It is a measure of the vector's overall size, indifferent to the signs of its components. And γ\gamma is, as in LayerNorm, a learned scale factor.

In one sentence: divide the vector by its overall size, without recentering it first.

Why remove the recentering? Empirical work has shown it does not always buy quality, while it does cost computation: recentering means sweeping the data once for the mean and again for the spread, where RMS is computed in a single pass. Zhang and Sennrich's paper reports speedups ranging, depending on the model tested, from a few percent to over half the running time; no single number can be quoted, and the ones that circulate should be treated with suspicion.

RMSNorm: the new LLM standard

LLaMA, Mistral, Gemma, Qwen and most recent large language models use RMSNorm rather than LayerNorm. The reasoning is simple: at the scale of models with tens of billions of parameters trained for weeks on thousands of GPUs, the bill is proportional to compute time, so any percentage saved lands straight in the budget. RMSNorm giving equivalent quality for less compute, the choice makes itself.

Comparison table

TechniqueNormalizes overDepends on batchPrimary use case
BatchNormThe entire batch (per feature)YesCNN, classic vision
LayerNormFeatures (per sample)NoTransformers, RNN
GroupNormGroups of featuresNoVision with small batches, U-Nets
RMSNormFeatures (magnitude only)NoModern LLMs, large Transformers

Where to place normalization?

The placement of normalization in the architecture is just as important as the choice of technique. Two main options exist in Transformers:

Post-norm (after the main layer)

This is the formulation from the original Transformer paper (2017): normalize after the skip connection. Simple conceptually, but unstable for deep networks because the residual path isn't "protected" by the normalization.

Pre-norm (before the main layer)

Normalize before the sub-layer, whether attention or feedforward. The gradient then travels back more directly along the residual connection, without crossing the normalization. Far more stable for deep networks, and it has become the standard for every current large language model. In-depth analysis in Pre-norm vs post-norm.

Practical guide: which choice to make?

ArchitectureRecommended techniqueWhy
Classic CNN (ResNet, VGG, EfficientNet)BatchNormValidated by years of practice, sufficiently large batches
Transformer (language, vision)LayerNorm, pre-normalizedProven standard, stable
Small batches in vision (segmentation, detection)GroupNorm (G=32)No batch dependency
Large language model (tens of billions of parameters)RMSNorm, pre-normalizedMaximum efficiency at scale
Style transfer / artistic generationInstanceNormNormalizes each channel/image separately

Why this matters

Normalization seems trivial, it's "just" putting values back to a good scale. But in practice, it's what makes training modern deep networks possible. Without normalization, networks of more than 10-20 layers diverge or converge so slowly that it's unusable. With the right normalization in the right place, you can train networks of 100+ layers without issues.

Knowing which variant to use and where to place it is a fundamental skill in deep learning. It's often the first thing to check when training isn't converging: is the normalization correct? Is it in the right place? Is the train/eval mode properly handled?

A more radical route removes these normalisation layers altogether: keep every vector in the model, weights included, on a sphere of radius 1. That is the subject of nGPT: training a Transformer on the sphere.

Check your understanding0 / 5

1. A batch of 64 images goes through a layer with 128 channels. What is the difference between BatchNorm and LayerNorm?

2. Your convolutional network gives inconsistent results in production even though everything looked fine during training. What classic BatchNorm trap does this page flag?

3. Why does LayerNorm eliminate an entire class of bugs that BatchNorm can spring on you?

4. You are segmenting high-resolution medical images: GPU memory only allows 2 images per batch. Why is BatchNorm unusable, and what should you do?

5. Why do recent large language models (LLaMA, Mistral, Gemma...) prefer RMSNorm over LayerNorm?