concept / rmsnorm
Next task →
University/Generative AI/Transformer architecture/Normalization Layers: LayerNorm and RMSNorm
Generative AI and LLMs · Transformer architecture · Normalization

Normalization Layers: LayerNorm and RMSNorm

LayerNorm standardises each token's activations across features using mean and variance; RMSNorm keeps only the root-mean-square rescaling, removing the mean-centering work and gaining speed while retaining the stabilising scale invariance that transformers need.

39 sectionsadvanced150 minhand-authored · structural 82/100
Take assessment →
Mastery requires: derivation reproduced, from-scratch implementation committed, failure case explained, and assessment score ≥ 80%. Current state: not_started.

1. Concept overview

Normalization layers re-scale a token's activation vector so its statistics stay stable as it passes through many transformer blocks. LayerNorm (Ba, Kiros & Hinton, 2016) standardises across the feature dimension dd independently for each token:

μ=1d∑i=1dxi,σ2=1d∑i=1d(xi−μ)2,x^i=xi−μσ2+ϵ,yi=γix^i+βi.\mu=\frac1d\sum_{i=1}^d x_i,\qquad \sigma^2=\frac1d\sum_{i=1}^d(x_i-\mu)^2,\qquad \hat x_i=\frac{x_i-\mu}{\sqrt{\sigma^2+\epsilon}},\qquad y_i=\gamma_i\hat x_i+\beta_i .

RMSNorm (Zhang, Dauphin & Sennrich, 2019) drops the mean and the shift parameter:

RMS(x)=1d∑i=1dxi2+ϵ,x^i=xiRMS(x),yi=γix^i.\mathrm{RMS}(x)=\sqrt{\frac1d\sum_{i=1}^d x_i^2+\epsilon},\qquad \hat x_i=\frac{x_i}{\mathrm{RMS}(x)},\qquad y_i=\gamma_i\hat x_i .

With γ=1\gamma=1, RMSNorm makes 1d∑iyi2≈1\frac1d\sum_i y_i^2\approx1: it places each token vector on a sphere of radius d\sqrt d, keeping only the direction. The learnable gain γ∈Rd\gamma\in\mathbb{R}^d lets the model restore per-feature magnitudes.

In modern LLMs the norm sits inside the residual branch (pre-norm): x^=Norm(x)\hat x=\mathrm{Norm}(x), then x′=x+Sublayer(x^)x'=x+\mathrm{Sublayer}(\hat x), with a final norm before the output head. RMSNorm is used in Llama, Gemma, Qwen and many other models because it is cheaper and empirically matches or beats LayerNorm.

2. Why this concept exists

Deep residual stacks have a scale problem: every sublayer adds an update to the residual stream, so activation magnitudes can drift across depth, pushing logits into saturated regions of nonlinearities and making gradients explode or vanish.

BatchNorm (Ioffe & Szegedy, 2015) fixed this for CNNs but depends on batch statistics — problematic for variable-length sequences, small batches and autoregressive decoding. LayerNorm normalises per example, so training and inference behave identically and sequence length is irrelevant. Its cost is a few elementwise passes over dd features per token — negligible next to attention.

RMSNorm asks whether all of LayerNorm's machinery is necessary. Empirical evidence suggests the re-centering (subtracting μ\mu) contributes little in transformers with zero-mean-pretrained weights, while costing memory traffic and a reduction. Dropping it saves 10–20% of normalization time and simplifies the backward pass, so it became the default in large language models.

3. Historical background

Ioffe and Szegedy (2015) introduced BatchNorm, normalising activations using batch statistics and reporting faster and more stable training. Ba, Kiros and Hinton (2016) introduced LayerNorm, which normalises across features per example and is independent of batch size. Salimans and Kingma (2016) studied weight normalisation. Zhang, Dauphin and Sennrich (2019) proposed RMSNorm, arguing that re-centring is unnecessary and demonstrating faster training on machine translation. Xiong et al. (2020) analysed pre-norm versus post-norm transformers, showing pre-LN has better-behaved gradients at initialization and often removes the need for warmup. Dettmers et al. (2022) and the Llama release popularised RMSNorm in large language models; Gemma and many open models followed. Normalization placement is now a standard design axis alongside attention and activation choice.

4. Fundamental problem

Design an operation that (a) bounds the scale of activations at every depth so residual additions do not compound, (b) does not depend on other examples in the batch, (c) is differentiable with a cheap backward pass, and (d) preserves expressive power through learned per-feature parameters.

The subtle part is the interaction with gradients. Normalisation is not just a forward rescaling: it makes the layer invariant to certain transformations of its input, and the backward pass must remove components parallel to the normalised vector (the radial direction), otherwise gradient descent would fight the normalisation. Understanding that projection is the key to implementing and debugging these layers.

5. First-principles explanation

Fact 1 (standardisation). Subtracting the mean and dividing by the standard deviation maps a vector to zero mean and unit variance across features. This removes scale information but preserves the pattern of relative deviations.

