AI Logic

Normalization

RMSNorm

Updated:

The range and method of RMSNorm's computation. Left: the computation pools the d values of one token (one column of the grid). Right: comparison of the input (2, 4, 6, 8) normalized by Layer Normalization and by RMSNorm. Below: the computation flow of Layer Normalization (using the mean and standard deviation) and RMSNorm (using only the RMS)

What Is RMSNorm?

RMSNorm (Root Mean Square Layer Normalization) is a normalization method that drops the mean subtraction from Layer Normalization and simply divides by the root mean square (RMS) of the values. Zhang and Sennrich proposed it in 2019. It is cheaper to compute while performing about as well as Layer Normalization; in the paper's experiments, training time was reduced by 7–64%.

Layer Normalization does two things: "equalizing the mean (re-centering)" and "equalizing the scale (re-scaling)." The paper argued that the latter is what stabilizes training and the former is unnecessary. RMSNorm keeps only the re-scaling part.

Today it is widely used in large language models. For example, LLaMA uses RMSNorm in the Pre-LN arrangement, normalizing the input of each sublayer.

The left side of the figure at the top of the article shows the range over which the mean and RMS are computed. As in Layer Normalization, the computation pools the dd values of one sample (one token in a Transformer). The right side shows an example of the same input normalized by Layer Normalization and by RMSNorm.

Computation Steps

Let a1,…,ana_1, \dots, a_n be the inputs to the nn units of a layer (the weighted sums). RMSNorm computes the following in order (Eq. (4) in the paper).

  1. Compute the root mean square. Square the values, average them, and take the square root. RMS(a)=1nβˆ‘i=1nai2\mathrm{RMS}(\boldsymbol{a}) = \sqrt{\frac{1}{n} \sum_{i=1}^{n} a_i^2}
  2. Divide each value by the RMS and multiply by the gain. gig_i is a learnable parameter for each unit, initialized to 1. aΛ‰i=aiRMS(a) gi\bar{a}_i = \frac{a_i}{\mathrm{RMS}(\boldsymbol{a})} \, g_i

For comparison, here is the Layer Normalization formula as well (Eqs. (2) and (3) in the paper).

aΛ‰i=aiβˆ’ΞΌΟƒβ€‰gi,ΞΌ=1nβˆ‘i=1nai,Οƒ=1nβˆ‘i=1n(aiβˆ’ΞΌ)2\bar{a}_i = \frac{a_i - \mu}{\sigma} \, g_i, \qquad \mu = \frac{1}{n} \sum_{i=1}^{n} a_i, \qquad \sigma = \sqrt{\frac{1}{n} \sum_{i=1}^{n} (a_i - \mu)^2}

RMSNorm does not compute ΞΌ\mu and uses the RMS instead of Οƒ\sigma. If the mean of the input is exactly 0, the RMS equals the standard deviation, and RMSNorm is exactly the same as Layer Normalization.

Worked Example

Compare using the same input as in the Layer Normalization article, a=(2,4,6,8)\boldsymbol{a} = (2, 4, 6, 8) (gi=1g_i = 1).

InputLayer NormalizationRMSNorm
Statistics usedβ€”ΞΌ=5\mu = 5, Οƒ=5β‰ˆ2.24\sigma = \sqrt{5} \approx 2.24RMS=(4+16+36+64)/4=30β‰ˆ5.48\mathrm{RMS} = \sqrt{(4 + 16 + 36 + 64)/4} = \sqrt{30} \approx 5.48
Normalized values(2,4,6,8)(2, 4, 6, 8)(βˆ’1.34,Β βˆ’0.45,Β 0.45,Β 1.34)(-1.34,\ -0.45,\ 0.45,\ 1.34)(0.37,Β 0.73,Β 1.10,Β 1.46)(0.37,\ 0.73,\ 1.10,\ 1.46)

The result of Layer Normalization has mean 0, but the result of RMSNorm does not. RMSNorm equalizes only the magnitude of the values (mean square of 1), so the information that the whole vector is skewed toward the positive side is preserved.

In implementations, a small value Ο΅\epsilon is added to avoid division by zero: 1nβˆ‘ai2+Ο΅\sqrt{\frac{1}{n}\sum a_i^2 + \epsilon}. If Ο΅\epsilon is not specified, PyTorch's nn.RMSNorm uses the machine epsilon of the floating-point type used in the computation (torch.finfo(...).eps).

