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.
Glossary
Attention Mask

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.
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.
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.
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
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
ican only attend to positions0throughi - 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
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
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
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
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
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.
Enabling Efficiency, Speed & Accuracy
Intelligent Analysis, Decision & Execution
We build AI systems for teams that need search across company data, workflow automation across tools, or AI features inside products and internal software.
Talk to Us
Search across company data
Give teams answers from docs, tickets, runbooks, and product data with sources and permissions.
Useful when people spend too long searching or get different answers from different systems.

Automate internal workflows
Use AI to route work, draft outputs, trigger actions, and keep approvals and logs in place.
Useful when repetitive work moves across multiple tools and teams.

Add AI to products and internal tools
Build assistants, guided actions, or decision support into the software your team or customers already use.
Useful when AI needs to be part of the product, not a separate tool.
Related Terms
Mastering the attention mask requires understanding its direct neighbors in the Transformer architecture. These concepts define how masking controls information flow, optimizes inference, and enforces autoregressive generation.
Causal Attention Mask
A triangular matrix that enforces the autoregressive property by preventing the model from attending to future tokens. During training, the mask sets all attention scores above the diagonal to negative infinity before the softmax operation, ensuring the prediction for token t depends only on tokens 0 through t-1. This is the specific instantiation of an attention mask used in decoder-only models like GPT. Without it, the model would cheat by peeking at the answer.
Padding Mask
A binary tensor that prevents the model from wasting computation on meaningless padding tokens. Since inputs within a batch must have uniform length, shorter sequences are padded with a special <PAD> token. The padding mask sets the attention score for these positions to a large negative number, ensuring the softmax output is effectively zero. This is distinct from the causal mask: it filters out static filler rather than enforcing temporal order.
KV-Cache
A memory optimization that stores the Key and Value tensors of previously generated tokens to avoid recomputing them at each autoregressive step. During generation, the causal attention mask is dynamically constructed to allow the new query token to attend to all cached keys and values. The mask ensures the query cannot see future queries that haven't been generated yet, while the cache eliminates redundant computation for the static prefix.
Self-Attention Mechanism
The core operation where the attention mask is applied. The mechanism computes Query (Q), Key (K), and Value (V) matrices from the input. The raw attention scores are calculated as the dot product of Q and K, scaled by the square root of the dimension. The attention mask is added element-wise to these scores before the softmax. This additive approach ensures masked positions receive a probability of zero, effectively removing them from the weighted sum of values.
Context Window
The maximum span of tokens a model can attend to, defining the absolute boundary of the attention mask. The mask's dimensions are directly constrained by this limit. When the input sequence exceeds the context window, truncation strategies must decide which tokens to drop. The attention mask then operates only on the surviving tokens, making the window size a hard architectural constraint that dictates the mask's maximum shape.
Cross-Attention Mask
Used in encoder-decoder architectures like T5, this mask controls how the decoder attends to the encoder's output. Unlike self-attention masks, cross-attention masks do not need to be causal because the decoder can attend to the entire encoded input sequence simultaneously. However, padding masks are still applied to the encoder output to ignore filler tokens. This allows the decoder to condition generation on the full source context.

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.
Partnered with leading AI, data, and software stack.
How We Work
Custom AI workflows for your Business
One-fit-all AI don't work for modern businesses. At Inferensys, we aim to understand your business & custom requirements; which we use to define most efficient agentic workflows, the data, and the tools for your business.
01
Review the use case
We understand the task, the users, and where AI can actually help.
Read more02
Pick the right approach
We define what needs search, automation, or product integration.
Read more03
Build the first useful version
We implement the part that proves the value first.
Read more04
Improve from there
We add the checks and visibility needed to keep it useful.
Read moreThe first call is a practical review of your use case and the right next step.
Talk to Us