The Causal Mask: No Peeking
Training already contains the answers later in the text. The decoder must not read them early. A causal mask enables parallel prefix predictions without leaking future input.
#Section 43Why Hide the Future
Training supplies the complete sequence and asks each position to predict what follows. Evaluating positions together is efficient, but the answer must remain hidden from its predictor.
If cat can read the following sat, it can use its target directly. Training would reward information unavailable during generation, producing misleadingly low loss.
The fix is the causal mask. It hides the future: each token may attend only to itself and the tokens before it. “Causal” refers to the direction of cause and effect. The past can influence the present, the future cannot. A model trained this way is called a causal language model, which is what GPT, Llama, Claude, Mistral and Finch-19 all are.
#Section 44One Pass, Seven Lessons
The targets are the source sequence offset by one position. Each output learns from its true prefix, as the figure shows.
In code this is almost embarrassingly short:
chunk = tokens[i : i + T + 1] # T+1 token ids from the training text
x = chunk[:-1] # input: positions 0 .. T-1
y = chunk[1:] # target: positions 1 .. TCausal masking allows all known-prefix predictions to run in parallel. Recurrent networks instead had to propagate state sequentially even during training.
Look again at the column view. When the model predicts position 4, it is given the true tokens at positions 0 to 3, straight from the dataset, not whatever it would have generated itself. This is called teacher forcing.
That small mismatch between training (always perfect prefixes) and use (your own prefixes) has a name, exposure bias. Large models trained on enough data cope with it well, and later training stages partly address it, but the term comes up in interviews.
#Section 45The Mask Itself
The mask is a grid the same size as the score grid, . Rows are queries, the tokens asking. Columns are keys, the tokens being looked at. A cell holds 0 where looking is allowed and where it is not:
Read it: query may look at key only if comes at or before . Row 0 sees only column 0. Row 1 sees columns 0 and 1. Row 6 sees everything. Everything above the diagonal is hidden. The allowed cells form a triangle, which is why people call it the causal triangle or a lower-triangular mask.
The mask is added to the scaled scores, before softmax. Any finite score plus is , and , so after softmax every hidden cell has a weight of exactly zero. The visible cells share the full weight of 1 among themselves, exactly as if the hidden tokens did not exist.
In code, the mask is built once and reused:
mask = torch.triu(torch.ones(T, T, dtype=torch.bool), diagonal=1) # True above the diagonal
scores = scores.masked_fill(mask, float('-inf')) # hide the future
weights = torch.softmax(scores, dim=-1) # each row sums to 1torch.triu(..., diagonal=1) picks the cells strictly above the diagonal. The diagonal=1 matters: it leaves the diagonal itself open, so every token can see itself.
#Section 46Mask Before Softmax, Not After
Masking must precede normalization. Otherwise future scores influence the denominator even if their final weights are zeroed.
Masking first redistributes the full weight over visible keys. Zeroing afterward drops part of that weight without undoing the hidden scores' contribution to normalization.
Changing a hidden future score would still change every visible weight through the denominator. That is future leakage, not merely a smaller output.
#Section 47Testing It, and the Other Masks
A live causality test
To check a mask on any model: Feed in the sentence, record the attention outputs at every position, then change only the last word (tired to hungry) and run it again. If the mask is right, the outputs at positions 0 to 5 stay exactly the same, bit for bit. Only position 6 changes. That is the definition of causal: changing the future must not change the past.
If an earlier position changes when you edit a later token, something is cheating. Suspiciously low training loss, much lower than comparable models report, is the classic symptom, and a leaky mask is the most common cause.
Padding masks
Real batches have sentences of different lengths. To stack them into one rectangular block, the short ones are filled up with a padding token. Padding is not real text, so no real token should attend to it. A padding mask hides the padding columns. In practice you need both masks at once, combined so that a cell is allowed only if both masks allow it, a logical AND.
The padding rows themselves are a separate concern. A padding position’s prediction is meaningless, so it must be excluded from the loss, typically by setting its target to a special “ignore” value.
Three mask shapes, three model families
The causal triangle is not the only shape. Encoders such as BERT use no mask at all, a full square, because they read a whole text to understand or classify it rather than generate it, and seeing both directions helps. Decoders such as GPT, Llama and Finch use the triangle. Prefix language models let the prompt see itself fully in both directions, then use a triangle for the part being generated.
Sharp edges of masks
Off by one on the diagonal. The diagonal is a token looking at itself and must stay open. Mask it too and the first token can see nothing at all, which produces the NaN of Section 42. torch.triu(..., diagonal=1) is correct; diagonal=0 is the bug.
Padding rows with nothing to see. With left padding, a padding token’s own row might have every key masked, giving NaN. Let pad rows see something harmless, such as themselves, and drop them from the loss.
Generation needs no triangle for the new token. When generating one new token at a time (Part XI), the new token is the last one and may see everything before it. There is nothing to hide. Applying a triangle aligned to the wrong corner at this step is a classic bug, which Unit II’s SDPA chapter looks at closely.
Sliding windows add, never replace. Some models let each token see only the last few thousand tokens. That is another mask, and it must be combined with the causal mask by AND. Overwriting one with the other lets tokens see the future again.