Skip to main content

Welcome to a Grasp lesson

Create a free account to keep studying and create your own study path.

Lesson 4

Stabilizing Transformer Training: Residual Connections and Layer Normalization

Recommended resources

Introduction

In our previous lessons, we assembled the core computational engine of the Transformer—multi-head self-attention—and endowed it with an understanding of sequence order through positional embeddings. We now have a powerful layer that can process a sequence of vectors. However, the true strength of deep learning models comes from stacking many such layers to learn increasingly abstract representations. Simply stacking dozens of attention layers, though, leads to a familiar challenge in deep learning: training instability.

This lesson addresses the critical question of how to train very deep Transformer models effectively. We will explore the two architectural components that make this possible: residual connections and layer normalization. You will learn not only what these components do but also why they are essential for preventing issues like vanishing gradients. Crucially, we will dissect the two primary ways these components are combined—Post-LN and Pre-LN—and uncover why this seemingly small choice of ordering has profound consequences for training stability and is a key reason modern large-scale models can be trained at all.


Residual Connections: The Gradient Highway

Training exceptionally deep neural networks has historically been plagued by the vanishing gradient problem. As gradients are propagated backward from the output layer to the input layers, they pass through many matrix multiplications. If these operations repeatedly scale the gradient down, its magnitude can shrink exponentially, causing the earliest layers of the network to learn very slowly or not at all.

The solution, which was a breakthrough in computer vision with the advent of Residual Networks (ResNets), is the residual connection, also known as a skip connection. The idea is remarkably simple: in addition to processing an input through a complex function (or sublayer) , we add the original input back to the output.

This creates a direct "highway" for the input signal to travel through the network. During the forward pass, it ensures that even if a layer learns nothing useful (), the original information is not lost. More importantly, during backpropagation, it provides a direct path for gradients to flow backward.

Let's consider the gradient of the loss with respect to the input . Using the chain rule on the residual connection formula:

That term is the gradient highway. It guarantees that, at a minimum, the gradient from the next layer can pass through to the previous layer unmodified, bypassing the potentially complex Jacobian of the sublayer. This ensures that even in a very deep network, a robust gradient signal can reach the initial layers, mitigating the vanishing gradient problem.

The following video offers a concise explanation of this mechanism within the Transformer context.

Layer Normalization - EXPLAINED (in Transformer Neural Networks)

This clip from CodeEmporium explains the motivation behind residual connections in Transformers.

Watch the segment from this point to understand how residual connections provide a stronger signal and help prevent vanishing gradients during backpropagation.


The Need for Normalization: Why Not Batch Normalization?

Residual connections solve one problem, but deep networks suffer from another: as activations pass through many layers, their mean and variance can shift unpredictably. This phenomenon, known as "internal covariate shift," forces subsequent layers to constantly adapt to a changing input distribution, slowing down and destabilizing training.

Normalization techniques address this by re-standardizing the activations at various points in the network. Given your experience with CNNs, you are likely very familiar with Batch Normalization (BN), which normalizes activations across the batch dimension. However, BN is ill-suited for Transformers and most sequence-based tasks for several reasons:

  1. Varying Sequence Lengths: Batches often contain sequences of different lengths that are padded to match. The statistics computed by BN would be biased by these artificial padding tokens.
  2. Semantic Incoherence: BN assumes that the activation for a specific feature at a specific position is drawn from the same distribution across all samples in the batch. This is not true for language; the token at position 5 might be a verb in one sentence and a noun in another. Averaging their statistics is meaningless.
  3. Small Batch Sizes: Training large Transformers often requires small batch sizes due to memory constraints. BN performs poorly with small batches because the estimated statistics are too noisy.

The solution adopted by Transformers is Layer Normalization (LN). Instead of normalizing across the batch dimension, LN normalizes across the feature dimension for each individual training example (i.e., each token) in the batch.

This diagram illustrates the key difference between Layer Normalization and Batch Normalization. Layer Normalization computes statistics along the feature dimension for each sample independently (left). Batch Normalization computes statistics along the batch dimension for each feature independently (right).

This approach elegantly sidesteps all the issues with BN. Statistics are computed for each token based on its own features, so it's independent of other sequences in the batch and unaffected by padding or batch size.

For a deeper dive into why BN fails for Transformers and how LN provides a solution, please read the following section from the "Layer Normalization" article by Michael Brenndoerfer.

Layer Normalization: Stabilizing Transformer Training - Interactive ...

This section clearly articulates the practical and theoretical problems with applying Batch Normalization to sequence models.

Read the section titled Why Batch Normalization Fails. Focus on the arguments about semantic incoherence and the instability caused by small batch sizes.


The Mechanics of Layer Normalization

