Settings

Theme
Lite Mode (saves mobile data)

In Lite Mode, animations and videos don't play until you tap them, and their size is shown first. Interactive widgets still work.

Text size

Back up or move your progress →

Part 4: Neural Network Foundations

Normalization layers

P4.1940 min●●○ IntermediateReviewed Dec 3, 2026

Why this matters for machine learning

A normalization layer re-scales the numbers inside a network to a steady size at every layer, so deep networks start and train more reliably. Which numbers share one mean and variance is the whole difference between the layers, and it decides whether a layer depends on the batch.

  • Vanishing and exploding gradients come from repeated multiplications by factors that are too small or too large, and normalization layers are one of the remedies. (P4.16: Vanishing and exploding gradients)
  • Every transformer block applies LayerNorm or RMSNorm around its attention and feed-forward parts. (P7.7: The transformer block, coming soon)
  • Modern decoder language models use RMSNorm in each block. (P10.C1: Anatomy of a modern decoder, coming soon)
  • Residual networks put BatchNorm after almost every convolution, and normalization together with skip connections is what lets very deep networks train. (P4.20: Residual connections)

Before this: The forward pass in matrix form, Weight initialization, Expectation and variance, Tensors, shapes and broadcasting

After this lesson you can

  • Write the normalization recipe (mean, variance, ϵ\epsilon, learned γ\gamma and β\beta) and compute it by hand over different axes
  • Say which numbers share one statistic in BatchNorm, LayerNorm, GroupNorm, InstanceNorm and RMSNorm, and which layers depend on the rest of the batch
  • Explain BatchNorm in training and inference (running averages, momentum, model.eval()) and why small batches and gradient accumulation cause trouble
  • Describe what normalization does for training, and which explanations are still debated

P4.12 showed that the size of the starting weights decides what happens to a signal in a deep network: too small and it vanishes, too large and it explodes, and only a rule such as He initialization keeps it steady, and only at the start of training.

There is another way to keep the scale steady: measure it and fix it at every layer. After each linear layer, subtract the mean of the numbers and divide by their spread. Whatever the weights did, the next layer receives numbers of a standard size. On the same kind of ten-layer ReLU network (the first code cell below), the standard deviation of the last layer’s output is:

  • Without normalization, weights with standard deviation 0.010.01 give 1.4×10−131.4\times10^{-13}, and with standard deviation 11 they give 1.4×1071.4\times10^{7}.
  • With normalization after every linear layer, every weight scale from 0.010.01 to 1010 gives about 0.590.59 (BatchNorm) or 0.600.60 (LayerNorm).

That is a normalization layer. This lesson explains the recipe, and then the five common versions: BatchNorm, LayerNorm, GroupNorm, InstanceNorm and RMSNorm. They share one recipe and differ in a single choice, which numbers are standardized together.

The recipe: standardize, then rescale

You met the operation in P1.D2 and P1.D4: standardizing subtracts the mean and divides by the standard deviation. For the seven values 2,3,3,5,7,8,302,3,3,5,7,8,30 of P1.D2, dividing by s=9.83s=9.83 (with n−1n-1) gave −0.64-0.64, −0.54-0.54, −0.54-0.54, −0.33-0.33, −0.13-0.13, −0.03-0.03, 2.212.21. A normalization layer divides by σ=9.10\sigma=9.10 (with nn), which gives −0.69-0.69, −0.58-0.58, −0.58-0.58, −0.36-0.36, −0.14-0.14, −0.03-0.03, 2.392.39.

For a set of mm numbers z1,…,zmz_1,\dots,z_m that share one statistic, a normalization layer computes

μ=1m∑kzk,σ2=1m∑k(zk−μ)2,z^k=zk−μσ2+ϵ,yk=γ z^k+β.\begin{aligned} \mu&=\frac1m\sum_{k}z_k,\\ \sigma^2&=\frac1m\sum_{k}(z_k-\mu)^2,\\ \hat z_k&=\frac{z_k-\mu}{\sqrt{\sigma^2+\epsilon}},\\ y_k&=\gamma\,\hat z_k+\beta . \end{aligned}

