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.
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 of its original size; if it grows them by 10%, it is 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.
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 : the output replaces the input. A residual layer computes
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 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 with respect to is : the “1” is a direct highway. Even if every 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 and bias . 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).
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.
Things to try:
- “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.
- “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.
- “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.
- “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 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, . 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,
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 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.
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.
What to look for:
- Plain stack, σ = 0.8. The gradient reaching layer 1 is around of what arrives at the top. Layer 1 would barely learn.
- 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.
- 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.
- 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 for 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 :
LayerNorm has parameters (); RMSNorm has (). Both are invariant to scaling by a positive constant; LayerNorm is also invariant to adding a constant to every entry.
Worked example. , , , .
| quantity | value |
|---|---|
| mean | 5 |
| variance | , so |
| LayerNorm | |
| RMS | |
| RMSNorm |
Scale to and both outputs are identical. Shift to and LayerNorm is identical, but the RMS becomes and RMSNorm gives .
Residual gradients. For , the Jacobian is . Across blocks the gradient picks up the product , which expands to : there is always a direct identity term, so the gradient cannot be multiplied down to zero the way 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))
- “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
Q1.A token vector is multiplied by 10 before entering a LayerNorm. What happens to the LayerNorm output (ignoring ε)?
Q2.Which change leaves LayerNorm's output unchanged but changes RMSNorm's?
Q3.What is the main reason residual connections help gradients reach early layers?
Q4.In a pre-norm block, which line is correct?
Q5.Why do Transformer LLMs use LayerNorm/RMSNorm rather than BatchNorm?
Further reading
- paperLayer Normalization (Ba, Kiros & Hinton, 2016) — The original LayerNorm paper.
- paperRoot Mean Square Layer Normalization (Zhang & Sennrich, 2019) — Introduces RMSNorm.
- paperDeep Residual Learning for Image Recognition (He et al., 2015) — ResNet: the paper that made residual connections standard.
- paperOn Layer Normalization in the Transformer Architecture (Xiong et al., 2020) — Why pre-norm trains more easily than post-norm.
- blogA Mathematical Framework for Transformer Circuits — Anthropic's write-up of the residual stream as a communication channel.