Skip to content
LearnAI
PART 2 · HOW LANGUAGE MODELS WORK/ Inside the Transformer

2.8LayerNorm, RMSNorm & residual connections

The unglamorous plumbing that lets Transformers stack dozens of layers without their numbers vanishing or exploding, and the "residual stream" that ties it all together.

⏱ 15 minIntermediate

The problem with depth

Attention and MLPs are the parts of a Transformer that get the attention (sorry). But if you stacked 12, 48 or 96 of those layers naively, one after another, the model would not train. Two failure modes appear as soon as networks get deep.

Signals vanish or explode. Each layer multiplies its input by a matrix. If that tends to shrink vectors by even 10%, then after 50 layers the signal is 0.950≈0.0050.9^{50} \approx 0.005 of its original size; if it grows them by 10%, it is 1.150≈1171.1^{50} \approx 117 times larger. Numbers drift out of the range where activations and softmaxes behave well.

Gradients vanish or explode, too. BackpropagationBackpropagationAn algorithm that computes the gradient of the loss with respect to every parameter by applying the chain rule backward through the network. multiplies local derivatives layer by layer on the way back down. The same compounding means early layers can receive gradients that are effectively zero (they never learn) or astronomically large (training diverges).

Two simple ideas solve most of this: the residual connectionResidual connectionAdding a layer's input to its output (x + f(x)). This creates a 'residual stream' and makes very deep networks trainable. and layer normalizationLayer normalizationRescales each token's vector to zero mean and unit variance, with learned scale and shift. RMSNorm is a simpler variant.. They’re small in code but they are the reason “deep” learning can be deep.

ANALOGY· A shared whiteboard in an open office

Picture a long office where a whiteboard rolls past a row of 24 specialists. Each specialist reads the board, thinks, and adds a few notes, but is not allowed to erase what’s already there. By the end, the board holds the original message plus everyone’s contributions, and anyone who didn’t have anything useful to say simply wrote nothing.

The whiteboard is the residual stream, each specialist is a sublayer (attention or MLP), and “add, don’t erase” is the residual connection. Before each specialist reads, an assistant photocopies the board at a standard size and contrast so that it’s never too faint or too dark to read: that is normalization. The board itself is never rescaled, only the copy handed to the specialist.

Residual connections: add, don’t replace

A plain layer computes xnew=f(x)x_\text{new} = f(x): the output replaces the input. A residual layer computes

xnew=x+f(x).x_\text{new} = x + f(x).

The layer only has to learn a correction to its input, not a whole new representation. If a layer has nothing useful to contribute, it can learn f(x)≈0f(x) \approx 0 and pass its input through untouched. This idea made 152-layer image networks trainable in 2015 (ResNet), and every Transformer uses it twice per block: once around attention, once around the MLP.

The benefit for gradients is just as important. The derivative of x+f(x)x + f(x) with respect to xx is 1+f′(x)1 + f'(x): the “1” is a direct highway. Even if every f′f' is tiny, gradients from the loss reach the first layer along the identity path without being multiplied down to nothing.

Normalization: a standard-size copy

Residual connections alone have a problem of their own: since every layer adds to the stream, its magnitude tends to grow with depth, and each sublayer would see inputs of a different scale. Normalization fixes the scale of what each sublayer reads.

LayerNorm works on one token’s vector at a time. It subtracts the vector’s mean, divides by its standard deviation, and then applies a learned per-dimension gain γ\gamma and bias β\beta. After it, every token’s vector has mean about 0 and spread about 1 (before the gain), however large or small it was going in.

RMSNormRMSNormA simpler LayerNorm that only divides a vector by its root-mean-square and multiplies by a learned gain, skipping the mean subtraction and bias. Used by most modern LLMs. is a simplification proposed in 2019. It skips the mean subtraction and the bias, and only divides by the root-mean-square (the typical size of the entries), then multiplies by a learned gain. It does slightly less work, and in practice it trains about as well, so it has become the default in most modern open LLMs (the Llama family and its many descendants, for example).

INTERACTIVENormalization visualizer
Try:
Input x (drag the bars)
630-3-61.2-0.62.10.4-1.40.93.0-0.2μ = 0.67
LayerNorm(x)
420-2-40.4-0.91.1-0.2-1.50.21.7-0.6mean = 0.00
RMSNorm(x)
420-2-40.8-0.41.40.3-0.90.62.0-0.1mean = 0.45
mean μ
0.675
variance σ²
1.817
std σ
1.348
RMS
1.507
LN out: std
1.000
RMSNorm out: RMS
1.000

In a real model γ and β are learned vectors with one value per dimension; here one shared value keeps it simple. Compare “Default” with “Scale ×2”: both normalized outputs are identical. Then try “Shift all +3”: LayerNorm doesn’t care, RMSNorm does.

Drag the input bars (or focus one and use the arrow keys). The middle and right panels show LayerNorm and RMSNorm of the same vector. Try the presets to see what each normalization ignores.

