Inferensys

Glossary

Attention Mask

A binary tensor applied during self-attention to prevent the model from attending to specific padding tokens or future positions in the input sequence.
ML engineer managing model training cluster on laptop, GPU utilization visible, technical deep learning setup.
DEFINITION

What is Attention Mask?

An attention mask is a binary tensor that explicitly controls which tokens a transformer model can attend to during the self-attention calculation, enforcing causality and ignoring padding.

An attention mask is a binary tensor applied to the attention scores within a transformer's self-attention mechanism. By setting specific positions to 0 (or -inf before softmax), the mask forces the model to ignore padding tokens in a batch or future tokens in autoregressive decoding. This ensures the model's predictions are only conditioned on valid, permissible context, preventing data leakage from subsequent positions.

The most common variants are the padding mask, which prevents attention to <pad> tokens in batched inputs of varying lengths, and the causal attention mask (or look-ahead mask), a triangular matrix that masks all positions j > i. This causal constraint is fundamental to autoregressive generation, enabling the model to predict the next token based solely on preceding context without peeking into the future.

MECHANICS

Key Characteristics of Attention Masks

Attention masks are binary tensors that enforce strict rules on which tokens can interact during self-attention. They are the fundamental mechanism that controls information flow in Transformer architectures.

01

Padding Mask

Prevents the model from attending to padding tokens in batched sequences of unequal length. Without this mask, the model would waste computation on empty positions and allow padding embeddings to corrupt the attention softmax.

  • Applied as an additive mask (large negative value) before softmax
  • Ensures padding tokens contribute zero weight to the output
  • Critical for efficient batched inference where sequences are padded to uniform length
  • Example: In a batch with sequences of lengths 5, 12, and 8, all are padded to 12; the mask zeros out positions 6-12 for the first sequence
-∞
Mask Value Applied
02

Causal Attention Mask

A lower triangular matrix that enforces autoregressive generation by preventing each token from attending to future positions. This is the defining characteristic of decoder-only architectures like GPT.

  • Token at position i can only attend to positions 0 through i
  • Implemented as an upper-triangular mask filled with negative infinity
  • Enables parallelized training despite sequential generation at inference
  • Without this mask, the model would cheat by peeking at the answer during next-token prediction
Triangular
Matrix Shape
03

Sequence-Length Mask

A dynamic mask that restricts attention to a sliding window or fixed span, used when processing documents that exceed the model's maximum context length.

  • Implements local attention patterns to handle arbitrarily long sequences
  • Often combined with global tokens that can attend to the full sequence
  • Reduces computational complexity from O(n²) to O(n × w) where w is window size
  • Example: Longformer and BigBird use this to process 4,096+ token documents efficiently
O(n × w)
Complexity Reduction
04

Cross-Attention Mask

Controls how the decoder attends to encoder outputs in encoder-decoder architectures like T5 and BART. Each decoder position can attend to the full encoder output sequence.

  • Queries come from the decoder, keys and values from the encoder
  • No causal restriction on the encoder side — full bidirectional access
  • Enables the model to condition generation on a complete understanding of the input
  • Distinct from self-attention masks which operate within a single sequence
Bidirectional
Encoder Access
05

Sparse Attention Patterns

Predefined mask structures that limit each token to attending to a subset of positions rather than the full sequence, dramatically reducing memory footprint for long contexts.

  • Strided pattern: Attend to every nth token plus local neighbors
  • Block-sparse: Divide sequence into blocks; tokens attend within their block and to select global tokens
  • Random pattern: Each token attends to a random subset, approximating full attention
  • Enables processing of sequences up to 1 million tokens on a single GPU
1M+
Max Token Support
06

Custom Entity Masking

Domain-specific masks that enforce structural constraints based on external knowledge, such as preventing cross-attention between unrelated entities in a knowledge graph.

  • Used in graph-aware Transformers for molecular modeling and code understanding
  • Masks can encode syntactic parse trees, ontology hierarchies, or molecule bonds
  • Prevents the model from forming spurious correlations between unrelated concepts
  • Example: In code generation, masking prevents a function from attending to variables outside its scope
Structural
Constraint Type
ATTENTION MASK MECHANICS

Frequently Asked Questions

Precise answers to the most common technical questions about attention masks, their implementation, and their role in transformer architectures.

An attention mask is a binary tensor applied to the attention scores within a transformer's self-attention mechanism to explicitly control which tokens the model is permitted to attend to. It works by adding a large negative value (typically -infinity) to the attention scores of disallowed positions before the softmax operation. This forces the softmax output for those positions to effectively zero, preventing the model from incorporating information from masked tokens. The mask is applied element-wise during the scaled dot-product attention calculation: Attention(Q, K, V) = softmax((QK^T / sqrt(d_k)) + mask) * V. This mechanism is fundamental for handling variable-length sequences via padding masks and enforcing autoregressive generation via causal masks.

Prasad Kumkar

About the author

Prasad Kumkar

CEO & MD, Inference Systems

Prasad Kumkar is the CEO & MD of Inference Systems and writes about AI systems architecture, LLM infrastructure, model serving, evaluation, and production deployment. Over 5+ years, he has worked across computer vision models, L5 autonomous vehicle systems, and LLM research, with a focus on taking complex AI ideas into real-world engineering systems.

His work and writing cover AI systems, large language models, AI agents, multimodal systems, autonomous systems, inference optimization, RAG, evaluation, and production AI engineering.