Fact 2 (RMS normalisation). Dividing by ∥x∥2/d\|x\|_2/\sqrt d preserves the direction of xx and fixes its norm. If activations entering a dot-product attention are all rescaled by a common factor, attention logits (which are scale-sensitive quadratically) stay controlled.

Fact 3 (gradient projection). For RMSNorm, differentiating yi=γixi/RMS(x)y_i=\gamma_i x_i/\mathrm{RMS}(x) gives

∂L∂xj=γjRMS(x)(d^j−x^jd∑ix^iγid^i),d^=∂L/∂y.\frac{\partial L}{\partial x_j}=\frac{\gamma_j}{\mathrm{RMS}(x)}\Big(\hat d_j-\frac{\hat x_j}{d}\sum_i \hat x_i\gamma_i \hat d_i\Big),\qquad \hat d=\partial L/\partial y .

The term in parentheses is d^\hat d with its component along x^\hat x removed: ⟨x^,∂L/∂x⟩=0\langle \hat x,\partial L/\partial x\rangle=0 (for ϵ→0\epsilon\to0). Gradient descent cannot change the norm of x^\hat x — the normalisation already fixed it.

Fact 4 (learned gain). Without γ\gamma, every normalised activation would have the same RMS, which is needlessly restrictive; γ\gamma restores the ability to amplify or suppress features after normalisation.

6. Prerequisite concepts

Required: (a) backpropagation and elementwise VJPs; (b) gradient descent and residual connections; (c) the softmax/self-attention forward pass, since normalization is applied to its inputs/outputs; (d) basic statistics (mean, variance, RMS); (e) exposure to BatchNorm to appreciate batch independence; (f) numerical precision issues in fp16 reductions. See the linked concepts for each.

7. Complete mathematical formulation

LayerNorm. For x∈Rdx\in\mathbb{R}^d and learnable γ,β∈Rd\gamma,\beta\in\mathbb{R}^d:

μ=1d∑ixi,σ2=1d∑i(xi−μ)2,x^i=xi−μσ2+ϵ,yi=γix^i+βi.\mu=\frac1d\sum_i x_i,\qquad \sigma^2=\frac1d\sum_i(x_i-\mu)^2,\qquad \hat x_i=\frac{x_i-\mu}{\sqrt{\sigma^2+\epsilon}},\qquad y_i=\gamma_i\hat x_i+\beta_i .

Its gradient (with d^i=∂L/∂yi\hat d_i=\partial L/\partial y_i) is

∂L∂xi=γiσϵ[d^i−d^‾−x^i d^x^‾],\frac{\partial L}{\partial x_i}=\frac{\gamma_i}{\sigma_\epsilon}\Big[\hat d_i-\overline{\hat d}-\hat x_i\,\overline{\hat d\hat x}\Big],

where σϵ=σ2+ϵ\sigma_\epsilon=\sqrt{\sigma^2+\epsilon}, bars denote averages over features, and the last term is the mean of d^⊙x^\hat d\odot\hat x. Also ∂L/∂γi=d^ix^i\partial L/\partial\gamma_i=\hat d_i\hat x_i, ∂L/∂βi=d^i\partial L/\partial\beta_i=\hat d_i.

RMSNorm. With r=RMS(x)=1d∑ixi2+ϵr=\mathrm{RMS}(x)=\sqrt{\frac1d\sum_i x_i^2+\epsilon} and x^=x/r\hat x=x/r:

yi=γix^i,∂L∂xi=γir[d^i−x^i (γ⊙d^)⊙x^‾],y_i=\gamma_i\hat x_i,\qquad \frac{\partial L}{\partial x_i}=\frac{\gamma_i}{r}\Big[\hat d_i-\hat x_i\,\overline{(\gamma\odot\hat d)\odot\hat x}\Big], ∂L∂γi=d^ix^i.\frac{\partial L}{\partial\gamma_i}=\hat d_i\hat x_i .

There is no β\beta and no mean subtraction.

Shapes. In a transformer, X∈RB×n×dX\in\mathbb{R}^{B\times n\times d}; both normalisations operate on the last axis, so μ,σ,r\mu,\sigma,r have shape B×n×1B\times n\times 1 and γ\gamma (and β\beta) shape (d,)(d,), broadcast over batch and sequence.

8. Notation dictionary

| Symbol | Meaning | Shape / type | |---|---|---| | x∈Rdx\in\mathbb{R}^d | one token's activation vector | vector | | μ\mu | feature mean of xx | scalar per token | | σ2\sigma^2 | feature variance of xx | scalar per token | | r=RMS(x)r=\mathrm{RMS}(x) | root mean square | scalar per token | | x^\hat x | normalised vector | vector | | γ,β\gamma,\beta | learned per-feature gain / bias | vectors in Rd\mathbb{R}^d | | ϵ>0\epsilon>0 | stabiliser, typically 10−510^{-5}–10−610^{-6} | scalar | | yy | output of the normalization layer | vector | | d^=∂L/∂y\hat d=\partial L/\partial y | upstream gradient | vector | | a‾\overline a | average of aia_i over features | scalar | | B,n,dB,n,d | batch size, sequence length, model width | integers |

9. Step-by-step derivation

