The problem
RMSNorm (root mean square layer normalization) is a simpler LayerNorm (layer normalization). LayerNorm shifts each vector to mean 0 and rescales it; RMSNorm only rescales it, so that its typical size is 1, then applies a learned gain of numbers. There is no bias. LLaMA (Large Language Model Meta AI) applies it before every attention and MLP (multilayer perceptron) block.
How it works
The typical size of a vector is measured by its RMS (root mean square): square every entry, take the mean, take the square root.
where:
- is one token's vector of numbers, and its entry ;
- (epsilon) is
eps, which avoids dividing by zero for an all-zero vector; - (gamma) is the learned gain, and is elementwise multiplication.
Example. , .
- Squares: . Mean: . Square root: .
- .
LayerNorm on the same vector gives : it removes the mean first, so half of the entries become negative. RMSNorm keeps them all positive.
What to implement
rmsnorm(x, gamma, eps=1e-6): x has shape , with any number of leading axes, and is normalized over the last axis. Return , same shape as x.
Requirements
- Do not subtract the mean: that is the difference from LayerNorm.
epsgoes inside the square root, as in PyTorch'storch.nn.RMSNorm.- No Python loops.
Hint
Take the mean of x**2 over the last axis with keepdims=True, so that the result has shape and divides every entry of its own vector.