Skip to main content

Welcome to a Grasp lesson

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

Lesson 14

Transformer Block Architecture

Recommended resources

Hello! Welcome to the first lesson of our third module, "Transformer Architecture and LLM Basics."

Introduction

In the previous module, we built the attention mechanism from the ground up. We explored scaled dot-product attention, saw how multi-head attention allows the model to focus on different aspects of the input, and finally, addressed the "order" problem by injecting sinusoidal positional encodings. We now have all the necessary ingredients.

In this lesson, we will assemble these pieces into a complete Transformer block. Our learning outcome is to describe the structure of a transformer block, including its four key components: self-attention, a feed-forward network, residual connections, and layer normalization.

This block is the fundamental, repeating unit that forms the backbone of modern large language models like GPT. Understanding its structure is the critical next step in our journey toward deconstructing state-of-the-art architectures.



1. A High-Level View of the Transformer Block

At its core, a Transformer block is a computational unit designed to take a sequence of context-aware token embeddings and refine them further. It consists of two main sub-layers:

  1. A Multi-Head Self-Attention layer.
  2. A Position-wise Feed-Forward Network (FFN).

Crucially, the block also includes two other components that are essential for training very deep networks: residual connections and layer normalization. These are applied around each of the two sub-layers.

Let's start with a clear, high-level diagram.

Transformer Encoder Block Architecture
A single Transformer encoder block. The input `x` (embedding + positional encoding) flows through the self-attention sub-layer, followed by a feed-forward network sub-layer. Notice the "Add & Norm" steps after each.

This "Add & Norm" step is where the magic of residual connections and layer normalization happens. Let's break down each of these four components.



2. The Two Computational Sub-layers

Self-Attention Layer (A Quick Review)

As we've covered, the self-attention layer is the heart of the Transformer. Its purpose is to update each token's representation by aggregating information from the entire input sequence. It computes Query, Key, and Value vectors for each token, allowing it to dynamically weigh the importance of other tokens when creating a new, context-aware representation for the current token. In a Transformer block, this is typically a multi-head self-attention layer, allowing it to perform this process in parallel across different "representation subspaces."

Position-wise Feed-Forward Network (FFN)

After the self-attention layer has produced its output (a context-aware embedding for each token), these embeddings are passed to the second sub-layer: a feed-forward network.

Why is this necessary? The self-attention layer itself is primarily composed of linear transformations (matrix multiplications) and weighted sums. While the softmax provides some non-linearity, the FFN adds significant computational depth and non-linearity, which is characteristic of deep learning models.

A "position-wise" FFN has two key properties:

  1. It is a simple two-layer Multi-Layer Perceptron (MLP), usually with a ReLU or similar activation in between.
  2. It processes each token's representation independently. The same FFN weights are applied to every token in the sequence, but it doesn't mix information between tokens. That job was already done by the self-attention layer.

The following video explains the role of the FFN in adding this necessary non-linearity and processing the output from the attention mechanism.

Stanford CS224N NLP with Deep Learning | 2023 | Lecture 8 - Self-Attention and Transformers

Let's watch this clip from a Stanford lecture, which explains why the feed-forward network is a crucial part of the Transformer block.

Watch from 00:30:21 to 00:32:51. Focus on the explanation of why the FFN is needed to add 'deep learning magic' (non-linearity) and how it processes each token's vector independently after the self-attention step.



3. The "Glue": Residual Connections and Layer Normalization

Stacking dozens of self-attention and FFN layers would be impossible to train effectively without two critical techniques borrowed from computer vision and adapted for NLP: residual connections and layer normalization.

You'll almost always see these paired together in diagrams as "Add & Norm".

The Illustrated Transformer

The 'Illustrated Transformer' blog post provides an excellent visual and conceptual introduction to these two components. It's a great starting point before we dive into each one.

Read the section 'The Residuals'. It shows a diagram of how both residual connections and layer normalization are wrapped around each sub-layer.

Residual Connections ("Add")

A residual connection, or "shortcut connection," is a simple but powerful idea. The input to a sub-layer is added directly to the output of that sub-layer.