Three details:

  • ϵ\epsilon is a tiny constant, 10−510^{-5} in PyTorch’s BatchNorm, LayerNorm and GroupNorm (nn.RMSNorm defaults to the machine epsilon of the data type, about 10−710^{-7} in float32). If all the numbers are equal, σ2=0\sigma^2=0, and without ϵ\epsilon the division would fail. With it, the output is 00, not NaN.
  • γ\gamma and β\beta are learned parameters, one pair per feature (or channel). Without them, every layer would be forced to output mean 00 and variance 11, which may be the wrong thing for the next layer. With them, the layer can choose any mean and spread, including the original ones: setting γ=σ2+ϵ\gamma=\sqrt{\sigma^2+\epsilon} and β=μ\beta=\mu gives back zkz_k. Training decides.
  • Gradients flow through μ\mu and σ2\sigma^2. They are computed from the numbers, so they are part of the computation graph (P4.8).

A hand-worked example, four ways

Take a batch of N=4N=4 examples with 44 features each. This is the matrix Z\mathbf{Z} of pre-activations that a linear layer produces, in the row-batch convention of P4.5: one row per example, one column per feature.

ex.f1f_1f2f_2f3f_3f4f_4
1210112
242034
363038
484010

Features have different units, as they do inside a network: the second feature is five times the first.

BatchNorm: one statistic per column. Each feature is standardized across the 4 examples. Feature 1 is 2,4,6,82,4,6,8, which is the example of P1.D4: mean 55, variance 55, output (−1.342,−0.447,0.447,1.342)(-1.342,-0.447,0.447,1.342). The four columns have means (5, 25, 2, 6)(5,\,25,\,2,\,6) and variances (5, 125, 1, 20)(5,\,125,\,1,\,20). In NumPy the axis to average over is axis=0, and keepdims=True keeps the result shaped (1,4)(1,4) so that it broadcasts back over the rows (P1.B14).

  • Example 1: −1.342, −1.342, −1.000, 1.342
  • Example 2: −0.447, −0.447, 1.000, −0.447
  • Example 3: 0.447, 0.447, 1.000, 0.447
  • Example 4: 1.342, 1.342, −1.000, −1.342

Features 1 and 2 are now identical: standardizing removed the unit of each feature, whatever its scale. Every column now has mean 00 and variance (nearly) 11.

LayerNorm: one statistic per row. Each example is standardized across its 4 features (axis=1). Example 1 is (2,10,1,12)(2,10,1,12) with mean 6.256.25 and variance 23.1923.19. The four rows have means (6.25, 7.75, 11.75, 12.25)(6.25,\,7.75,\,11.75,\,12.25) and variances (23.19, 50.19, 114.19, 266.19)(23.19,\,50.19,\,114.19,\,266.19).

  • Example 1: −0.883, 0.779, −1.090, 1.194
  • Example 2: −0.529, 1.729, −0.670, −0.529
  • Example 3: −0.538, 1.708, −0.819, −0.351
  • Example 4: −0.260, 1.701, −0.690, −0.751

Now each row has mean 00 and variance (nearly) 11, but the columns do not: feature 2 is the biggest number in examples 2, 3 and 4, and its column now averages 1.481.48. LayerNorm does not look at the other examples at all, so row 1 would be the same in a batch of one.

GroupNorm with 2 groups: one statistic per row and half-row. Split the 4 features into groups {f1,f2}\{f_1,f_2\} and {f3,f4}\{f_3,f_4\}, and standardize each group of each example. Example 1 has group means 66 and 6.56.5 and variances 1616 and 30.2530.25. A group of only two numbers always becomes −1-1 and +1+1, so example 1 gives (−1,1,−1,1)(-1,1,-1,1). Real groups hold many channels and positions, so they keep much more information.

RMSNorm: one number per row, and no mean. Divide each example by its root mean square, 1d∑zj2\sqrt{\tfrac1d\sum z_j^2}, without subtracting anything. Example 1 has 14(4+100+1+144)=62.25\tfrac14(4+100+1+144)=62.25, so the divisor is 62.25=7.89\sqrt{62.25}=7.89 and the row becomes (0.253, 1.267, 0.127, 1.521)(0.253,\,1.267,\,0.127,\,1.521). It is not centred: the mean of the output row is 0.7920.792, but the mean of its squares is 11.

Running the PyTorch layers on this matrix (the first static block below) reproduces these numbers.

Which numbers share a statistic