Why the Mean Need Not Be Subtracted

The paper organizes the properties of normalization in terms of invariance, that is, what can be changed without changing the output.

  • Re-scaling invariance: The output does not change no matter how much the input xx or the weight matrix WW is scaled. Since the RMS satisfies RMS(Ξ±a)=α RMS(a)\mathrm{RMS}(\alpha \boldsymbol{a}) = \alpha \, \mathrm{RMS}(\boldsymbol{a}), scaling WW by Ξ΄\delta scales both the numerator and the denominator by Ξ΄\delta, leaving the output unchanged (Eqs. (6) and (7) in the paper). Both RMSNorm and Layer Normalization have this property.
  • Re-centering invariance: The output does not change when a constant is added to the input or weights. Layer Normalization, which subtracts the mean, has this property, but RMSNorm does not.

The paper's hypothesis is that what lets Layer Normalization stabilize training is re-scaling invariance, while re-centering invariance contributes little. Its gradient analysis also shows that in RMSNorm the weight gradients do not depend on the scaling of the input, and the larger the weights, the smaller the gradients. The paper calls this an "implicit learning rate adaptation" that keeps the weights from growing too large.

In fact, when the mean and standard deviation of hidden states were measured in an RNN translation model, RMSNorm kept the mean more stable than no normalization, even though it does not equalize the mean directly (Table 5 in the paper).

Dividing by the length of the vector (the Euclidean norm, which is n\sqrt{n} times the RMS) instead of the RMS was also tried, but it did not work well in the paper's experiments. The paper argues that dividing by the RMS brings the values to a magnitude of about 1 regardless of the vector dimension nn, so it behaves the same across layers of different dimensions.

Experimental Results

The paper compares no normalization, Layer Normalization, and RMSNorm on translation, reading comprehension, image–caption retrieval, and image classification. Speed is the reduction in training time relative to Layer Normalization.

Task and modelLayer NormalizationRMSNormRMSNorm speedup
Translation, RNN (TensorFlow)BLEU 22.6 / 23.6BLEU 22.4 / 23.724.7% shorter
Translation, RNN (Theano)BLEU 22.3 / 23.8BLEU 22.5 / 23.234.0% shorter
Translation, RNN (PyTorch)BLEU 23.2 / 24.3BLEU 22.9 / 24.511.0% shorter
Translation, TransformerBLEU 26.6 / 27.7BLEU 26.8 / 27.76.9% shorter
Reading comprehension (CNN article cloze), LSTMComparable error rateComparable error rate15.1% shorter
Image–caption retrieval (COCO)Comparable recallComparable recall40.8% shorter
Image classification (CIFAR-10), CNNError 10.49%Error 8.83%20.5% shorter

(Translation BLEU is WMT14 Enβ†’De newstest2014 / newstest2017. From Tables 2–4, 6, 8, and 10 of the paper.)

  • Performance is comparable to Layer Normalization, slightly better or worse depending on the task.
  • The speedup depends on the share of normalization in the total computation. RNNs repeat normalization at every time step, so the effect is large; Transformers normalize relatively few times, so the gain was only 7–9%.
  • In the Transformer, removing all normalization made training fail. Normalization itself is necessary; only the mean computation can be omitted.
  • In an experiment that shifted the center of the initial weights to 0.2, Layer Normalization became very unstable, while RMSNorm was more stable.

The paper also proposes pRMSNorm, which estimates the RMS from only part of the input (for example, the first 6.25%). In principle it is even cheaper, but depending on the implementation it was not faster, and on some tasks accuracy dropped.

Practical Considerations

RMSNorm does not correct shifts in the mean. If the whole input is skewed positive or negative, that skew remains in the output. Although it gave good results on image classification (CIFAR-10) in the paper, Batch Normalization is still the standard for convolutional networks. RMSNorm is mainly used in sequence models such as Transformers; when using it in other kinds of models, verify it against Layer Normalization.

Do not swap Layer Normalization and RMSNorm in a pretrained model. For inputs whose mean is not 0, the output changes, so applying RMSNorm to weights trained with Layer Normalization (or vice versa) will not work correctly. Retrain if you switch.

