On this page
In a 32-layer decoder, every token carries a hidden vector through the stack. That running vector is the residual stream. Take one token state: [3.0, 1.0, -1.0, 5.0]. Attention reads other visible tokens and adds an update; the feed-forward network adds another. Across dozens of layers, repeated additions stretch the stream's scale. How do we keep what each sublayer reads well-scaled without strangling gradients on their way back from the loss?
LayerNorm centers a single token's features and scales them by their spread, then applies learned gain and shift parameters. Placing that exact operation after the residual addition (Post-LN) versus before the sublayer branch (Pre-LN) creates two completely different forward trajectories and backward gradient paths.
One residual stream, many writes
Write the bare residual update for any transformer sublayer (attention or MLP):
If each sublayer adds a roughly independent perturbation with variance , hidden variance grows linearly with depth and standard deviation expands like :
Correlated writes can bend that curve faster or slower, yet left unchecked, deep residual sums drift in magnitude. Normalization tames that drift, and where it sits around the + decides how error signals flow backward during backpropagation.[1] First, trace the exact arithmetic inside LayerNorm on one vector.
LayerNorm by hand
Take a single 4-dimensional token state x = [3.0, 1.0, -1.0, 5.0] and compute every step without framework magic:
- Feature mean: Average across the token's hidden features:
- Centering: Subtract from every coordinate, giving
[1.0, -1.0, -3.0, 3.0]. - Population variance: Average the squared deviations using (not Bessel's ):
- Standardize: Ignoring for the hand check, divide by :
- Affine transform: Multiply by learned per-channel scale (initialized to
1) and add shift (initialized to0), giving the general formula for :[2]
Adding (typically or ) prevents division by zero on constant vectors, turning pre-affine output variance into . Notice that every reduction stays strictly inside one token's feature axis.
![Three side-by-side calibrated bar plots track features f1 through f4 on a shared vertical scale from -3 to 6. Stage 1 Input x = [3, 1, -1, 5] has mean 2 (dashed line) and variance 5. Stage 2 subtracts mean 2 to produce centered [1, -1, -3, 3] with mean 0 and variance 5. Stage 3 divides by sqrt(5) to yield normalized [0.45, -0.45, -1.34, 1.34] with mean 0 and variance 1.](https://assets.leetllm.com/v1/e2a978ce9b33/fundamentals/layer-normalization-pre-ln-post-ln/illustrations/_generated/layer_norm_dark.png)
Why transformers use LayerNorm instead of BatchNorm
BatchNorm normalizes each feature channel across the mini-batch (and often across time in BatchNorm1d), creating three headaches for causal language models:[3]
| Property | BatchNorm | LayerNorm |
|---|---|---|
| Reduction axis | Mini-batch (and temporal positions) | Feature coordinates within one token |
| Causality & padding | Time reduction can leak future tokens; padding skews stats | Hidden-only stats never mix tokens |
| Train vs eval behavior | Uses batch stats in training, stored running averages in eval | Identical per-token computation in both modes |
| Single-token decoding | Relies on running estimates; sensitive to batch shift | Exact match with training, even at batch size 1 |
In PyTorch, passing an integer nn.LayerNorm(d_model) to a (batch, seq_len, d_model) tensor normalizes strictly along the last axis.[4] Passing a tuple (seq_len, d_model) reduces over time too and leaks future-token edits backward into earlier positions. In mixed precision, always upcast FP16/BF16 inputs to FP32 for the mean and variance reductions before casting back.
import torch
import torch.nn as nn
class LayerNorm(nn.Module):
def __init__(self, d_model: int, eps: float = 1e-5):
super().__init__()
self.gamma = nn.Parameter(torch.ones(d_model))
self.beta = nn.Parameter(torch.zeros(d_model))
self.eps = eps
def forward(self, x: torch.Tensor) -> torch.Tensor:
work = x.float() if x.dtype in (torch.float16, torch.bfloat16) else x
mean = work.mean(dim=-1, keepdim=True)
var = work.var(dim=-1, keepdim=True, unbiased=False)
x_hat = (work - mean) / torch.sqrt(var + self.eps)
return (self.gamma * x_hat + self.beta).to(x.dtype)
# 1. Match the hand calculation on [3, 1, -1, 5].
ln = LayerNorm(4)
out = ln(torch.tensor([[[3.0, 1.0, -1.0, 5.0]]]))
print("hand check:", out.round(decimals=2).detach().tolist())
assert torch.allclose(out.round(decimals=2), torch.tensor([[[0.45, -0.45, -1.34, 1.34]]]))
# 2. Hidden-only LayerNorm isolates token 0 when token 1 changes; reducing over (seq, d) leaks future edits.
seq = torch.tensor([[[1.0, 2.0, 4.0], [2.0, 5.0, 8.0]]], dtype=torch.float64)
edited = seq.clone()
edited[:, 1] += 100.0
per_token = nn.LayerNorm(3, elementwise_affine=False).double()
over_time = nn.LayerNorm((2, 3), elementwise_affine=False).double()print("token 0 unchanged (hidden-only):", torch.allclose(per_token(seq)[:, 0], per_token(edited)[:, 0]))
print("token 0 unchanged (seq+hidden): ", torch.allclose(over_time(seq)[:, 0], over_time(edited)[:, 0]))
assert torch.allclose(per_token(seq)[:, 0], per_token(edited)[:, 0])
assert not torch.allclose(over_time(seq)[:, 0], over_time(edited)[:, 0])hand check: [[[0.44999998807907104, -0.44999998807907104, -1.340000033378601, 1.340000033378601]]]
token 0 unchanged (hidden-only): True
token 0 unchanged (seq+hidden): FalseIf you pass a batch of 16 sequences through nn.LayerNorm(d_model), which numbers determine the mean and variance of token t in sequence b?
Answer
Only the d_model feature coordinates of that single token (b, t). Neighboring tokens in the sequence and other examples in the batch have zero effect on its statistics.
Pre-LN vs Post-LN: placement and gradient flow
Every transformer block wraps two sublayers (multi-head attention and an MLP), each taking and adding an update . Two classic placements put LayerNorm on opposite sides of the addition:
- Pre-LN (GPT-2, Llama, Mistral, Qwen) normalizes the branch input before , leaving the residual highway untouched and appending one final norm before the output head:[7][1]

Why Pre-LN trains more stably
Differentiating each block exposes why depth behaves so differently in backward pass. For one token with standardized state and denominator , the LayerNorm Jacobian scales inversely with and projects out the constant mean direction and radial scaling direction:
Now compare how block Jacobians chain from layer to output :
- Post-LN: . Every backward signal along the skip path must pass through a chain of normalization Jacobians . Under Xiong et al.'s initialization analysis, gradients concentrate heavily near the top layers (final-FFN norm vs Pre-LN's ), making careful learning-rate warmup essential to keep early steps from diverging.[1]
- Pre-LN: . Expanding across layers keeps an explicit identity term outside the branch products:
That additive identity highway carries gradients cleanly to early blocks right from step zero. (Note that does not create an absolute lower bound, since a branch can cancel along specific directions where , and real recipes still pair Pre-LN with tuned warmup and initialization.)[1][8]
Verify both block Jacobians and the forward/backward contrast directly in PyTorch:
import torch
import torch.nn as nn
from torch.autograd.functional import jacobian
# 1. Verify exact analytical block Jacobians against autograd.
torch.manual_seed(11)x = torch.tensor([3.0, 1.0, -1.0, 5.0], dtype=torch.float64, requires_grad=True)
W = torch.randn(4, 4, dtype=torch.float64) * 0.2
I = torch.eye(4, dtype=torch.float64)
ln = lambda v: nn.functional.layer_norm(v, (4,), eps=1e-5)
pre = lambda v: v + W @ ln(v)
post = lambda v: ln(v + W @ v)
torch.testing.assert_close(jacobian(pre, x), I + W @ jacobian(ln, x))
torch.testing.assert_close(jacobian(post, x), jacobian(ln, x + W @ x) @ (I + W))
print("Block Jacobians match autograd: True")
# 2. Compare stream norm growth and per-block gradients across a 6-layer residual MLP stack.
def run_stack(style: str, depth: int = 6, d_model: int = 64):
torch.manual_seed(0)
norms = nn.ModuleList([nn.LayerNorm(d_model) for _ in range(depth)])
mlps = nn.ModuleList([
nn.Sequential(nn.Linear(d_model, d_model * 4), nn.ReLU(), nn.Linear(d_model * 4, d_model))
for _ in range(depth)
])
final_norm = nn.LayerNorm(d_model) if style == "pre" else nn.Identity()
head = nn.Linear(d_model, 16)
h = torch.randn(2, 8, d_model)
target = torch.randn(2, 8, 16)
for norm, mlp in zip(norms, mlps):
h = h + mlp(norm(h)) if style == "pre" else norm(h + mlp(h))
stream_rms = float(h.pow(2).mean().sqrt())
loss = nn.functional.mse_loss(head(final_norm(h)), target)
loss.backward()
grads = [round(float(m[0].weight.grad.norm()), 4) for m in mlps]
print(f"{style:4s} | pre-head stream RMS={stream_rms:.3f} | block grads={grads}")
run_stack("pre")
run_stack("post")Block Jacobians match autograd: True
pre | pre-head stream RMS=1.151 | block grads=[0.2664, 0.2565, 0.2494, 0.2392, 0.2472, 0.2415]
post | pre-head stream RMS=1.000 | block grads=[0.2663, 0.2614, 0.2619, 0.2555, 0.2684, 0.2698]Notice two concrete signatures in that output: Post-LN clamps the stream RMS right at 1.000, while Pre-LN's unnormalized residual stream has already grown to 1.151 after just 6 blocks, which is why deleting FinalNorm in a Pre-LN checkpoint port changes the scale hitting the language-modeling head.
Representation collapse and DeepNorm
Leaving the Pre-LN residual highway unnormalized carries a structural tradeoff in very deep stacks. Because , uncorrelated unit-scale writes push , so each late layer's relative write shrinks like:
In deep Pre-LN translation models, ResiDual documented rising cosine similarity between consecutive normalized states and diminishing late-layer updates (often called representation collapse).[9] Before declaring a late block redundant from a small norm ratio alone, run a controlled ablation zeroing only that block's write on held-out tokens and check task loss directly.
To recover Post-LN's crisp representation updates at extreme depth without instability, DeepNorm (Wang et al., 2022) scales the residual skip by a depth-dependent constant while down-scaling selected sublayer initializations (FFN weights and attention value/output projections) by :[10]
For an -layer encoder-only or -layer decoder-only model, DeepNorm sets and (encoder-decoder stacks adjust constants for cross-attention). Critically, is applied only at weight initialization, never as a second runtime multiplier on . DeepNet scaled Post-LN transformers to 1,000 layers while still retaining learning-rate warmup in its translation runs.[10]
| Property | Post-LN | Pre-LN | DeepNorm |
|---|---|---|---|
| Residual equation | |||
| Skip gradient path | Chained | Direct identity | Scaled skip through |
| Final norm needed? | No (last block normalizes) | Yes (stream unnormalized) | No (last block normalizes) |
| Primary risk | Steep top-layer gradients without warmup | Relative write dilution at great depth | Must preserve exact init recipe |
RMSNorm and mixed-precision traps
Zhang and Sennrich (2019) asked whether mean-centering was necessary at all and introduced RMSNorm, which drops mean subtraction and learned bias , dividing only by the uncentered root mean square:[11]
![Two side-by-side paired grouped bar charts compare LayerNorm (purple) and RMSNorm (green) on input x = [3, 1, -1, 5] and shifted input x + 10 = [13, 11, 9, 15] over a shared [-1.6, 1.9] axis. LayerNorm outputs remain invariant at [0.45, -0.45, -1.34, 1.34] after the +10 shift because mean subtraction removes uniform offsets, whereas uncentered RMSNorm shifts from [1.00, 0.33, -0.33, 1.67] to all-positive [1.07, 0.90, 0.74, 1.23].](https://assets.leetllm.com/v1/9a92fe7b0c62/fundamentals/layer-normalization-pre-ln-post-ln/illustrations/_generated/norm_variants_dark.png)
x and x + 10 (). Centering makes LayerNorm invariant to uniform additive shifts; uncentered RMSNorm pulls every output positive.Llama, Mistral, Qwen 2.5, and Gemma 2 all adopt RMSNorm.[12][13] Do not assume dropping mean calculation halves GPU runtime, though: fused LayerNorm kernels compute mean and variance in one pass via Welford's algorithm, so memory bandwidth dominates, and even halving a normalization kernel that takes 2% of step time only trims 1% end to end.[14][15][11]
In mixed precision, always cast FP16 activations to FP32 before squaring. A finite FP16 number like 300.0 squares to 90,000, overflowing FP16's ceiling (65,504) into inf before the square root ever runs. Separately, FP32 accumulation cannot rescue precision already destroyed by input rounding ([10000, 10001, 9999, 10002] all round to 10000.0 in FP16 before normalization starts):[16][17]
import torch
import torch.nn as nn
class RMSNorm(nn.Module):
def __init__(self, d_model: int, eps: float = 1e-6):
super().__init__()
self.weight = nn.Parameter(torch.ones(d_model))
self.eps = eps
def forward(self, x: torch.Tensor) -> torch.Tensor:
work = x.float() if x.dtype in (torch.float16, torch.bfloat16) else x
rms = torch.sqrt(work.pow(2).mean(dim=-1, keepdim=True) + self.eps)
return (self.weight * (work / rms)).to(x.dtype)
x = torch.tensor([[[3.0, 1.0, -1.0, 5.0]]])
out = RMSNorm(4)(x)
print("RMSNorm([3, 1, -1, 5]):", out.round(decimals=4).detach().tolist())
large = torch.tensor([300.0, -300.0], dtype=torch.float16)
fp16_rms = (large.square().mean() + 1e-6).sqrt()
fp32_rms = (large.float().square().mean() + 1e-6).sqrt()
print(f"FP16 squaring RMS={fp16_rms.item()} | FP32 upcast RMS={fp32_rms.item():.1f}")
assert torch.isinf(fp16_rms) and fp32_rms.item() == 300.0RMSNorm([3, 1, -1, 5]): [[[1.0, 0.33329999446868896, -0.33329999446868896, 1.666700005531311]]]
FP16 squaring RMS=inf | FP32 upcast RMS=300.0Modern layouts: QK-Norm and Peri-LN
Modern frontier models combine residual placement with targeted internal normalizers:
| Layout | Representative models | Structural mechanism |
|---|---|---|
| Pre-RMSNorm | Llama 3, Mistral, Qwen 2.5 | RMSNorm on sublayer inputs + final norm[12] |
| Peri-LN / Sandwich | Gemma 2, Kim et al. (2025) | Norm on both input and output of each branch, before the residual add[13][8] |
| QK-Norm | ViT-22B, Gemma 3, Qwen3 | Normalizes per-head and inside attention before dot products[18][19][20] |
QK-Norm tames attention logit growth
Inside self-attention, can grow extreme score differences as projection weights expand during long runs, pushing attention softmax toward one-hot spikes whose Jacobian collapses near zero. QK-Norm normalizes per-head queries and keys right before the dot product:[21][22]
By Cauchy-Schwarz, unit-RMS vectors (Euclidean length ) bound un-gained logits to . Learned gains raise that ceiling, and aligned signs across large can still produce sharp softmax weights, so QK-Norm controls one scale source inside attention without replacing residual-stream normalization.
Peri-LN (sandwich normalization)
Sandwich layouts normalize both the incoming branch input and the outgoing branch write inside the branch before adding to the residual stream:
Because stays before the +, the direct identity skip survives while every newly added write has controlled scale. Kim et al. (2025) reported fewer gradient spikes and lower validation loss across 400M–3.2B models relative to Pre-LN.[8]
Debugging normalization failures
| Symptom | Likely cause | Check and fix |
|---|---|---|
| Nonfinite loss on early steps | FP16 squaring overflow, bad mask, or steep Post-LN gradients | Find the first nonfinite tensor; verify FP32 norm reduction and test learning-rate warmup |
| Nearly one-hot attention | Growing projection norms or affine gains | Log attention logit gaps and entropy; compare QK-Norm or logit soft-capping |
| Shifted logits after porting Pre-LN | Dropped FinalNorm or mismatched eps | Restore final norm, match checkpoint eps (note PyTorch nn.RMSNorm defaults eps=None to machine epsilon), and verify activations |
| Small early-block gradients | Chained Post-LN Jacobians or branch cancellation | Log per-block gradient norms across depth; compare Pre-LN or DeepNorm scaling |
| Suspected late-layer redundancy | Large Pre-LN stream diluting relative write size | Measure loss with only that block's write zeroed on held-out tokens before pruning |