Batch norm and layer norm: which way do you average?

These are two ways to put values back on a common scale between the layers of a neural network. The formula is the same. The only difference is which numbers get grouped to compute the mean and variance. That one choice explains the training vs inference difference, the small-batch problem, and why transformers pick layer norm.

Short answer. Picture a grid where each row is an example and each column is a feature. Batch norm averages down a column (one feature across the examples in the batch). Layer norm averages across a row (all the features of one example). Batch norm depends on the other examples, so at inference it uses a mean and variance collected during training, and it gets shaky with small batches. Layer norm only looks at one example, so it has neither problem. That is why transformers use it.

Starting values. Click a cell to pick it. Each color band is one group. The orange outline shows the cells the picked cell is actually grouped with
After normalizing, x̂ (γ = 1, β = 0)

Each row is one example (sample) in the batch, and each column is one feature. The numbers are made up. This is a scaled-down toy: just a 4 × 4 grid instead of a real network. A real layer has dozens of examples and hundreds of features. The stored μ and σ² in "inference" are also made-up values that we pretend were collected during training.

Definitions

The text below explains with a grid of numbers and the lab. These are the textbook definitions. xi,k is feature k of example i in the batch. The batch has m examples, and each example has H features.

normalization layer
A layer that subtracts the mean μ of a group, divides by √(σ² + ε) to get mean 0 and variance 1, then stretches and shifts the result with learned numbers γ (scale) and β (shift). ε is a very small positive number that stops division by 0, and there is one γ and one β per feature. Batch normalization and layer normalization share this formula and differ only in the group used for μ and σ².

y=γ·x−μσ2+ϵ+β

batch normalization
Normalization that, for each feature k, takes the mean and variance over the values of that feature in the m examples of the batch. In a convolutional layer it groups, for each channel, the values at every position (width and height) of every example in the batch. At inference it uses the mean and variance collected during training instead of the batch values.

μk=1m∑i=1mxi,k

σk2=1m∑i=1m(xi,k−μk)2

layer normalization
Normalization that, for each example i, takes the mean and variance over the H feature values of that example. It does not depend on other examples, so training and inference compute the same thing. In a transformer it groups the cells of each token vector, token by token.

μi=1H∑k=1Hxi,k

σi2=1H∑k=1H(xi,k−μi)2

group normalization
Normalization that splits the channels of one example into a few groups and takes the mean and variance of each group over every position of its channels. It does not depend on the batch.
moving average
How batch normalization collects, during training, the mean and variance it will use at inference. For each batch it moves the stored value μ̂ toward this batch's mean μB by a fraction α. In PyTorch, α is the momentum argument, and its default is 0.1. The variance is collected the same way.

μ^←(1−α)μ^+αμB

1. Same formula, different direction

Both methods apply normalization (standardization) between layers. Subtract the mean, divide by the standard deviation to get mean 0 and variance 1, then stretch and shift again with two learned numbers, γ and β. The formula itself and the reason for γ and β are on that page. This page is about what gets averaged together.

Batch normLayer norm
Cells groupedOne feature (a column) across the examples in the batchOne example (a row) across its features
How many means and variancesOne per featureOne per example
In images (convolutions)Per channel, over every example in the batch and every position (height and width)Per example, over all channels and positions
In transformersRarely usedPer token, over the entries of that token's vector

The block figure below shows which cells get grouped in images (convolutions). It also draws group norm from section 8.

N examples C channels H·W positions

Batch norm (batch direction)
Grouped together: one channel, every example, every position

Layer norm (sample direction)
Grouped together: one example, every channel, every position

Group norm
Grouped together: one example, one group of channels, every position (the dashed line splits 6 channels into two groups of 3)

In a convolutional layer the values form a block of N (examples in the batch) × C (channels) × H·W (positions, height and width). The positions are flattened into one line and drawn as depth. The cells filled orange and outlined form one group that shares a mean and standard deviation. The other cells form their own groups of the same shape. The 4 × 4 grid in the lab above is the front face (examples × features) when there is only one position.