Real tensors have more than two axes. An image batch has shape (N,C,H,W)(N, C, H, W): NN examples, CC channels, and H×WH\times W positions. A batch of token sequences has shape (N,L,C)(N, L, C): NN sequences, LL tokens, CC features per token. In both, the three kinds of axis are the same: examples, channels (features) and positions (pixels or tokens). The widget draws a tensor with N=4N=4 examples, C=4C=4 channels and L=3L=3 positions as a cube, so you can see which cells are grouped.

BatchNorm: one statistic per channel, over the examples and positions.

C channelsN examplesLpositions

4 statistics, each over 12 numbers. Showing slice 1 of 4.

The 12 numbers in the highlighted slice, before and after. The mean is 2.5 and the variance is 1.44.

before
0.62.01.42.31.44.02.62.81.43.84.53.8
after
−1.63−0.46−0.96−0.21−0.961.210.040.21−0.961.041.631.04

After: mean 0.00 and variance 1.00 (just under 1, because of ε = 0.00001).

A tensor of 4 examples, 4 channels and 3 positions, drawn as a cube. Choose a layer: the hatched blue box marks the cells that share one mean and variance. Step moves to the next box, so you can see that each cell is in exactly one. The readout counts the statistics, and the panel shows the highlighted numbers before and after. GroupNorm has a groups selector. In Lite Mode there is no automatic play.

What to see, for this 4×4×34\times4\times3 tensor:

  • BatchNorm: the box is one channel across all examples and positions: 44 statistics, each over N⋅L=12N\cdot L=12 numbers.
  • LayerNorm: the box is one example and one position across the channels: 1212 statistics, each over 44 numbers. This is the transformer form, where each token’s feature vector is normalized on its own.
  • GroupNorm: one example, a group of channels, all positions. With 2 groups: 88 statistics over 66 numbers. With 1 group: 44 statistics over 1212, which is LayerNorm over channels and positions, the original image form.
  • InstanceNorm: one example and one channel: 1616 statistics over 33 numbers. It is GroupNorm with one channel per group (4 groups here), and was first used for image style transfer.
  • RMSNorm: the same boxes as LayerNorm, but the mean is not removed.

The same rules for an image batch

For a batch of shape (N,C,H,W)(N,C,H,W), the number of statistics and the size of each set:

LayerStatisticsNumbers each
BatchNormCCN⋅H⋅WN\cdot H\cdot W
LayerNorm (image form)NNC⋅H⋅WC\cdot H\cdot W
GroupNorm, GG groupsN⋅GN\cdot G(C/G)⋅H⋅W(C/G)\cdot H\cdot W
InstanceNormN⋅CN\cdot CH⋅WH\cdot W

The learned γ\gamma and β\beta are one pair per channel (or one per element of the normalized shape in LayerNorm), not per statistic.

What the layers do not do

None of these layers removes the correlations between features. They standardize with one mean and one variance per set, not with a covariance matrix. In the BatchNorm example, features 1 and 2 are perfectly correlated before and still perfectly correlated after. Removing correlations is whitening (P1.D7), and BatchNorm standardizes each feature separately using batch statistics, which is not whitening.

BatchNorm in detail

BatchNorm (Ioffe and Szegedy, ICML 2015) standardizes each feature using the other examples in the batch. For a layer output Z\mathbf{Z} of shape (N,d)(N,d):

μj=1N∑i=1Nzij,σj2=1N∑i=1N(zij−μj)2,yij=γj zij−μjσj2+ϵ+βj.\begin{aligned} \mu_j&=\frac1N\sum_{i=1}^{N}z_{ij},\\ \sigma_j^2&=\frac1N\sum_{i=1}^{N}(z_{ij}-\mu_j)^2,\\ y_{ij}&=\gamma_j\,\frac{z_{ij}-\mu_j}{\sqrt{\sigma_j^2+\epsilon}}+\beta_j . \end{aligned}

For images the sum also runs over the H×WH\times W positions, so there is one pair (μ,σ2)(\mu,\sigma^2) per channel.

Training and inference differ. In training the statistics come from the current batch. At inference you may predict one example at a time, and a single example has no useful batch statistics (with one value, the variance is 00). So BatchNorm also keeps running averages of the batch means and variances during training, and uses those fixed numbers at inference. The output for an example then does not depend on the other examples.