Step 1 — LayerNorm forward. Compute μ\mu and σϵ=σ2+ϵ\sigma_\epsilon=\sqrt{\sigma^2+\epsilon}; form x^i=(xi−μ)/σϵ\hat x_i=(x_i-\mu)/\sigma_\epsilon and yi=γix^i+βiy_i=\gamma_i\hat x_i+\beta_i.

Step 2 — LayerNorm backward. ∂yi/∂x^j=γiδij\partial y_i/\partial\hat x_j=\gamma_i\delta_{ij}, so the first factor is γid^i\gamma_i\hat d_i. The normalisation derivative ∂x^i/∂xj=1σϵ(δij−1d−x^ix^j/d)\partial\hat x_i/\partial x_j=\frac{1}{\sigma_\epsilon}(\delta_{ij}-\frac1d-\hat x_i\hat x_j/d) produces

∂L/∂xj=1σϵ(γjd^j−γ⊙d^‾−x^j γ⊙d^⊙x^‾),\partial L/\partial x_j=\frac{1}{\sigma_\epsilon}\Big(\gamma_j\hat d_j-\overline{\gamma\odot\hat d}-\hat x_j\,\overline{\gamma\odot\hat d\odot\hat x}\Big),

which is the formula above (the −γ⊙d^‾-\overline{\gamma\odot\hat d} term subtracts the mean because ∑jx^j=0\sum_j\hat x_j=0).

Step 3 — RMSNorm derivative. With D=r2=1d∑kxk2+ϵD=r^2=\frac1d\sum_k x_k^2+\epsilon, ∂r/∂xj=xj/(dr)\partial r/\partial x_j=x_j/(dr). Hence

∂x^i∂xj=δijr−xixjdr3=1r(δij−x^ix^jd).\frac{\partial\hat x_i}{\partial x_j}=\frac{\delta_{ij}}{r}-\frac{x_ix_j}{dr^3}=\frac1r\Big(\delta_{ij}-\frac{\hat x_i\hat x_j}{d}\Big).

Step 4 — assemble the VJP. ∂L/∂xj=∑iγid^i∂x^i/∂xj=1r(γjd^j−x^jd∑ix^iγid^i)\partial L/\partial x_j=\sum_i \gamma_i\hat d_i\partial\hat x_i/\partial x_j=\frac{1}{r}\big(\gamma_j\hat d_j-\frac{\hat x_j}{d}\sum_i\hat x_i\gamma_i\hat d_i\big) — a diagonal term minus a rank-one projection.

Step 5 — invariance consequence. Contract with x^j\hat x_j: using ∑jx^j2≈d\sum_j\hat x_j^2\approx d, the two terms cancel, so ⟨x^,∇xL⟩=0\langle\hat x,\nabla_x L\rangle=0. The gradient is tangent to the sphere — normalisation removes the radial degree of freedom exactly.

Step 6 — parameters. ∂L/∂γi=d^ix^i\partial L/\partial\gamma_i=\hat d_i\hat x_i; LayerNorm additionally has ∂L/∂βi=d^i\partial L/\partial\beta_i=\hat d_i. These reductions are over batch and sequence in a transformer.

10. Proofs and proof intuition

Lemma 1 (RMS after normalisation). With γi=1\gamma_i=1 and ϵ→0\epsilon\to0, 1d∑ix^i2=1\frac1d\sum_i \hat x_i^2=1. Proof. ∑ix^i2=∑ixi2/RMS(x)2=(d RMS2)/RMS2=d\sum_i\hat x_i^2=\sum_i x_i^2/\mathrm{RMS}(x)^2=(d\,\mathrm{RMS}^2)/\mathrm{RMS}^2=d. □\square

Lemma 2 (LayerNorm invariances). For a>0a>0 and any bb, LN(ax+b1)=LN(x)\mathrm{LN}(a x+b\mathbf1)=\mathrm{LN}(x) (with γ,β\gamma,\beta fixed). Proof. μ→aμ+b\mu\to a\mu+b, x^i=(axi+b−aμ−b)/(aσ)=(xi−μ)/σ\hat x_i=(a x_i+b-a\mu-b)/(a\sigma)=(x_i-\mu)/\sigma. □\square RMSNorm is invariant only to positive scaling, RMSNorm(ax)=RMSNorm(x)\mathrm{RMSNorm}(ax)=\mathrm{RMSNorm}(x), since a shift changes the norm but not the mean subtraction (there is none).

Lemma 3 (gradient orthogonality for RMSNorm). ⟨x^,∇xL⟩=0\langle\hat x,\nabla_xL\rangle=0 when ϵ=0\epsilon=0. Proof. From Step 4, ∑jx^j(γjd^j)=S\sum_j\hat x_j(\gamma_j\hat d_j)=S and 1d(∑jx^j2)S=S\frac{1}{d}(\sum_j\hat x_j^2)S=S, so the difference is zero. □\square For ϵ>0\epsilon>0 the identity holds up to a factor d RMS2/(d RMS2−ϵ)d\,\mathrm{RMS}^2/(d\,\mathrm{RMS}^2-\epsilon).

