TExcelTAD
Home › Math for Deep Learning & LLMs › Layer Normalization and RMSNorm

Layer Normalization and RMSNorm

Batch normalization averages over the batch, which is awkward for variable-length sequences, tiny batches and autoregressive generation one token at a time. Layer normalization (Ba, Kiros and Hinton, 2016) normalizes each example on its own, across its features. It is the normalization of the transformer, and its simplified cousin RMSNorm is used in Llama and most recent LLMs.

LayerNorm

For one token's hidden vector x∈Rd\mathbf{x} \in \mathbb{R}^d:

μ=1d∑i=1dxi,σ2=1d∑i=1d(xi−μ)2,LN⁡(x)=γ⊙x−μσ2+ϵ+β\mu = \frac{1}{d}\sum_{i=1}^{d}x_i, \qquad \sigma^2 = \frac{1}{d}\sum_{i=1}^{d}(x_i - \mu)^2, \qquad \operatorname{LN}(\mathbf{x}) = \boldsymbol{\gamma} \odot \frac{\mathbf{x} - \mu}{\sqrt{\sigma^2 + \epsilon}} + \boldsymbol{\beta}

The statistics come from the vector itself, so the operation is identical at training and inference time and does not care about the batch size. Compared with batch normalization, the averaging axis changes from "over examples, per feature" to "over features, per example".

RMSNorm

RMSNorm drops the mean subtraction and the bias:

RMSNorm⁡(x)=γ⊙x1d∑ixi2+ϵ\operatorname{RMSNorm}(\mathbf{x}) = \boldsymbol{\gamma} \odot \frac{\mathbf{x}}{\sqrt{\frac{1}{d}\sum_i x_i^2 + \epsilon}}

It rescales x\mathbf{x} to have root mean square 1, i.e. norm d\sqrt{d}: geometrically, it projects the vector onto a sphere (then stretches each axis by γi\gamma_i). It is cheaper (one reduction instead of two) and works as well in practice.

python · try it yourself
import numpy as np

rng = np.random.default_rng(0)
X = rng.normal(3.0, 2.0, size=(2, 3, 8))               # (batch, tokens, features)
eps = 1e-5
def layer_norm(x): 
    mu = x.mean(-1, keepdims=True); var = x.var(-1, keepdims=True)
    return (x - mu) / np.sqrt(var + eps)
def rms_norm(x):
    return x / np.sqrt(np.mean(x**2, -1, keepdims=True) + eps)
ln, rn = layer_norm(X), rms_norm(X)
print("LayerNorm per token: mean", np.round(ln.mean(-1)[0], 6) + 0, " std", np.round(ln.std(-1)[0], 4))
print("RMSNorm per token:   rms ", np.round(np.sqrt(np.mean(rn**2, -1))[0], 4), " norm", np.round(np.linalg.norm(rn, axis=-1)[0], 3), " sqrt(d) =", round(np.sqrt(8), 3))
print("RMSNorm keeps the mean: ", np.round(rn.mean(-1)[0], 3))
LayerNorm per token: mean [0. 0. 0.]  std [1. 1. 1.]
RMSNorm per token:   rms  [1. 1. 1.]  norm [2.828 2.828 2.828]  sqrt(d) = 2.828
RMSNorm keeps the mean:  [0.958 0.668 0.926]

Invariances

LayerNorm's output is unchanged if the input is scaled by c>0c > 0 or shifted by a constant vector a1a\mathbf{1}; RMSNorm is invariant only to scaling. Scale invariance makes the layer's output insensitive to the overall size of the weights before it, which stabilizes training. Its gradient is correspondingly orthogonal to x\mathbf{x} (for RMSNorm) or to both 1\mathbf{1} and x^\hat{\mathbf{x}} (for LayerNorm).

python · try it yourself
import numpy as np

