CSCE 471 Natural Language Processing · Spring 2027

Transformer Decoder

Kuan-Hao Huang · Course Website

Note: This page was created with the help of AI as a supplementary reading. It may contain errors or simplifications. The lecture slides are the primary reference for this course; please refer to them first.

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.

After reading this, you should be able to use Transformer outputs for token-level and sentence-level tasks · explain why an unmasked Transformer cannot be trained to predict the next word · describe what each position can see in an encoder vs. a decoder · implement causal masking with $-\infty$ before the softmax · explain how a decoder is trained in parallel and how it generates text one token at a time · distinguish encoder-only, decoder-only, and encoder–decoder models

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:

Figure 1 (interactive). Three ways to use the output vectors (yellow) of a Transformer encoder. Inputs are blue; the gray box stands for the stack of Transformer layers, where every token attends to every token.

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:

Position012345
Input<bos>Ilikecatsalot
Target (next token)Ilikecatsalot<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.

Click a row to pick the query
rows: query position · columns: key position
Figure 2 (interactive). Which keys each query can attend to (blue = allowed). The red outline marks the token the query's output must predict. In the encoder, every query can see its own answer; in the decoder, it never can.

3Generating one token at a time

At generation (inference) time, a decoder works step by step:

  1. Start with the input <bos>.
  2. Run the decoder; the output at the last position gives a probability distribution over the next token.
  3. Choose a token (e.g., the most likely one, or by sampling), append it to the input, and repeat.
  4. 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.

Figure 3 (interactive). A toy one-layer decoder (2-dimensional outputs) generating I like cats a lot. Each column is one generation step; each row is one position's output. When a new token is added (highlighted), the outputs of earlier positions stay exactly the same.
Why this matters in practice. Since earlier positions never change, a decoder does not need to recompute them at every step. Implementations store the keys and values of earlier positions (the KV cache) and only compute the new token's query, key, and value at each step.

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.

Careful: multiplying the scores by 0 does not work. A score of 0 is not “no attention”: $e^{0}=1$, so the softmax would still give the future tokens a sizeable weight. Masking must happen with $-\infty$ before the softmax, or, equivalently, by zeroing out the weights after the exponential and renormalizing each row. Try both in Figure 4.
Step:Masking method:
Figure 4 (interactive). Causal masking on the toy decoder's scores for <bos> I like cats a lot. Step through scores → mask → softmax. With $-\infty$, the upper triangle gets weight 0. With “multiply by 0”, future tokens still receive weight, which leaks the answer.

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.

TrainingGeneration (inference)
Inputthe whole true sentencethe tokens generated so far
Positions computedall at once, in parallelone new token per step
What prevents seeing the futurethe causal maskfuture 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:

FamilyAttentionTypical usesExamples
Encoder-onlyfull (no mask)classification, taggingBERT
Decoder-onlycausal masktext generation, chatGPT models
Encoder–decoderencoder: full; decoder: causal + cross-attentiontranslation, summarizationoriginal Transformer, T5
Cross-attention. In an encoder–decoder model, each decoder layer has an extra attention sublayer in which the queries come from the decoder and the keys and values come from the encoder's outputs. This lets the decoder look at the whole source sentence (e.g., the sentence being translated) while generating the target one token at a time. A decoder-only model has no encoder and no cross-attention.

7Summary

8Practice

Exercise 1: the mask

Write the causal mask $M$ for a 4-token input. How many entries are $-\infty$? For $n$ tokens?

$$M=\begin{bmatrix}0&-\infty&-\infty&-\infty\\0&0&-\infty&-\infty\\0&0&0&-\infty\\0&0&0&0\end{bmatrix}$$ 6 entries are $-\infty$ (above the diagonal). For $n$ tokens: $n(n-1)/2$.

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$.)

(a) Masked scores $[1, 2, -\infty]$: $e^1=2.72$, $e^2=7.39$, $e^{-\infty}=0$; sum $10.11$; weights $\approx[0.27,\ 0.73,\ 0]$.
(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.

Input <bos> the cat sat; four predictions: <bos> → the; <bos> the → cat; <bos> the cat → sat; <bos> the cat sat → <eos>.

Quick quiz

9Further reading