Lemma 4 (LayerNorm gradient orthogonality). x^\hat x has zero mean and unit variance, and ∇xL\nabla_xL also has zero mean (the −γ⊙d^‾-\overline{\gamma\odot\hat d} term enforces it), so normalisation removes both the radial and the shift directions. □\square

Proof intuition. Both layers restrict the optimisation to a manifold (a sphere, or a sphere intersected with a hyperplane). Backprop projects the upstream gradient onto the tangent space of that manifold; that is what the subtraction terms do.

11. Geometric interpretation

In Rd\mathbb{R}^d, LayerNorm first projects xx onto the hyperplane ∑ixi=0\sum_i x_i=0 by subtracting the mean, then radially projects onto the sphere ∥x^∥2=d\|\hat x\|_2=\sqrt d. RMSNorm skips the hyperplane projection and only does the radial step, so it preserves the direction of xx and its mean offset. The learned γ\gamma then stretches the sphere into an axis-aligned ellipsoid (and β\beta translates it for LayerNorm).

Because gradients are tangent to these manifolds, training moves the direction of a token's vector rather than its norm — a form of built-in trust region. Pre-norm placement means the residual stream itself is an unnormalised accumulator while each sublayer sees a normalised view; post-norm normalises after each addition, bounding the stream directly but complicating gradient flow at initialization.

12. Visual explanation

Use the Normalization Projection Playground. In a 2D plot, show a vector x=(3,1)x=(3,1): LayerNorm first shifts it to x−μ=(1,−1)x-\mu=(1,-1) (a point on the line x1+x2=0x_1+x_2=0), then scales it onto the circle of radius 2\sqrt2; RMSNorm scales xx directly onto the circle of radius 10/2⋅2\sqrt{10/2}\cdot\sqrt2 — i.e. the same direction, unit RMS. Draw the gradient arrow and its projection onto the circle's tangent, showing the radial component is removed. A second panel shows histograms of activation values before and after each normalization for a real transformer layer, and a block diagram comparing pre-norm (x+Sublayer(Norm(x))x+\mathrm{Sublayer}(\mathrm{Norm}(x))) with post-norm (Norm(x+Sublayer(x))\mathrm{Norm}(x+\mathrm{Sublayer}(x))).

13. Numerical worked example

Take x=(1,2,3,4)x=(1,2,3,4), so d=4d=4 and ϵ=0\epsilon=0.

LayerNorm. μ=2.5\mu=2.5, deviations (−1.5,−0.5,0.5,1.5)(-1.5,-0.5,0.5,1.5), squared deviations (2.25,0.25,0.25,2.25)(2.25,0.25,0.25,2.25), so σ2=1.25\sigma^2=1.25, σ=1.1180\sigma=1.1180. Thus x^=(−1.3416,−0.4472,0.4472,1.3416)\hat x=(-1.3416,-0.4472,0.4472,1.3416); it has mean 00 and variance 11.

RMSNorm. 1d∑xi2=(1+4+9+16)/4=7.5\frac1d\sum x_i^2=(1+4+9+16)/4=7.5, r=7.5=2.7386r=\sqrt{7.5}=2.7386, so

x^=(0.3651, 0.7303, 1.0954, 1.4619).\hat x=(0.3651,\,0.7303,\,1.0954,\,1.4619).

Check: mean of x^i2\hat x_i^2 is (0.1333+0.5333+1.2000+2.1333)/4=1.0000(0.1333+0.5333+1.2000+2.1333)/4=1.0000.

Backward for RMSNorm with γ=(1,1,1,1)\gamma=(1,1,1,1) and d^=(1,0,0,0)\hat d=(1,0,0,0): S=∑ix^id^i=0.3651S=\sum_i \hat x_i\hat d_i=0.3651. Then ∂L/∂xj=1r(d^j−x^j4S)\partial L/\partial x_j=\frac1r(\hat d_j-\frac{\hat x_j}{4}S):

∂L/∂x=(0.3530, −0.0243, −0.0365, −0.0487).\partial L/\partial x=(0.3530,\, -0.0243,\, -0.0365,\, -0.0487).

Check orthogonality: 0.3651(0.3530)+0.7303(−0.0243)+1.0954(−0.0365)+1.4619(−0.0487)≈0.00000.3651(0.3530)+0.7303(-0.0243)+1.0954(-0.0365)+1.4619(-0.0487)\approx0.0000. A finite-difference check at h=10−5h=10^{-5} agrees to ∼10−7\sim10^{-7}.

Why the distinction matters. With a downstream dot product, LayerNorm's output has zero mean while RMSNorm's retains the mean x‾=2.5\overline x=2.5 scaled by 1/r1/r; that extra offset can carry useful information in the residual stream, which is one reason RMSNorm works well despite being simpler.

14. Real-world analogy

Before a relay race, each runner's heartbeat is measured. One coach (LayerNorm) subtracts the team average heart rate and divides by the spread, so every runner has "average" zero and "spread" one. Another coach (RMSNorm) only scales each runner's rate by the team's root-mean-square level, preserving who is above or below the average but fixing overall intensity. Both keep the team in a comparable state race after race, regardless of the day's conditions, but the second coach does less measuring — useful when you have thousands of runners (billions of tokens).

