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

Attn⁡=softmax⁡ ⁣(QK⊤dk+M)V, where Q,K,V are the query, key and value matrices and dk is the key dimension. The mask is Mij=0 if j≤i and −∞ if j>i. Since e−∞=0, future positions get weight exactly 0, and each row still sums to 1.

Steps

  1. Write the masked attention formula with the additive mask M.
  2. For n=4: M=(0−∞−∞−∞00−∞−∞000−∞0000) Row i (the query) may attend to columns j≤i, including itself.
  3. 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.
  4. 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

How long your answer should be

The formula, the 4×4 matrix and two sentences.

Last checked on 4 December 2026.

Read this

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 n and model dimension d? For n=4096 and d=1024, which part dominates?