An attention mask is a binary tensor generated during the tokenization and batching process that explicitly defines which tokens in a sequence are valid content and which are [PAD] tokens. By adding a large negative value to the attention scores of padding tokens before the softmax operation, the mask forces their attention weights to zero, ensuring the model's self-attention mechanism only aggregates information from semantically meaningful tokens.
Glossary
Attention Mask

What is an Attention Mask?
An attention mask is a binary tensor that explicitly instructs a Transformer model's self-attention mechanism which tokens in an input sequence represent genuine semantic content and which are non-informative padding, preventing the model from attending to void positions.
This mechanism is critical for handling variable-length sequences in a fixed-size batch. Without an attention mask, a model would waste computation attending to padding tokens and, more critically, allow these void positions to corrupt the contextualized representations of genuine tokens. In autoregressive decoder-only architectures, a variant called a causal attention mask is also used to prevent tokens from attending to future positions, preserving the left-to-right autoregressive property.
Key Characteristics of Attention Masks
Attention masks are binary tensors that serve as the gatekeepers of self-attention, explicitly defining which tokens carry semantic meaning and which are computational placeholders.
Binary Filtering Logic
An attention mask is a tensor of boolean values where 1 indicates a genuine content token and 0 indicates a padding token. During the scaled dot-product attention calculation, positions corresponding to 0 are set to a large negative value (e.g., -1e9) before the softmax function. This forces the attention weights for those positions to effectively zero, ensuring the model's focus is strictly constrained to real linguistic content and not wasted on empty computational slots.
Causal Masking (Autoregressive)
In decoder-only architectures like GPT, the attention mask takes the form of an upper triangular matrix filled with negative infinity. This prevents a token at position i from attending to any token at position j where j > i. By masking out future tokens, the model is forced to predict the next word based solely on the preceding context, preserving the autoregressive property essential for coherent text generation without information leakage from the future.
Padding Mask Generation
Since neural networks process data in fixed-size batches, sequences of varying lengths must be standardized. A padding mask is dynamically generated by the tokenizer during the collation step. The mask marks all positions beyond the original sequence length as 0. This allows the model to process a batch containing a 10-word sentence and a 50-word sentence simultaneously without the shorter sequence's padding tokens distorting the attention distribution or the final contextualized representations.
Sequence Classification Aggregation
For tasks like sentiment analysis, the attention mask plays a critical role in pooling. Rather than averaging all output tokens—which would dilute the signal with padding—the mask ensures that only the hidden states of genuine tokens are aggregated. In BERT, the [CLS] token's final hidden state is used for classification, but its attention is strictly governed by the mask to summarize only the real input span, ignoring the padded tail of the batch.
Loss Function Masking
Attention masks are not just for the forward pass; they are crucial for accurate loss calculation. During language modeling, the cross-entropy loss is computed only on the tokens where the mask is 1. If padding tokens were included in the loss calculation, the model would waste capacity learning to predict the [PAD] token itself. Masking the loss ensures the optimization signal focuses exclusively on reconstructing meaningful linguistic content, leading to faster convergence and better generalization.
Multi-Head Mask Broadcasting
In the Multi-Head Attention mechanism, the same attention mask is broadcast across all attention heads. The mask tensor typically has a shape of [batch_size, 1, 1, seq_len] or [batch_size, 1, seq_len, seq_len]. The singleton dimensions allow NumPy-style broadcasting to align with the [batch_size, num_heads, query_len, key_len] attention scores tensor. This ensures a consistent filtering logic across every parallel representation subspace without duplicating the mask data.
Frequently Asked Questions
Clear, technical answers to the most common questions about attention masks in transformer architectures, covering their purpose, generation, and impact on model computation.
An attention mask is a binary tensor that explicitly instructs a transformer model's self-attention mechanism which tokens in an input sequence represent genuine content and which are padding artifacts. It works by adding a large negative value (typically -10,000 or -infinity) to the attention scores of masked positions before the softmax operation. This forces the softmax output for those positions to be effectively zero, ensuring that padding tokens contribute nothing to the weighted sum of values. The mask is generated during the tokenization and batching process, where sequences of varying lengths are padded to a uniform length with a special [PAD] token. Without this mask, the model would treat padding as meaningful context, corrupting the contextualized representations of real tokens and degrading downstream task performance.
Attention Mask vs. Causal Mask vs. Padding Mask
A technical comparison of the three distinct masking mechanisms used in Transformer architectures to control information flow, handle variable-length sequences, and enforce autoregressive generation constraints.
| Feature | Attention Mask | Causal Mask | Padding Mask |
|---|---|---|---|
Primary Purpose | General-purpose mechanism to control which tokens can attend to which other tokens | Enforce autoregressive property by preventing tokens from attending to future positions | Instruct model to ignore padding tokens added for batch uniformity |
Typical Values | 0 (attend) and -∞ or very large negative number (mask) | 0 for allowed positions, -∞ for future positions | 1 for real tokens, 0 for padding tokens |
Application Scope | Can implement any attention pattern including causal, padding, or custom masks | Strictly upper-triangular pattern; a specific subset of attention masking | Applied per-sequence based on actual content length within a batch |
Matrix Shape | Arbitrary boolean or float tensor matching attention score dimensions | Square upper-triangular matrix of size sequence_length × sequence_length | Broadcastable tensor aligned to batch × sequence_length dimensions |
Use in Encoder-Decoder | Used in cross-attention to control which encoder outputs the decoder attends to | Applied in decoder self-attention only; encoder uses bidirectional attention | Applied to both encoder and decoder inputs for variable-length batches |
Use in Decoder-Only Models | Typically implemented as combined causal + padding mask | Core mechanism enabling next-token prediction in GPT-style models | Required for efficient batched inference with sequences of different lengths |
Addition Method | Added to attention scores before softmax: scores + mask | Added to attention scores before softmax: scores + causal_mask | Typically multiplied with or added to attention scores; implementation varies by framework |
Effect on Softmax | Masked positions become approximately 0 after softmax (e^{-∞} ≈ 0) | Future positions receive zero attention weight, preserving autoregressive property | Padding positions receive zero attention weight, preventing noise from empty tokens |
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
Core concepts that interact with the attention mask to control sequence processing and ensure efficient, correct model computation.
Padding
The strategy of adding a special [PAD] token to shorter sequences in a batch to ensure all input tensors have a uniform length. This enables efficient parallel processing on GPUs. The attention mask is the mechanism that tells the model to ignore these padding tokens during computation, preventing them from influencing the representation of genuine content tokens.
Causal Mask
Also known as a look-ahead mask, this is a triangular matrix applied during self-attention in autoregressive decoders. It prevents a token from attending to future tokens in the sequence, preserving the autoregressive property. While an attention mask ignores padding, a causal mask enforces the temporal order of generation by setting attention weights to negative infinity for all subsequent positions.
Sequence Length
The total number of tokens in an input, including both genuine content and padding tokens. The attention mask is a binary tensor of this length. Mismatched sequence lengths within a batch are the primary reason padding and attention masks are required. Models have a maximum context window, and inputs exceeding this length must be truncated.
Special Tokens
Reserved vocabulary entries with specific control functions that interact with masking logic. Key examples include:
- [PAD]: The token explicitly ignored by the attention mask.
- [CLS]: A classification token whose final hidden state represents the entire sequence; it must not be masked.
- [SEP]: A separator token used to delineate sentence boundaries, which is a genuine content token and must be attended to.
Loss Masking
A parallel concept in loss calculation where a binary mask is applied to the output logits to ignore the loss contribution from padding positions. Without this, the model would be penalized for not correctly predicting padding tokens, introducing noise into the training signal. This ensures the objective function focuses solely on learning from genuine content tokens.

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