15. Algorithm pseudocode

algorithm LayerNormForward(X[B,n,d], gamma[d], beta[d], eps):
    mu[b,i]    <- (1/d) * sum_j X[b,i,j]
    var[b,i]   <- (1/d) * sum_j (X[b,i,j] - mu[b,i])^2
    sig[b,i]   <- sqrt(var[b,i] + eps)
    Xhat       <- (X - mu) / sig
    Y          <- gamma * Xhat + beta
    return Y, cache(Xhat, sig, gamma)

algorithm RMSNormForward(X[B,n,d], gamma[d], eps):
    r[b,i] <- sqrt((1/d) * sum_j X[b,i,j]^2 + eps)
    Xhat   <- X / r
    Y      <- gamma * Xhat
    return Y, cache(Xhat, r, gamma)

# RMSNorm backward with upstream dY:
# S[b,i]  <- (1/d) * sum_j Xhat[b,i,j] * gamma[j] * dY[b,i,j]
# dX      <- gamma * dY / r - Xhat * S / r
# dgamma  <- sum_{b,i} dY[b,i,j] * Xhat[b,i,j]

16. Implementation from scratch

import numpy as np

def layernorm_forward(x, gamma, beta, eps=1e-5):
    mu = x.mean(axis=-1, keepdims=True)
    var = ((x - mu) ** 2).mean(axis=-1, keepdims=True)
    sig = np.sqrt(var + eps)
    xhat = (x - mu) / sig
    return gamma * xhat + beta, (xhat, sig, gamma)

def layernorm_backward(dy, cache):
    xhat, sig, gamma = cache
    g = gamma * dy
    dg = (dy * xhat).sum(axis=tuple(range(dy.ndim - 1)))
    db = dy.sum(axis=tuple(range(dy.ndim - 1)))
    dx = (g - g.mean(axis=-1, keepdims=True)
          - xhat * (g * xhat).mean(axis=-1, keepdims=True)) / sig
    return dx, dg, db

def rmsnorm_forward(x, gamma, eps=1e-5):
    r = np.sqrt((x ** 2).mean(axis=-1, keepdims=True) + eps)
    xhat = x / r
    return gamma * xhat, (xhat, r, gamma)

def rmsnorm_backward(dy, cache):
    xhat, r, gamma = cache
    gd = gamma * dy
    S = (gd * xhat).mean(axis=-1, keepdims=True)
    dx = (gd - xhat * S) / r
    dg = (dy * xhat).sum(axis=tuple(range(dy.ndim - 1)))
    return dx, dg

x = np.array([1., 2., 3., 4.])
g = np.ones(4)
y, cache = rmsnorm_forward(x, g, eps=0.0)
dy = np.array([1., 0., 0., 0.])
dx, dg = rmsnorm_backward(dy, cache)
print(np.round(y, 4), np.round(dx, 4))
# [0.3651 0.7303 1.0954 1.4619]  [0.3530 -0.0243 -0.0365 -0.0487]

h = 1e-5
def loss(xp):
    return rmsnorm_forward(xp, g, eps=0.0)[0][0]
fd = (loss(x + np.array([h,0,0,0])) - loss(x - np.array([h,0,0,0]))) / (2*h)
assert abs(fd - dx[0]) < 1e-6, (fd, dx[0])
print("gradient check passed")

The reduction axes tuple(range(dy.ndim - 1)) sum over batch and sequence, leaving one gradient per feature — the parameter shapes match gamma and beta.

17. Professional library implementation

import torch
import torch.nn.functional as F

B, N, D = 2, 8, 16
x = torch.randn(B, N, D, requires_grad=True)
gamma = torch.ones(D, requires_grad=True)
beta = torch.zeros(D, requires_grad=True)

y_ln = F.layer_norm(x, (D,), weight=gamma, bias=beta, eps=1e-5)
y_rms = F.rms_norm(x, (D,), weight=gamma, eps=1e-5)   # PyTorch >= 2.5
print(y_ln.shape, y_rms.shape)                        # torch.Size([2, 8, 16]) twice

(y_ln.sum() + y_rms.sum()).backward()
print(x.grad.shape, gamma.grad.shape)                # (2, 8, 16), (16,)

# Canonical pre-norm transformer sublayer:
class RMSNorm(torch.nn.Module):
    def __init__(self, d, eps=1e-6):
        super().__init__()
        self.weight = torch.nn.Parameter(torch.ones(d))
        self.eps = eps
    def forward(self, x):
        return F.rms_norm(x, (x.shape[-1],), self.weight, eps=self.eps)

attn = torch.nn.MultiheadAttention(D, 4, batch_first=True)
h = RMSNorm(D)
x2 = x.detach() + attn(h(x.detach()), x.detach(), x.detach())[0]   # residual add

Some frameworks initialise γ=0\gamma=0 for output-layer norms; try both and compare training stability. Keep reductions in fp32 even when inputs are fp16.

