How do you combine a padding mask and a causal mask into a single attention mask?

Last updated 22 November 2026

  • Broadcast a (1, 1, T, T) lower-triangular causal mask with a (B, 1, 1, T_k) padding mask to get (B, 1, T, T), then convert to additive form (0 allowed, dtype minimum blocked).

  • The combination rule depends on convention: AND if True = allowed (F.scaled_dot_product_attention), OR if True = blocked (nn.MultiheadAttention), sum for additive float masks.

  • Left padding can fully mask a pad query's row and cause NaN. Use a finite minimum or let pad queries attend to themselves, since their outputs are ignored in the loss.

  • https://www.abhik.ai/concepts/transformers/masked-attention
  • https://mbrenndoerfer.com/writing/attention-masking-transformers
  • https://life-is-also-pizza.tistory.com/379
All Transformers interview questions