Home/How Learning Works

Layer Normalization

BatchNorm normalizes down a column, across samples. LayerNorm normalizes across a row, within one sample — and does not care how many other samples are in the batch.

Overview

Start here

BatchNorm normalizes each feature — each column — using the mean and standard deviation computed across every sample currently in the batch. That is powerful, and it has one structural weakness: its statistics depend on which other examples happen to be in the batch with you, which becomes a real problem at batch size 1 and in architectures like transformers where "the batch" is not a stable, meaningful group.

LayerNorm normalizes each sample against itself — the mean and standard deviation are computed across that one row's own features, so no other sample's presence or absence changes the answer.

Normalization Mode

four samples, five features, deliberately different overall scales

Activations

Per-Row Stats

Per-Column Stats

 

Layer Normalization: A Practical Guide

Normalize the axis that does not depend on who else is in the batch.

The formula, row instead of column

LayerNorm: yi = (xi − μrow) / σrow

μrow and σrow are the mean and standard deviation of that one sample's own feature vector. Compare to BatchNorm's μcol, σcol — computed down a column, across samples. Same shape of formula, different axis.

Normalising across features, not across the batch

Batch normalisation standardises each feature using statistics computed across the examples in a batch. Layer normalisation does the opposite: it standardises each example using statistics computed across its own features.

x̂ = (x − μexample) / √(σ²example + ε)    out = γx̂ + β

That change of axis has one enormous practical consequence: the computation does not depend on the batch at all. Each example is normalised in isolation.

 BatchNormLayerNorm
Statistics overThe batch, per featureThe features, per example
Depends on batch sizeYesNo
Train and inference differYes — running averagesNo — identical
Works with batch size 1NoYes
Handles variable-length sequencesPoorlyYes
Standard inCNNsTransformers, RNNs

Why transformers use it

Three reasons, all following from batch independence.

Sequences vary in length. Batch normalisation would compute statistics across positions in a batch, mixing a sentence's third token with another's third token — and with padding, mixing real tokens with padding tokens. Layer normalisation normalises each token's own feature vector, which is a meaningful operation.

Inference is often batch size 1. Generating text one request at a time gives no batch to compute statistics from. Layer normalisation needs none.

Training and inference behave identically. There are no running averages to accumulate, no train()/eval() distinction for this layer, and no risk of a train/serve mismatch.

Together those made layer normalisation the obvious choice for sequence models, and it has been standard since the original transformer.

Pre-norm versus post-norm

Where the normalisation sits relative to the residual connection turns out to matter a great deal.

Post-norm — the original transformer — is x + sublayer(x) followed by normalisation. It works, and beyond about 12 layers it needs careful warm-up to train at all.

Pre-norm is x + sublayer(norm(x)). The normalisation is inside the residual branch, so the identity path from input to output is completely clean — no normalisation touches it. Gradients flow back through that path unchanged, and very deep transformers become trainable.

Every large language model uses pre-norm, and it is one of the small architectural details that made scaling to 100 layers practical.

RMSNorm is the further simplification now common in large models: it divides by the root mean square of the features and skips the mean subtraction entirely. One fewer statistic to compute, no accuracy cost in practice, and measurably faster at scale.

The same idea, along the other axis

LayerNorm normalises across the features of one row instead of across the batch. That one change makes it independent of batch size, which is why every transformer uses it.

example_01.pyNumPy
Output

Guided experiments

  1. Start at None. Four samples with deliberately different overall magnitudes — Sample B in particular is roughly 500x the scale of Sample C. Per-column stats are dominated by whichever sample happens to be largest.
  2. Switch to LayerNorm. Every row now has mean 0 and standard deviation 1, regardless of its original scale — the per-row stats confirm it, and the wildly different starting magnitudes stop mattering to whatever layer reads this next.
  3. Switch to BatchNorm instead. Now the per-column stats read 0/1, but the rows keep their very different scales — this is the complementary normalization, useful when the batch is a meaningful, stable group.
  4. Shrink the batch to one sample. Tick Batch Size = 1. Under BatchNorm, a single sample has no variation to normalize against — its standard deviation is 0, and the column stats break down. Under LayerNorm nothing changes at all, because it never depended on the other samples in the first place.

