Attention & Transformers

Causal Self-Attention Mask

How decoder-only Transformers prevent future-token leakage by masking attention logits before softmax.

status: reviewimportance: criticaldifficulty 3/5math: undergraduateread: 12mlive demo

Concept Structure

Causal Self-Attention Mask

01Intuition

Start with the picture, metaphor, or geometric mechanism.

02Math

Make the objects explicit and connect them with notation.

03Code

Mirror the equations with runnable implementation details.

04Interactive Demo

Manipulate the mechanism and watch the idea respond.

2prerequisites
2next concepts
3related links

Learner Contract

What this page should let you do.

You are here becauseHow decoder-only Transformers prevent future-token leakage by masking attention logits before softmax.

This Attention & Transformers concept is the current idea: keep the same invariant visible across Intuition, Math, Code, Interactive Demo.

By the end4/4 sections ready | runnable code expected | live demo

Explain the mechanism, trace the main notation, and test one prediction in the live demo.

Do this firstIntuition

Read the intuition before the notation; the math should name a mechanism you already felt.

Test the linkManipulate one control and predict the visible change.Then continue to Decoder-Only Transformer Forward Pass (review)

Claim/source review status

Substantive review recorded

1/1 claims have bounded review metadata; still check caveats and source scope.Metadata-derived; review may be AI-assisted. Not a human certification.
Claims1/1 reviewed
Sources2 cited
Codeattached
Demolive
Reviewed2026-07-02
Updatedpage 2026-07-02

Learning item flow

4/4 sections readyAsk about thisResearch room
ConceptCausal Self-Attention MaskAttention & Transformers
3 sources attachedLocal snapshot ready
concept:attention-transformers/causal-self-attention-mask
01

01

Intuition

Build the mental picture first so the rest of the page has something to attach to.

Section prompt

In a decoder-only language model, position ii is trying to predict what comes next using only the tokens it is allowed to know.

Without a causal mask, the token at position ii could attend to position i+1i+1, position i+2i+2, and so on. During training, those future tokens are sitting in the same matrix. If the model can read them, the task is no longer honest next-token prediction.

The causal mask is the read-permission rule:

query row ii can read key columns jij \le i, and cannot read future columns j>ij > i.

This is different from the loss mask in the previous page. A loss mask decides which labels contribute to the objective. A causal attention mask decides which token representations can be read while computing an attention output.

02

02

Math

Translate the story into symbols, assumptions, and a derivation you can inspect.

Section prompt

Let XRT×dmodelX \in \mathbb{R}^{T \times d_{\text{model}}} be the sequence of hidden states. For one attention head,

Q=XWQ,K=XWK,V=XWV,Q = XW_Q,\qquad K = XW_K,\qquad V = XW_V,

with Q,K,VRT×dkQ,K,V \in \mathbb{R}^{T \times d_k}.

The unmasked score from query position ii to key position jj is

sij=qikjdk.s_{ij} = \frac{q_i^\top k_j}{\sqrt{d_k}}.

For causal self-attention, define a mask