Try this. ① At the start, the batch direction is on and the value 2 at example 1, feature 1 is picked. It is grouped with the feature 1 column 2, 8, 8, 10, so μ = 7, σ² = 9, and x̂ = −1.67. ② Click "Sample direction". The same 2 is now grouped with the example 1 row 2, 8, 2, 0, so μ = 3, σ² = 9, and x̂ = −0.33. The same value gives a different result depending on the direction. ③ Click "Batch direction (inference)". The orange outline stays on the picked cell only. It uses the stored μ = 6 and σ² = 9, so x̂ = −1.33. On the right, the feature 1 column is −1.33, 0.67, 0.67, 1.33, so its mean is not 0. ④ In the batch direction, feature 4 is 0 for all four examples, so its variance is 0. Yet the results are all 0. Section 2 shows why.

2. How the formula is built

Using the group you picked above, we build y = γ·(x − μ) ÷ √(σ² + ε) + β one step at a time. μ is the mean of the group and σ² is its variance (the squared distances to the mean, divided by the number of values).

  1. Subtract the mean: x − μ. This moves the center of the group to 0. In the batch direction, μ is the mean of one feature over several examples. In the sample direction, it is the mean over the features of one example.
  2. Divide by the standard deviation: (x − μ) ÷ √σ². This makes the spread 1. If every value in the group is the same, σ² = 0 and you get 0 ÷ 0, which is not a number (NaN).
  3. Add ε: (x − μ) ÷ √(σ² + ε). A tiny number added to the variance stops division by 0. PyTorch's BatchNorm and LayerNorm use 0.00001 by default. For a normal group it barely changes the result.
  4. Scale by γ, shift by β: y = γ·(…) + β. The model stretches and shifts the result by amounts it learns. In both methods there is one γ and one β per feature. So a batch-direction group (one feature) gets one pair, while in a sample-direction group (many features) each cell gets its own γ and β.

Try this. In the lab, γ for features 1 to 4 is 2, 1, 0.5, 1 and β is 1, 0, 0, 0.5 (made-up values we pretend were learned). ① In the batch direction with feature 1, click "Next" four times. The values −1.67, 0.33, 0.33, 1 become −2.33, 1.67, 1.67, 3 with γ = 2 and β = 1. ② Pick a cell in feature 4 and go to step ③. It is NaN and cannot be drawn. At step ④ the values all become 0. ③ In the sample direction with example 1, go to step ⑤. The values −0.33, 1.67, −0.33, −1 get a different γ and β in each cell and become 0.33, 1.67, −0.17, −0.5. ④ In inference mode at step ②, the stored μ = 6 is subtracted, so the center is 1, not 0.

3. Work it out by hand

Take the first cell of the lab, the value 2 at example 1, feature 1, and normalize it both ways (ε is so small that we leave it out).

StepBatch direction (feature 1 column)Sample direction (example 1 row)
Grouped values2, 8, 8, 102, 8, 2, 0
Mean μ28 ÷ 4 = 712 ÷ 4 = 3
Distance to the mean−5, 1, 1, 3−1, 5, −1, −3
Variance σ²(25 + 1 + 1 + 9) ÷ 4 = 9(1 + 25 + 1 + 9) ÷ 4 = 9
x̂ = (2 − μ) ÷ √σ²−5 ÷ 3 = −1.67−1 ÷ 3 = −0.33
y = γ·x̂ + β (feature 1: γ = 2, β = 1)2 × (−1.67) + 1 = −2.332 × (−0.33) + 1 = 0.33

Both variances are 9, but the means differ, so the results differ. In the batch direction, the 2 means "quite a bit smaller than this feature in the other examples". In the sample direction, it means "a little smaller than the other features of this example".

4. Training vs inference (batch norm only)

In batch norm, μ and σ² come from the other examples in the batch. That is fine during training. But when you use the finished model (inference), the answer for one input must not depend on what else came in with it. Inputs may also arrive one at a time. So the original paper uses the mean and variance of the whole dataset at inference instead of batch statistics. Libraries such as PyTorch collect those values during training as a running average. At inference μ and σ² are fixed, so normalization becomes a fixed multiply and add for each feature.

# Running average in PyTorch BatchNorm (momentum defaults to 0.1)
stored mean ← (1 − 0.1) × stored mean + 0.1 × mean of this batch
# Example: stored mean 6, batch mean 7 → 0.9 × 6 + 0.1 × 7 = 6.1

