A decoder language model is trained on whole sequences at once, but each position must predict its next token using only earlier tokens, exactly as it will at generation time, when the future does not yet exist. The causal mask enforces this by setting attention scores to −∞ for every key after the query, so the softmax gives them zero weight. Padding masks hide filler tokens in batches, and prefix-LM masks allow bidirectional attention over a prompt. Getting a mask wrong is a classic silent bug: training loss looks superb because the model reads the answer, and generation collapses. This page covers causal, padding, combined and prefix masks, their implementation, numerical details and how to detect leakage. In the exercises you build and combine masks, then train the same one-layer GPT with a correct mask, an off-by-one mask (which lets each position see one token ahead) and no mask. With the correct mask, loss was 0.61 in training and at generation. The off-by-one model reached 0.07 in training, impossibly below the task's 0.50 entropy floor, by putting 96% of its attention on the answer token. At generation it scored 2.06, nearly random.
★☆☆☆☆ Introductory⏱ 5 minGeneral audience. No mathematics required.
No peeking at the answer
When a language model learns, it sees whole sentences, but at each word it must guess the next one as if it couldn’t see the rest. If it could peek, it would just copy the answer and learn nothing useful, like a student who reads the answer key. The causal mask is a rule built into the attention step: every word may look only at itself and the words before it. The demo draws this mask as a triangle.
LLM lab
Row i shows what token i may attend to: itself and earlier tokens only (36 of 64 pairs). This is what lets one forward pass train on every next-token prediction at once.
Why engineers care
Leakage bugs are not only an LLM problem: any sequence model for telemetry forecasting or trajectory prediction that can see future samples during training will look excellent in validation and fail in flight. The causal mask is the guard against that.
📝 Quick check (Level 0)
0/3 answered
1. The causal mask stops a token from attending to…
2. A model that can peek at the next token during training…
3. The allowed attention pattern of a causal mask is a…
Level 1: Beginner
★★☆☆☆ Basic⏱ 20 minSecondary-school mathematics: arithmetic and elementary algebra.
By hand
Causal mask: add M to the scores before softmax, with M_ij = 0 if j ≤ i and −∞ (in practice −10⁹, or −10⁴ in fp16) if j > i. Allowed pairs: T(T + 1)/2 of T² (524,800 of 1,048,576 for T = 1024).
Why it enables parallel training: with the mask, one forward pass yields T valid next-token predictions per sequence, all trained together (teacher forcing).
Padding mask: batches of different lengths are padded; padded keys must get zero attention and padded targets must be excluded from the loss. Combine masks with logical AND.
Prefix-LM mask: bidirectional attention within a prefix (prompt), causal after it (T5’s prefix-LM, UL2).
Leakage signs: training loss below what the data allows; validation loss with the training mask much lower than with true autoregressive decoding; attention concentrated on position i + 1.
Shifting: inputs are tokens 0…T−1 and targets 1…T. Shifting the wrong way, or masking from the wrong diagonal, produces the off-by-one leak.
📝 Quick check (Level 1)
0/3 answered
1. Allowed pairs for T = 1024:
2. Masks are combined with…
3. A prefix-LM mask is bidirectional…
Level 2: Intermediate
★★★☆☆ Intermediate⏱ 25 minUndergraduate students and practising engineers.
Masks in code
Exercise 1.
Build causal and padding masks and combine them.
Apply a masked softmax that gives exactly zero weight to disallowed keys.
Practice.
PyTorch’s scaled_dot_product_attention(..., is_causal=True) applies the causal mask efficiently; Hugging Face models build causal masks internally and take an attention_mask for padding.
Use a large finite negative value rather than −inf if a row could be fully masked, to avoid NaNs; keep the mask in fp32 under mixed precision.
Test for leakage: perturb future tokens and check that earlier outputs do not change.
Pack several documents per sequence to avoid padding, with document-boundary masks if they must not attend to each other.
import torch, torch.nn.functional as Fq = k = v = torch.randn(2, 4, 16, 32) # (batch, heads, T, d_head)out = F.scaled_dot_product_attention(q, k, v, is_causal=True)# leakage test: changing the last token must not change earlier positionsv2 = v.clone(); v2[:, :, -1] += 1assert torch.allclose(out[:, :, :-1], F.scaled_dot_product_attention(q, k, v2, is_causal=True)[:, :, :-1])
🐍 Exercise 1: causal, padding and combined masks
Build causal and padding masks, combine them, and implement a masked softmax.
📝 Quick check (Level 2)
0/3 answered
1. PyTorch flag for causal attention:
2. A direct leakage test is to…
3. Instead of −inf, masks often use…
Level 3: Advanced
★★★★☆ Advanced⏱ 25 minGraduate level, with full derivations and proofs.
Theory
Training–inference consistency. The model is evaluated at generation time on P(x_(t+1) | x_≤t). Training must optimise exactly this conditional. With a leaky mask it optimises P(x_(t+1) | x_≤t+1) instead, which is trivial (copy x_(t+1)) and unrelated to the real task.
Why the loss goes below the floor. The entropy of the next token given the past is a lower bound on achievable expected cross-entropy. A training loss below it is proof that the model sees information it will not have later.
Partial leakage is worse than none. A model trained with no mask still learns some genuine structure, because attending to the past also helps. The off-by-one model relied almost entirely on the leak, so removing it at generation left it with nearly nothing. In exercise 2 the no-mask model scored 0.97 at generation and the off-by-one model 2.06.
📝 Quick check (Level 3)
0/3 answered
1. A leaky mask optimises…
2. Training loss below the conditional entropy proves…
3. Generation uses…
Level 4: Expert
★★★★★ Expert⏱ 30 minResearchers: original papers and open problems.
What happens when the causal mask is wrong?
History.
A. Vaswani et al., “Attention is all you need” (NeurIPS 2017), introducing masked decoder self-attention.
C. Raffel et al., “Exploring the limits of transfer learning with a unified text-to-text transformer” (JMLR 2020), comparing causal, prefix-LM and encoder–decoder masks.
Exercise 2.
Task and model: the copy-8-back task and one-layer GPT from F4-1 (entropy floor 0.50 nats).
Training masks:
correct causal mask (keys j ≤ i);
off-by-one mask (keys j ≤ i + 1);
no mask.
Evaluation: loss under the training mask, and under the correct causal mask, which is the situation at generation time. Also the attention each position pays to position i + 1, the token it must predict.
training mask
loss with training mask
loss at generation
attention on the answer token
correct
0.611
0.611
0.000
off by one
0.070
2.057
0.964
none
0.069
0.973
0.930
The correct model is consistent: the same loss in training and generation, close to the floor.
Leaky models cheat: training losses of about 0.07 are far below the 0.50 floor, which is impossible without seeing the answer, and attention sits on the answer token.
At generation they fail: the off-by-one model is almost random (2.06 against 2.30 for guessing). The no-mask model is better (0.97) because it also partly learned the real copy rule.
Seed 1: off-by-one 0.089 in training against 2.094 at generation; correct 0.621 both ways.
🐍 Exercise 2 (research): what happens when the causal mask is wrong?
Train the same GPT with a correct, an off-by-one and no causal mask; compare losses under the training mask and at generation, and attention on the answer token.
Causal masking in AI, robotics and aerospace
Forecasting: telemetry and trajectory models must never see future samples during training.
Data pipelines: time-ordered splits and leakage tests are the dataset-level analogue of the causal mask.
Design lesson: a loss that is too good to be true usually is; test that outputs do not depend on the future.
References
A. Vaswani et al. (2017). “Attention is all you need.” NeurIPS.
C. Raffel et al. (2020). “Exploring the limits of transfer learning with a unified text-to-text transformer.” JMLR 21.
Off-by-one mask: training loss 0.07 (floor 0.50) but 2.06 at generation; correct mask 0.61 both ways.
Practice
Show:
Level 0
Problem 1Level 0
Allowed attention pairs in a causal mask over 4 tokens?
10.
Problem 2Level 0
Next-token predictions trained per 2048-token sequence?
2048.
Problem 3Level 0
Entropy floor of the copy task (nats)?
0.5.
Level 1
Problem 4Level 1
Allowed pairs for T = 1024?
524800.
Problem 5Level 1
Padded fraction for lengths 100, 300, 512, 112 padded to 512?
0.5.
Problem 6Level 1
Mask constant typically used in fp16?
-10000.
Problem 7Level 1
Fraction of pairs allowed by a causal mask for T = 2 (3 decimals)?
0.75.
Level 2
Problem 8Level 2
Training loss with the off-by-one mask?
0.07.
Problem 9Level 2
Generation loss of the off-by-one model?
2.057.
Problem 10Level 2
Loss of the correctly masked model?
0.611.
Problem 11Level 2
Generation loss of the unmasked model?
0.973.
Problem 12Level 2
Attention on the answer token with the off-by-one mask?
0.964.
Problem 13Level 2
Attention on the answer token with the correct mask?
0.
Level 3
Problem 14Level 3
Prove that with a causal mask, output i does not depend on tokens after i.
Output i = Σ_j A_ij v_j with A_ij = 0 for j > i, so only v_j for j ≤ i contribute. Each v_j depends only on token j (and its position). In deeper models, induction over layers shows every layer’s output at i depends only on positions ≤ i. ∎
Problem 15Level 3
Explain why the off-by-one model failed so badly at generation.
During training, position i could see token i + 1, which is exactly its target, so copying it was the easiest way to reduce the loss; attention converged there (0.96) and the genuine 8-back rule was barely learned. At generation the next token is unavailable, so the model’s main strategy disappears and its predictions are close to random. ∎
Problem 16Level 3
Compare causal and prefix-LM masks.
A causal mask lets every position see only the past, which suits pure generation and lets every position be a training target. A prefix-LM mask lets the prompt attend bidirectionally, giving richer prompt representations for conditional generation, while generated tokens stay causal; loss is usually computed only on the non-prefix part. ∎
Problem 17Level 3
Advise on validating a sequence model for predicting engine temperature.
Use time-ordered splits, check that features never include future values, and run a leakage test that perturbs future inputs and confirms predictions do not change. Compare validation loss against a simple persistence baseline; a model far better than seems physically possible is a red flag. ∎
Level 4
Problem 18Level 4
Training loss of the off-by-one model, seed 1?
0.089.
Problem 19Level 4
Training loss of the unmasked model?
0.069.
Problem 20Level 4
Uniform-guess loss for the 10-token vocabulary (3 decimals)?
2.303.
Coding practice
🐍 Code 1 (Level 0): allowed pairs
T(T + 1)/2.
🐍 Code 2 (Level 0): predictions per sequence
T.
🐍 Code 3 (Level 0): mask constant
−10⁹ or −10⁴.
🐍 Code 4 (Level 0): padding fraction
1 − Σlengths / (B·T).
🐍 Code 5 (Level 0): prefix-LM mask
j ≤ i or j in the prefix.
Topic test
A timed test drawn at random from this topic's question bank. Each attempt gets new questions. For a longer test across the whole chapter, see the chapter test, or mix topics in the question bag.
Causal Masking: topic test
10 questions, drawn at random from a bank of 21. Every attempt is different.
⏱ Time limit: 15 minutes. The test submits itself when time runs out.
Levels covered: 0, 1, 2, 3, 4. No hints or solutions until you submit.