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.
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 σ².
- 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.
- 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.
- 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
momentumargument, and its default is 0.1. The variance is collected the same way.
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 norm | Layer norm | |
|---|---|---|
| Cells grouped | One feature (a column) across the examples in the batch | One example (a row) across its features |
| How many means and variances | One per feature | One 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 transformers | Rarely used | Per 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.
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)
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).
- 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. - Divide by the standard deviation:
(x − μ) ÷ √σ². This makes the spread 1. If every value in the group is the same, σ² = 0 and you get0 ÷ 0, which is not a number (NaN). - 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. - 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).
| Step | Batch direction (feature 1 column) | Sample direction (example 1 row) |
|---|---|---|
| Grouped values | 2, 8, 8, 10 | 2, 8, 2, 0 |
| Mean μ | 28 ÷ 4 = 7 | 12 ÷ 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.33 | 2 × (−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.
- 2 examples. If the values are a and b, the distances to the mean are ±(a − b) ÷ 2 and the standard deviation is |a − b| ÷ 2. So the result is always −1 and 1, no matter the values (as long as they differ). 3 and 7 give −1, 1. So do 100 and −5. The size information in the feature is gone.
- 1 example. The variance is 0, so even with ε the result is always 0.
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
- It does not depend on the batch. Layer norm computes from one example only, so the batch size does not matter, and it does exactly the same computation at training and test time (layer norm paper). No stored values, no
train()vseval()difference. - Sentences have different lengths. Sentences in one batch have different numbers of words, so they are padded to the same length. Layer norm normalizes each token (the entries of that token's vector) on its own, so other sentences and padding do not affect it. The batch direction would mix in tokens from other sentences.
- It works directly on sequences. The layer norm paper says it is straightforward to use in recurrent networks by computing the statistics separately at each time step. It also says it is not obvious how to apply batch norm to recurrent networks.
The "add and norm" step on the transformer page is this layer norm.
7. Key properties
| Property | Batch norm | Layer norm |
|---|---|---|
| Depends on batch size | Yes. Small batches give shaky statistics (2 examples always give −1, 1) | No |
| Training vs inference | Different. Inference uses stored mean and variance | Same |
| Result changes with the other examples in the batch | Yes, during training (−1.67 → −0.94) | No |
| Where mean 0 and variance 1 hold after normalizing | Each feature (column) | Each example (row) |
| γ and β | One per feature | One 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.
| Option | Pros | Cons | Use it when |
|---|---|---|---|
| Batch norm | With 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 add | Depends on batch size. You must switch between training and inference modes. Does not fit sequences of different lengths | Convolutional networks for image classification where you can use large batches |
| Layer norm | Independent of batch size, same computation at training and inference. Normalizes each token or time step on its own | With 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 norm | Independent 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 groups | Image tasks where memory forces small batches: object detection, segmentation, video |
| No normalization between layers | Simple. No extra computation | Deep 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
- Between layers of convolutional networks. Batch norm often goes after a convolution and before the activation function (convolution).
- In every transformer block. Layer norm sits around the attention and feed-forward layers (attention, transformer).
- Image tasks with small batches. Object detection, segmentation, and video use group norm instead of batch norm.
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 here | Textbook term |
|---|---|
| a batch | mini-batch. Its size is the batch size |
| one example | sample, example |
| a feature | feature, neuron, or channel in images |
| batch direction / sample direction | batch dimension / feature dimension |
| normalizing over the batch | batch normalization (BN) |
| normalizing within one example | layer normalization (LN) |
| normalizing groups of channels | group normalization (GN) |
| stored mean and variance | running mean, running variance, exponential moving average |
| the 0.1 mixing rate | momentum. Not the same meaning as momentum in optimizers |
| using the finished model | inference. Evaluation mode, eval(), in PyTorch |
| tiny number that prevents division by 0 | epsilon (ε) |
| the stretch and the shift | γ (scale, gain), β (shift, bias). Learned parameters |
| not a number | NaN |
Sources
- Sergey Ioffe, Christian Szegedy, Batch Normalization: Accelerating Deep Network Training by Reducing Internal Covariate Shift, arXiv:1502.03167. Batch mean and variance, whole-dataset statistics and moving averages at inference, grouping over positions per channel in convolutions.
- Jimmy Lei Ba, Jamie Ryan Kiros, Geoffrey E. Hinton, Layer Normalization, arXiv:1607.06450. Mean and variance within one example, the same computation at training and test time, use in recurrent networks per time step.
- Yuxin Wu, Kaiming He, Group Normalization, arXiv:1803.08494. Batch norm's error growing with small batches, splitting channels into groups.
- PyTorch docs: BatchNorm1d (momentum 0.1, ε 0.00001, stored variance divides by n − 1), LayerNorm (ε 0.00001, per-element γ and β).