rng = np.random.default_rng(1)
x = rng.normal(size=6); eps = 0.0
rms = lambda x: x / np.sqrt(np.mean(x**2) + eps)
ln = lambda x: (x - x.mean()) / np.sqrt(x.var() + eps)
print("RMSNorm scale-invariant:", np.allclose(rms(5 * x), rms(x)), " shift-invariant:", np.allclose(rms(x + 2), rms(x)))
print("LayerNorm scale-invariant:", np.allclose(ln(5 * x), ln(x)), " shift-invariant:", np.allclose(ln(x + 2), ln(x)))
up = rng.normal(size=6)
L = lambda x: rms(x) @ up
g = np.array([(L(x + e) - L(x - e)) / 2e-6 for e in np.eye(6) * 1e-6])
print("RMSNorm gradient is orthogonal to x:", np.isclose(g @ x, 0, atol=1e-6))
RMSNorm scale-invariant: True  shift-invariant: False
LayerNorm scale-invariant: True  shift-invariant: True
RMSNorm gradient is orthogonal to x: True

Pre-norm versus post-norm

The original transformer normalized after each residual addition: x←LN⁡(x+F(x))\mathbf{x} \leftarrow \operatorname{LN}(\mathbf{x} + F(\mathbf{x})) (post-norm). Modern models normalize before the sublayer: x←x+F(LN⁡(x))\mathbf{x} \leftarrow \mathbf{x} + F(\operatorname{LN}(\mathbf{x})) (pre-norm). Pre-norm keeps an un-normalized identity path from input to output, so gradients reach early layers undisturbed (Residual Connections); it trains stably without careful learning-rate warmup. A final norm is applied before the output layer. Some recent models also normalize queries and keys inside attention (QK-norm) to keep attention logits bounded.

In software

  • nn.LayerNorm(d, eps=1e-5) and nn.RMSNorm(d) normalize over the last dimension.
  • Normalization statistics are usually computed in fp32 even under bf16 training (Floating Point).
  • Group normalization (statistics over groups of channels) is the CNN analogue for small batches.

Exercises

Exercise 1: LayerNorm by hand

Apply LayerNorm (no ϵ\epsilon, γ=1\gamma = 1, β=0\beta = 0) to (2,4,6,8)(2, 4, 6, 8).

Answer

About (−1.342,−0.447,0.447,1.342)(-1.342, -0.447, 0.447, 1.342).

Solution

Mean 5, deviations (−3,−1,1,3)(-3, -1, 1, 3), variance (9+1+1+9)/4=5(9 + 1 + 1 + 9)/4 = 5, std 2.2362.236.

Exercise 2: RMSNorm by hand

Apply RMSNorm (no ϵ\epsilon, γ=1\gamma = 1) to (3,4)(3, 4).

Answer

About (0.849,1.131)(0.849, 1.131).

Solution

RMS =(9+16)/2=12.5≈3.536= \sqrt{(9 + 16)/2} = \sqrt{12.5} \approx 3.536; divide: (0.849,1.131)(0.849, 1.131), whose norm is 2\sqrt{2}.

Exercise 3: Which axis? (code)

For a tensor of shape (batch, tokens, features), compute the shapes of the statistics used by batch norm (over batch and tokens) and by layer norm.

Answer

Batch norm: one mean per feature; layer norm: one mean per (batch, token).

Solution
python · try it yourself
import numpy as np
X = np.zeros((4, 10, 16))
print(X.mean(axis=(0, 1)).shape, X.mean(axis=-1).shape)
(16,) (4, 10)

Test yourself

Layer normalization computes its mean and variance…

  1. over the batch, per feature
  2. over the features of each example (token)
  3. over the whole dataset
  4. once at initialization

What does RMSNorm leave out compared with LayerNorm?

  1. The division
  2. The mean subtraction (and the bias)
  3. The learned gain
  4. Everything

Why do modern transformers prefer pre-norm?

  1. It uses fewer parameters
  2. The residual path stays an identity, so gradients flow well and training is stable
  3. It removes the need for attention
  4. It is required for RMSNorm