How is causal (look-ahead) masking implemented in decoder self-attention? What is the mask for a sequence of length 4, and why are masked logits set to rather than the attention weights being set to 0?
Sequence models and transformers, Attention
Level L2 Elementary. Length Short. Nature Th+Mat Both.
What's being asked
Whether you know where the mask goes (before the softmax), and why.
Key idea
, where are the query, key and value matrices and is the key dimension. The mask is if and if . Since , future positions get weight exactly 0, and each row still sums to 1.
Steps
- Write the masked attention formula with the additive mask .
- For : Row (the query) may attend to columns , including itself.
- Explain why goes on the logits (the scores before the softmax): the softmax then renormalises over the allowed positions only. Zeroing weights after the softmax would leave rows summing to less than 1, unless you renormalise. Adding 0 to a logit does nothing, so the allowed positions are untouched.
- Say why it matters: it lets you train all positions in parallel with teacher forcing, while each position sees only its past, just as in generation. In code, use a large negative number or the dtype's minimum to avoid NaN in half precision.
Common mistakes
- Masking the diagonal. A token must be allowed to attend to itself.
- Applying the mask after the softmax without renormalising.
- Confusing the causal mask with the padding mask, which masks the key columns of padding tokens in every row.
How long your answer should be
The formula, the matrix and two sentences.
Last checked on 4 December 2026.
Read this
- Dive into Deep Learning: Attention Scoring and Masking: Sections 10.2.2.1 'The Masked Softmax Operation' (set masked logits to a large negative value before the softmax) and 10.2.2.2 'Causal Masking' (the lower-triangular mask), with code.
- The Illustrated GPT-2 (Jay Alammar): Part 2, 'The Illustrated Masked Self-Attention' and 'GPT-2 Masked Self-Attention': pictures of the score matrix before and after the upper-triangular -inf mask and the renormalised softmax rows.
Previous in Sequence models and transformers: What is teacher forcing when training a sequence-to-sequence decoder, and what is exposure bias?
Next in Sequence models and transformers: What are the time and memory costs of one self-attention layer for sequence length and model dimension ? For and , which part dominates?