Skip to main content

Causal masking

Preventing access to future tokens in an autoregressive model

Lesson objective. Read a causal-mask row, infer the accessible prefix and identify the next token to predict.

Lesson skeleton

See the path

Review this lesson

Causal masking is an information constraint: to predict the token at position \(t+1\), the computation at position \(t\) must depend only on the available prefix. It is not merely a visualization convention.

Questions and exercises: Open the dedicated practice page.

Verified Concept Architecture: Autoregressive Decoder

TipThe one-minute mental model

Causal masking enforces an information rule: the output at position \(i\) must not depend on a token after position \(i\). It blocks the corresponding scores before softmax. The current position is usually allowed because the target is the next token.

First pass: inspect the lower-triangular matrix and remember the rule \(j\leq i\). This lets the model compute multiple positions in parallel without revealing their future.

Go deeper: study API-specific boolean-mask conventions, then the invariance test that detects information leakage.

Scaled scores Causal mask (j ≤ i) Softmax over allowed positions Aggregate values V

Intuition

When training a model to predict the next token, all positions in a sequence can be computed in parallel. Without a mask, however, a position’s representation could use tokens that would not yet be known during generation. The mask makes parallel training compatible with the autoregressive objective.

For “What have the Romans ever done for us?”, the final position of the prefix can attend to the whole question, including its own token. If the question and continuation are present together during training, the mask prevents this position from attending to “They” and the rest of the continuation. During generation, the continuation is appended after prediction.

Definition

For a sequence of length \(T\), position \(i\) can access positions \(j\leq i\). Two complementary boolean conventions express this relation: \(\mathrm{allowed}_{ij}=\mathbf{1}[j\leq i]\) (key allowed) and \(\mathrm{blocked}_{ij}=\mathbf{1}[j>i]\) (key blocked). One can also use an additive mask \(M\):

\[ M_{ij}= \begin{cases} 0 & j\leq i,\\ -\infty & j>i. \end{cases} \]

The additive mask is applied to scores before softmax:

\[ A=\operatorname{softmax}\left(\frac{QK^\top}{\sqrt{d_k}}+M\right). \]

Lower-triangular matrix: each position can access itself and all earlier positions

Four-position causal mask.

Future positions then receive zero weight in ideal arithmetic. In practice, libraries may represent the mask as a boolean tensor or use an attention primitive that incorporates the constraint. Each query row must retain at least one allowed key: if every score in a row is masked to \(-\infty\), the ordinary softmax is undefined and needs explicit handling. In the reference scaled_dot_product_attention primitive, a fully masked row is assigned zero weights and a zero output by convention; those weights are not a probability distribution. This implementation convention is not universal. The triangular causal mask shown here avoids the case by always allowing the diagonal.

Takeaway: allowed and blocked are complementary boolean encodings of the same causal relation. The meaning of True depends on the API, as detailed in the supplementary resources.

In a common training convention, the output computed at position \(i\) is compared with target \(x_{i+1}\): inputs and targets are shifted by one token. The mask allows the diagonal \(j=i\) because the input at that position contains \(x_i\), not the future target \(x_{i+1}\). Boundary handling depends, among other things, on the chosen beginning-of-sequence and end-of-sequence token conventions.

Return to the example with the same ID in the second position. A change in the past can reach the current state. A change in the future can change the observed target at that position.

Causal masking and other masks have different roles

  • Causal attention mask: prevents a query from reading a future key; it enforces the autoregressive constraint.
  • Padding attention mask: generally prevents padding positions from being used as keys; it does not define temporal order. How padded query positions are handled depends on the implementation.
  • Document-boundary attention mask: when multiple documents are packed into one sequence, it can prevent interactions across distinct documents. It can be combined with causal masking.
  • Loss/target mask: excludes selected positions from the training objective; by itself, it does not prevent attention layers from accessing information. Shifted-target construction and padding/loss masks belong to the data-and-corpus lesson.

These masks answer different questions and must not be substituted for one another.

Trace visible positions and targets counted in the loss in one worked example.

Provenance and purpose

Causal masking supports an autoregressive factorization of the sequence distribution:

\[ P(x_1,\ldots,x_T)=\prod_{t=1}^{T}P(x_t\mid x_{<t}). \]

Decoder-only Transformers such as GPT use this constraint to learn next-token prediction while computing positions in a training batch in parallel. Attention Is All You Need (Vaswani et al., 2017) describes masking decoder attention.

Misconceptions and counterexamples

  • “The data are already ordered, so masking is unnecessary.” False: token order does not stop an unmasked attention operation from reading representations at future positions.
  • “Softmax alone makes attention causal.” No: without a mask, normalization still applies to future positions, which receive positive weights.
  • “Zeroing future weights after softmax is sufficient.” Without renormalization, the remaining weights may no longer sum to one. Masking and renormalizing are equivalent in exact arithmetic if the remaining sum is nonzero; masking scores before softmax is the usual formulation.
  • “Testing only the mask matrix proves there is no leakage.” False: another computation path could still pass future information.
  • “Causal means attention sees only the previous token.” False: it can see all earlier positions unless another restriction, such as a sliding window, is imposed.
Common Fallacy: “Why bother adding \(-\infty\) before softmax? Multiplying future weights by zero after softmax is much simpler!”

Why? If future positions have positive weight, zeroing them after softmax without renormalizing leaves a sum below one. The result differs from normalized causal attention; the output norm does not necessarily shrink because vectors can cancel. Masking before softmax normalizes over allowed positions. Zeroing and then renormalizing gives the same result in exact arithmetic if the remaining sum is nonzero.

A useful consequence of the causal rule is prefix invariance: with parameters and a prefix held fixed, appending or changing future tokens must not change the outputs already computed for that prefix. This is a testable property of the computation; a mask-matrix check alone does not establish that every path through a complete model is causal.

Connections to other concepts

Language: Français · English

Practice

Further exploration

Supplementary resources Consult API conventions and reference implementation details when moving from the concept to code.

In code, boolean-mask polarity is API-specific. In PyTorch 2.15 scaled dot-product attention, True in the boolean attn_mask means that a query-key pair participates in attention. In PyTorch 2.15 MultiheadAttention, True in attn_mask means that the pair is not allowed to attend, while True in key_padding_mask means that the corresponding key is ignored. Thus the boolean polarity of MultiheadAttention masks is opposite to SDPA’s attn_mask convention. Do not transfer a boolean mask between these APIs without checking its documented convention. This is separate from the causal rule itself: the allowed query-key pairs must still exclude future keys.

Version note: the API conventions above were checked against the PyTorch 2.15 documentation, released on 28 October 2026 (release announcement). API details can evolve; check the documentation matching the installed version before transferring masks.

A tested reference implementation is available in src/llm_lab/foundations/attention.py (causal_mask and scaled_dot_product_attention). The attention function accepts an additive 2D mask of exact shape (T_q, T_k); it does not support boolean masks or batch/head broadcasting. The tests provide two complementary levels of evidence: tests/unit/test_attention.py checks the single-head attention primitive, while tests/unit/test_gpt.py compares prefix logits with the corresponding logits from an extended input under the same GPT. These are targeted regression checks, not formal proofs for every architecture or input. The full-model test does not add padding-mask support; the reference GPT.forward interface has no padding-mask argument.