Layer Normalization and RMSNorm
Batch normalization averages over the batch, which is awkward for variable-length sequences, tiny batches and autoregressive generation one token at a time. Layer normalization (Ba, Kiros and Hinton, 2016) normalizes each example on its own, across its features. It is the normalization of the transformer, and its simplified cousin RMSNorm is used in Llama and most recent LLMs.
LayerNorm
For one token's hidden vector :
The statistics come from the vector itself, so the operation is identical at training and inference time and does not care about the batch size. Compared with batch normalization, the averaging axis changes from "over examples, per feature" to "over features, per example".
RMSNorm
RMSNorm drops the mean subtraction and the bias:
It rescales to have root mean square 1, i.e. norm : geometrically, it projects the vector onto a sphere (then stretches each axis by ). It is cheaper (one reduction instead of two) and works as well in practice.
import numpy as np
rng = np.random.default_rng(0)
X = rng.normal(3.0, 2.0, size=(2, 3, 8)) # (batch, tokens, features)
eps = 1e-5
def layer_norm(x):
mu = x.mean(-1, keepdims=True); var = x.var(-1, keepdims=True)
return (x - mu) / np.sqrt(var + eps)
def rms_norm(x):
return x / np.sqrt(np.mean(x**2, -1, keepdims=True) + eps)
ln, rn = layer_norm(X), rms_norm(X)
print("LayerNorm per token: mean", np.round(ln.mean(-1)[0], 6) + 0, " std", np.round(ln.std(-1)[0], 4))
print("RMSNorm per token: rms ", np.round(np.sqrt(np.mean(rn**2, -1))[0], 4), " norm", np.round(np.linalg.norm(rn, axis=-1)[0], 3), " sqrt(d) =", round(np.sqrt(8), 3))
print("RMSNorm keeps the mean: ", np.round(rn.mean(-1)[0], 3))LayerNorm per token: mean [0. 0. 0.] std [1. 1. 1.]
RMSNorm per token: rms [1. 1. 1.] norm [2.828 2.828 2.828] sqrt(d) = 2.828
RMSNorm keeps the mean: [0.958 0.668 0.926]
Invariances
LayerNorm's output is unchanged if the input is scaled by or shifted by a constant vector ; RMSNorm is invariant only to scaling. Scale invariance makes the layer's output insensitive to the overall size of the weights before it, which stabilizes training. Its gradient is correspondingly orthogonal to (for RMSNorm) or to both and (for LayerNorm).
import numpy as np
rng = np.random.default_rng(1)
x = rng.normal(size=6); eps = 0.0
rms = lambda x: x / np.sqrt(np.mean(x**2) + eps)
ln = lambda x: (x - x.mean()) / np.sqrt(x.var() + eps)
print("RMSNorm scale-invariant:", np.allclose(rms(5 * x), rms(x)), " shift-invariant:", np.allclose(rms(x + 2), rms(x)))
print("LayerNorm scale-invariant:", np.allclose(ln(5 * x), ln(x)), " shift-invariant:", np.allclose(ln(x + 2), ln(x)))
up = rng.normal(size=6)
L = lambda x: rms(x) @ up
g = np.array([(L(x + e) - L(x - e)) / 2e-6 for e in np.eye(6) * 1e-6])
print("RMSNorm gradient is orthogonal to x:", np.isclose(g @ x, 0, atol=1e-6))RMSNorm scale-invariant: True shift-invariant: False
LayerNorm scale-invariant: True shift-invariant: True
RMSNorm gradient is orthogonal to x: True
Pre-norm versus post-norm
The original transformer normalized after each residual addition: (post-norm). Modern models normalize before the sublayer: (pre-norm). Pre-norm keeps an un-normalized identity path from input to output, so gradients reach early layers undisturbed (Residual Connections); it trains stably without careful learning-rate warmup. A final norm is applied before the output layer. Some recent models also normalize queries and keys inside attention (QK-norm) to keep attention logits bounded.
In software
nn.LayerNorm(d, eps=1e-5)andnn.RMSNorm(d)normalize over the last dimension.- Normalization statistics are usually computed in fp32 even under bf16 training (Floating Point).
- Group normalization (statistics over groups of channels) is the CNN analogue for small batches.
Exercises
Exercise 1: LayerNorm by hand
Apply LayerNorm (no , , ) to .
Answer
About .
Solution
Mean 5, deviations , variance , std .
Exercise 2: RMSNorm by hand
Apply RMSNorm (no , ) to .
Answer
About .
Solution
RMS ; divide: , whose norm is .
Exercise 3: Which axis? (code)
For a tensor of shape (batch, tokens, features), compute the shapes of the statistics used by batch norm (over batch and tokens) and by layer norm.
Answer
Batch norm: one mean per feature; layer norm: one mean per (batch, token).
Solution
import numpy as np
X = np.zeros((4, 10, 16))
print(X.mean(axis=(0, 1)).shape, X.mean(axis=-1).shape)(16,) (4, 10)
Test yourself
Layer normalization computes its mean and variance…
- over the batch, per feature
- over the features of each example (token)
- over the whole dataset
- once at initialization
What does RMSNorm leave out compared with LayerNorm?
- The division
- The mean subtraction (and the bias)
- The learned gain
- Everything
Why do modern transformers prefer pre-norm?
- It uses fewer parameters
- The residual path stays an identity, so gradients flow well and training is stable
- It removes the need for attention
- It is required for RMSNorm