18. Code walkthrough

Scratch version. layernorm_backward computes g=γ⊙d^g=\gamma\odot\hat d, subtracts its mean and its projection onto x^\hat x, then divides by σϵ\sigma_\epsilon — exactly the formula in section 7. rmsnorm_backward computes S=γ⊙d^⊙x^‾S=\overline{\gamma\odot\hat d\odot\hat x} and subtracts x^S\hat x S, then divides by rr; it has no mean term because there is no centering. The parameter gradients sum over all but the last axis, matching broadcast semantics.

PyTorch version. F.layer_norm and F.rms_norm fuse the reduction and normalisation into optimized kernels; eps follows the framework default (10−510^{-5} for LayerNorm). The custom RMSNorm module shows the pre-norm pattern: normalise the residual stream before feeding the sublayer, then add the sublayer output to the unnormalised stream.

Numerical detail. In fp16, summing thousands of squares can underflow or overflow; accumulate the variance / mean-square in fp32 even if xx is fp16. PyTorch's fused kernels already do this.

19. Tensor and memory analysis

For X∈RB×n×dX\in\mathbb{R}^{B\times n\times d} in fp16 (2 bytes), with B=8B=8, n=2048n=2048, d=4096d=4096: XX alone is 8⋅2048⋅4096⋅2≈1348\cdot2048\cdot4096\cdot2\approx134 MB. Each saved tensor for backward (x^\hat x, rr or μ,σ\mu,\sigma, YY) is another ~134 MB. LayerNorm needs μ,σ\mu,\sigma (tiny, BnB n scalars) and x^\hat x; RMSNorm needs rr (tiny) and x^\hat x — essentially the same activation memory, but fewer reduction passes and no mean buffer.

Because normalization sits next to every attention and MLP block, a model with L=48L=48 layers stores roughly LL times this activation memory during training (~6 GB for the example), which is why checkpointing and fused kernels matter. Parameters γ,β\gamma,\beta cost only 2d2d floats — negligible.

20. Time complexity

Both layers are O(Bnd)O(Bnd) elementwise work with a single reduction over dd per token; the backward is also O(Bnd)O(Bnd) with one additional reduction for γ\gamma (and β\beta). RMSNorm performs one sum of squares and one division per token, LayerNorm needs a mean, a second pass for variance, and a subtraction — typically 10–20% slower in practice. These costs are small relative to attention (O(Bn2d)O(Bn^2d)) or MLP (O(Bnd2)O(Bnd^2)), but at large nn and small dd they become noticeable, which motivated RMSNorm in large-scale training.

21. Space complexity

O(Bnd)O(Bnd) for activations and saved normalised tensors, plus O(Bn)O(Bn) for the per-token statistics and O(d)O(d) for γ,\eta\gamma,\eta. No batch statistics are stored (unlike BatchNorm), so inference uses the same computation as training and there is no running-mean state in the checkpoint.

22. Experimental demonstration

Run four experiments. (1) Reproduce x=(1,2,3,4)x=(1,2,3,4): LN output (−1.3416,−0.4472,0.4472,1.3416)(-1.3416,-0.4472,0.4472,1.3416), RMSNorm output (0.3651,0.7303,1.0954,1.4619)(0.3651,0.7303,1.0954,1.4619), and the RMSNorm backward (0.3530,−0.0243,−0.0365,−0.0487)(0.3530,-0.0243,-0.0365,-0.0487); gradient-check to 10−610^{-6}. (2) Invariance test: apply LN and RMSNorm to ax+b1a x+b\mathbf1 for a∈{0.1,10}a\in\{0.1,10\}, b∈{−5,3}b\in\{-5,3\}; verify LN is invariant to both and RMSNorm only to aa. (3) Train a small transformer with pre-LN, post-LN and pre-RMSNorm on a toy task; log gradient norms and loss spikes for 1000 steps — post-LN typically needs warmup. (4) Benchmark F.layer_norm versus F.rms_norm for d∈{512,2048,8192}d\in\{512,2048,8192\} and record throughput and peak memory.

23. Benchmark results

Zhang et al. (2019) report RMSNorm giving roughly 7–18% faster training than LayerNorm on Transformer translation models with comparable or slightly better BLEU, and the pattern has held in many open-source LLM stacks where RMSNorm is now standard. On modern GPUs the absolute difference per layer is small (microseconds), so end-to-end gains depend on how much of the step is normalization-bound. Do not treat the speedup as universal: for small dd or heavily fused blocks it can vanish, and post-LN versus pre-LN affects training stability far more than the choice of RMS versus full LayerNorm. Always report the block structure, precision and kernel versions.

24. Limitations

  • RMSNorm loses re-centering invariance, so a constant offset in the residual stream is no longer removed.
  • Neither layer regularises using batch statistics; they do not provide BatchNorm's noise benefits.
  • Normalising per token can discard useful magnitude information; the learned gain only partially restores it.
  • Post-norm transformers can have poor gradient flow at initialization without warmup.
  • ϵ\epsilon choice matters at low precision; too small causes division by near-zero, too large biases the scale.
  • Cost scales linearly with dd and appears in every block, so it is not free at very large width.
  • The normalised vector's gradient is constrained to a manifold; this helps stability but can limit representable updates.

