Foundations to Frontier
Tests
F. NLP and Large Language Models › F4 Transformer Language Models

Causal Masking

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.

Level 0: Foundation

★☆☆☆☆ 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. 1. The causal mask stops a token from attending to…
  2. 2. A model that can peek at the next token during training…
  3. 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. 1. Allowed pairs for T = 1024:
  2. 2. Masks are combined with…
  3. 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 F
q = 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 positions
v2 = v.clone(); v2[:, :, -1] += 1
assert 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. 1. PyTorch flag for causal attention:
  2. 2. A direct leakage test is to…
  3. 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. 1. A leaky mask optimises…
  2. 2. Training loss below the conditional entropy proves…
  3. 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

  1. A. Vaswani et al. (2017). “Attention is all you need.” NeurIPS.
  2. C. Raffel et al. (2020). “Exploring the limits of transfer learning with a unified text-to-text transformer.” JMLR 21.
  3. PyTorch documentation, torch.nn.functional.scaled_dot_product_attention.