Introduction
In our last lesson, we traced the full forward pass of an input sequence through a Transformer encoder, seeing how matrix operations enable parallel processing and how self-attention allows every token to draw context from all other tokens in the sequence. This bidirectional context is ideal for tasks like analysis or feature extraction, where the entire input is available at once.
However, the goal of many models is not just to understand, but to generate—to produce a new sequence, such as a sentence or a piece of code. This is an inherently sequential, step-by-step process. In this lesson, we will explore the core mechanism that enables this generative capability in Transformers: masked self-attention. You will learn how the Transformer decoder modifies the self-attention mechanism to prevent it from "seeing the future," and how this enables the autoregressive generation process that powers models like GPT.
The Autoregressive Principle
Before we dive into the mechanics of masking, it's crucial to understand the principle behind generation: autoregression. An autoregressive model generates a sequence one element at a time, where the prediction for each new element is conditioned on all the elements that came before it.
For example, to generate the sentence "Vision models are powerful", the process looks like this:
- Given a starting prompt (e.g., a special
[START]token), the model predicts the first word: "Vision". - Given "[START] Vision", it predicts the next word: "models".
- Given "[START] Vision models", it predicts "are".
- Given "[START] Vision models are", it predicts "powerful".
- Given "[START] Vision models are powerful", it predicts an
[END]token, and the generation stops.
From a probabilistic standpoint, this decomposes the joint probability of the entire sequence into a product of conditional probabilities, a direct application of the chain rule of probability:
Each term represents a single prediction step. The challenge for a Transformer is to compute these conditional probabilities efficiently.
The following resource provides a clear explanation of this concept, which is foundational to understanding the decoder's role.
Decoder Architecture: Causal Masking & Autoregressive ...
This article by Michael Brenndoerfer provides an excellent conceptual framework for the decoder.
Please read the introduction, "Decoder Architecture", which sets the stage. Then, continue with the section "Understanding Autoregressive Generation" to solidify your understanding of the chain rule's application in this context.
The Problem with Bidirectional Attention
Now, consider the self-attention mechanism we studied in the encoder. It calculates attention scores between all pairs of tokens. If we were to use this mechanism directly for training a generative model, we would face a critical issue.
During training, we have the complete target sequence available (e.g., "Vision models are powerful"). To train the model to predict "models" from "Vision", we would feed it "Vision". But if the self-attention mechanism is bidirectional, the representation for "Vision" would be computed using context from "models", "are", and "powerful". The model would simply "cheat" by looking at the answer that is present just a few positions ahead in the input sequence. This prevents the model from learning to actually predict based on past context.
To make generation possible, we must enforce the autoregressive property within the attention mechanism itself. Information must only flow from past tokens to future tokens, not the other way around. This is achieved through causal masking.
Causal Masking: Forcing a Left-to-Right Information Flow
Causal masking modifies the scaled dot-product attention formula to prevent any position from attending to subsequent positions. The core idea is to manipulate the attention scores before the softmax function is applied.
Recall the scaled dot-product attention formula:
The masking is introduced by adding a mask matrix to the scores:
The mask matrix is constructed such that:
- if position is allowed to attend to position (i.e., if ).
- if position is forbidden from attending to position (i.e., if ).
Why does this work? When we apply the softmax function, an input of results in an output of 0.
Therefore, any query-key pair whose score has been masked to will have an attention weight of exactly zero. The query token is effectively blind to those key tokens. In practice, a very large negative number (e.g., ) is used instead of true infinity to maintain numerical stability.
The following video provides an intuitive walkthrough of this masking process.
Transformers - Part 7 - Decoder (2): masked self-attention
This video from Lennart Svensson's Transformer series clearly visualizes how masking prevents information from future tokens from influencing the current token's representation.
First, watch the segment from the beginning to understand the "no cheating" requirement for parallelized training. Next, focus on the example from this point, which shows how the output for word Y3 is computed without depending on future inputs X4 and X5. Finally, the segment from here shows the matrix formulation and how the softmax operates on the masked scores.
To reinforce the mathematical details and see a direct implementation, the following text is also highly recommended.
Decoder Architecture: Causal Masking & Autoregressive ...
This part of the Brenndoerfer article formalizes the masking concept and shows how to implement it.
Read the section "The Causal Masking Requirement" for the formal argument. Pay close attention to the formula where the mask matrix M is added. Then, continue through "Designing the Mask", which explains the role of -\infty and shows the resulting triangular mask pattern. The short Python snippet in the "Implementation" section provides a concrete example of generating this mask.
The Masked Multi-Head Attention Block
With the concept of causal masking established, we can now define the masked multi-head self-attention layer, which is the cornerstone of the Transformer decoder. It operates identically to the multi-head attention layer in the encoder, with one crucial difference: the causal mask is applied to the attention scores in each head before the softmax.
This ensures that for every head, and for every token in the sequence, the resulting contextualized embedding is only influenced by previous tokens. The rest of the decoder block architecture is analogous to the encoder block we've already studied: it includes a feed-forward network, residual connections, and layer normalization, all preserving the shape of the tensor as it passes through.
The image below provides a comprehensive visual summary of the entire masked self-attention process, from input projections to the final masked output.

