Highlights

Contents

Part VIII
08

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.

YOU ARE HERE"raw text"tokenizerembeddings+ positionslearnedwavesRoPEDECODER BLOCK× NnormattentionQKVsoftmaxmaskheadsn × n+normMLP+residual streamKV cachefinal normLM headsoftmaxP(next)training: the loss sends a correction back to every weight

#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.

WITHOUT A MASK, “CAT” CAN READ THE ANSWER IT IS SUPPOSED TO PREDICTThe␠cat␠sat␠because␠itpeek!target: ␠sattraining loss ≈ 0,model learns nothing
Figure 1.58The cheating problem. Without a mask, the token whose job is to predict ␠sat can attend directly to ␠sat. It aces training and fails completely at generation.

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.

ONE FORWARD PASS, SEVEN PREDICTIONS: TARGETS ARE THE INPUT SHIFTED LEFT BY ONEinputtargetThe0␠cat␠cat1␠sat␠sat2␠because␠because3␠it␠it4␠was␠was5␠tired␠tired6.position 3 sees these four tokensand must predict ␠itevery position is its own guessing exercise, all computed at once
Figure 1.59Shifted targets. One chunk of text yields one prediction per position. The target row is the input row moved one step left, so position 3 sees four tokens and must predict ␠it.

In code this is almost embarrassingly short:

python
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 .. T

Causal 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 MM the same size as the score grid, T×TT \times T. Rows are queries, the tokens asking. Columns are keys, the tokens being looked at. A cell holds 0 where looking is allowed and −∞-\infty where it is not:

Mij={0if j≤i−∞if j>iM_{ij} = \begin{cases} 0 & \text{if } j \le i \\ -\infty & \text{if } j > i \end{cases}

Read it: query ii may look at key jj only if jj comes at or before ii. 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 −∞-\infty is −∞-\infty, and e−∞=0e^{-\infty} = 0, 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.

SCORES + CAUSAL MASK → ROW-WISE SOFTMAX (6 TOKENS, ILLUSTRATIVE SCORES)raw scores1.20.32.0-0.50.80.10.71.50.21.1-0.30.90.42.10.90.61.70.20.10.81.61.00.41.30.90.20.51.80.70.60.31.90.40.21.11.5+causal mask M0−∞−∞−∞−∞−∞00−∞−∞−∞−∞000−∞−∞−∞0000−∞−∞00000−∞000000→softmax, each row1.0000000.31.690000.12.67.20000.10.20.45.2500.18.09.12.45.150.07.37.08.07.16.25row = query (the token asking), column = key (the token looked at)upper triangle = the futureeach row sums to 1and only looks back
Figure 1.60Building the masked attention. The raw scores plus the causal mask, then softmax along each row. Every row sums to one and only reaches back in time.

In code, the mask is built once and reused:

python
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 1

torch.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.

ROW “SAT”: MASK BEFORE SOFTMAX VERSUS SOFTMAX THEN ZEROright: mask, then softmax0.253The0.319cat0.428sathiddenbec.sum = 1.000wrong: softmax, then zero0.191The0.240cat0.322sathiddenbec.sum = 0.75324.7% of the weight was spent on a hidden token
Figure 1.61Mask before softmax versus after. Masking first gives weights that sum to one over the visible tokens. Zeroing after softmax leaves weights summing to 0.753.

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.

THE CAUSALITY TEST: CHANGE THE LAST WORD, EARLIER OUTPUTS MUST NOT MOVE…it was ␠tired…it was ␠hungrysame ✓same ✓same ✓same ✓same ✓same ✓changed (fine)if any earlier strip changes, information is leaking from the future
Figure 1.62The causality test. Changing the last token must leave every earlier output identical. If any earlier row changes, information is leaking backwards.

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.

CAUSAL AND PADDING MASKS COMBINE BY “AND”: ALLOWED ONLY IF BOTH ALLOWcausalANDpadding (last 2 are pad)=combinedorange = may attend. Pad columns are hidden from everyone; pad rows are dropped from the loss.
Figure 1.63Combining masks. The causal triangle AND a padding mask that hides the last two positions gives the mask real code actually uses.

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.

THREE MASK SHAPES, THREE MODEL FAMILIESencoder (BERT)sees everythingdecoder (GPT, Llama)sees only the pastprefix LM (T5-style)prompt sees itself fully
Figure 1.64Three mask shapes. A full square for encoders, a triangle for decoders, and a prefix language model that lets the prompt see itself fully before generating causally.

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.