PyTorch updates the running averages after every training batch with a parameter called momentum, whose default is 0.10.1:

running←(1−m)⋅running+m⋅batch statistic.\begin{aligned} \text{running}\leftarrow{}&(1-m)\cdot\text{running}\\ &{}+m\cdot\text{batch statistic}. \end{aligned}

Note that this is the reverse of the usual meaning of momentum (P4.13), where a value such as 0.90.9 is the weight kept on the old value. In PyTorch’s BatchNorm, mm is the weight of the new batch, so m=0.1m=0.1 keeps 9090 percent of the old average. The running mean starts at 00 and the running variance at 11. After one batch of a feature with true mean 55, the running mean is only 0.50.5 (the PyTorch run below shows 0.50.5 for feature 1). It takes a few dozen batches to get close: the second code cell shows 0.470.47 after 1 batch, 3.173.17 after 10 and 5.065.06 after 50, for a feature with true mean 55. One more detail: PyTorch normalizes a training batch with the variance that divides by NN, but stores the unbiased variance (dividing by N−1N-1) in the running average. The run below shows a running variance of 6.676.67 for feature 1, which is 43×5\tfrac43\times5.

Why model.eval() matters. model.train() and model.eval() (P2.7) switch BatchNorm between the two behaviours. If you forget model.eval() when predicting, each prediction depends on the other examples in the test batch (and the running averages are updated by test data). In training mode, PyTorch’s BatchNorm refuses a batch with a single value per channel.

Train and inference are close, not equal. In the PyTorch run below, feature 1 gives −1.342-1.342 for the first example in training mode and −1.162-1.162 in eval mode after the running averages have settled: the divisor uses the batch variance 55 in one case and the stored unbiased variance 6.676.67 in the other. With realistic batch sizes the two are much closer.

Batch size. BatchNorm’s statistics are estimated from the batch, and a small batch estimates them badly. The standard deviation of a batch mean of BB values with spread 11 is 1/B1/\sqrt{B} (P1.D8): 0.710.71 for B=2B=2, 0.350.35 for B=8B=8, 0.180.18 for B=32B=32 and 0.090.09 for B=128B=128 (second code cell). With B=2B=2 the “mean” is mostly noise, and every example is standardized with a different, noisy yardstick. This is why BatchNorm networks degrade at very small batch sizes, and why GroupNorm was proposed for them. The noise is also a mild regularizer, a side effect that some people value.

Gradient accumulation. P4.15 showed that accumulating the gradients of 4 micro-batches of 64 matches one batch of 256 for ordinary layers. BatchNorm breaks this: each micro-batch is standardized with its own 64 examples, not with all 256. In the second code cell, the first of 256 values becomes 1.6091.609 with batch-256 statistics and 1.4641.464 with 64-example statistics, and the largest difference over the 256 values is 0.2560.256. The result is not the big-batch result, however carefully you divide the loss.

LayerNorm

LayerNorm (Ba, Kiros and Hinton, 2016) standardizes one example at a time, over its features. It has no batch in it: the output for an example is the same whether the batch holds 1 or 1000 examples, and the layer computes the same thing in training and in inference. The paper’s experiments are mostly on recurrent networks, where batch statistics are awkward because sequences have different lengths.

In a transformer (P7.7) each token is a vector of CC features, and LayerNorm standardizes each token’s vector separately, which is the LayerNorm box of the widget. γ\gamma and β\beta have one entry per feature. This is why transformers use LayerNorm (or RMSNorm), and not BatchNorm: the statistics do not depend on the other sequences in the batch, on the length of the sequence, or on padding. In the cube, this form has N⋅LN\cdot L statistics. For images, the original form averages over (C,H,W)(C,H,W) together, which the cube shows as GroupNorm with one group.

GroupNorm and InstanceNorm

GroupNorm (Wu and He, 2018) was designed for vision with small batches. It splits the CC channels into GG groups and standardizes each group of each example over its channels and positions. Like LayerNorm, it uses no other examples, so its accuracy stays much steadier at small batch sizes, and it computes the same thing in training and inference. The two extremes are known layers: G=1G=1 is LayerNorm over (C,H,W)(C,H,W), and G=CG=C (one channel per group) is InstanceNorm (Ulyanov, Vedaldi and Lempitsky, 2016), which was introduced for fast image stylization. The widget’s “4 groups” is exactly InstanceNorm. A common choice for GG is 32, when CC allows it; the best value depends on the network.

