A causal attention mask is a binary matrix applied during the self-attention computation of a decoder-only transformer. It ensures that the prediction for token at position i depends only on tokens at positions 0 through i, and not on any subsequent token i+1 or later. This is implemented by setting the attention scores for all future positions to negative infinity before the softmax operation, effectively zeroing out their influence. This mechanism is the fundamental architectural constraint that enables autoregressive generation, where text is produced sequentially from left to right.
Glossary
Causal Attention Mask

What is Causal Attention Mask?
A causal attention mask is a triangular matrix that enforces the autoregressive property in transformer decoders by preventing tokens from attending to future positions in a sequence.
Without a causal mask, the model would be bidirectional and could cheat by peeking at the ground-truth answer during training. In practice, the mask is a strict upper-triangular matrix of -inf values. During inference, this allows the model to generate one token at a time, appending it to the KV-cache for subsequent steps. This contrasts with the padding mask used in encoder models, which only hides irrelevant tokens. The causal mask is the defining feature that distinguishes generative pre-trained architectures like GPT from bidirectional encoders like BERT.
Key Characteristics of Causal Attention Masks
The causal attention mask is the fundamental mechanism that enforces the autoregressive property in decoder-only transformer models, ensuring temporal causality during training and inference.
Triangular Matrix Structure
The mask is a square matrix where the upper triangle is set to -infinity (or a very large negative number) and the lower triangle is set to 0. This forces the softmax function to assign zero probability to future positions.
- Shape: [seq_len, seq_len] for each attention head
- Upper Triangle: Masked (prevented from attending)
- Lower Triangle & Diagonal: Unmasked (allowed to attend)
- Implementation: Added to attention scores before softmax:
scores = scores + mask
Autoregressive Property Enforcement
The mask ensures that the prediction for token at position i depends only on tokens at positions 0 through i-1. This is the mathematical implementation of the chain rule of probability in sequence modeling.
- Token
tcan only attend to tokens[0, 1, ..., t] - Token
t+1is completely invisible during the prediction of tokent - Enables teacher forcing during training: the model learns to predict the next token given all previous ground-truth tokens
Training vs. Inference Behavior
The mask operates differently depending on the phase:
Training (Teacher Forcing)
- The full sequence is fed in parallel
- The mask prevents information leakage from future tokens
- All positions are computed simultaneously via matrix multiplication
Inference (Autoregressive Decoding)
- Tokens are generated one at a time
- The KV-Cache stores previous Key and Value tensors
- The mask grows incrementally with each new token generated
Relationship to Self-Attention
The causal mask is applied to the scaled dot-product attention scores before the softmax normalization. Without it, the model would have bidirectional context and could cheat by looking at the answer.
- Attention formula:
Attention(Q, K, V) = softmax(QK^T / sqrt(d_k) + M) * V - M is the causal mask matrix
- After softmax, masked positions have weight 0.0
- The mask is applied independently in each attention head across all layers
Padding Mask Distinction
The causal mask is often confused with the padding mask, but they serve different purposes:
- Causal Mask: Prevents attending to future tokens (temporal constraint)
- Padding Mask: Prevents attending to
<PAD>tokens in batched sequences of different lengths - Both are combined in practice:
combined_mask = causal_mask & padding_mask - Padding masks are typically 1 for real tokens and 0 for padding tokens
Decoder-Only Architecture Foundation
The causal attention mask is the defining characteristic of decoder-only transformers like GPT, LLaMA, and Claude. It distinguishes them from encoder-only models like BERT which use bidirectional attention.
- GPT Family: Causal self-attention in every layer
- Encoder-Decoder Models (T5, BART): Causal mask only in the decoder cross-attention
- Prefix Language Models: Hybrid approach with bidirectional attention on the prefix and causal attention on the generated portion
Causal Mask vs. Padding Mask vs. Bidirectional Attention
A comparison of the three primary attention masking strategies used in transformer architectures to control information flow during self-attention computation.
| Feature | Causal Mask | Padding Mask | Bidirectional Attention |
|---|---|---|---|
Primary Purpose | Prevents attending to future tokens during autoregressive generation | Prevents attending to padding tokens in variable-length batches | Allows attending to all tokens in the sequence simultaneously |
Mask Structure | Upper triangular matrix (-∞ above diagonal) | Binary mask based on padding positions | No mask (all attention scores preserved) |
Information Flow | Unidirectional (left-to-right) | Selective (ignores padding only) | Omnidirectional (all-to-all) |
Typical Use Case | GPT-style text generation, decoder-only models | Batch processing of sequences with different lengths | BERT-style encoding, sentence classification |
Supports Autoregressive Generation | |||
Handles Variable-Length Inputs | |||
Contextual Depth | Limited to preceding context only | Full context minus padding | Full bidirectional context |
Computational Complexity | O(n²) with triangular sparsity | O(n²) with irregular sparsity | O(n²) dense computation |
Frequently Asked Questions
Explore the mechanics of the causal attention mask, the foundational mechanism that enforces the autoregressive left-to-right generation constraint in modern language models.
A causal attention mask is a triangular matrix applied during the self-attention mechanism to enforce autoregressive generation. It works by adding a large negative value (typically negative infinity) to the attention scores of all future tokens before the softmax operation. This forces the softmax to convert those scores to zero, ensuring that the prediction for token t depends only on tokens 0 through t-1. The mask is strictly lower-triangular, meaning the diagonal is included (allowing a token to attend to itself), but all positions to the right are masked. This mechanism is the mathematical implementation of the constraint that a language model cannot peek at the answer when predicting the next word.
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
Master the mechanisms that control information flow in autoregressive models. These concepts are essential for understanding how causal attention masks enforce temporal logic in transformer architectures.
Attention Mask
A binary tensor applied during the self-attention mechanism to control which tokens can interact. It sets attention weights to negative infinity before the softmax, effectively zeroing them out.
- Padding Mask: Prevents the model from attending to meaningless padding tokens in batched inputs.
- Causal Mask: A specific triangular matrix that prevents attending to future tokens.
- Applied at every transformer layer during both training and inference.
Autoregressive Generation
A sequence modeling paradigm where the prediction of the next token is conditioned solely on previously generated tokens. The causal attention mask is the architectural enforcement of this principle.
- Each token is generated one at a time, left to right.
- The output at step t becomes part of the input at step t+1.
- Contrasts with bidirectional attention used in encoder models like BERT.
KV-Cache
A memory optimization that stores the Key and Value tensors of previously computed tokens during autoregressive decoding. Without a causal mask, the KV-cache would be invalidated by bidirectional contamination.
- Eliminates redundant computation for past tokens.
- Transforms inference from quadratic to linear complexity per step.
- The causal mask ensures the cache remains a faithful representation of the prefix.
Teacher Forcing
The dominant training strategy for autoregressive models where the ground-truth previous token is fed as input, regardless of the model's own prediction. The causal mask makes this parallelizable.
- The entire target sequence is shifted right by one position.
- The mask allows the model to compute loss for all positions simultaneously.
- Prevents compounding of early errors during the training phase.
Self-Attention Mechanism
The core operation where every token in a sequence computes a weighted representation of all other tokens. The causal mask modifies this to be unidirectional.
- Computes Query, Key, and Value vectors for each token.
- The attention score matrix is element-wise added to the mask.
- Without the mask, this is bidirectional self-attention; with it, it becomes masked self-attention.
Context Window
The maximum span of tokens a model can attend to. The causal mask operates strictly within this boundary, defining the limit of the model's immediate working memory.
- Modern models range from 4K to 1M+ tokens.
- The mask is a square matrix of size [window_size x window_size].
- Truncation strategies must respect the causal structure to avoid logical breaks.

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