A Transformer encoder reads a whole sentence at once and gives every word a context-aware vector. That is perfect for understanding text: classifying a review, tagging names, finding answers. But many tasks require generating text, one word at a time: writing, translating, chatting. Can the same architecture do that?
It can, with one small but essential change: each word is only allowed to attend to itself and the words before it. This reading explains why that restriction is needed, how it is implemented with a causal mask, and how the resulting Transformer decoder is trained and used to generate text.
1Using a Transformer encoder
A stack of Transformer layers maps $n$ input vectors to $n$ output vectors, one per token, each informed by the whole sentence. How we use these outputs depends on the task:
- Token-level tasks (e.g., part-of-speech tagging, named entity recognition): use each token's output vector to make a prediction for that token.
- Sentence-level tasks (e.g., sentiment classification): we need one vector for the whole sentence. Two common options:
- Average pooling: average all output vectors.
- A special
<cls>token: add an extra token at the start of the input and use its output vector. The token itself means nothing; because it attends to every word, training teaches it to collect whatever information the task needs. BERT uses this approach.
2Can a Transformer generate text?
A language model generates text by repeatedly predicting the next token. With a Transformer, the natural setup is: start the input with a beginning-of-sentence token <bos>, and train the output at each position to predict the next token:
| Position | 0 | 1 | 2 | 3 | 4 | 5 |
|---|---|---|---|---|---|---|
| Input | <bos> | I | like | cats | a | lot |
| Target (next token) | I | like | cats | a | lot | <eos> |
But there is a problem. In an encoder, every position attends to every position. The output at <bos> is supposed to predict I, yet its attention can look directly at the input I at position 1. The model can simply copy the answer instead of learning to predict it. And at generation time, the future tokens do not even exist yet, so a model that relied on them would be useless.
The fix: when computing attention for a token, allow it to see only itself and the tokens before it.
- Encoder: each word can see itself and the words before and after it.
- Decoder: each word can see itself and only the words before it.
3Generating one token at a time
At generation (inference) time, a decoder works step by step:
- Start with the input
<bos>. - Run the decoder; the output at the last position gives a probability distribution over the next token.
- Choose a token (e.g., the most likely one, or by sampling), append it to the input, and repeat.
- Stop when the model produces
<eos>or reaches a maximum length.
Because each token only attends to tokens before it, adding a new token at the end does not change the outputs at earlier positions. Figure 3 shows this with real numbers.
4Causal masking
How do we stop a token from attending to later tokens? Write the attention scores for all pairs as an $n\times n$ matrix $S = QK^\top/\sqrt{d_k}$ (row $i$ = query $i$, column $j$ = key $j$). The entries above the diagonal ($j>i$) are the forbidden “future” pairs. We need their attention weights to be exactly 0.
The standard trick is to add a mask matrix $M$ before the softmax:
$$M_{ij} = \begin{cases}0 & j \le i \\ -\infty & j > i\end{cases}\qquad\qquad \text{CausalAttention}(Q,K,V) = \text{softmax}\!\left(\frac{QK^\top}{\sqrt{d_k}} + M\right)V.$$Allowed scores are unchanged, forbidden scores become $-\infty$, and since $e^{-\infty}=0$, the softmax gives them weight 0. The remaining weights in each row still sum to 1.
5Training a decoder
The causal mask gives the decoder a big advantage in training: we can feed in the whole target sentence at once and compute all positions in parallel. Position 0 predicts I using only <bos>; position 1 predicts like using <bos> I; and so on. The mask guarantees no position cheats, so one forward pass gives $n$ next-token predictions.
On top of the last layer, each position's output vector $h_t$ goes through a linear layer and a softmax over the vocabulary:
$$P(w_{t+1}\mid w_{0},\dots,w_{t}) = \text{softmax}(W h_t + b),\qquad \mathcal{L} = -\sum_{t=0}^{n-1}\log P(w_{t+1}^{\text{true}}\mid w_0,\dots,w_t).$$The loss is the cross-entropy at every position, added up. Feeding the true previous tokens as input during training (rather than the model's own predictions) is teacher forcing.
| Training | Generation (inference) | |
|---|---|---|
| Input | the whole true sentence | the tokens generated so far |
| Positions computed | all at once, in parallel | one new token per step |
| What prevents seeing the future | the causal mask | future tokens do not exist yet (the mask keeps it consistent with training) |
6The decoder block and model families
A Transformer decoder layer is the same as an encoder layer except for the mask:
Masked multi-head self-attention → Add & Norm → Feed-forward → Add & Norm
As in the encoder, the input is the token embedding plus the positional encoding, and $N$ such layers are stacked. A linear layer and softmax on top produce next-token probabilities.
This gives three families of Transformer models:
| Family | Attention | Typical uses | Examples |
|---|---|---|---|
| Encoder-only | full (no mask) | classification, tagging | BERT |
| Decoder-only | causal mask | text generation, chat | GPT models |
| Encoder–decoder | encoder: full; decoder: causal + cross-attention | translation, summarization | original Transformer, T5 |
7Summary
- Encoder outputs can be used per token, or pooled (average or
<cls>) into one sentence vector. - To predict the next token, a position must not see later tokens; an unmasked Transformer would just copy the answer.
- A decoder uses causal attention: each token sees itself and earlier tokens only.
- The mask is implemented by adding $-\infty$ to future scores before the softmax.
- Training: all positions in parallel with teacher forcing; loss = sum of cross-entropies. Generation: one token at a time, appending each prediction to the input.
- Encoder-only (BERT), decoder-only (GPT), and encoder–decoder (T5) models are built from the same layers.
8Practice
Exercise 1: the mask
Write the causal mask $M$ for a 4-token input. How many entries are $-\infty$? For $n$ tokens?
Exercise 2: softmax with a mask
Query 1 has scores $[1.0,\ 2.0,\ 3.0]$ for keys 0, 1, 2. Compute its attention weights (a) with the causal mask added and (b) if the score for key 2 were multiplied by 0 instead. (Use $e\approx 2.72$, $e^2\approx 7.39$.)
(b) Scores $[1, 2, 0]$: $2.72,\ 7.39,\ 1$; sum $11.11$; weights $\approx[0.24,\ 0.67,\ 0.09]$. Key 2 (a future token) still gets 9% of the attention.
Exercise 3: training examples
A decoder is trained on the sequence <bos> the cat sat <eos>. List the (context → target) predictions made in one forward pass.
<bos> the cat sat; four predictions: <bos> → the; <bos> the → cat; <bos> the cat → sat; <bos> the cat sat → <eos>.
Quick quiz
9Further reading
- Alammar. The Illustrated GPT-2. (Decoder-only Transformers and masked self-attention, with many figures.)
- Cho et al. Transformer Explainer. (An interactive GPT-2 in the browser; see the causal mask and next-token probabilities.)
- Karpathy. Let's build GPT: from scratch, in code, spelled out. (Video; builds a small decoder-only Transformer in PyTorch.)
- Alammar. The Illustrated Transformer. (See the decoder side for cross-attention in the encoder–decoder model.)