RMSNorm

RMSNorm (Zhang and Sennrich, NeurIPS 2019) asks whether the mean subtraction in LayerNorm is needed. It drops it. For a vector z\mathbf{z} with dd entries,

RMS(z)=1d∑jzj2,yj=γj zjRMS(z)2+ϵ.\begin{aligned} \mathrm{RMS}(\mathbf{z})&=\sqrt{\frac1d\sum_{j}z_j^2},\\ y_j&=\gamma_j\,\frac{z_j}{\sqrt{\mathrm{RMS}(\mathbf{z})^2+\epsilon}} . \end{aligned}

It has no β\beta, and it is cheaper because it computes one statistic and not two. It is also the “divide by the length” of P1.B4 with one change: the RMS is ∥z∥/d\lVert\mathbf{z}\rVert/\sqrt d, so RMSNorm divides z\mathbf{z} by its length and multiplies by d\sqrt d (ignoring ϵ\epsilon), so the result always has length d\sqrt d. For z=(3,4)\mathbf{z}=(3,4) the length is 55, the RMS is 3.543.54, and the output is (0.849, 1.131)(0.849,\,1.131) with length 2\sqrt2.

The LLaMA paper (Touvron et al., 2023) states that it uses RMSNorm on the input of each transformer sub-layer, and P10.C1 shows it in a modern decoder block. Check a model’s published architecture before assuming it uses RMSNorm: closed models do not publish theirs.

Where does the layer go?

Conventions vary, and none is a law. The original BatchNorm paper normalizes the pre-activation (linear, BatchNorm, ReLU), a common order in convolutional networks, and some architectures normalize after the activation instead. Because normalization subtracts the mean of each feature, the bias bb of the linear layer before it has no effect, so such layers often have no bias (a Go-deeper box shows why).

In a transformer block, the original transformer (Vaswani et al., 2017) normalizes after adding each sub-layer’s output to its input, called post-norm. GPT-2 moved the LayerNorm to the input of each sub-block, called pre-norm, and many large models since then do the same. P7.7 compares them.

What it does for training

The ten-layer experiment of the opening shows the first effect: the scale of the signal no longer depends on the scale of the weights. P4.12 gave rules for choosing the starting weights, and these layers make training much less sensitive to the choice (not independent of it: the learning rate, the first steps and the choice of γ,β\gamma,\beta still matter).

A second effect is on how fast the network trains. A short training run on a toy problem shows it (the second static block below, with 5 seeds each): 8 hidden layers of 32 ReLU units, 200 full-batch steps of plain gradient descent, and the accuracy on the 512 training points.

At learning rates 0.010.01, 0.10.1 and 0.50.5 the accuracy was: without normalization 0.500.50, 0.750.75, 0.850.85; with BatchNorm 1.001.00, 1.001.00, 1.001.00; with LayerNorm 0.990.99, 0.950.95, 0.800.80.

This is one small problem, not a benchmark. It shows that the unnormalized network, at a small learning rate, had not learned anything after 200 steps (0.500.50 is chance), while BatchNorm reached 1.001.00 at every learning rate tried. The run does not test whether normalization lets you use larger learning rates: the unnormalized network never diverged here. LayerNorm helped at the small rates, and at 0.50.5 it was no better than no normalization (0.800.80 against 0.850.85, with the seeds overlapping).

Why it helps is partly debated. The BatchNorm paper explained the benefit as reducing internal covariate shift: the distribution of each layer’s inputs keeps changing as the earlier layers learn, and normalizing keeps it steady. A later study (Santurkar et al., NeurIPS 2018) found that stabilizing the input distributions contributes little, and argued that the main effect is a smoother loss landscape, with gradients that predict better what happens after a step. Other explanations exist, and “it reduces internal covariate shift” is best treated as the original motivation, not a settled explanation.

Depth: three ways to see it

Intuition

A normalization layer is a thermostat between layers. The weights before it may push the numbers up or down, but the thermostat reads the temperature of a group of numbers and brings it back to a standard. The choice among BatchNorm, LayerNorm and the others is the choice of which numbers are in the room whose temperature is read. The analogy breaks in one place: a thermostat only holds a fixed target, whereas γ\gamma and β\beta let the network move the target.

