An attention mask is a binary matrix applied during a transformer model's self-attention computation that explicitly controls which tokens in an input sequence are allowed to attend to (or influence) which other tokens. It enforces structural constraints, such as causal masking for autoregressive generation (preventing future tokens from being seen) and padding masking to ignore placeholder tokens in batched inputs. This deterministic gating is fundamental to the model's ability to process sequences with correct dependencies and variable lengths.
Glossary
Attention Mask

What is an Attention Mask?
A core mechanism in transformer models for controlling information flow during sequence processing.
Technically, the mask is applied by adding large negative values to the attention scores of prohibited token pairs before the softmax step, effectively zeroing out their influence. Beyond basic causal and padding masks, specialized masks enable sparse attention patterns (like sliding windows) for long sequences and support bidirectional attention in encoder models. This makes the attention mask a critical tool for context window management, directly shaping the model's "field of view" for each token during inference and training.
Key Types and Functions of Attention Masks
Attention masks are fundamental control mechanisms in transformer architectures, enforcing structural and semantic constraints on the self-attention computation. This section details their primary operational types and core functions.
Causal Mask
A causal mask (or autoregressive mask) is a triangular matrix that enforces a unidirectional flow of information. It ensures each token can only attend to previous tokens and itself, preventing the model from 'seeing the future.' This is the standard mask used in decoder-only models like GPT for autoregressive text generation. The mask is typically applied by setting future positions to -inf before the softmax operation, forcing their attention weights to zero.
- Key Property: Preserves the sequential, causal nature of language.
- Implementation: Upper-triangular matrix of
-inf(or very large negative) values. - Example: In the sequence
[A, B, C], tokenCcan attend toA,B, andC, but tokenAcannot attend toBorC.
Padding Mask
A padding mask is used during batch processing to ignore padding tokens added to standardize sequence lengths. It prevents the model from attending to these meaningless tokens, which would dilute the attention signal and waste computation. The mask is applied by setting the attention scores for padding token positions to -inf before the softmax.
- Key Property: Enables efficient batch training and inference.
- Implementation: Binary mask where
1indicates a real token and0indicates a pad token. - Example: For a batch with sequences
[[cat, dog, <PAD>], [bird, <PAD>, <PAD>]], the mask ensures attention is only calculated forcat, dog, bird.
Encoder Self-Attention Mask
In encoder models like BERT, the standard self-attention mask is a full attention mask. It allows every token in the input sequence to attend to every other token, enabling a bidirectional understanding of context. This is fundamental for tasks like text classification and named entity recognition, where the meaning of a word depends on its entire surrounding context.
- Key Property: Enables full, bidirectional context understanding.
- Implementation: A matrix of all ones (or zeros for
-inf). - Contrast: Differs fundamentally from the causal mask used in decoders.
Cross-Attention Mask
A cross-attention mask controls the flow of information between two distinct sequences in encoder-decoder architectures (e.g., T5, BART). It governs which tokens from the encoder's output (the source) the decoder can attend to at each generation step. This is crucial for sequence-to-sequence tasks like translation and summarization.
- Key Property: Manages information flow from a source context to a generating target.
- Implementation: Often a full mask from decoder query to encoder keys/values, but can be constrained (e.g., for document grounding).
- Function: Allows the decoder to 'look back' at the encoded source sequence while generating the output.
Custom & Sparse Attention Masks
Beyond standard types, custom attention masks are engineered to impose specific, often sparse, connectivity patterns. This includes:
- Sliding Window Masks: Restrict attention to a local neighborhood of tokens to enable processing of very long sequences.
- Block-Sparse Masks: Allow attention only between predefined blocks of tokens, reducing quadratic complexity.
- Task-Specific Masks: For example, masking out certain segments of a document to simulate a fill-in-the-blank task or enforcing graph-based relationships between tokens.
These are central to efficient transformer variants like Longformer and BigBird, which trade off some global context for the ability to handle much longer inputs.
Combined Masking in Practice
In real training and inference, masks are often combined using element-wise addition. The most common combination merges a causal mask with a padding mask. The logic is additive: a position is masked if either the causal rule or the padding rule dictates it should be ignored. The combined mask tensor is added to the attention scores before the softmax, where masked positions are set to a large negative value to zero out their probability.
- Workflow: 1) Calculate raw attention scores (Q•K^T). 2) Add the combined mask tensor. 3) Apply softmax.
- Result: The model simultaneously respects the autoregressive generation order and ignores computational padding.
- Example: In a batched generation task, the final mask for each sequence is the logical OR of its causal and padding masks.
Attention Mask Types: Comparison and Use Cases
A technical comparison of common attention mask patterns used in transformer models to enforce sequence processing constraints.
| Mask Type | Causal Mask | Padding Mask | Sliding Window Mask | Custom/Band Mask |
|---|---|---|---|---|
Primary Function | Enforce autoregressive generation; prevent tokens from attending to future tokens. | Ignore padding tokens in batched inputs; prevent real tokens from attending to padding. | Enable efficient long-sequence processing; limit attention to a fixed local window of preceding tokens. | Enforce arbitrary, task-specific attention patterns (e.g., graph structure, segment isolation). |
Mask Shape | Lower-triangular binary matrix. | Binary matrix based on padding token positions. | Band matrix with a fixed width (window size). | Arbitrary binary matrix defined by the user. |
Attention Complexity | O(n²) (full sequence), but computation is masked. | O(n²) (full sequence), but computation is masked for padding. | O(n * w), where w is the window size (linear for fixed w). | Varies; typically sparse, complexity depends on mask density. |
Common Use Case | Text generation, decoder-only models (e.g., GPT). | Training or inference with batched sequences of variable lengths. | Processing sequences longer than the training context (e.g., long document QA). | Encoder models for structured data, image processing, or multi-modal alignment. |
Position Info Required | Absolute position of each token in the sequence. | Knowledge of which token indices are padding. | Relative position within the defined window. | Pre-defined relationships between specific token pairs. |
Built-in HF Support | ||||
Typical Implementation Layer | Model's self-attention mechanism. | Applied before softmax in the attention calculation. | Core architecture of models like Longformer or Mistral. | Requires manual mask creation and injection into the attention module. |
Impact on KV Cache | Standard; caching of all previous tokens is valid. | Padding tokens are typically not cached, saving memory. | Only tokens within the sliding window are kept relevant for caching. | Caching strategy must align with the custom attention pattern. |
Practical Applications of Attention Masks
Attention masks are fundamental to controlling information flow within transformer models. These binary matrices enforce structural constraints during self-attention computation, enabling core functionalities from causal language modeling to efficient batch processing.
Causal Language Modeling
The causal mask (or autoregressive mask) is a triangular matrix that enforces the unidirectional constraint essential for text generation. It ensures each token can only attend to previous tokens and itself, preventing the model from 'seeing the future' during autoregressive decoding. This is implemented by setting future positions to -inf (effectively zero after softmax).
- Implementation: A lower-triangular matrix of ones.
- Use Case: All autoregressive decoder-only models like GPT-3, LLaMA, and GPT-4 use this for next-token prediction.
Padding for Batched Inference
A padding mask handles variable-length sequences within a single batch. Shorter sequences are padded with a special token (e.g., [PAD]), and the mask prevents the model from attending to these meaningless padding tokens, which would dilute the attention scores.
- Mechanism: The mask sets attention weights to
-inffor all[PAD]token positions. - Impact: Enables efficient GPU utilization by processing multiple sequences of different lengths simultaneously without computational waste or information leakage.
Encoder-Decoder Architectures
In models like T5 or BART, distinct masks govern the encoder and decoder blocks. The encoder uses a full attention mask, allowing each token to attend to all others in the input. The decoder uses a causal mask for its own output and a cross-attention mask to selectively attend to the encoder's final hidden states.
- Cross-Attention: The decoder's queries attend to the encoder's keys and values, with the mask controlling which encoder tokens are accessible for each decoding step.
Structured Data & Prompt Engineering
Masks can enforce task-specific attention patterns. For example, in JSON or SQL generation, a mask can restrict a model to only attend to relevant schema keys or column names when generating a value. In few-shot prompting, a mask can isolate the demonstration examples from the query to prevent leakage.
- Example: A system prompt defining a role can be masked to prevent the model from attending to user instructions meant for a different part of the workflow.
Sparse Attention & Long Context
For processing sequences longer than the standard context window, sparse attention patterns like sliding window attention are implemented via specialized masks. These masks limit each token's attention to a local neighborhood, reducing computational complexity from O(n²) to O(n*k).
- BigBird & Longformer: Use a combination of global, window, and random attention patterns defined by fixed masks to handle documents of up to 4096+ tokens.
Contrastive & Instruction Tuning
During fine-tuning, masks are crucial for contrastive learning objectives like those used in RLHF. For a given prompt, the positive completion and negative (rejected) completion are processed in parallel. A mask ensures the model computes loss only on the token differences between the two sequences, isolating the impact of the qualitative divergence.
Frequently Asked Questions
An attention mask is a fundamental component of transformer architecture, controlling the flow of information during self-attention. This FAQ addresses its core mechanics, applications, and relationship to other context management techniques.
An attention mask is a binary matrix (typically composed of 1s and 0s) applied during a transformer's self-attention computation to control which tokens in the input sequence are allowed to attend to which other tokens. It enforces structural constraints like causality (preventing future tokens from being seen) and padding (ignoring placeholder tokens).
Mechanically, the mask is added to the attention scores (the QK^T matrix) before the softmax operation. A large negative value (e.g., -inf) is added to positions where attention is forbidden, forcing the softmax to assign a probability of essentially zero to those connections. This allows the model to process batches of variable-length sequences efficiently and generate text autoregressively.
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
An attention mask operates within a broader ecosystem of techniques for managing a transformer model's limited context. These related concepts define the constraints and optimization strategies for sequence processing.
Context Window
The context window is the fixed-size, contiguous block of tokens a transformer model can process in a single forward pass. It acts as the model's working memory for a given input and output sequence. The attention mask directly operates within this bounded space.
- Fixed Limit: Defines the maximum sequence length (e.g., 128K tokens).
- Working Memory: All contextual understanding for a generation is derived from tokens within this window.
- Attention Scope: The self-attention mechanism, guided by the mask, computes relationships only between tokens present in the current window.
Positional Encoding
Positional Encoding (or embeddings) injects information about the absolute or relative order of tokens into the model's input. Since the self-attention mechanism is permutation-invariant, this is essential for understanding sequence structure.
- Absolute vs. Relative: Methods like sinusoidal functions or learned embeddings provide positional cues.
- Interaction with Masking: The attention mask controls which tokens attend to each other, while positional encoding informs the model where those tokens are in the sequence.
- Long Context Challenges: Techniques like Rotary Positional Embedding (RoPE) help generalize to sequences longer than those seen in training.
KV Cache (Key-Value Cache)
The KV Cache is a critical inference optimization that stores computed key and value vectors for previous tokens during autoregressive generation. This prevents redundant computation, drastically improving speed for long sequences.
- Cache Management: The attention mask determines which cached key-value pairs are relevant for the current generation step.
- Memory Footprint: The cache grows linearly with sequence length, creating memory pressure for long contexts.
- Eviction Policies: Techniques like cache eviction (e.g., LRU) are needed to manage the cache when memory is full, directly interacting with attention masking strategies.
Sparse Attention
Sparse Attention is a class of transformer architectures that restrict the full self-attention mechanism to a predefined subset of token pairs. This reduces computational complexity from quadratic to near-linear for very long sequences.
- Architectural Masking: Implements a fixed, often learnable, attention mask pattern (e.g., local windows, strided patterns, global tokens).
- Efficiency vs. Expressivity: Trades off the model's ability to see all pairwise connections for the ability to process much longer contexts.
- Examples: Sliding Window Attention, where a token only attends to a fixed number of preceding tokens, is a common sparse pattern.
Context Compression
Context Compression refers to techniques that reduce the token footprint of information within the context window while attempting to preserve semantic utility. It's a higher-level strategy for managing limited context.
- Techniques: Includes context summarization, redundancy elimination, and selective pruning.
- Relationship to Masking: Compression often creates a new, shorter sequence. A standard attention mask is then applied to this compressed context.
- Goal: To free up token budget for new inputs or longer outputs without simply truncating earlier information.
Causal Mask
A Causal Mask (or autoregressive mask) is a specific type of attention mask that enforces a unidirectional flow of information. It is fundamental to decoder-only models used for text generation.
- Mechanism: Allows a token to attend only to itself and preceding tokens in the sequence, preventing "peeking" at future tokens.
- Implementation: A triangular matrix of 1s (allow) and 0s (block), typically applied to the attention scores before the softmax.
- Contrast with Padding Mask: A causal mask is applied uniformly for modeling, while a padding mask handles variable-length sequences in a batch.

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