What is the purpose of a causal (look-ahead) mask in an autoregressive decoder?

Last updated 22 November 2026

A causal mask stops each position from attending to later positions. Token t's representation then depends only on tokens ≤ t, which matches generation, where the future doesn't exist yet. It also lets the model be trained on all positions in parallel without cheating.

  • Prevents cheating during training: The target at position t is token t+1. Without the mask, the model could just attend to it and copy it, giving near-zero loss and learning nothing useful.

  • Enables parallel teacher forcing:

    • One forward pass over the whole sequence yields T next-token predictions at once.

    • Each prediction sees exactly the context it would see at inference time.

  • Train/inference consistency: Because past representations never depend on future tokens, they can be computed once and reused. This is what makes the KV cache valid during incremental decoding.

  • Implementation:

    • Use a lower-triangular T×T mask, e.g. torch.tril(torch.ones(T, T)).bool().

    • Entries above the diagonal get −∞ added before the softmax.

    • Alternatively, pass is_causal=True to F.scaled_dot_product_attention.

  • Scope: it applies to decoder self-attention only. Encoder self-attention and cross-attention to encoder outputs are not causally masked.

  • https://www.techmazone.com/pages/interview-transformers.html
  • https://neuraprep.com/blog/llm-engineer-interview-questions/
  • https://www.geeksforgeeks.org/nlp/transformer-attention-mechanism-in-nlp/
All Transformers interview questions