Layer Normalisation and RMSNorm
Batch normalisation computes its statistics across the examples of a batch. That is a poor fit for three common situations: batches of one or two (large images, long sequences, online inference), sequences of different lengths, where position 37 exists in some examples and is padding in others, and autoregressive generation, where the model sees one new token at a time. Layer normalisation (LayerNorm, LN) keeps the idea of standardising activations but computes the statistics within one example: over the features of a vector. Because it never looks at other examples it behaves identically in training and inference, needs no running statistics, and works with any batch size. Every transformer uses it or its cheaper variant RMSNorm.
The formulas, their invariances and the gradient are in Layer Normalization and RMSNorm. Here you implement both, match them against nn.LayerNorm and nn.RMSNorm, place them in a residual stack (pre-norm versus post-norm) and measure the difference.
Which axis
The only difference between BN and LN is the axis the mean and variance are taken over:
For an activation of shape , BN produces means (one per column) and LN produces means (one per row). For a transformer activation of shape , batch by tokens by model width, LN normalises each of the token vectors on its own.
The formulas
For one vector :
RMSNorm (Zhang and Sennrich, 2019) drops the mean subtraction and the shift . It is invariant to rescaling , but not to shifting it. It costs one reduction instead of two and has half the parameters, and in large language models (LLaMA, Mistral, Gemma and many others) it trains as well as LayerNorm, so it has become the default there. Both layers have of size ; LayerNorm adds of size .
From scratch in NumPy
import numpy as np
def batch_norm(x, eps=1e-5): # statistics over the batch axis 0, one per feature
return (x - x.mean(0)) / np.sqrt(x.var(0) + eps)
def layer_norm(x, g, b, eps=1e-5): # statistics over the last axis, one per example (or token)
mu = x.mean(-1, keepdims=True)
var = x.var(-1, keepdims=True)
return g * (x - mu) / np.sqrt(var + eps) + b
def rms_norm(x, g, eps=1e-6): # no mean subtraction, no beta
return g * x / np.sqrt((x ** 2).mean(-1, keepdims=True) + eps)
rng = np.random.default_rng(0)
d = 6
x = rng.normal(2.0, 3.0, (4, d)) # 4 examples, 6 features
g, b = np.ones(d), np.zeros(d)
ln = layer_norm(x, g, b)
print("LN: per-row mean", (np.round(ln.mean(1), 6) + 0.0).tolist(), " per-row std", np.round(ln.std(1), 4).tolist())
rms = rms_norm(x, g)
print("RMS: per-row root-mean-square", np.round(np.sqrt((rms ** 2).mean(1)), 4).tolist())
# batch independence: change the OTHER examples, look at example 0
x2 = x.copy(); x2[1:] = rng.normal(-5.0, 1.0, (3, d))
print("example 0 changes under BN:", not np.allclose(batch_norm(x)[0], batch_norm(x2)[0]))
print("example 0 changes under LN:", not np.allclose(layer_norm(x, g, b)[0], layer_norm(x2, g, b)[0]))
# invariances: LN ignores a shift and a scale of a row, RMSNorm only the scale
row = x[:1]
print("LN(3x + 7) == LN(x):", np.allclose(layer_norm(3 * row + 7, g, b), layer_norm(row, g, b), atol=1e-6))
print("RMS(3x) == RMS(x):", np.allclose(rms_norm(3 * row, g), rms_norm(row, g)),
" RMS(x + 7) == RMS(x):", np.allclose(rms_norm(row + 7, g), rms_norm(row, g)))
# a transformer activation: (batch, tokens, d_model); LN normalises each token vector
h = rng.normal(0, 1, (2, 5, 8)) * rng.uniform(0.1, 10, (2, 5, 1)) # tokens with very different scales
out = layer_norm(h, np.ones(8), np.zeros(8))
print("token norms before:", np.round(np.linalg.norm(h[0], axis=-1), 2).tolist())
print("token norms after: ", np.round(np.linalg.norm(out[0], axis=-1), 3).tolist())LN: per-row mean [0.0, 0.0, 0.0, 0.0] per-row std [1.0, 1.0, 1.0, 1.0]
RMS: per-row root-mean-square [1.0, 1.0, 1.0, 1.0]
example 0 changes under BN: True
example 0 changes under LN: False
LN(3x + 7) == LN(x): True
RMS(3x) == RMS(x): True RMS(x + 7) == RMS(x): False
token norms before: [9.8, 5.29, 23.27, 7.88, 4.39]
token norms after: [2.828, 2.828, 2.828, 2.828, 2.828]
After LN each row has mean 0 and standard deviation 1; after RMSNorm each row has root-mean-square 1 (its mean is not 0). The batch-independence test is the important one: replacing examples 1 to 3 by different data changes the BN output of example 0, but not its LN output. The invariance lines show the difference between the two layers: LN gives the same output for as for , RMSNorm only for . In the transformer-shaped tensor the five token vectors have norms from 4.39 to 23.27 before LN and all have norm after it (mean 0 and variance 1 over 8 values means a squared norm of 8).
In PyTorch, number for number
The recorded example (PyTorch 2.14.1 on CPU, float64) compares nn.LayerNorm and nn.RMSNorm with the NumPy formulas and shows how GroupNorm relates to the others:
import numpy as np
import torch
from torch import nn
torch.manual_seed(0)
x = torch.randn(2, 5, 8, dtype=torch.float64) * 3 + 1 # (batch, tokens, d_model)
xn = x.numpy()
ln = nn.LayerNorm(8).double() # eps 1e-5, weight 1, bias 0
rms = nn.RMSNorm(8, eps=1e-6).double() # weight 1, no bias
with torch.no_grad():
ln.weight.uniform_(0.5, 1.5); ln.bias.uniform_(-0.5, 0.5); rms.weight.uniform_(0.5, 1.5)
g, b = ln.weight.detach().numpy(), ln.bias.detach().numpy()
mu, var = xn.mean(-1, keepdims=True), xn.var(-1, keepdims=True) # biased variance
ln_np = g * (xn - mu) / np.sqrt(var + 1e-5) + b
r = rms.weight.detach().numpy()
rms_np = r * xn / np.sqrt((xn ** 2).mean(-1, keepdims=True) + 1e-6)
print("nn.LayerNorm == NumPy:", np.abs(ln(x).detach().numpy() - ln_np).max() < 1e-12)
print("nn.RMSNorm == NumPy:", np.abs(rms(x).detach().numpy() - rms_np).max() < 1e-12)
print("parameters LayerNorm:", sum(p.numel() for p in ln.parameters()),
" RMSNorm:", sum(p.numel() for p in rms.parameters()),
" buffers:", len(list(ln.buffers())))
print("default RMSNorm eps:", nn.RMSNorm(8).eps, "(None = torch.finfo(dtype).eps)")
ln.eval()
print("same output in eval mode:", np.abs(ln(x).detach().numpy() - ln_np).max() < 1e-12)
# normalised_shape picks the trailing axes: (5, 8) normalises each whole sequence
print("LayerNorm((5, 8)) weight shape:", tuple(nn.LayerNorm((5, 8)).weight.shape))
# GroupNorm on images (N, C, H, W): groups of channels, per example
img = torch.randn(4, 6, 3, 3, dtype=torch.float64)
gn = nn.GroupNorm(num_groups=2, num_channels=6, affine=False).double()
grp = img.view(4, 2, 3 * 3 * 3) # 2 groups of 3 channels each
manual = ((grp - grp.mean(-1, keepdim=True)) / torch.sqrt(grp.var(-1, unbiased=False, keepdim=True) + 1e-5)).view_as(img)
print("GroupNorm(2 groups) == manual:", torch.allclose(gn(img), manual))
ln_chw = nn.LayerNorm((6, 3, 3), elementwise_affine=False).double()
print("GroupNorm(1 group) == LayerNorm over (C, H, W):",
torch.allclose(nn.GroupNorm(1, 6, affine=False).double()(img), ln_chw(img)))
inst = nn.InstanceNorm2d(6).double()
print("GroupNorm(6 groups) == InstanceNorm2d:", torch.allclose(nn.GroupNorm(6, 6, affine=False).double()(img), inst(img)))nn.LayerNorm == NumPy: True
nn.RMSNorm == NumPy: True
parameters LayerNorm: 16 RMSNorm: 8 buffers: 0
default RMSNorm eps: None (None = torch.finfo(dtype).eps)
same output in eval mode: True
LayerNorm((5, 8)) weight shape: (5, 8)
GroupNorm(2 groups) == manual: True
GroupNorm(1 group) == LayerNorm over (C, H, W): True
GroupNorm(6 groups) == InstanceNorm2d: True
Both layers match the formulas to , with the biased variance (divisor ) in LayerNorm. The parameter counts are for LayerNorm and for RMSNorm, and neither layer has buffers, so eval mode changes nothing. Three API details:
normalized_shapenames the trailing axes to normalise over:nn.LayerNorm(8)on normalises each token;nn.LayerNorm((5, 8))would normalise each whole sequence, with a weight. Transformers always use the first form.nn.RMSNorm's defaulteps=Nonemeans the machine epsilon of the computation type:torch.finfo(torch.float32).eps(about ) for float32, float16 and bfloat16 inputs, the float64 one for float64. Model code usually passes the value the checkpoint was trained with, such as1e-6or1e-5; a different is a small but real mismatch when you port weights.elementwise_affine=False(LayerNorm) oraffine=False(GroupNorm) drops and .
GroupNorm (Wu and He, 2018) is the image version: it splits the channels of one example into groups and normalises each group over its channels and all pixels. With it is LayerNorm over ; with it is InstanceNorm, as the last two lines confirm. Like LN it is independent of the batch, which is why detection, segmentation and diffusion U-Nets use it (typically ) where batches are small.
Pre-norm versus post-norm
Where does the normalisation go in a residual block ? The original transformer (2017) normalised after the addition, post-norm: . Almost every model since GPT-2 normalises the input of the branch, pre-norm: , plus one final LN before the output head. In pre-norm the identity path from the input to the output contains no normalisation at all, so the gradient reaches the first block through a chain of additions; in post-norm it passes through one LN per block.
The experiment: a residual MLP of 24 blocks on Digits, each block = Linear(64, 128), GELU, Linear(128, 64), trained with Adam for 8 epochs at two learning rates, no warm-up, accuracy on the validation split. The first lines report, at initialisation, the standard deviation of the residual stream after block 1 and after block 24 and the ratio of the gradient norms of the first and the last block.
import torch
from torch import nn
from sklearn.datasets import load_digits
from sklearn.model_selection import train_test_split
X, y = load_digits(return_X_y=True)
X = X / 16.0
X_tmp, X_te, y_tmp, y_te = train_test_split(X, y, test_size=0.2, random_state=0, stratify=y)
X_tr, X_va, y_tr, y_va = train_test_split(X_tmp, y_tmp, test_size=0.25, random_state=0, stratify=y_tmp)
X_tr, X_va = (torch.tensor(a, dtype=torch.float32) for a in (X_tr, X_va))
y_tr, y_va = (torch.tensor(a) for a in (y_tr, y_va))
D, BLOCKS = 64, 24
class Block(nn.Module):
def __init__(self, norm, pre):
super().__init__()
self.pre = pre
self.norm = nn.LayerNorm(D) if norm == "LN" else nn.RMSNorm(D)
self.ff = nn.Sequential(nn.Linear(D, 2 * D), nn.GELU(), nn.Linear(2 * D, D))
def forward(self, h):
if self.pre:
return h + self.ff(self.norm(h)) # pre-norm: the identity path is untouched
return self.norm(h + self.ff(h)) # post-norm: every block normalises the sum
class Net(nn.Module):
def __init__(self, norm, pre):
super().__init__()
self.inp = nn.Linear(64, D)
self.blocks = nn.Sequential(*[Block(norm, pre) for _ in range(BLOCKS)])
self.final = nn.LayerNorm(D) if pre else nn.Identity() # pre-norm needs a final norm
self.head = nn.Linear(D, 10)
def forward(self, x):
return self.head(self.final(self.blocks(self.inp(x))))
for name, norm, pre in (("post-norm LN", "LN", False), ("pre-norm LN", "LN", True), ("pre-norm RMS", "RMS", True)):
for lr in (1e-3, 1e-2):
torch.manual_seed(0)
model = Net(norm, pre)
nn.functional.cross_entropy(model(X_tr[:256]), y_tr[:256]).backward()
g1 = model.blocks[0].ff[0].weight.grad.norm().item()
gL = model.blocks[-1].ff[0].weight.grad.norm().item()
with torch.no_grad():
stream = [model.blocks[:k](model.inp(X_tr[:256])).std().item() for k in (1, BLOCKS)]
opt = torch.optim.Adam(model.parameters(), lr=lr)
gen = torch.Generator().manual_seed(0)
for epoch in range(8):
model.train()
for idx in torch.randperm(len(y_tr), generator=gen).split(64):
loss = nn.functional.cross_entropy(model(X_tr[idx]), y_tr[idx])
opt.zero_grad(); loss.backward(); opt.step()
model.eval()
with torch.no_grad():
acc = (model(X_va).argmax(1) == y_va).float().mean().item()
if lr == 1e-3:
print(f"{name}: at init, stream std after block 1 {stream[0]:.2f}, after block {BLOCKS} {stream[1]:.2f};"
f" grad norm block 1 / block {BLOCKS} {g1 / gL:.2f}")
print(f" lr {lr:<6} val acc after 8 epochs {acc:.3f}")post-norm LN: at init, stream std after block 1 1.00, after block 24 1.00; grad norm block 1 / block 24 0.97
lr 0.001 val acc after 8 epochs 0.961
lr 0.01 val acc after 8 epochs 0.100
pre-norm LN: at init, stream std after block 1 0.38, after block 24 1.00; grad norm block 1 / block 24 3.95
lr 0.001 val acc after 8 epochs 0.969
lr 0.01 val acc after 8 epochs 0.914
pre-norm RMS: at init, stream std after block 1 0.38, after block 24 1.01; grad norm block 1 / block 24 3.71
lr 0.001 val acc after 8 epochs 0.950
lr 0.01 val acc after 8 epochs 0.928
At learning rate 0.001 all three variants train to 0.950 to 0.969. At 0.01 the post-norm network collapses to chance (0.100), while pre-norm LN reaches 0.914 and pre-norm RMSNorm 0.928. This mirrors what happened with transformers: post-norm models train well but need a learning-rate warm-up and care, pre-norm models are robust, which matters more as the model and the learning rate grow. (Some studies report slightly better final quality for post-norm when it does train, which is why it still appears in some recipes.)
The initial measurements show the mechanism of pre-norm. Its residual stream is never normalised, so it grows as the blocks add their outputs, here from 0.38 after block 1 to 1.00 after block 24, and the late blocks see a larger stream that their own LN divides down. The early blocks therefore receive the larger gradients (3.95 times those of block 24 with LN). In post-norm the stream is renormalised to standard deviation 1.00 after every block and the gradients are balanced at initialisation (0.97); its instability shows up after training starts, when large updates pass through 24 normalisations in a row.
Why transformers use LN or RMSNorm
- Batch independence. The output for one sequence does not depend on which other sequences share the batch, so training, evaluation and generation with batch size 1 compute the same function.
- Variable lengths. Each token is normalised on its own; padded positions do not pollute the statistics of real ones (BN over a padded batch would average padding into its means).
- Generation. With a KV cache the model processes one token per step; a per-token normalisation needs nothing else (Building a Transformer Block).
- No running statistics to get wrong when switching between train and eval mode, or when fine-tuning on a different distribution.
Pitfalls
- Normalising the wrong axis. On a tensor of shape ,
nn.LayerNorm(d)is right;nn.LayerNorm(T)on a transposed tensor normalises over time and mixes tokens. Checknormalized_shapeagainst the last dimensions. - Using
BatchNorm1don sequences.nn.BatchNorm1dexpects and normalises each channel over the batch and all positions, including padding. - Forgetting the final norm in a pre-norm stack. Without it the head sees the un-normalised, growing residual stream.
- Mismatched or variant when loading weights: a checkpoint trained with RMSNorm, needs exactly that.
- Low precision. Compute the statistics in float32 even when the model runs in bf16 or float16; PyTorch's fused kernels do this, hand-written versions often do not.
Practice
- How many parameters do the normalisation layers of a 12-block pre-norm transformer with have, with two LayerNorms per block and one final LayerNorm? How many with RMSNorm?
Answer
layers parameters with LayerNorm, and with RMSNorm. Tiny next to the roughly 85 million weights of the blocks.
- Write RMSNorm as an
nn.Modulewith a learnable weight.
Answer
class MyRMSNorm(nn.Module):
def __init__(self, d, eps=1e-6):
super().__init__()
self.eps = eps
self.weight = nn.Parameter(torch.ones(d))
def forward(self, x):
rms = torch.sqrt(x.pow(2).mean(-1, keepdim=True) + self.eps)
return self.weight * x / rmsIt should match nn.RMSNorm(d, eps=1e-6) with the same weight; in bf16 code cast x to float32 inside forward and back at the end.
- A token vector is . What do LayerNorm and RMSNorm (with , , ) output?
Answer
LayerNorm: , , so and the output is (with there is no division by zero). RMSNorm: , output . RMSNorm keeps a constant direction that LayerNorm removes.
Test yourself
For an activation of shape (batch, tokens, d_model), what does nn.LayerNorm(d_model) normalise over?
- The batch axis, one mean per feature
- The last axis: each token vector separately
- All values of the batch
- The token axis
What does RMSNorm leave out compared with LayerNorm?
- The scale
- The mean subtraction and the shift
- The square root
- The
Why does LayerNorm need no running statistics?
- It uses the statistics of the training set
- Its statistics come from the example itself, so training and inference compute the same thing
- It has no parameters
- It only runs in eval mode
In the 24-block experiment at learning rate 0.01, which variant failed?
- Pre-norm LayerNorm
- Pre-norm RMSNorm
- Post-norm LayerNorm, which fell to chance (0.100)
- None
What is nn.GroupNorm(1, C) equivalent to on images of shape ?
- BatchNorm2d
- InstanceNorm2d
- LayerNorm over for each example
- No normalisation