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.
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 independently for each token:
RMSNorm (Zhang, Dauphin & Sennrich, 2019) drops the mean and the shift parameter:
With , RMSNorm makes : it places each token vector on a sphere of radius , keeping only the direction. The learnable gain lets the model restore per-feature magnitudes.
In modern LLMs the norm sits inside the residual branch (pre-norm): , then , 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 features per token — negligible next to attention.
RMSNorm asks whether all of LayerNorm's machinery is necessary. Empirical evidence suggests the re-centering (subtracting ) 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 preserves the direction of 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 gives
The term in parentheses is with its component along removed: (for ). Gradient descent cannot change the norm of — the normalisation already fixed it.
Fact 4 (learned gain). Without , every normalised activation would have the same RMS, which is needlessly restrictive; 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 and learnable :
Its gradient (with ) is
where , bars denote averages over features, and the last term is the mean of . Also , .
RMSNorm. With and :
There is no and no mean subtraction.
Shapes. In a transformer, ; both normalisations operate on the last axis, so have shape and (and ) shape , broadcast over batch and sequence.
8. Notation dictionary
| Symbol | Meaning | Shape / type | |---|---|---| | | one token's activation vector | vector | | | feature mean of | scalar per token | | | feature variance of | scalar per token | | | root mean square | scalar per token | | | normalised vector | vector | | | learned per-feature gain / bias | vectors in | | | stabiliser, typically – | scalar | | | output of the normalization layer | vector | | | upstream gradient | vector | | | average of over features | scalar | | | batch size, sequence length, model width | integers |
9. Step-by-step derivation
Step 1 — LayerNorm forward. Compute and ; form and .
Step 2 — LayerNorm backward. , so the first factor is . The normalisation derivative produces
which is the formula above (the term subtracts the mean because ).
Step 3 — RMSNorm derivative. With , . Hence
Step 4 — assemble the VJP. — a diagonal term minus a rank-one projection.
Step 5 — invariance consequence. Contract with : using , the two terms cancel, so . The gradient is tangent to the sphere — normalisation removes the radial degree of freedom exactly.
Step 6 — parameters. ; LayerNorm additionally has . These reductions are over batch and sequence in a transformer.
10. Proofs and proof intuition
Lemma 1 (RMS after normalisation). With and , . Proof. .
Lemma 2 (LayerNorm invariances). For and any , (with fixed). Proof. , . RMSNorm is invariant only to positive scaling, , since a shift changes the norm but not the mean subtraction (there is none).
Lemma 3 (gradient orthogonality for RMSNorm). when . Proof. From Step 4, and , so the difference is zero. For the identity holds up to a factor .
Lemma 4 (LayerNorm gradient orthogonality). has zero mean and unit variance, and also has zero mean (the term enforces it), so normalisation removes both the radial and the shift directions.
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 , LayerNorm first projects onto the hyperplane by subtracting the mean, then radially projects onto the sphere . RMSNorm skips the hyperplane projection and only does the radial step, so it preserves the direction of and its mean offset. The learned then stretches the sphere into an axis-aligned ellipsoid (and 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 : LayerNorm first shifts it to (a point on the line ), then scales it onto the circle of radius ; RMSNorm scales directly onto the circle of radius — 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 () with post-norm ().
13. Numerical worked example
Take , so and .
LayerNorm. , deviations , squared deviations , so , . Thus ; it has mean and variance .
RMSNorm. , , so
Check: mean of is .
Backward for RMSNorm with and : . Then :
Check orthogonality: . A finite-difference check at agrees to .
Why the distinction matters. With a downstream dot product, LayerNorm's output has zero mean while RMSNorm's retains the mean scaled by ; 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 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 , subtracts its mean and its projection onto , then divides by — exactly the formula in section 7. rmsnorm_backward computes and subtracts , then divides by ; 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 ( 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 is fp16. PyTorch's fused kernels already do this.
19. Tensor and memory analysis
For in fp16 (2 bytes), with , , : alone is MB. Each saved tensor for backward (, or , ) is another ~134 MB. LayerNorm needs (tiny, scalars) and ; RMSNorm needs (tiny) and — 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 layers stores roughly times this activation memory during training (~6 GB for the example), which is why checkpointing and fused kernels matter. Parameters cost only floats — negligible.
20. Time complexity
Both layers are elementwise work with a single reduction over per token; the backward is also with one additional reduction for (and ). 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 () or MLP (), but at large and small they become noticeable, which motivated RMSNorm in large-scale training.
21. Space complexity
for activations and saved normalised tensors, plus for the per-token statistics and for . 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 : LN output , RMSNorm output , and the RMSNorm backward ; gradient-check to . (2) Invariance test: apply LN and RMSNorm to for , ; verify LN is invariant to both and RMSNorm only to . (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 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 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.
- choice matters at low precision; too small causes division by near-zero, too large biases the scale.
- Cost scales linearly with 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
- All-zero input to RMSNorm: , so but the gradient divides by a tiny number; initialise gains properly and avoid zero-only batches.
- 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.
- fp16 reduction errors: variance of large activations overflows or small ones underflow; accumulate in fp32.
- Wrong : inherited from LayerNorm can be too large for RMSNorm with small activations, damping normalisation.
- Applying normalization twice: a leftover LayerNorm in a pre-RMSNorm block double-normalises and shrinks gradients.
- Post-norm instability: with deep stacks and no warmup, gradient norms blow up at initialization; switch to pre-norm or add warmup.
- Gain initialised to zero: outputs are identically zero, gradients to are zero and the layer cannot recover — a subtle dead-layer failure.
- 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 ; 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.
- " and 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
- Implement LayerNorm and RMSNorm forward/backward from memory and gradient-check both at float64.
- Reproduce the numbers and the RMSNorm backward vector to four decimals.
- Verify the invariance lemmas numerically for , and explain which transformation RMSNorm does not handle.
- Check for random and explain the result geometrically.
- 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.
- Benchmark
F.layer_normvsF.rms_normfor ; report throughput and any accuracy difference on the toy task.
33. Debugging challenges
- Gradient check fails for LayerNorm: you omitted the mean term or the rank-one projection.
- RMSNorm output is all zeros: 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 : confirm whether your implementation uses or inside the square root.
- Gains explode: is too small and the normalised input is nearly zero; raise or inspect dead units.
34. Advanced exercises
- Prove the RMSNorm gradient formula and the orthogonality lemma symbolically, including the correction factor.
- Derive the LayerNorm backward from and show where the zero-mean constraint enters.
- Implement a fused RMSNorm kernel in NumPy that computes forward and both gradients in a single pass over ; compare memory traffic with the naive version.
- Study post-norm versus pre-norm theoretically: compute gradient norms at initialization for a linear residual block and relate to Xiong et al. (2020).
- Replace by a context-dependent gain (FiLM) and implement its backward; discuss when this is worth the cost.
- 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 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 , and why should reductions be done in fp32?
- Derive for both layers and explain the reduction axes in a 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 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 ; (4) prove the invariance and orthogonality lemmas; (5) explain pre/post-norm stability, 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 .
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.`