The following video and reading excerpt further detail how masking is integrated and how the decoder operates during training and inference.
Attention is all you need (Transformer) - Model explanation (including math), Inference and Training
This segment from Umar Jamil's tutorial focuses specifically on the masked multi-head attention block and the logic of applying the mask.
Watch the section from this point, which explains how the triangular mask is applied to the q*k scores before the softmax to make the model causal.
Training vs. Inference
The use of causal masking creates an important distinction between how a decoder is used during training versus inference.
-
Training (Parallel): During training, we can feed the entire ground-truth output sequence (e.g.,
<start> I am a robot <end>) to the decoder at once. The causal mask ensures that when predicting the token at positiont, the model can only use the inputs from positions1tot-1. This allows for efficient, parallel computation across the entire sequence, just like in the encoder. -
Inference (Sequential/Autoregressive): During inference, we don't have the target sequence. We must generate it token by token.
- Feed the
<start>token to the decoder. - The model predicts the first token (e.g., "I").
- Feed
<start> Ito the decoder. - The model predicts the next token (e.g., "am").
- This loop continues until the model predicts an
<end>token.
- Feed the
This token-by-token generation is computationally more intensive. A critical optimization for this process is KV Caching, where the Key and Value matrices for already processed tokens are stored and reused in subsequent steps. This avoids redundant computations and significantly speeds up inference, a detail highly relevant in practical deployments.
Decoder Architecture: Causal Masking & Autoregressive ...
These sections explain the practicalities of generation and the crucial KV Caching optimization.
First, read "The Generation Loop" to understand the step-by-step inference process. Then, review the section "Key-Value Caching for Efficient Generation". Given your background, you'll appreciate how this optimization transforms the computational complexity of the attention calculation during inference.
Conclusion
In this lesson, we have demystified the core mechanism that allows Transformers to generate sequences. By building upon our knowledge of the encoder, we've seen how a single, elegant modification—causal masking—transforms bidirectional self-attention into a powerful tool for autoregressive modeling.
Here are the key takeaways:
- Autoregressive Generation: Language generation is a sequential process where each token is predicted based on the tokens that came before it, mathematically described by the chain rule of probability.
- Causal Masking: To prevent the model from "cheating" during training, a mask is applied to the attention scores. This mask sets the scores for all future positions to negative infinity before the softmax step.
- Zero Attention Weight: The masking forces the attention weights for all future tokens to become zero, ensuring a strict left-to-right information flow.
- Training vs. Inference: Causal masking enables efficient, parallel processing of entire sequences during training, while inference remains a sequential, token-by-token process that is heavily optimized in practice using techniques like KV caching.
We have now completed our foundational tour of the Transformer architecture, covering both the encoder and the decoder. In the next module, we will begin exploring how these fundamental blocks are used to construct the backbones of modern language models, starting with tokenization and the architectures of BERT and GPT.