Math

Scaling the numbers of a set by a>0a>0 leaves z^\hat z unchanged up to ϵ\epsilon, so the layer is scale-invariant: that is why the weight scale of the layer before it stops mattering. Adding a constant to the set also leaves z^\hat z unchanged for the layers that subtract the mean, but not for RMSNorm.

Code

import torch
import torch.nn as nn

X = torch.tensor([[2., 10., 1., 12.],
                  [4., 20., 3., 4.],
                  [6., 30., 3., 8.],
                  [8., 40., 1., 0.]])
bn, ln = nn.BatchNorm1d(4), nn.LayerNorm(4)
gn, rn = nn.GroupNorm(2, 4), nn.RMSNorm(4)

print("parameters:", [sum(p.numel() for p in m.parameters())
                      for m in (bn, ln, gn, rn)])
print("BN  col 0:", bn(X)[:, 0].detach().numpy().round(3))
print("LN  row 0:", ln(X)[0].detach().numpy().round(3))
print("GN  row 0:", gn(X)[0].detach().numpy().round(3))
print("RMS row 0:", rn(X)[0].detach().numpy().round(3))

print("running_mean after 1 batch:", bn.running_mean.numpy().round(2))
for _ in range(100):
    bn(X)                            # more batches, same data
print("running_mean after 101    :", bn.running_mean.numpy().round(2))
print("running_var  after 101    :", bn.running_var.numpy().round(2))
bn.eval()
print("BN eval col 0:", bn(X)[:, 0].detach().numpy().round(3))
print("eval, one example:", tuple(bn(X[:1]).shape))
bn.train()
try:
    bn(X[:1])
except ValueError as e:
    print("train, one example:", str(e)[:24], "...")

Output from a local run with PyTorch 2.9.1:

parameters: [8, 8, 8, 4]
BN  col 0: [-1.342 -0.447  0.447  1.342]
LN  row 0: [-0.883  0.779 -1.09   1.194]
GN  row 0: [-1.  1. -1.  1.]
RMS row 0: [0.253 1.267 0.127 1.521]
running_mean after 1 batch: [0.5 2.5 0.2 0.6]
running_mean after 101    : [ 5. 25.  2.  6.]
running_var  after 101    : [  6.67 166.66   1.33  26.67]
BN eval col 0: [-1.162 -0.387  0.387  1.162]
eval, one example: (1, 4)
train, one example: Expected more than 1 val ...

The parameter counts are γ\gamma and β\beta (4+44+4) for BatchNorm, LayerNorm and GroupNorm, and only γ\gamma (44) for RMSNorm. The running mean and variance of BatchNorm are stored in the layer but are buffers, not parameters: the optimizer does not train them. They match the hand-worked tables above.

A short training comparison (this takes a few seconds on a CPU):

import torch
import torch.nn as nn
from sklearn.datasets import make_moons

X, y = make_moons(512, noise=0.15, random_state=0)
X, y = torch.tensor(X).float(), torch.tensor(y)

def make(norm, depth=8, width=32):
    layers, d = [], 2
    for _ in range(depth):
        layers.append(nn.Linear(d, width)); d = width
        if norm == "batch": layers.append(nn.BatchNorm1d(width))
        if norm == "layer": layers.append(nn.LayerNorm(width))
        layers.append(nn.ReLU())
    return nn.Sequential(*layers, nn.Linear(d, 2))

def accuracy(norm, lr, seed):
    torch.manual_seed(seed)
    model = make(norm)
    opt = torch.optim.SGD(model.parameters(), lr=lr)
    for _ in range(200):                 # full-batch steps
        opt.zero_grad()
        nn.functional.cross_entropy(model(X), y).backward()
        opt.step()
    model.eval()
    return (model(X).argmax(1) == y).float().mean().item()

for lr in (0.01, 0.1, 0.5):
    row = {n: sum(accuracy(n, lr, s) for s in range(5)) / 5
           for n in ("none", "batch", "layer")}
    print(f"lr {lr:<4} none {row['none']:.2f}"
          f" BN {row['batch']:.2f} LN {row['layer']:.2f}")