Things to try:

  1. “Scale ×2”. Doubling the input leaves both outputs unchanged. Normalization makes sublayers blind to the overall size of the stream; only the direction of the vector reaches them.
  2. “Shift all +3”. LayerNorm’s output doesn’t move: it subtracts the mean, so adding a constant to every dimension is invisible. RMSNorm’s output changes, because a constant offset changes the vector’s direction. The fact that RMSNorm works just as well suggests the re-centering wasn’t doing much in practice.
  3. “One huge outlier”. One dimension dominates the variance, so after normalization the others are squashed near zero. Real LLMs do develop a few such massive dimensions, and they cause real headaches for quantization.
  4. “Nearly constant”. The input is almost flat, with tiny wiggles. LayerNorm blows those wiggles up to unit variance. Normalization amplifies whatever variation exists, even noise; the small ϵ\epsilon in the formula keeps it from dividing by zero.

Pre-norm vs post-norm

Where should the normalization go? The original 2017 Transformer used post-norm: compute the sublayer, add the residual, then normalize the sum, x←LN(x+f(x))x \leftarrow \text{LN}(x + f(x)). That puts a normalization on the residual path itself, so gradients flowing down the highway get rescaled at every block. Post-norm Transformers famously needed a careful learning-rate warm-up and became hard to train as they got deeper.

GPT-2 (2019) moved to pre-norm: normalize only the copy that the sublayer reads, and leave the highway clean,

x←x+f(LN(x)).x \leftarrow x + f(\text{LN}(x)).

A 2020 analysis showed that with pre-norm, gradients at initialization are much better behaved, and models can be trained with less warm-up. Pre-norm needs one extra normalization at the very end of the stack (the “final LayerNorm”), since the stream itself is never normalized. Essentially all current LLMs use the pre-norm layout, typically with RMSNorm. Some recent designs add extra norms, for example after each sublayer as well (sometimes called “sandwich” norm) or on the queries and keys inside attention (“QK-norm”), mainly for stability in very large training runs. The pre-normPre-norm vs post-normWhere normalization sits in a Transformer block. Post-norm (original Transformer) normalizes after each residual add; pre-norm (GPT-2 onward) normalizes the input of each sublayer and leaves the residual path untouched, which trains more stably when deep. layout is the baseline those variations start from.

The residual stream

Put residuals and pre-norm together and a different picture of the Transformer emerges. Each token has a vector of size dmodeld_\text{model} that travels from the embedding at the bottom to the unembedding at the top. Every attention layer and every MLP reads a normalized copy of that vector and adds a contribution back. Nothing ever overwrites it.

Interpretability researchers call this vector the residual streamResidual streamThe running vector for each token that flows through a Transformer: every attention and MLP sublayer reads from it and adds its output back into it, like a shared communication bus. and treat it as a shared communication bus:

  • Attention layers move information between streams (from one token’s stream to another’s).
  • MLP layers process information within a stream (for example, recalling a fact associated with a word).
  • A layer at depth 3 can write something that a layer at depth 20 reads directly, skipping everything in between, because addition preserves it (unless later layers actively write the opposite).
  • The final output is literally the sum of the embedding plus every sublayer’s contribution, which is why tools like the “logit lens” can peek at what the stream “predicts” partway up the stack.

This view is a big part of why Transformers are analyzable at all; see interpretability for where it leads.

INTERACTIVEDeep network with and without residuals
Plot
1e-81e-411e41e81e1201020304050layer (0 = input, 50 = output)healthy zone (0.1× to 10×)
Plain stack (no residuals)
gradient at layer 1: 1.0e-5×
Residuals + pre-norm
gradient at layer 1: 6.52×

Values are relative: signal is compared with the input, gradient with the gradient arriving at the top layer. Lines leaving the chart have vanished below 1e-8 or exploded past 1e12.

A toy 50-layer network (width 48, ReLU, random weights). Switch between gradient and signal magnitude, move the weight scale away from 1, and compare a plain stack with residual + pre-norm. Lines that leave the chart have vanished or exploded.

What to look for:

  1. Plain stack, σ = 0.8. The gradient reaching layer 1 is around 10−510^{-5} of what arrives at the top. Layer 1 would barely learn.
  2. Plain stack, σ = 1.2. Now it explodes instead. Only at σ ≈ 1.0 (a carefully tuned initialization) does the plain stack stay healthy: a knife’s edge.
  3. Residual + pre-norm. Across the whole slider range, the gradient at layer 1 stays within roughly an order of magnitude of the top. The forward signal grows gently with depth, as each layer adds to the stream.
  4. Residuals without norm. Switch on this third network and you’ll see that residual connections alone are not enough here: every layer adds a positive-ish ReLU output to an un-normalized stream, so it grows exponentially. Real models fight this with normalization and by initializing each layer’s output weights small (GPT-2 scales them by 1/N1/\sqrt{N} for NN residual layers).

The toy is crude (real Transformers have attention, two sublayers per block and trained weights), but the qualitative story matches what makes deep Transformers trainable.

MATH CORNER · optionalThe formulas, with a 4-number example