25. Failure scenarios

  1. All-zero input to RMSNorm: r=ϵr=\sqrt\epsilon, so x^=0\hat x=0 but the gradient divides by a tiny number; initialise gains properly and avoid zero-only batches.
  2. Normalizing the wrong axis: using axis 0 (batch) instead of the feature axis turns the layer into a batch-dependent operation and breaks autoregressive decoding.
  3. fp16 reduction errors: variance of large activations overflows or small ones underflow; accumulate in fp32.
  4. Wrong ϵ\epsilon: 10−510^{-5} inherited from LayerNorm can be too large for RMSNorm with small activations, damping normalisation.
  5. Applying normalization twice: a leftover LayerNorm in a pre-RMSNorm block double-normalises and shrinks gradients.
  6. Post-norm instability: with deep stacks and no warmup, gradient norms blow up at initialization; switch to pre-norm or add warmup.
  7. Gain initialised to zero: outputs are identically zero, gradients to γ\gamma are zero and the layer cannot recover — a subtle dead-layer failure.
  8. Residual scale mismatch: normalising inside the residual branch but adding with unnormalised activations of very different magnitude can dominate the update; tune initialization.

26. Common misconceptions

  • "RMSNorm is LayerNorm without batch statistics." It is LayerNorm without mean centering and without β\beta; LayerNorm itself is already batch-independent.
  • "Normalization prevents all instability." It controls activation scale but does not fix exploding attention logits or bad learning rates.
  • "γ\gamma and β\beta are computed from the batch." They are learned parameters shared across tokens, not statistics.
  • "RMSNorm is always faster and better." Gains are modest and architecture-dependent; LayerNorm remains strong in many settings.
  • "Pre-norm and post-norm only change where a line of code sits." Placement qualitatively changes gradient flow at initialization.
  • "The gradient through normalization is just elementwise multiplication." It includes a projection term that removes the radial (and, for LN, the mean) component — omitting it breaks gradient checks.

27. Alternative approaches

  • BatchNorm: normalises over batch and spatial dims; strong in CNNs, awkward for sequences.
  • InstanceNorm / GroupNorm: alternatives for vision; group norm avoids batch dependence.
  • WeightNorm / SpectralNorm: normalise weights instead of activations.
  • DeepNorm: scale residual branches by a depth-dependent factor to stabilise very deep post-norm transformers.
  • Fixup / SkipInit: remove normalization entirely with carefully scaled initialisation.
  • nGPT / normalised transformers: constrain all activations and weights to a hypersphere, making normalisation a global design principle.
  • RMSNorm with learned per-token gain or FiLM conditioning: adapt the gain to context instead of a fixed vector.

29. Research applications

  • LLM architecture: RMSNorm is standard in Llama, Gemma, Qwen and Mistral; LayerNorm in GPT-style and T5 models.
  • Vision transformers: pre-LN is the default; normalisation placement affects fine-tuning stability.
  • Diffusion models: normalization inside UNet/transformer blocks conditions on timestep embeddings via FiLM-like gains.
  • Reinforcement learning: normalization stabilises value networks under nonstationary targets.
  • Efficient inference: fused RMSNorm kernels reduce memory traffic in autoregressive decoding.
  • Theory: studying how normalization shapes the loss landscape and implicit bias of transformers.

30. Important research papers

  • Ioffe S., Szegedy C. (2015), Batch Normalization: Accelerating Deep Network Training by Reducing Internal Covariate Shift, ICML.
  • Ba J. L., Kiros J. R., Hinton G. E. (2016), Layer Normalization, arXiv:1607.06450.
  • Salimans T., Kingma D. P. (2016), Weight Normalization: A Simple Reparameterization to Accelerate Training of Deep Neural Networks, NIPS.
  • Zhang B., Sennrich R. (2019), Root Mean Square Layer Normalization, NeurIPS — RMSNorm.
  • Xiong W. et al. (2020), On Layer Normalization in the Transformer Architecture, ICML — pre-LN vs post-LN gradient analysis.
  • Dettmers T. et al. (2022), LLM.int8(): 8-bit Matrix Multiplication for Transformers at Scale, NeurIPS — RMSNorm in modern LLM stacks.

31. Further reading

  • Ba et al. (2016), arXiv:1607.06450 — LayerNorm definition and invariance discussion.
  • Zhang & Sennrich (2019), arXiv:1910.07467 — RMSNorm derivation and experiments.
  • Xiong et al. (2020), arXiv:2002.04745 — pre-norm gradient analysis.
  • PyTorch docs: docs.pytorch.org/docs/stable/nn.functional.html#layer-norm.
  • The illustrated Transformer with normalization placement: jalammar.github.io/illustrated-transformer/.