lr 0.01 none 0.50 BN 1.00 LN 0.99
lr 0.1  none 0.75 BN 1.00 LN 0.95
lr 0.5  none 0.85 BN 1.00 LN 0.80

The numbers are the accuracy on the 512 training points, averaged over 5 seeds. They need scikit-learn and PyTorch, so they are not run in the browser.

Go deeper Why a bias before BatchNorm does nothing

A linear layer computes z=w⋅x+bz=\mathbf{w}\cdot\mathbf{x}+b. For one feature across the batch, adding the constant bb to every value shifts the batch mean by bb and leaves the variance alone, so the subtraction of the mean removes it: (z−μ)(z-\mu) is the same with or without bb. The shift is then supplied by β\beta. For this reason layers directly followed by BatchNorm are often built without a bias, which saves a few parameters. This argument needs every number of the set to be shifted by the same constant. In LayerNorm over features the biases differ from feature to feature, so there the bias is not removed.

Go deeper Folding BatchNorm into the layer before it at inference

In inference mode BatchNorm uses fixed numbers μ\mu, σ2\sigma^2, γ\gamma and β\beta, so it is an affine map of each feature. A linear layer followed by such a map is again a linear layer: scale each row of W\mathbf{W} by γj/σj2+ϵ\gamma_j/\sqrt{\sigma_j^2+\epsilon} and adjust the bias to γj(bj−μj)/σj2+ϵ+βj\gamma_j(b_j-\mu_j)/\sqrt{\sigma_j^2+\epsilon}+\beta_j. Deployment tools often fold BatchNorm into the previous layer this way, which removes the layer at no cost in accuracy. LayerNorm cannot be folded, because its statistics depend on each input.

Go deeper Normalization, weight scale and the effective learning rate

If a weight matrix is followed by a layer that is scale-invariant, multiplying the weights by a>0a>0 does not change the output. Then the length of the weights does not matter to the loss, only their direction, and the gradient with respect to the weights is perpendicular to the weights and shrinks like 1/a1/a. Gradient steps then increase the length of the weights, which lowers the effective learning rate over time. This is one of the explanations for how normalization interacts with the learning rate and with weight decay (P4.17). It is a result about the scale-invariant case, and real networks only approximate it.

Try it in Python

The first cell is the experiment of the opening: 10 ReLU layers of 64 units, 128 made-up inputs, the same weights with and without normalization, and four weight scales. It prints the standard deviation of the last layer’s output. (Its random numbers are not those of the P4.12 widget, so the figures differ slightly from that lesson’s.) The second cell shows the running averages with the PyTorch momentum convention, how noisy a batch mean is for small batches, and what micro-batches do to BatchNorm.

Weight scale with and without normalization

Runs real Python in your browser. First run downloads about 9 MB (once; your browser keeps it).

Running the cell gives, for weight standard deviations 0.010.01, 0.1770.177, 11 and 1010: without normalization 1.41×10−131.41\times10^{-13}, 0.4260.426, 1.41×1071.41\times10^{7} and 1.41×10171.41\times10^{17}, and with BatchNorm or LayerNorm about 0.590.59 to 0.600.60 for every scale. The value 0.590.59 is the standard deviation of a ReLU applied to standardized numbers: 12−12π=0.584\sqrt{\tfrac12-\tfrac1{2\pi}}=0.584 in theory.

Running averages, small batches, micro-batches

Runs real Python in your browser. First run downloads about 9 MB (once; your browser keeps it).

The running mean reaches 0.470.47, 3.173.17 and 5.065.06 after 1, 10 and 50 batches, and the running variance (true value 44) is 1.161.16, 3.183.18 and 3.883.88. The batch mean has standard deviation 0.7060.706, 0.3530.353, 0.1770.177 and 0.0880.088 for B=2B=2, 88, 3232, 128128. The standardized first value is 1.6091.609 with 256 values and 1.4641.464 with 64.

Common mistakes

Quiz

Check your understanding

  1. A linear layer produces Z\mathbf{Z} of shape (32,64)(32, 64): 32 examples, 64 features. BatchNorm takes its mean over which axis, and how many means does it compute?

  2. Why does BatchNorm keep running averages of the means and variances during training?

  3. In PyTorch's BatchNorm with the default momentum=0.1, a feature has running mean 00 and then two batches in a row each have mean 1010. What is the running mean after the second batch?

  4. Why do transformers normalize with LayerNorm or RMSNorm and not with BatchNorm?

  5. What does RMSNorm change compared with LayerNorm?