The primary benefit is that it makes training very deep networks feasible. By providing a "shortcut" path, it allows gradients to flow directly through the network during backpropagation. This helps mitigate the vanishing gradient problem, where gradients become too small to provide a useful learning signal in deep architectures.

The following video segment provides a fantastic intuition for why residual connections are so helpful for the optimization process.

Stanford CS224N NLP with Deep Learning | Winter 2021 | Lecture 9 - Self- Attention and Transformers

This clip from a Stanford lecture visualizes the effect of residual connections on the 'loss landscape'—the conceptual space the model navigates during training.

Watch from 00:49:32 to 00:50:30. Notice how much smoother the landscape becomes with residual connections, making it easier for the model to find a good minimum.

Layer Normalization ("Norm")

After the residual connection adds the layer's input and output, the result is passed through a Layer Normalization step.

Layer Normalization (LayerNorm) is a technique that stabilizes training by normalizing the activations. For each token's vector individually, it recalculates the features to have a mean of 0 and a standard deviation of 1.

Where:

  • and are the mean and variance of the elements within that single vector .
  • is a small constant for numerical stability.
  • (gamma) and (beta) are learnable parameters that allow the model to scale and shift the normalized output if needed.

The key difference from the more common Batch Normalization is that LayerNorm's calculations are completely independent of other examples in the batch. It normalizes across the feature dimension for each token, which has been found to work much better for variable-length sequences in NLP.

Residual Connection and Layer Normalization

To solidify your understanding, let's read a short section from the 'Dive into Deep Learning' book that explicitly implements and compares LayerNorm and BatchNorm.

Read section 11.7.3, 'Residual Connection and Layer Normalization'. Pay close attention to the text explaining the difference between layer normalization and batch normalization, and look at the code example that demonstrates this difference in output.



4. Assembling the Full Transformer Block

Now, let's put all four components together to trace the path of data through one complete Transformer block.

Transformer Architecture: Encoder-Decoder Diagram
A full diagram of the Transformer. Focus on the repeating gray box labeled 'Nx' in the encoder on the left. This is the Transformer block we've been building.

A sequence of token embeddings, , enters the block.

  1. First "Add & Norm":

    • The embeddings are passed into a Multi-Head Self-Attention layer to produce .
    • A residual connection adds the original input to the attention output: .
    • The result is Layer Normalized: . Let's call this intermediate result .
  2. Second "Add & Norm":

    • The intermediate result is passed into the Position-wise Feed-Forward Network to produce .
    • A second residual connection adds the input of the FFN to its output: .
    • The result is Layer Normalized again: .

The output of this final normalization is the output of the Transformer block, which is then fed as input to the next identical block in the stack.

For a programming-oriented perspective, the TransformerEncoderBlock class described in the "Dive into Deep Learning" resource shows how these components are structured in code.

The Transformer Architecture - Encoder

Let's look at how these pieces are assembled in a typical implementation.

Read section 11.7.4, 'Encoder'. You don't need to understand every line of the PyTorch code, but observe how the forward method of the TransformerEncoderBlock class clearly shows the sequence: attention -> addnorm1 -> ffn -> addnorm2.



Conclusion

In this lesson, we have successfully assembled the Transformer block, the fundamental repeating unit of modern language models.

Key Takeaways:

  • A Transformer block is composed of two main sub-layers: a multi-head self-attention layer and a position-wise feed-forward network.
  • The self-attention layer creates context-aware representations by allowing tokens to communicate with each other.
  • The feed-forward network provides additional non-linear processing for each token independently.
  • Residual connections ("Add") are used around each sub-layer to enable effective gradient flow and the training of very deep networks.
  • Layer normalization ("Norm") is applied after each residual connection to stabilize training by normalizing the activations for each token.

Preview of the Next Lesson:
We've now seen all the components of the standard Transformer block. In the next lesson, "Explain LayerNorm and how it stabilizes training in deep networks," we will take a deeper dive into Layer Normalization. We'll explore its mathematical properties more formally and build a stronger intuition for exactly why it is so crucial for achieving stable training in deep Transformer models.