32. Practical exercises

  1. Implement LayerNorm and RMSNorm forward/backward from memory and gradient-check both at float64.
  2. Reproduce the x=(1,2,3,4)x=(1,2,3,4) numbers and the RMSNorm backward vector to four decimals.
  3. Verify the invariance lemmas numerically for a∈{0.1,10}a\in\{0.1,10\}, b∈{−5,3}b\in\{-5,3\} and explain which transformation RMSNorm does not handle.
  4. Check ⟨x^,∇xL⟩≈0\langle\hat x,\nabla_x L\rangle\approx0 for random x,γ,d^x,\gamma,\hat d and explain the result geometrically.
  5. Train a 4-layer transformer on a toy next-token task with pre-LN, post-LN and pre-RMSNorm; plot gradient norms and loss for 1000 steps.
  6. Benchmark F.layer_norm vs F.rms_norm for d∈{512,2048,8192}d\in\{512,2048,8192\}; report throughput and any accuracy difference on the toy task.

33. Debugging challenges

  • Gradient check fails for LayerNorm: you omitted the −γ⊙d^‾-\overline{\gamma\odot\hat d} mean term or the rank-one projection.
  • RMSNorm output is all zeros: γ\gamma was initialised to zero and cannot recover; initialise to ones.
  • Training is unstable with post-norm: add warmup or move the norm to the pre-norm position.
  • NaNs in normalization: variance computed in fp16 overflowed; accumulate in fp32.
  • Model behaves differently between train and eval: you accidentally used batch statistics somewhere (e.g. a leftover BatchNorm).
  • Output scale is wrong by d\sqrt d: confirm whether your implementation uses 1d∑xi2\frac1d\sum x_i^2 or ∑xi2\sum x_i^2 inside the square root.
  • Gains explode: ϵ\epsilon is too small and the normalised input is nearly zero; raise ϵ\epsilon or inspect dead units.

34. Advanced exercises

  1. Prove the RMSNorm gradient formula and the orthogonality lemma symbolically, including the ϵ>0\epsilon>0 correction factor.
  2. Derive the LayerNorm backward from ∂x^i/∂xj\partial\hat x_i/\partial x_j and show where the zero-mean constraint enters.
  3. Implement a fused RMSNorm kernel in NumPy that computes forward and both gradients in a single pass over xx; compare memory traffic with the naive version.
  4. Study post-norm versus pre-norm theoretically: compute gradient norms at initialization for a linear residual block and relate to Xiong et al. (2020).
  5. Replace γ\gamma by a context-dependent gain (FiLM) and implement its backward; discuss when this is worth the cost.
  6. Reproduce the reported 7–18% speedup on a small transformer and carefully document where the time is saved.

35. Interview questions

  • Derive the RMSNorm backward formula and explain the projection term.
  • Why is ⟨x^,∇xL⟩=0\langle\hat x,\nabla_x L\rangle=0 for RMSNorm, and what does that mean for optimisation?
  • State the exact invariances of LayerNorm and RMSNorm; which does RMSNorm lack?
  • How do pre-norm and post-norm differ in gradient flow at initialization?
  • What is the role of ϵ\epsilon, and why should reductions be done in fp32?
  • Derive ∂L/∂γ\partial L/\partial\gamma for both layers and explain the reduction axes in a B×n×dB\times n\times d tensor.
  • Why might RMSNorm be preferred in a large language model despite LayerNorm being more expressive?
  • How would you debug a normalization layer whose gradient check fails only at the mean term?

36. Research questions

  • Is the re-centering in LayerNorm necessary, or is RMSNorm's success evidence that mean information is irrelevant in the residual stream?
  • How does normalization placement interact with scaling laws and depth in very deep transformers?
  • Can normalisation be replaced entirely by better initialisation (Fixup, DeepNorm) without losing stability?
  • What is the optimal ϵ\epsilon as a function of precision, width and activation distribution?
  • Does constraining activations to a sphere improve robustness or harm expressivity on out-of-distribution inputs?
  • How do learned gains distribute across features and layers in trained LLMs, and can they be predicted?

37. Mastery assessment

To pass: (1) derive both forward and backward formulas without notes; (2) reproduce the four-element example and the backward vector numerically; (3) implement both layers and gradient-check to 10−610^{-6}; (4) prove the invariance and orthogonality lemmas; (5) explain pre/post-norm stability, ϵ\epsilon and fp32 reductions; (6) answer the interview questions. Complete the linked assessment; reading the page is not mastery.

38. Implementation submission

Push a repository with norms.py (NumPy LayerNorm and RMSNorm with full backward), tests/test_norms.py (gradient checks, invariance tests and orthogonality checks), experiments.ipynb (worked example, pre/post-norm training curves, throughput benchmark) and a README.md with the derivations and a table of measured timings. Include the exact reproduction command and a comparison against F.layer_norm / F.rms_norm to 10−610^{-6}.

39. Completion criteria

All of: derivations reproduced on paper; both layers implemented and gradient-checked; invariance and orthogonality verified numerically; pre/post-norm experiment with recorded gradient norms; throughput benchmark with reported setup; assessment score at least 80%; one failure case reproduced and one research question answered in a one-page note citing a paper. Only then mark the concept mastered.`

Research papers linked to this concept