Exercises

  1. Apply LayerNorm (ignore ϵ\epsilon) to the single example (2,4,6,8)(2,4,6,8).
    Show answerThe mean is 55 and the variance is 14(9+1+1+9)=5\tfrac14(9+1+1+9)=5, so the output is (−3,−1,1,3)/5=(−1.342,−0.447,0.447,1.342)(-3,-1,1,3)/\sqrt5=(-1.342,-0.447,0.447,1.342), the same numbers as in P1.D4. In the lesson’s example this was a column (BatchNorm); here it is a row (LayerNorm). The arithmetic is the same, only the axis differs.
  2. Apply RMSNorm (ignore ϵ\epsilon) to z=(3,4)\mathbf{z}=(3,4). What is the length of the result?
    Show answerThe mean of squares is (9+16)/2=12.5(9+16)/2=12.5, so the RMS is 3.5363.536, and the result is (0.849, 1.131)(0.849,\,1.131). Its length is 0.72+1.28=2=1.414\sqrt{0.72+1.28}=\sqrt2=1.414, which is d\sqrt d with d=2d=2.
  3. A batch of images has shape (8,6,10,10)(8,6,10,10): 8 examples, 6 channels, 10×1010\times10 positions. How many statistics does each layer compute, and over how many numbers each: BatchNorm, LayerNorm over (C,H,W)(C,H,W), GroupNorm with 2 groups, InstanceNorm?
    Show answerBatchNorm: 66 statistics, each over 8⋅100=8008\cdot100=800 numbers. LayerNorm: 88 statistics, each over 6⋅100=6006\cdot100=600. GroupNorm with 2 groups: 8⋅2=168\cdot2=16 statistics, each over 3⋅100=3003\cdot100=300. InstanceNorm: 8⋅6=488\cdot6=48 statistics, each over 100100.
  4. A BatchNorm layer is applied to 64 features. How many learnable parameters does it have, and how many numbers does it store that are not learned?
    Show answerγ\gamma and β\beta give 2⋅64=1282\cdot64=128 learnable parameters. It also stores a running mean and a running variance, 2⋅64=1282\cdot64=128 numbers, which are buffers and not trained (PyTorch also keeps a counter of batches).
  5. After normalizing feature 4 of the lesson’s example (values 12,4,8,012,4,8,0, mean 66, variance 2020), what γ\gamma and β\beta restore the original values?
    Show answerz^=(z−6)/20+ϵ\hat z=(z-6)/\sqrt{20+\epsilon}, so z=20+ϵ z^+6z=\sqrt{20+\epsilon}\,\hat z+6. Setting γ=20+ϵ≈4.472\gamma=\sqrt{20+\epsilon}\approx4.472 and β=6\beta=6 gives back 12,4,8,012,4,8,0. This is why γ\gamma and β\beta let the layer undo the normalization.

Next: P4.20 covers residual connections, the other idea that lets very deep networks train, and P7.7 puts LayerNorm, attention and a residual path together in one transformer block. P4.16 treats the vanishing and exploding gradients that normalization helps to prevent, and P10.C1 shows RMSNorm in a modern decoder block.

Key takeaways

  • A normalization layer subtracts the mean of a set of numbers, divides by σ2+ϵ\sqrt{\sigma^2+\epsilon}, then applies a learned scale γ\gamma and shift β\beta (which let it undo the normalization). It is the standardization of P1.D4 inside the network.
  • The layers differ only in which numbers share one mean and variance: a feature across the batch (BatchNorm), one example across its features (LayerNorm), a group of channels (GroupNorm), one channel (InstanceNorm). RMSNorm is LayerNorm without the mean and without β\beta.
  • BatchNorm uses batch statistics in training and stored running averages in inference, so call model.eval() for prediction. Small batches give noisy statistics, and gradient accumulation does not reproduce a large batch.
  • LayerNorm, GroupNorm and RMSNorm do not depend on other examples, which is why transformers and small-batch vision use them.
  • Normalization makes a deep network much less sensitive to the weight scale and can allow larger learning rates. Why it helps is partly debated.
Found a mistake? Tell us