Linear algebra for LLMsPart 6: The rest of the transformer
LayerNorm and RMSNorm
7 min
LayerNorm
and are the mean and variance of one token’s features (Part 4: over dim=-1). is a tiny constant against dividing by zero. and are learned, one per feature.
Write
Step 1: center
The mean of is 5. Subtracting it leaves values that sum to 0.
Step 2: divide by the standard deviation
Now the features have mean 0 and variance 1 (ignoring ). Then and rescale and shift each feature, so the model can undo any of it that it doesn’t want.
Write
What it does geometrically
Centering removes the all-ones direction (Part 3’s projections). Dividing by then puts every token on a sphere of radius : here , and indeed . Then stretches each axis (a diagonal matrix, Part 2).
Write
RMSNorm skips the centering
No mean, no : just divide by the root mean square and apply the gain. It’s cheaper and works about as well (Zhang & Sennrich, 2019). Llama uses RMSNorm.
Write
✏️ Your turn
Normalize this, both ways
Take , and ignore . Write and .
Work it out on paper, then go to the next card to check.
Answer: the same, this time
The mean is already 0, so centering does nothing; . LayerNorm and RMSNorm only differ when the mean isn’t 0.
In PyTorch
nn.LayerNorm(d) # (x - mean) / sqrt(var + eps) * weight + bias
nn.RMSNorm(d) # x / sqrt(mean(x**2) + eps) * weightBoth normalize over the last axis: one token at a time, never across the batch.
📌 Recap
LayerNorm and RMSNorm in one card
- LayerNorm: subtract the mean, divide by the standard deviation, then .
- RMSNorm: divide by the root mean square, then .
- Per token, over its features.
- Geometry: remove the mean direction, land on a sphere of radius , rescale each axis.
Write