Inferensys

Glossary

Attention Mask

A binary tensor generated during tokenization that instructs the model's attention mechanism to ignore padding tokens and only process genuine content tokens.
ML engineer managing model training cluster on laptop, GPU utilization visible, technical deep learning setup.
SEQUENCE MASKING

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.

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.

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.

MECHANICS

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.

01

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.

0 or 1
Binary State
02

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.

-∞
Future Token Value
03

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.

[PAD]
Special Token
04

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.

[CLS]
Aggregation Token
05

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.

0.0
Padded Loss Weight
06

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.

4D
Tensor Shape
ATTENTION MASK ESSENTIALS

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.

MASK TYPE COMPARISON

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.

FeatureAttention MaskCausal MaskPadding 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

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.