286. Normalize activations with RMSNorm
Many recent LLMs replace LayerNorm with RMSNorm: it skips subtracting the mean and only divides by the root mean square, then multiplies by a learned weight per feature.
Write rmsnorm(x, weight, eps=1e-6) where x has shape (..., d) and weight has shape (d,):
rms = sqrt(mean(x**2 over the last axis) + eps)
return x / rms * weight
Keep the input's shape. It must work for a single vector and for a batch.
def rmsnorm(x, weight, eps=1e-6)RMSNorm on one token's features
x / √(mean(x²) + ε) · w. No mean is subtracted, so shifting all inputs up changes the output, unlike LayerNorm.
- rms
- 2.092
- output rms
- 1
Example 1
Input: x = [3.0, 4.0], weight = [1.0, 1.0], eps = 0.0
Output: [3.0, 4.0] / np.sqrt(12.5)
Example 2
Input: x = [1.0, 1.0], weight = [2.0, 0.5], eps = 0.0
Output: [2.0, 0.5]
Example 3
Input: rmsnorm(np.array([[1.0, 2.0, 3.0], [10.0, 0.0, -10.0]]), np.ones(3), eps=0.0)[1]
Output: [10.0, 0.0, -10.0] / np.sqrt(200 / 3)
Constraints
xhas shape(..., d)weighthas shape(d,)- Python 3 with NumPy. Code runs in your browser.
- Your code must pass all 4 tests to be accepted.
Hint 1
RMSNorm is LayerNorm without subtracting the mean: divide by the root mean square of the last axis, then scale.
Hint 2
Square x, take the mean over the last axis, add eps, take the square root, divide x by it, and multiply by the weight.
Hint 3
Use np.mean(x * x, axis=-1, keepdims=True) so the result broadcasts back over x for both a single vector and a batch; eps goes inside the square root.
Common mistakes
- Normalizing over the whole batch at once, as the buggy version does, mixes rows together.
Understand the idea
RMSNorm rescales each vector so its typical size is about 1, then multiplies by a learned weight per feature. Unlike LayerNorm it does not subtract the mean; it only divides by the root mean square. It is like adjusting the volume of a song without changing the tune.
x = [3, 4], weight = [1, 1], tiny eps ignored. Squares are 9 and 16, mean 12.5, square root 3.536. So output = [3/3.536, 4/3.536] = [0.849, 1.131]. Each vector in a batch is normalised on its own, over the last axis only, so one row never affects another.
rms = sqrt(mean(x^2 over last axis) + eps); output = x / rms * weight
Keep dims when taking the mean so it broadcasts back. Llama, Mistral and many recent LLMs use RMSNorm because it is simpler and slightly faster than LayerNorm.