Also keep the following in mind.

  • The speedup varies by environment. The paper also notes that actual speed depends on the framework, hardware, model architecture, and the computational cost of other components. In models where normalization is already cheap, the difference is small.
  • Check whether there is a bias. PyTorch's nn.RMSNorm learns only an element-wise gain (weight), with no bias. The general form in the paper (Eq. (5)) adds a bias bb, but this corresponds to the bias of the layer that follows the normalization.
  • Normalization is over the last axis. Like nn.LayerNorm, nn.RMSNorm(d_model) computes the RMS over the last axes of the tensor (those specified by normalized_shape).

Comparison with Other Normalization Methods

AspectRMSNormLayer NormalizationBatch Normalization
Range for statisticsUnits of a layer in one sampleUnits of a layer in one sampleOne unit across the whole mini-batch
Statistics computedRoot mean square (RMS) onlyMean and standard deviationMean and variance
Centers the mean at 0NoYesYes
Learnable parametersGain ggGain gg and bias bbScale Ξ³\gamma and shift Ξ²\beta
Affected by batch sizeNoNoYes
Computational costLightModerateModerate (fixed linear transform at inference)
Main usesLarge language models (LLaMA, etc.)Transformers, RNNsCNNs

Rough guidelines for choosing:

  • Training a new Transformer or RNN and wanting it a bit faster: RMSNorm. It can simply replace Layer Normalization with comparable performance.
  • Matching an existing model's architecture, or also correcting mean shifts: Layer Normalization.
  • CNNs with sufficiently large batches: Batch Normalization.

Where to place normalization (before or after adding the residual) is a separate choice from the type of normalization. RMSNorm can be used with either the Pre-LN or Post-LN arrangement.

PyTorch example

Show code
python
import torch
import torch.nn as nn

# Example from the text: one token with d = 4
a = torch.tensor([[2.0, 4.0, 6.0, 8.0]])
rms = a.pow(2).mean(dim=-1, keepdim=True).sqrt()   # √30 β‰ˆ 5.477
print(a / rms)                                      # about [0.365, 0.730, 1.095, 1.461]

# Implementation following Eq. (4) of the paper (only the gain g is learned)
class RMSNorm(nn.Module):
    def __init__(self, d: int, eps: float = 1e-6):
        super().__init__()
        self.eps = eps
        self.weight = nn.Parameter(torch.ones(d))   # g starts at 1

    def forward(self, x: torch.Tensor) -> torch.Tensor:
        # mean square over the last axis (d values); the mean ΞΌ is not computed
        rms = torch.sqrt(x.pow(2).mean(dim=-1, keepdim=True) + self.eps)
        return x / rms * self.weight

# PyTorch built-in (available in recent versions). Computes the RMS over the last axis; only the gain is learned
builtin = nn.RMSNorm(4, eps=1e-6)
print(torch.allclose(RMSNorm(4)(a), builtin(a), atol=1e-6))   # True

# Use in a Transformer (Pre-LN arrangement: normalize the input of each sublayer)
x = torch.randn(2, 10, 512)          # [batch, sequence length, d_model]
norm = nn.RMSNorm(512)
ffn = nn.Sequential(nn.Linear(512, 2048), nn.SiLU(), nn.Linear(2048, 512))
y = x + ffn(norm(x))
print(y.shape)                       # torch.Size([2, 10, 512])

FAQ

Q. Should I use RMSNorm or Layer Normalization?
A.

In Transformers and RNNs, performance is roughly the same with either. Use RMSNorm to make computation a bit lighter; use Layer Normalization to match the architecture of an existing model (such as BERT) or to also correct mean shifts. When using pretrained weights, match whichever the model uses.

Q. Doesn't skipping the mean subtraction make training unstable?
A.

In the paper's experiments it was as stable as Layer Normalization. The paper's claim is that what stabilizes training is equalizing the scale of the values, and equalizing the mean contributes little. In fact, the mean of RNN hidden states was more stable than with no normalization, even though the mean was not equalized directly.

Q. How much faster is it?
A.

In the paper, training time was 7–64% shorter than with Layer Normalization. The effect is large for RNNs, which repeat normalization many times, and was 7–9% for Transformers. The smaller the share of normalization in the model's computation, the smaller the difference.

References

  1. B. Zhang and R. Sennrich, "Root Mean Square Layer Normalization," NeurIPS, 2019.
  2. J. L. Ba, J. R. Kiros, and G. E. Hinton, "Layer Normalization," arXiv:1607.06450, 2016.
  3. H. Touvron et al., "LLaMA: Open and Efficient Foundation Language Models," arXiv:2302.13971, 2023.
  4. PyTorch Documentation, "torch.nn.RMSNorm."