Summing up

BatchNorm and LayerNorm are the same normalization idea applied to different axes: BatchNorm down a column, across the batch; LayerNorm across a row, within one sample. That single difference in axis is why LayerNorm works identically at any batch size, including one, while BatchNorm's statistics depend on the batch it happens to see — which is why transformers and RNNs, which often run with small or variable batches, use LayerNorm almost universally.

The other members of the family

NormalisationStatistics computed overTypical use
BatchNormBatch, per channelCNNs, batch size 16+
LayerNormAll features of one exampleTransformers, RNNs
GroupNormGroups of channels, one exampleVision with small batches
InstanceNormOne channel of one exampleStyle transfer, generative models
RMSNormScale only, one exampleLarge language models

GroupNorm is the one to know for computer vision. It splits channels into groups (32 is the usual default) and normalises within each group, per example. Being batch-independent, it works at batch size 2 — which is exactly the situation in detection and segmentation, where large images force small batches. It is the standard replacement for batch normalisation there.

Note that GroupNorm with one group is LayerNorm, and with one channel per group is InstanceNorm. They are points on the same axis.

In code, and the shape that trips people up

import torch.nn as nn

norm = nn.LayerNorm(512)              # normalise the last dimension, size 512
x = torch.randn(8, 100, 512)          # (batch, sequence, features)
out = norm(x)                         # each of the 800 tokens normalised separately

nn.LayerNorm(512) normalises over the last dimension only, which for a transformer is the feature dimension — correct. You can pass a tuple to normalise over several trailing dimensions, which is what image applications sometimes need.

The mistake to avoid is normalising over the wrong axis. nn.LayerNorm([100, 512]) on the tensor above would normalise across sequence positions as well as features, mixing tokens together — not what a transformer wants, and it produces a model that trains poorly for no obvious reason.

Parameter count is 2 per normalised feature: 1,024 for a 512-dimensional layer. Negligible, and like batch normalisation's parameters they should be excluded from weight decay.

Questions people ask

Which should I use? LayerNorm for anything sequential or transformer-shaped; BatchNorm for CNNs with reasonable batch sizes; GroupNorm for CNNs with small batches.

Does LayerNorm need a model.eval() switch? Not for its own behaviour — it computes the same thing in both modes. You still need eval() for dropout and any batch normalisation elsewhere.

Why does it help at all? It keeps activations in a stable range through depth, which keeps gradients in a usable range and allows higher learning rates. The precise theoretical account is still debated, exactly as with batch normalisation.

Is pre-norm always better? For deep networks, yes in practice. Post-norm sometimes reaches slightly better final quality on shallow models with careful tuning.

What is RMSNorm's advantage? One fewer statistic, so slightly faster, with no measurable loss in quality. Standard in recent large language models.

Can I use both BatchNorm and LayerNorm? In one model, technically yes, and it is unusual. Pick the one that matches the data's structure.

Recap in one screen

  • LayerNorm standardises each example across its own features, so it is completely independent of the batch.
  • That makes it correct for variable-length sequences and for batch size 1, and identical in training and inference.
  • Transformers use it, in the pre-norm arrangement, which keeps the residual path clean and makes deep stacks trainable.
  • GroupNorm is the batch-independent choice for vision with small batches.
  • RMSNorm drops the mean subtraction and is now common in large language models.

Recall check

0 of 3

Say the answer out loud before you reveal it — recalling it is what makes it stick, and rereading it is not.

  1. What does this module say about “Start here”?

  2. What does this module say about “Normalising across features, not across the batch”?

  3. What does this module say about “Pre-norm versus post-norm”?

Cheat sheet

Layer Normalization

BatchNorm normalizes down a column, across samples. LayerNorm normalizes across a row, within one sample — and does not care how many other samples are in the batch.

DEEP LEARNING · vizlearn.in/deep_learning/layer_normalization.html

Further reading

About the author

Ashish Jangra builds and maintains VizLearn. Every module here is written and the visualisation behind it hand-built, so the numbers in a readout come from the same code that draws the picture. Corrections are genuinely welcome and get priority over everything else — if a page states something wrong, or an animation misrepresents what the algorithm does, get in touch.