Residual Connections & Layer Normalization
Imagine stacking fifty layers of Multi-Head Attention and feed-forward blocks to build a powerful language model. Naively, the gradient signal used to train the earliest layers must travel through all fifty layers during backpropagation. It shrinks or explodes at every step. Without a fix, deep Transformers simply fail to train. Loss curves stall, gradients vanish, and adding depth makes the model worse, not better. This is the exact problem residual connections and layer normalization solve together. These two ingredients are unglamorous compared to attention. Yet they are what makes every practical deep Transformer trainable at all. A residual (skip) connection lets information and gradient flow around a layer via an identity shortcut. The network only has to learn a correction to its input rather than reinvent it from scratch. Layer normalization rescales the activations flowing through the network at every layer. This keeps their scale in a numerically friendly range regardless of depth. Together they turn "a deep stack of complicated functions" into "a stable, well-conditioned optimization problem." The big picture is architectural humility. Instead of asking each layer to transform its input into something entirely new, we ask each layer to compute a small additive update. We normalize before things get out of hand. This design pattern was pioneered for convolutional networks and adapted for Transformers. It is now completely standard, appearing in every major encoder and decoder stack. This includes the original Transformer, GPT, BERT, and beyond. This article gives a precise definition of residual connections and layer normalization. It works through the pre-norm vs. post-norm placement debate. It derives why gradients survive deep stacks. It traces a concrete numerical example through a two-layer block. It closes with pitfalls, history, and where these ideas show up in real systems. This sets up the fuller Transformer Encoder Stack and Transformer Decoder Stack architectures built entirely from these components.
- A residual connection adds a sublayer's output to its input: `x + Sublayer(x)`, giving gradients a direct identity path back through the network.
- Layer normalization rescales each token's activation vector to zero mean and unit variance, then applies a learned affine transform.
- Post-norm (original Transformer) normalizes after the residual add; pre-norm (modern default) normalizes before the sublayer, which trains more stably at depth.
- Residual connections make the identity function trivial to represent, so extra depth cannot make training worse in principle — only optimization difficulty can.
- Layer norm operates per-token, independent of batch size, unlike batch normalization — crucial for variable-length sequences and small batches.
- Together, these components let Transformers scale to 100+ layers, a prerequisite for the Transformer Encoder Stack and Transformer Decoder Stack used in modern LLMs.
Residual connections give gradients a direct identity path through the network, and layer normalization keeps activation scales stable at every depth — together they make very deep Transformers trainable.
The idea
A residual connection (or skip connection) wraps a sublayer (attention or feed-forward) so that the block computes
instead of directly. The input is added back to the sublayer's output, forming a shortcut path that bypasses entirely. This means only needs to learn the residual — the difference between what the input already represents and what the output should represent — rather than reconstructing the entire representation from nothing.
Layer normalization (LayerNorm) is a normalization technique applied per token (per position in the sequence), independent of other tokens in the batch. For a single token's activation vector , LayerNorm computes
where are learned scale and shift parameters, and is a small constant preventing division by zero. Unlike batch normalization, LayerNorm's statistics are computed across the feature dimension of a single example, not across the batch dimension — this makes it insensitive to batch size and well-suited to sequences of varying length, since each token is normalized using only its own features. The interaction of these two components inside a Transformer sublayer is called a residual block, and its exact wiring — whether normalization happens before or after the residual add — is a design choice with real consequences, discussed next.
How it works
A Transformer layer contains two sublayers: multi-head attention and a position-wise feed-forward network. Each is wrapped in a residual-plus-norm block. There are two standard arrangements.
Post-LN (original Transformer, 2017). Normalize after adding the residual:
Pre-LN (modern default, used in GPT-2 and later). Normalize before feeding into the sublayer, and add the raw residual afterward:
The pre-LN arrangement keeps an unbroken identity path from the very first layer to the very last — the residual stream is never itself passed through a normalization layer before being added back, only a normalized copy is fed to the sublayer. This detail turns out to matter enormously for gradient flow at depth (see Complexity & Correctness). Each sublayer in practice also uses dropout on the sublayer output before the residual add, as a regularizer: ``` Sublayer output → Dropout → Add to residual stream → (Post-LN: Normalize here) ```
Pseudocode: a full pre-norm Transformer block
``` function TransformerBlockPreLN(x, W_attn, W_ffn, gamma1, beta1, gamma2, beta2):
# x: matrix of shape (seq_len, d_model), one row per token
# --- Sublayer 1: Multi-Head Attention --- normed1 = LayerNorm(x, gamma1, beta1) # normalize per token attn_out = MultiHeadAttention(normed1, W_attn) # see Multi-Head Attention attn_out = Dropout(attn_out, p=dropout_rate) x = x + attn_out # residual connection
# --- Sublayer 2: Position-wise Feed-Forward --- normed2 = LayerNorm(x, gamma2, beta2) ffn_out = FeedForward(normed2, W_ffn) # e.g. Linear -> ReLU -> Linear ffn_out = Dropout(ffn_out, p=dropout_rate) x = x + ffn_out # residual connection return x
function LayerNorm(x, gamma, beta, eps=1e-5):
# x: (seq_len, d_model); normalize each row independently for each token row t in x: mu = mean(t) # scalar var = mean((t - mu)^2) # scalar (biased estimator) t_hat = (t - mu) / sqrt(var + eps) # normalized row t_out = gamma t_hat + beta # elementwise affine, gamma,beta in R^d output_row[t] = t_out return output_row ``` The post-LN variant is identical except the normalization call moves after* the residual add: ``` function TransformerBlockPostLN(x, W_attn, W_ffn, gamma1, beta1, gamma2, beta2): attn_out = MultiHeadAttention(x, W_attn) attn_out = Dropout(attn_out, p=dropout_rate) x = LayerNorm(x + attn_out, gamma1, beta1) # normalize AFTER residual add ffn_out = FeedForward(x, W_ffn) ffn_out = Dropout(ffn_out, p=dropout_rate) x = LayerNorm(x + ffn_out, gamma2, beta2) # normalize AFTER residual add return x ``` A full encoder or decoder stacks of these blocks, feeding the output of one directly as the input to the next — a design elaborated fully in the Transformer Encoder Stack and Transformer Decoder Stack articles.
Complexity & correctness
Time and space complexity. Both operations are cheap relative to attention. The residual add is elementwise: time and space for a sequence of length and hidden dimension . LayerNorm computes a mean and variance per token, each an reduction, over tokens: time, space for the normalized output (or extra space beyond the input if done in place). Compare this to self-attention's time — residual and norm operations are asymptotically negligible, adding no new bottleneck to the architecture's overall complexity, which remains dominated by attention.
Why residual connections fix gradient flow: an invariant argument. Consider a stack of residual blocks in pre-LN form, . By the chain rule, the gradient of the loss with respect to an early layer's input is
Each factor is the identity matrix plus a Jacobian term. Expanding the product, the identity terms alone contribute directly to — an unattenuated path exists regardless of how small or ill-conditioned the sublayer Jacobians become. Without the residual connection ( alone), the same product would consist purely of sublayer Jacobians, and if each has, say, spectral norm , the product shrinks geometrically with depth — the vanishing gradient problem. The identity term structurally guarantees a gradient floor, which is the essence of why residual connections make arbitrarily deep networks trainable: the network is never forced to lose the input signal, only permitted to add to it.
Why depth cannot hurt (in principle). With residual connections, if the ideal function for a block is the identity, only needs to learn , which is trivially reachable (e.g., zero-initialized output weights). This means adding a residual block can only make the hypothesis class the network can represent a superset of what a shallower network could represent — the identity is always achievable, so a deeper residual network is never forced to represent a strictly worse function than a shallower one. Without residuals, learning an identity mapping through several nonlinear layers is nontrivial, since generic nonlinear layers do not naturally sit near identity at initialization.
Why LayerNorm stabilizes optimization. LayerNorm rescales each token vector to have unit variance across features at every layer, which keeps the input distribution to each sublayer within a numerically stable range independent of depth. This mitigates the internal covariate shift problem: without renormalization, activation magnitudes can compound multiplicatively across layers (either shrinking toward zero or exploding), making learning rates that work for one layer inappropriate for another. Because LayerNorm's statistics are computed per token rather than per batch, this stabilization is exact and deterministic at both training and inference time — there is no dependency on batch statistics that must be estimated and can behave differently at test time (a known pitfall of batch normalization in sequence models).
Pre-LN vs. post-LN: a real tradeoff. Post-LN, as used in the original Transformer, applies LayerNorm to the sum , meaning the residual stream itself is renormalized every layer — the identity shortcut is not perfectly clean, since normalization is a nonlinear (though gentle) operation inserted directly into the gradient path back through the residual stream. Empirically and theoretically, this causes gradients at initialization to grow with depth in post-LN Transformers, requiring learning-rate warmup to train stably beyond a modest number of layers. Pre-LN keeps the residual stream itself untouched by any normalization — LayerNorm only appears on the branch feeding into each sublayer — preserving the clean identity path derived above and enabling stable training without warmup, even for very deep stacks (dozens to over a hundred layers). The tradeoff: pre-LN stacks can suffer from representation collapse in extremely deep settings (very late layers contribute a shrinking relative fraction of the final normalized output) and sometimes require an additional final LayerNorm after the last block to control output scale — a detail present in GPT-2's architecture.
Worked example
Trace one pre-LN block on a toy input with , one token, to make every number concrete. Let the token's residual-stream vector be
Step 1 — LayerNorm before attention. Assume , (identity affine, common at initialization), .
Step 2 — Toy attention sublayer. Suppose (for illustration) the attention sublayer, after self-attention and output projection, produces for this token (a small update, as is typical near initialization).
Step 3 — Residual add. The key operation: add back to the original, un-normalized , not to .
Notice is close to the original — the block made a small, controlled correction rather than replacing the representation. This is exactly the intended residual behavior.
Step 4 — Feed into sublayer 2 (feed-forward). Repeat: normalize (mean , similar rescaling), pass through the feed-forward network to get some small update , and add it to (not to the normalized copy) to produce the block's final output.
| Stage | Vector | Notes |
|---|---|---|
| Input | residual stream entering block | |
| zero mean, unit variance | ||
| attention sublayer output | ||
| residual add — stream barely perturbed |
This trace illustrates the core mechanic: LayerNorm operates on a branch copy used only to compute the sublayer's output, while the actual residual stream accumulates small additive updates across layers, exactly the structure the gradient-flow argument above relies on.
Common pitfalls & traps
| Pitfall | Why it happens | Fix |
|---|---|---|
| Adding the residual to the normalized value instead of the original input | Confusing pre-LN wiring: `x = LN(x) + F(LN(x))` breaks the clean identity path | Always add `F(LN(x))` back to the original `x`, not to `LN(x)` |
| Using post-LN with no learning-rate warmup on very deep stacks | Post-LN's residual stream is itself renormalized, causing gradient growth early in training | Use pre-LN, or add a warmup schedule if post-LN is required |
| Treating LayerNorm like BatchNorm (normalizing across the batch dimension) | Conceptual mix-up between the two normalization families | LayerNorm normalizes across the feature dimension of each token independently |
| Forgetting the final LayerNorm after the last block in a pre-LN stack | Pre-LN leaves the residual stream un-normalized until explicitly normalized at the end | Add one final `LayerNorm` after the last residual block before the output projection |
| Using a too-small or omitting it entirely | Numerical instability when a token's variance is near zero (e.g., a constant activation vector) | Keep a small (commonly or ) inside the square root |
| Assuming residual connections alone guarantee good gradients regardless of normalization | The identity-path argument assumes bounded, well-scaled sublayer Jacobians; without normalization, activations can still blow up | Always pair residual connections with LayerNorm (or a comparable normalization) |
Pioneers & history
Residual connections originated in computer vision, and layer normalization was developed for recurrent and sequence models; both were combined into the Transformer architecture, whose motivating problem was training arbitrarily deep sequence models without recurrence.
Origins · 1 minKaiming He and how this was discovered
Where this matters
Every major Transformer-based system — encoder-only models like BERT, decoder-only models like the GPT family, and encoder-decoder models like T5 — is built from residual blocks wrapped in layer normalization, stacked dozens to over a hundred times. Without this pairing, none of these models could be trained at their actual depths; the vanishing-gradient problem that plagued deep recurrent networks would reappear immediately in deep attention stacks. Production LLM training pipelines depend on the specific pre-LN vs. post-LN choice to determine whether learning-rate warmup schedules are necessary and how large a model can be scaled before training destabilizes. Variants of this idea — RMSNorm (a simplified LayerNorm without mean-centering), and various residual-scaling schemes — appear in more recent large models seeking marginal efficiency or stability gains, but the underlying principle, an identity shortcut plus per-token normalization, remains unchanged. This foundation is exactly what the Transformer Encoder Stack and Transformer Decoder Stack articles build upon when assembling full multi-layer architectures, and it is inseparable from why Multi-Head Attention can be stacked at all at production scale.
Ask the tutor: Why does pre-LN Transformer training remain stable without learning-rate warmup, while post-LN does not?
Why is layer normalization applied per token instead of per batch?
Sequences in a batch often have different lengths and different numbers of padding tokens, so per-batch statistics (as in BatchNorm) would mix meaningful and padding activations together and would depend on the specific batch composition. LayerNorm sidesteps this entirely by computing mean and variance across the feature dimension of a single token's vector, making the operation identical during training and inference and independent of batch size. This is essential for sequence models processing variable-length inputs, and it is one reason LayerNorm (not BatchNorm) became the default normalization inside Transformers, RNNs, and other sequence architectures.
Do residual connections add any new parameters to the model?
No — the residual connection itself is a parameter-free operation, simply an elementwise addition of the sublayer's input to its output. All the learnable parameters live inside the sublayer (attention projections, feed-forward weights) and inside the accompanying LayerNorm (the scale and shift vectors, each of size ). This means residual connections are essentially free in terms of parameter count and computational cost, while providing an outsized benefit to trainability — a very favorable cost-benefit tradeoff that explains their universal adoption.
Why does pre-LN avoid the need for learning-rate warmup while post-LN does not?
In post-LN, the residual stream itself is passed through LayerNorm at every layer, which is a nonlinear rescaling operation inserted directly into the backward path carrying gradients to earlier layers. Near initialization, this causes gradient magnitudes at the output layer to be much larger than at early layers, so a learning rate suited to early layers can destabilize later layers (and vice versa) unless warmup gradually ramps the learning rate up. Pre-LN avoids this because the residual stream itself is never renormalized — only a branch copy fed to each sublayer is — preserving a much more uniform gradient scale across depth from the start of training.
Is layer normalization the only normalization scheme used in modern Transformers?
No. RMSNorm, used in several modern large language models, simplifies LayerNorm by skipping the mean-centering step and only rescaling by the root-mean-square of the activations, which is slightly cheaper to compute and empirically performs comparably in many settings. Other variants adjust where normalization is placed (e.g., "sandwich" norm schemes applying normalization both before and after a sublayer) to further stabilize very deep or very wide models. All of these share the same underlying goal as standard LayerNorm: keeping per-token activation scales controlled and depth-independent.
Can residual connections cause any problems of their own?
Yes — in extremely deep pre-LN stacks, the residual stream's activation magnitude can grow roughly proportionally with depth, since each block adds a further increment without ever subtracting or rescaling the accumulated stream. This can lead to a phenomenon sometimes called representation or gradient imbalance, where later blocks contribute a shrinking relative fraction to the final output, since their contribution is small relative to the accumulated magnitude of the stream. Mitigations include a final LayerNorm after the last block, careful initialization schemes that scale sublayer outputs down with depth, and architectural variants that rescale residual contributions explicitly.
How do residual connections and layer normalization relate to attention specifically?
Multi-Head Attention itself has no built-in mechanism to prevent vanishing gradients or activation blowup across many stacked layers — it is simply a sublayer, like the feed-forward network, that residual connections and LayerNorm wrap around. Every attention block in a real Transformer is written as `x + MultiHeadAttention(LayerNorm(x))` (pre-LN) or `LayerNorm(x + MultiHeadAttention(x))` (post-LN), never as bare attention output. This means the trainability benefits described here apply identically whether the sublayer is attention or a feed-forward network, which is why the same residual-plus-norm wrapper appears twice in every Transformer layer.
Why does the identity-path argument not fully solve all deep-network training difficulties?
The identity-path argument guarantees a gradient floor via the additive identity term in each layer's Jacobian, but it does not guarantee that the sublayer gradients themselves are well-scaled or that the loss landscape is convex or easy to optimize. Extremely deep networks can still suffer from issues like representation collapse, where late-layer contributions become negligible in relative magnitude, or from optimization difficulties unrelated to vanishing gradients, such as sharp loss curvature. Residual connections and LayerNorm are necessary conditions for training very deep Transformers reliably, not a complete guarantee of optimal convergence on every task.