According to the PyTorch docs, the variance used to normalize during training divides by n, but the stored variance divides by n − 1. With model.train() it normalizes with batch statistics and updates the stored values. With model.eval() it normalizes with the stored values.

You can see the dependence in numbers. Change example 4, feature 1 in the lab from 10 to 30. The result for example 1, feature 1 in the batch direction (training) moves from −1.67 to −0.94, even though example 1 did not change. The inference result (−1.33) and the sample direction result (−0.33) stay the same.

5. The small-batch problem

With a small batch, the μ and σ² computed from those few values swing a lot from batch to batch. The extreme cases make it clear.

The group norm paper reports that batch norm's error grows quickly as the batch gets smaller, and says the cause is inaccurate estimates of the batch statistics. This hurts in tasks like object detection, segmentation, and video, where memory forces small batches.

6. Why transformers use layer norm

The "add and norm" step on the transformer page is this layer norm.

7. Key properties

PropertyBatch normLayer norm
Depends on batch sizeYes. Small batches give shaky statistics (2 examples always give −1, 1)No
Training vs inferenceDifferent. Inference uses stored mean and varianceSame
Result changes with the other examples in the batchYes, during training (−1.67 → −0.94)No
Where mean 0 and variance 1 hold after normalizingEach feature (column)Each example (row)
γ and βOne per featureOne per feature

8. Which one to use when

Group norm splits the channels of one example into a few groups and computes a mean and variance for each group. It sits in between: it does not depend on the batch, and it does not lump all the channels together.

OptionProsConsUse it when
Batch normWith large enough batches, training gets faster and you can use much higher learning rates (original paper). At inference it is a cheap fixed multiply and addDepends on batch size. You must switch between training and inference modes. Does not fit sequences of different lengthsConvolutional networks for image classification where you can use large batches
Layer normIndependent of batch size, same computation at training and inference. Normalizes each token or time step on its ownWith very few features, the statistics from those few values are shaky (2 features always give −1, 1)Transformers, recurrent networks, anywhere the batch can be 1
Group normIndependent of batch size, with accuracy that stays stable over a wide range of batch sizes (group norm paper)One more setting to choose: the number of groupsImage tasks where memory forces small batches: object detection, segmentation, video
No normalization between layersSimple. No extra computationDeep networks need lower learning rates and careful initialization (the problem the batch norm paper starts from)Shallow models. Just standardize the inputs

Where it is used

Frequently asked questions

My model with batch norm gives shaky results at inference. Why?

If you run inference in training mode, it uses the mean and variance of the current batch instead of the stored ones. Then the answer for one input changes with whatever other inputs came in with it. In training mode the stored values also keep changing. In PyTorch, call model.eval() before inference.

Do layer norm and batch norm use different formulas?

No, the formula is the same. Subtract the mean, divide by the square root of the variance plus ε, scale by γ, and shift by β. The only difference is which cells are grouped to get the mean and variance. That is why only batch norm needs stored values at inference.

What if I cannot use a large batch?

Switch to a method that does not depend on the batch size. For convolutional networks on images, look at group norm. For sequences, look at layer norm. The group norm paper showed that batch norm's error grows quickly as the batch gets smaller, while group norm's accuracy stays stable over a wide range of batch sizes.

Words

Plain words used hereTextbook term
a batchmini-batch. Its size is the batch size
one examplesample, example
a featurefeature, neuron, or channel in images
batch direction / sample directionbatch dimension / feature dimension
normalizing over the batchbatch normalization (BN)
normalizing within one examplelayer normalization (LN)
normalizing groups of channelsgroup normalization (GN)
stored mean and variancerunning mean, running variance, exponential moving average
the 0.1 mixing ratemomentum. Not the same meaning as momentum in optimizers
using the finished modelinference. Evaluation mode, eval(), in PyTorch
tiny number that prevents division by 0epsilon (ε)
the stretch and the shiftγ (scale, gain), β (shift, bias). Learned parameters
not a numberNaN

Sources

← Reading CNN architecturesResidual connections (ResNet) →