Layer Normalization re-centers and re-scales the vector representation of each token to have a mean of 0 and a variance of 1. For a single token's representation vector , the process involves four steps:

  1. Compute Mean: Calculate the mean of all features for that token.

  2. Compute Variance: Calculate the variance of all features for that token.

  3. Normalize: Use the mean and variance to scale the vector. A small constant (e.g., ) is added for numerical stability.

  4. Scale and Shift: Apply two learnable parameter vectors, a scale and a shift (both of size ).

The normalized vector has a standard distribution, which is great for stability. However, this could be too restrictive. The final scale-and-shift step restores the model's representational power. By learning appropriate and values, the network can effectively "undo" the normalization if needed, or learn any other mean and variance for each feature that is optimal for the task. Initially, is set to a vector of ones and to a vector of zeros, so the layer starts by just standardizing the input.

The following reading provides a clear, step-by-step breakdown of this formula and the rationale behind the learnable parameters.

Layer Normalization: Stabilizing Transformer Training - Interactive ...

This resource breaks down the mathematics of Layer Normalization and explains the critical role of its learnable parameters.

First, read through the sections from Step 1 to Step 4 to understand each part of the formula. Then, read the section The Role of Learnable Parameters to solidify why \gamma and \beta are necessary to maintain the model's flexibility.


Pre-LN vs. Post-LN: A Crucial Architectural Choice

Now we have our two stabilizing components: a residual connection Add and a LayerNorm. Within a Transformer block, we apply them after each sublayer (self-attention and the feed-forward network). But in what order? This seemingly minor detail is one of the most important distinctions between the original Transformer and modern variants.

There are two main configurations:

  1. Post-LN (Post-Normalization): This was used in the original "Attention Is All You Need" paper. The sublayer is applied, then the residual connection is added, and finally, the result is normalized.

  2. Pre-LN (Pre-Normalization): This is the standard in modern large models like GPT, LLaMA, and ViT. The input is first normalized, then passed to the sublayer, and finally, the residual connection is added.

Comparison of Post-LN (left) and Pre-LN (right) architectures. The key difference is the placement of the "Add & Norm" operation relative to the sublayer (Multi-Head Attention or Feed Forward). In Pre-LN, the LayerNorm happens *before* the sublayer, and the residual connection bypasses it.

Why does this matter so much? The answer lies in the gradient flow.

In the Post-LN architecture, the gradient highway created by the residual connection must pass through the LayerNorm layer. As we saw in the gradient derivation, the LayerNorm Jacobian is a multiplicative term that gates the entire backward pass. In deep networks, the repeated multiplication of these Jacobian matrices can lead to vanishing or exploding gradients, making training unstable and requiring a careful learning rate "warmup" period.

In the Pre-LN architecture, the gradient highway is pristine. The + x addition is the final step, meaning the gradient flows backward through the +1 identity path without ever being altered by a LayerNorm Jacobian. This creates an uninterrupted highway from the final layer all the way to the input embeddings, resulting in exceptionally stable training even for very deep networks and removing the need for learning rate warmup.

This stability is the single most important reason why Pre-LN has become the de-facto standard for training large-scale Transformers. The following reading provides a superb, in-depth analysis of this phenomenon.

Pre-Norm vs Post-Norm: Choosing Layer Normalization Placement ...

This article offers a deep and intuitive explanation for why Pre-LN is more stable than Post-LN, focusing on the mathematical perspective of gradient flow.

Please read the entire section titled Training Stability: The Gradient Flow Perspective. Pay close attention to the derivation of the gradient flow for both architectures and the "gradient highway" analogy. The visualizations in this section are particularly insightful for understanding the difference.

While Pre-LN offers superior training stability, it's worth noting the trade-off. Because the output of each block is not normalized, the magnitude of the activations can grow layer by layer. In practice, this is handled by placing one final LayerNorm at the very end of the model, just before the output projection layer.


Conclusion

In this lesson, we have dissected the mechanisms that allow Transformers to be stacked into deep, powerful architectures while maintaining training stability.

Here are the key takeaways:

  • Residual Connections create a "gradient highway" by adding the input x to the output of a sublayer. This combats the vanishing gradient problem and is essential for training deep networks.
  • Layer Normalization stabilizes training by re-standardizing activations for each token across its feature dimension. It is preferred over Batch Normalization for sequence models due to its independence from batch size and sequence length.
  • The learnable parameters and in LayerNorm give the network the flexibility to learn the optimal distribution for its features, ensuring no representational power is lost.
  • The placement of these two components is critical. The Pre-LN architecture (x + Sublayer(LayerNorm(x))) ensures a clean, unimpeded gradient highway, leading to superior training stability compared to the original Post-LN design. This stability is what has enabled the training of today's massive language and vision models.

We have now examined three of the four key components of a Transformer encoder block: multi-head attention, positional embeddings, and the Add & Norm layers. In the next lesson, we will introduce the final piece of the puzzle: the Position-wise Feed-Forward Network, which provides additional non-linear processing capacity within each block.