Mij={0,ji,,j>i.M_{ij} = \begin{cases} 0, & j \le i, \\\\ -\infty, & j > i. \end{cases}

Then attention probabilities are computed row-wise:

aij=softmaxj(sij+Mij).a_{ij} = \operatorname{softmax}_j(s_{ij} + M_{ij}).

So every future column receives zero probability:

j>iaij=0.j > i \quad\Rightarrow\quad a_{ij} = 0.

The output for position ii is

oi=j=0T1aijvj.o_i = \sum_{j=0}^{T-1} a_{ij}v_j.

The mask changes which values can enter that sum. It does not change which labels count toward the loss.

03

03

Code

Keep the implementation aligned with the notation so the algorithm is legible.

Section prompt
import numpy as np

def softmax(x):
    x = x - np.max(x)
    e = np.exp(x)
    return e / e.sum()

scores = np.array([
    [0.20, 0.50, -0.10, 0.30, 1.40, 0.90],
    [0.10, 0.30, 0.70, 0.20, 1.10, 0.40],
    [0.40, 0.20, 0.50, 0.80, 0.90, 0.10],
    [0.31, 0.47, 0.15, 0.25, 1.10, 0.90],
    [0.05, 0.15, 0.35, 0.20, 0.60, 0.70],
    [0.20, 0.10, 0.30, 0.05, 0.40, 0.55],
])

T = scores.shape[0]
mask = np.triu(np.ones((T, T)), k=1).astype(bool)
masked_scores = scores.copy()
masked_scores[mask] = -np.inf

i = 3
before = softmax(scores[i])
after = softmax(masked_scores[i])

print("query position:", i)
print("allowed keys:", [j for j in range(T) if j <= i])
print("future mass before mask:", round(before[i + 1:].sum(), 3))
print("future mass after mask:", round(after[i + 1:].sum(), 3))
assert np.allclose(after[i + 1:], 0.0)
04

04

Interactive Demo

Use direct manipulation to connect the explanation to a moving system.

Section prompt

Before reveal, pick which key positions a query row is allowed to read. The reveal shows the lower-triangular mask, the leak that would happen without it, and the masked softmax row where future-token probability is exactly zero.

Live Concept Demo

Explore Causal Self-Attention Mask

The stage is code-native and interactive. Use it to test the explanation against the mechanism.

difficulty 3/5undergraduatecode-aligned
Demo Prediction Checkpoint

Manipulate one control and predict the visible change.

Commit to what Causal Self-Attention Mask should make visible before reading the result.

After The First Pass

Turn the concept into an inspected object.

Once the invariant is visible in the intuition, math, code, and demo, use these panels to inspect the mechanism visually, check source support, practice the idea, and attach a grounded research question.

Mechanism Storyboard

See the idea move before the page explains it

How decoder-only Transformers prevent future-token leakage by masking attention logits before softmax.

Prediction open01 / Intuition
Prediction lens

Start with the picture, metaphor, or geometric mechanism.

Commit first

Before reading further, choose the kind of change Causal Self-Attention Mask should make visible.

Visual Inquiry

Make the image answer a mathematical question

How decoder-only Transformers prevent future-token leakage by masking attention logits before softmax.

4/4 stages readyLive demo connected
Prediction

Which visible object should carry the first intuition?

Commit first

Pick the cue that should make Causal Self-Attention Mask easier to reason about before the page gives the answer.

Source Grounding

Canonical references for the mechanism on this page.

paper · 2017Attention Is All You NeedVaswani et al.

Primary Transformer source. The decoder self-attention layer masks subsequent positions so autoregressive predictions cannot depend on future outputs.

Open source
reference · 2026Dive into Deep Learning: Transformer DecoderZhang, Lipton, Li, and Smola

Pedagogical source for decoder self-attention attending only up to the query position and preserving autoregression.

Open source
course-notes · 2026Stanford CS336: Language Modeling from ScratchStanford CS336 course staff

Course-level route source for implementing language-model components from scratch; this page uses it for route placement, not exact code claims.

Open source

Claim Review

How decoder-only Transformers prevent future-token leakage by masking attention logits before softmax.

Status1 substantive review recorded

Claims without a substantive review badge still need exact source-support review.

Sources3 references

vaswani-2017-attention, d2l-transformer-decoder, cs336-language-modeling-from-scratch

Local checks4 local checks

Use equations, runnable code, and demos to check whether the source support is operational.

Substantively reviewedIn autoregressive decoder self-attention, query position i may attend only to key positions j <= i; future positions j > i are masked before softmax so their attention probability is zero.Claim metadata: source checked

Vaswani et al. state that decoder self-attention is modified to prevent positions from attending to subsequent positions and that illegal connections are masked by setting softmax inputs to negative infinity. D2L states that decoder self-attention may use positions only up to the query position to preserve autoregression.

Sources: Attention Is All You Need, Dive into Deep Learning: Transformer DecoderThis checks the causal read-permission mask only. Padding masks, document-boundary masks, packed-sequence block masks, efficient kernels, KV-cache layout, and exact framework APIs are separate implementation details.A bounded review summary is present; still check caveats and exact reference scope.

Checked Vaswani et al. sections 3.1 and 3.2.3 plus D2L Transformer decoder text for masked decoder self-attention. The page is review-status pending GPT Pro publication critique.

Reviewer: codex-local-source-audit; reviewed 2026-07-02

Practice Loop

Try the idea before it explains itself

How decoder-only Transformers prevent future-token leakage by masking attention logits before softmax.

Readiness0/3 checks ready
Predict

Before touching the demo, predict one visible change that should happen in Causal Self-Attention Mask.

Hint 1

Reveal when your model needs a nudge.

Hint 2

Reveal when your model needs a nudge.

Hint 3

Reveal when your model needs a nudge.

Grounded research drawerClose
ConceptCausal Self-Attention MaskAttention & Transformers
Runnable code comparisonCausal Self-Attention Mask runnable code 1scores = np.array([Prediction before revealCausal Self-Attention Mask interactive demoManipulate one control and predict the visible change.
Grounded room questionWhat is the smallest example that makes Causal Self-Attention Mask click without losing the math?Local snapshot ready

Research Room

Attach the question to a claim, equation, code, or demo

Pick the concept, equation, source, runnable code, claim, misconception, or demo state before asking for help. The handoff keeps that page item in context.
Next local actionNo local draft saved yet

Open the draft below to save one note and next action in this browser.

conceptAttention & Transformers

Causal Self-Attention Mask

Attached question

What is the smallest example that makes Causal Self-Attention Mask click without losing the math?

Local action draftNo local draft saved yetExpand only when ready to capture one local next action
Local action draft

This draft stays in this browser, attached to the selected learning item.

No local draft saved.
Evidence to inspect
  • References to inspect: attached references on this page.
  • Definition, prerequisite, and contrast concept links
  • The equation or runnable code that makes the concept operational
  • One demo state that shows the invariant instead of a slogan
What would resolve this
  • The learner can state the mechanism in their own words
  • The learner can name the prerequisite that would repair confusion
  • The learner can predict how the mechanism changes under one perturbation
Grounded AI handoff

I am working in Continuous Function's research reading room. Object: concept - Causal Self-Attention Mask Selected item key: recorded for copy. Context: Attention & Transformers Page anchor: recorded for copy. Open question: What is the smallest example that makes Causal Self-Attention Mask click without losing the math? Evidence to inspect: - References to inspect: attached references on this page. - Definition, prerequisite, and contrast concept links - The equation or runnable code that makes the concept operational - One demo state that shows the invariant instead of a slogan What would resolve this: - The learner can state the mechanism in their own words - The learner can name the prerequisite that would repair confusion - The learner can predict how the mechanism changes under one perturbation Answer as a careful research tutor: stay source-grounded, separate verified evidence from assumptions, name the relevant math objects, and end with one next action.

View it in context
concept/concept-notebook/attention-transformers/causal-self-attention-mask concept:attention-transformers/causal-self-attention-mask