Equations · Zhang and Sennrich, “Root Mean Square Layer Normalization” (2019); used in LLaMA and most recent LLMs

The RMSNorm formula, explained

A cheaper LayerNorm: divide by the root mean square of the features and apply a learned gain. It skips subtracting the mean and has no shift.

RMSNorm⁡(x)=xRMS⁡(x)⊙g,RMS⁡(x)=1d∑i=1dxi2+ϵ\operatorname{RMSNorm}(\mathbf{x}) = \frac{\mathbf{x}}{\operatorname{RMS}(\mathbf{x})} \odot \mathbf{g}, \quad \operatorname{RMS}(\mathbf{x}) = \sqrt{\frac{1}{d}\sum_{i=1}^{d} x_i^2 + \epsilon}

Open in the decoder →

Term by term

  1. RMS⁡(x)\operatorname{RMS}(\mathbf{x})

    The root of the mean of the squares: a measure of the vector's typical size.

  2. xi2x_i^2

    The ii-th entry, squared.

  3. ϵ\epsilon

    A small constant for numerical safety. The paper's formula has none; implementations such as LLaMA's add it inside the root.

  4. ⊙ g\odot\, \mathbf{g}

    A learned per-feature gain, applied elementwise.

A small worked example

x=(1,2,3)\mathbf{x} = (1, 2, 3): mean of squares =14/3≈4.67= 14/3 \approx 4.67, RMS⁡≈2.16\operatorname{RMS} \approx 2.16, so the output is about (0.46,0.93,1.39)(0.46, 0.93, 1.39) times the gain. LayerNorm would give (−1.22,0,1.22)(-1.22, 0, 1.22): it also re-centres.

In code

import numpy as np

def rms_norm(x, g, eps=1e-6):
    rms = np.sqrt(np.mean(x**2, -1, keepdims=True) + eps)
    return x / rms * g

Every symbol in it

dk\sqrt{d_k}Square root∑i=1Nxi\sum_{i=1}^{N} x_iSummationab\frac{a}{b}Fractionxi,  Wq,  pθ,  dmodelx_i,\; W_q,\; p_\theta,\; d_{\text{model}}Subscript (index or label)x2,  βt,  WQx^2,\; \beta^t,\; W^QSuperscript (power or label)ϵ\epsilonEpsilona⊙b\mathbf{a} \odot \mathbf{b}Hadamard (elementwise) productx∈Rd\mathbf{x} \in \mathbb{R}^{d}Bold lowercase (vector)

Other equations