Hello! Welcome to the fourth lesson in our module on Transformer Architectures.
In our last lesson, we explored two crucial upgrades to the basic self-attention mechanism: Multi-Head Attention and Positional Encoding. You learned how multi-head attention allows the model to capture different types of linguistic relationships in parallel and how positional encoding injects vital information about word order.
We now have all the necessary components. In this lesson, we will assemble them into the fundamental building blocks of the Transformer: the encoder block and the decoder block. Understanding these modular components is key to grasping the architecture of any modern large language model.
1. The Architecture of a Transformer Encoder Block
The primary role of the encoder is to read and understand the entire input sequence, creating a rich, context-aware representation for each token. It does this by passing the input through a stack of identical encoder blocks.
Let's look at what's inside a single block.
As you can see, a single encoder block consists of two main sublayers:
- A Multi-Head Self-Attention mechanism.
- A Position-wise Feed-Forward Network.
Crucially, a residual connection followed by layer normalization is applied around each of these two sublayers. Let's break this down.
Sublayer 1: Multi-Head Self-Attention
This is the component we studied in detail in the last two lessons. It's where each token in the input sequence can look at all other tokens to gather contextual information. Thanks to positional encodings (which are added to the input just before the first encoder block), this attention is position-aware.
Sublayer 2: Position-wise Feed-Forward Network (FFN)
After the attention mechanism has aggregated information from other tokens, the feed-forward network's job is to process this information for each token individually.
An FFN is a simple two-layer fully connected network that is applied independently to each position's vector. You can think of it as running each token's representation through the same small neural network. If attention allows tokens to talk to each other, the FFN gives each token some private "thinking time" to process the results of those conversations.
Its mathematical form for a vector at a single position is:
Here, are weight matrices and bias vectors that are the same across all positions but unique to each encoder block.
Connecting the Sublayers: Add & Norm
The "Add & Norm" steps are critical for training deep Transformer models successfully.
- Add (Residual Connection): After a vector passes through a sublayer (like attention or FFN), the original input is added back to the sublayer's output: . This creates a direct path for the gradient to flow during backpropagation, which helps prevent the vanishing gradient problem in deep networks. For you as a developer, you can think of it as a default pass-through; the network can easily learn to bypass a sublayer if it's not helpful for the task.
- Norm (Layer Normalization): This step normalizes the output of the residual connection. It stabilizes the training process by ensuring that the vectors being passed between layers have a consistent distribution (mean of 0 and standard deviation of 1).
The Complete Encoder Block
Putting it all together, the flow of data through a single encoder block for an input is:
Y = AddNorm(X, MultiHeadAttention(X))Output = AddNorm(Y, FeedForwardNetwork(Y))
Let's look at how this is implemented in code.
The 'Dive into Deep Learning' book provides an excellent, concise implementation of the TransformerEncoderBlock. Seeing the code will solidify your understanding of how the components connect.
Please read the section titled 'Encoder'. Focus on the TransformerEncoderBlock class. Notice how the forward pass directly implements the two sublayers we just discussed, each wrapped in an AddNorm call (addnorm1 and addnorm2).
A full Transformer encoder is then created by stacking N of these identical blocks on top of each other, where the output of one block becomes the input for the next.
2. The Architecture of a Transformer Decoder Block
The decoder has a more complex job: it must generate an output sequence one token at a time. To do this, it needs to consider two sources of information:
- The sequence of tokens it has already generated (the target sequence).
- The contextualized representations of the entire input sequence produced by the encoder.
This dual role is reflected in its architecture, which has three sublayers.
Sublayer 1: Masked Multi-Head Self-Attention
The first sublayer is a self-attention mechanism, similar to the one in the encoder. However, it has a crucial modification: it is masked.
During generation, when predicting the fourth word, the model should only have access to the first three words it has already generated. The mask prevents each position from attending to subsequent positions. This ensures the autoregressive property—the prediction for the current token depends only on the known past, not the future.
Sublayer 2: Encoder-Decoder (Cross-)Attention
This is the bridge connecting the encoder and decoder. It's where the decoder consults the input sentence to guide its output. This layer works like the multi-head attention you already know, but with a key difference in its inputs:
- Queries (Q): These come from the output of the decoder's first sublayer (the masked self-attention). They represent the "questions" the decoder has based on what it has generated so far.
- Keys (K) and Values (V): These come from the output of the final encoder block. They represent the complete, contextualized input sequence.
So, the decoder asks a question (Q) like "What part of the input is most relevant for generating the next word?" and uses the encoder's output (K, V) to find and retrieve the answer.
Encoder-Decoder Architecture: Cross-Attention & Sequence-to ...
This article provides a superb conceptual breakdown of the decoder block and the cross-attention mechanism that powers it.
First, read the section 'Anatomy of a Decoder Block with Cross-Attention' to get a clear overview of the three sublayers. Then, to deepen your understanding of the second sublayer, read 'Cross-Attention: The Bridge Between Encoder and Decoder'. Pay special attention to the distinction that Queries come from the decoder, while Keys and Values come from the encoder.
Sublayer 3: Position-wise Feed-Forward Network
This sublayer is identical in structure and function to the FFN in the encoder. It provides additional processing for the combined information from the self-attention and cross-attention layers.
Just like in the encoder, each of these three sublayers is wrapped in an "Add & Norm" connection.
The Complete Decoder Block
The flow of data through a decoder block is:
Y1 = AddNorm(X, MaskedMultiHeadAttention(X))Y2 = AddNorm(Y1, CrossAttention(Y1, encoder_output))Output = AddNorm(Y2, FeedForwardNetwork(Y2))
A full decoder consists of a stack of N identical decoder blocks. Finally, after the last decoder block, a linear layer followed by a softmax function is used to convert the final vector representation into a probability distribution over the entire vocabulary to predict the next token.
Test your understanding!
Why is masking required in the decoder's self-attention layer but not in the encoder's self-attention or the decoder's cross-attention layer?
Show answer
- Decoder's self-attention: Masking is required to preserve the autoregressive property. When generating a token, the model cannot see future tokens in the output sequence.
- Encoder's self-attention: No masking is needed because the encoder's goal is to build a deep understanding of the entire input sequence. It should have access to all words, both before and after the current one (bidirectional context).
- Decoder's cross-attention: No masking is needed because the decoder is attending to the encoder's output, which represents the fully processed input sentence. The entire input sentence is known and available at every step of decoding.
3. Summary & Comparison
Let's summarize the key similarities and differences between the encoder and decoder blocks.
| Feature | Encoder Block | Decoder Block |
|---|---|---|
| Number of Sublayers | 2 | 3 |
| Sublayer 1 | Multi-Head Self-Attention (Bidirectional) | Masked Multi-Head Self-Attention (Causal/Autoregressive) |
| Sublayer 2 | Position-wise Feed-Forward Network | Encoder-Decoder Cross-Attention |
| Sublayer 3 | N/A | Position-wise Feed-Forward Network |
| Primary Function | Build context-rich representations of the input. | Generate an output sequence based on past outputs and the encoder's context. |
Conclusion
In this lesson, you've seen how the components we learned about earlier are assembled into the powerful and modular encoder and decoder blocks.
Key Takeaways:
- An encoder block consists of two sublayers: a multi-head self-attention layer and a position-wise feed-forward network. Its purpose is to understand the input sequence bidirectionally.
- A decoder block has three sublayers: a masked multi-head self-attention layer, an encoder-decoder cross-attention layer, and a feed-forward network. Its purpose is to generate an output sequence autoregressively.
- The masked self-attention in the decoder ensures it only uses past information during generation.
- Cross-attention is the critical mechanism that allows the decoder to consult the encoder's representation of the input.
- Residual connections and layer normalization ("Add & Norm") are essential for stabilizing the training of deep stacks of these blocks.
Next up:
Now that you understand the fundamental building blocks, the next lesson will explore how they are used to create the three main families of Transformer models: encoder-only (e.g., BERT), decoder-only (e.g., GPT), and encoder-decoder (e.g., T5). This will bridge the gap between these architectural details and the famous large language models you use today.