For a token vector x∈Rdx \in \mathbb{R}^d:

μ=1d∑ixi,σ2=1d∑i(xi−μ)2,\mu = \frac{1}{d}\sum_i x_i, \qquad \sigma^2 = \frac{1}{d}\sum_i (x_i - \mu)^2,LayerNorm(x)i=γi xi−μσ2+ϵ+βi,RMSNorm(x)i=gi xi1d∑jxj2+ϵ.\text{LayerNorm}(x)_i = \gamma_i \,\frac{x_i - \mu}{\sqrt{\sigma^2 + \epsilon}} + \beta_i, \qquad \text{RMSNorm}(x)_i = g_i \,\frac{x_i}{\sqrt{\frac{1}{d}\sum_j x_j^2 + \epsilon}} .

LayerNorm has 2d2d parameters (γ,β\gamma, \beta); RMSNorm has dd (gg). Both are invariant to scaling xx by a positive constant; LayerNorm is also invariant to adding a constant to every entry.

Worked example. x=(2,4,6,8)x = (2, 4, 6, 8), γ=g=1\gamma = g = 1, β=0\beta = 0, ϵ≈0\epsilon \approx 0.

quantityvalue
mean μ\mu5
variance σ2\sigma^2(9+1+1+9)/4=5(9 + 1 + 1 + 9)/4 = 5, so σ=2.236\sigma = 2.236
LayerNorm(x)(x)(−1.342,−0.447,0.447,1.342)(-1.342, -0.447, 0.447, 1.342)
RMS(4+16+36+64)/4=30=5.477\sqrt{(4 + 16 + 36 + 64)/4} = \sqrt{30} = 5.477
RMSNorm(x)(x)(0.365,0.730,1.095,1.461)(0.365, 0.730, 1.095, 1.461)

Scale to x=(4,8,12,16)x = (4, 8, 12, 16) and both outputs are identical. Shift to x=(3,5,7,9)x = (3, 5, 7, 9) and LayerNorm is identical, but the RMS becomes 41=6.403\sqrt{41} = 6.403 and RMSNorm gives (0.469,0.781,1.093,1.406)(0.469, 0.781, 1.093, 1.406).

Residual gradients. For y=x+f(x)y = x + f(x), the Jacobian is ∂y/∂x=I+∂f/∂x\partial y/\partial x = I + \partial f/\partial x. Across LL blocks the gradient picks up the product ∏ℓ(I+Jℓ)\prod_\ell (I + J_\ell), which expands to I+∑ℓJℓ+…I + \sum_\ell J_\ell + \ldots: there is always a direct identity term, so the gradient cannot be multiplied down to zero the way ∏ℓJℓ\prod_\ell J_\ell can in a plain stack.

In code

A pre-norm Transformer block, the shape used by GPT-2 and (with RMSNorm and a different MLP) by Llama-style models:

import torch, torch.nn as nn

class RMSNorm(nn.Module):
    def __init__(self, d, eps=1e-6):
        super().__init__()
        self.eps, self.g = eps, nn.Parameter(torch.ones(d))
    def forward(self, x):
        return self.g * x * torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + self.eps)

class Block(nn.Module):
    def __init__(self, d, attn, mlp):
        super().__init__()
        self.norm1, self.norm2 = RMSNorm(d), RMSNorm(d)   # or nn.LayerNorm(d)
        self.attn, self.mlp = attn, mlp
    def forward(self, x):                 # x is the residual stream
        x = x + self.attn(self.norm1(x))  # read a normalized copy, add back
        x = x + self.mlp(self.norm2(x))
        return x
# post-norm (2017) would instead be: x = norm1(x + attn(x)); x = norm2(x + mlp(x))
COMMON MISCONCEPTIONS
  • “Normalization makes every layer’s output small.” It only normalizes the copy a sublayer reads. In a pre-norm model the residual stream itself is never normalized until the final norm, and its magnitude typically grows with depth.
  • “LayerNorm normalizes across the batch or across tokens.” It normalizes each token’s vector on its own, across that vector’s dimensions. That’s what makes it work identically at training and generation time.
  • “Residual connections are a minor optimization trick.” Without them, deep Transformers essentially don’t train. They also shape how the model computes: information written early can be read much later.
  • “RMSNorm is an approximation that loses accuracy.” It drops mean-centering and the bias, which turn out to matter little. Many strong modern models use it by choice, not as a compromise.

Check your understanding

0/5 answered
  1. Q1.A token vector is multiplied by 10 before entering a LayerNorm. What happens to the LayerNorm output (ignoring ε)?

  2. Q2.Which change leaves LayerNorm's output unchanged but changes RMSNorm's?

  3. Q3.What is the main reason residual connections help gradients reach early layers?

  4. Q4.In a pre-norm block, which line is correct?

  5. Q5.Why do Transformer LLMs use LayerNorm/RMSNorm rather than BatchNorm?

Further reading

Progress is saved in this browser only.
Type to search across all lessons and glossary terms.