AI Wiki中文/EN

Causal masking: who can see which answer?

因果掩码

Check information flow, target shifting, padding and rectangular cache masks.

On this pageIntuitionMathematics & methodImplementationLimitationsExercisesResearch connections

A covered answer can still arrive through another door

Give a model the sequence “red, blue, red” and ask it to predict those same tokens at the same positions. Hiding future attention links does not make this a fair next-token task: the current input already contains the answer. A residual connection can carry it straight to the prediction head.

Causal masking restricts which earlier representations a query may read. Target shifting determines which token the query is supposed to predict. The original Transformer uses both: its decoder attends through the current input position, while the target sequence is shifted relative to the inputs. Start with multi-head attention and autoregressive models.

Think of the attention matrix as a reading permission table. Rows are readers, or queries; columns are available records, or keys. A triangular picture is convenient when both axes begin at the same position. During cached generation they often do not. The GPT-2 implementation accounts for that offset when constructing a rectangular mask.

Absolute query positions select the correct cached keys; a mask cannot remove an unshifted residual shortcut.
Absolute query positions select the correct cached keys; a mask cannot remove an unshifted residual shortcut.

Visibility, indexing and a proof of isolation

Let query and key positions be integers, with later positions representing later input tokens. A permitted key must be no later than its query and must not be padding. Use zero for an allowed additive mask entry and negative infinity otherwise:

Mij={0,kj≤qi and key j is valid,−∞,otherwise.M_{ij}=\begin{cases}0,&k_j\le q_i\text{ and key }j\text{ is valid},\\-\infty,&\text{otherwise}.\end{cases}

With finite query, key and value vectors, masked attention is:

A=softmax⁡row(QK⊤dk+M),O=AV.A=\operatorname{softmax}_{\mathrm{row}}\left(\frac{QK^\top}{\sqrt{d_k}}+M\right),\qquad O=AV.

Here each row of the softmax sums to one over its allowed keys. At least one key must be allowed for every query that is actually evaluated. An entirely blocked row is not a meaningful probability distribution; the program raises an error. Library conventions differ: a boolean True may mean “allow” in one interface and “block” in another. This implementation explicitly means “allow.”

For a sequence of targets indexed from one, teacher forcing supplies the known previous target as the next input. If the loss includes only active target positions, its normalization counts those positions:

ut={BOS,t=1,xt−1,t>1,pt=softmax⁡(Wht+b),L=−∑tmtlog⁡pt(xt)∑tmt,∑tmt>0.u_t=\begin{cases}\mathrm{BOS},&t=1,\\x_{t-1},&t>1,\end{cases}\quad p_t=\operatorname{softmax}(Wh_t+b),\quad \mathcal L=-\frac{\sum_t m_t\log p_t(x_t)}{\sum_t m_t},\quad \sum_t m_t>0.

The symbol BOS denotes a beginning-of-sequence token. Position one can attend to its own BOS representation without seeing the first target. During training all inputs are available in memory, so the matrix operation can run in parallel; the mask enforces the dependence structure. Generation still has to obtain each new token before using it as the next input.

Why does the restriction survive multiple layers? Suppose the input representation at position i uses only that input token and its fixed position. At each layer, attention at i reads representations at j no greater than i. By induction those representations depend only on inputs through i. Residual additions, per-token feed-forward networks and normalization across that token’s feature dimensions preserve this property:

hi(ℓ)=Fℓ(u1,…,ui),∂hi(ℓ)∂uj=0(j>i).h_i^{(\ell)}=F_\ell(u_1,\ldots,u_i),\qquad \frac{\partial h_i^{(\ell)}}{\partial u_j}=0\quad(j>i).

The derivative statement treats input embeddings as continuous variables. It assumes there is no extra sequence-wide pooling, normalization or other operation carrying future information into the prefix. It is a statement about model computation, not a claim about causal relationships in the world. It also does not repair an unshifted target sitting in the current residual stream.

For a cache containing P past positions, a new chunk’s row r has absolute position P+r. Key column c is allowed through that position:

Mrcchunk={0,c≤P+r,−∞,c>P+r,0≤r<m,0≤c<P+m.M^{\mathrm{chunk}}_{rc}=\begin{cases}0,&c\le P+r,\\-\infty,&c>P+r,\end{cases}\qquad 0\le r<m,\quad 0\le c<P+m.

With P=3 and two new queries, the rows allow columns 0–3 and 0–4, respectively. A naive two-by-five lower triangle would allow only column 0 in the first row and columns 0–1 in the second. It blocks valid history rather than implementing the intended decoder.

Applying a mask after the softmax introduces a separate trap. Multiplying probabilities by zeros removes mass. Renormalizing the remaining weights is mathematically equivalent to masking finite logits first, provided some allowed probability remains; merely multiplying is not:

A~ij=Aij1[j∈Ai],∑jA~ij≤1,Aij′=A~ij∑kA~ik.\widetilde A_{ij}=A_{ij}\mathbf1[j\in\mathcal A_i],\qquad \sum_j\widetilde A_{ij}\le1,\qquad A'_{ij}=\frac{\widetilde A_{ij}}{\sum_k\widetilde A_{ik}}.

In floating-point code, pre-softmax masking also avoids relying on tiny surviving probabilities after a badly scaled full softmax. A finite negative sentinel is an approximation whose behavior depends on numerical scale. This example uses negative infinity and explicitly rejects empty rows.

Change the future and inspect the prefix

Save the following program as causal_masking.py and run it with Python 3 and NumPy. It performs real attention calculations and a two-layer residual experiment; it does not train a language model.

"""Original finite attention/visibility experiment; NumPy only, no LM training."""
import json
import numpy as np


def positions(value, name):
    a = np.asarray(value)
    if a.ndim != 1 or not a.size or a.size > 128 or a.dtype.kind not in 'iu':
        raise ValueError(name + ' must be a nonempty bounded integer vector')
    return a


def causal_mask(query_positions, key_positions, key_valid=None):
    q, k = positions(query_positions, 'queries'), positions(key_positions, 'keys')
    allowed = k[None, :] <= q[:, None]
    if key_valid is not None:
        valid = np.asarray(key_valid)
        if valid.dtype != bool or valid.shape != k.shape:
            raise ValueError('key_valid must be a matching boolean vector')
        allowed &= valid[None, :]
    return allowed


def attention(q, k, v, allowed):
    q, k, v = [np.asarray(x, dtype=float) for x in (q, k, v)]
    mask = np.asarray(allowed)
    if any(x.ndim != 2 or not x.size or max(x.shape) > 128 or not np.isfinite(x).all() for x in (q, k, v)):
        raise ValueError('finite bounded matrices required')
    if q.shape[1] != k.shape[1] or k.shape[0] != v.shape[0] or mask.dtype != bool or mask.shape != (len(q), len(k)):
        raise ValueError('incompatible attention shapes or mask')
    if not mask.any(axis=1).all():
        raise ValueError('every active query needs an allowed key')
    scores = np.where(mask, q @ k.T / np.sqrt(q.shape[1]), -np.inf)
    weights = np.exp(scores - scores.max(axis=1, keepdims=True))
    weights /= weights.sum(axis=1, keepdims=True)
    return weights @ v, weights


def stack(x, allowed, layers=2):
    if not isinstance(layers, int) or not 1 <= layers <= 8:
        raise ValueError('layers must be 1..8')
    h = np.asarray(x, dtype=float)
    for _ in range(layers):
        h = np.tanh(h + attention(h, h, h, allowed)[0])
    return h


def demo():
    rng = np.random.default_rng(17)
    x = rng.normal(size=(5, 3)); changed = x.copy(); changed[3:] += 4
    mask = causal_mask(np.arange(5), np.arange(5))
    prefix_delta = float(np.max(np.abs(stack(x, mask)[:3] - stack(changed, mask)[:3])))
    full_delta = float(np.max(np.abs(stack(x, np.ones((5, 5), bool))[:3] - stack(changed, np.ones((5, 5), bool))[:3])))
    correct = causal_mask([3, 4], np.arange(5))
    wrong = np.tril(np.ones((2, 5), dtype=bool))
    rectangular = attention(x[3:], x, x, correct)[0]
    full = attention(x, x, x, mask)[0]
    # A residual can copy an unshifted label even when attention is strictly causal.
    seq = np.array([0, 1, 0, 1]); copied = seq.copy()
    shifted = np.r_[2, seq[:-1]]  # BOS=2 is distinct from both labels.
    return dict(causal_prefix_change=prefix_delta, unmasked_prefix_change=full_delta,
                allowed_rectangular=correct.astype(int).tolist(), wrong_local_triangle=wrong.astype(int).tolist(),
                cached_chunk_error=float(np.max(np.abs(rectangular - full[3:]))),
                unshifted_copy_accuracy=float(np.mean(copied == seq)),
                shifted_copy_accuracy=float(np.mean(shifted == seq)),
                row_sums=attention(x, x, x, mask)[1].sum(axis=1).tolist())


if __name__ == '__main__':
    print(json.dumps(demo(), indent=2))

The fixed seed generates five three-dimensional inputs. Changing the final two inputs leaves the first three outputs exactly unchanged under the causal mask. With unrestricted attention, their maximum change is about 1.56109. The correctly offset two-query chunk matches the corresponding full attention outputs exactly.

The copied-target experiment is deliberately separate. Copying the unshifted alternating labels gets accuracy one without learning sequence structure. After inserting BOS and shifting, the same copying rule gets zero on this particular alternating example. Zero is not the performance of a trained causal model; it exposes what the trivial shortcut was using.

Dense attention with n queries, n keys and width d costs order n²d after projection and stores n² weights. A cached chunk with m queries and P+m keys uses an m-by-(P+m) attention matrix. A dense mask containing many blocked entries does not itself make dense multiplication cheaper. Sparse or fused implementations need separate engineering.

Check the other routes into the answer

A padding-key mask prevents reading padded values, but does not force padded query outputs to zero. Exclude those positions from the loss and handle queries with no valid history explicitly. Packing multiple documents into one row may also require a document-identity condition so one document cannot read another unless that behavior is intended.

The isolated stack here uses only attention, residual addition and pointwise tanh. A full decoder adds learned projections, normalization, feed-forward layers and an output distribution. Future-isolation tests must cover those actual paths too. Caching assumes unchanged parameters, position conventions and past computation; training-time stochastic changes can invalidate a comparison.

Find the shortcut before measuring accuracy

  1. A cache has three tokens and a new chunk has two. Write its boolean attention mask.

Answer: The rows are [1,1,1,1,0] and [1,1,1,1,1]. Rows represent absolute positions three and four, not zero and one. Check the query/key axis convention before drawing a triangle.

  1. Four logits are equal. You keep three keys by multiplying the softmax weights by a mask. What is the remaining row sum, and how do you repair it?

Answer: Each weight was one quarter, so the sum becomes three quarters. Divide the allowed weights by three quarters to obtain one third each, or mask the forbidden logit before the softmax. Reject the case with no allowed key.

  1. Does removing the attention diagonal prevent a model from copying an unshifted target through a residual connection?

Answer: No. The residual bypasses attention and still contains the current input token. Shift the inputs relative to targets or use an appropriate corruption objective; a stricter attention triangle cannot remove a separate information path.

  1. Extend the program with a mean over all sequence positions before each layer. Will changing future inputs still leave the prefix unchanged?

Answer: In general it will not. The sequence-wide mean carries changed future values into earlier positions. The induction relied on the other operations being per-token. Test both the perturbation result and the location of that new dependence rather than trusting the visible attention mask.

Read the mask together with the input convention

The Transformer decoder description explicitly combines masking with an offset between inputs and outputs. The fixed GPT-2 source supplies a useful engineering cross-check: its mask aligns from the lower right of the query-key rectangle, and its position indices include the past length. The code is read as a source, not imported or executed here. Next, examine positional encoding and decoder-only models, where a correct mask becomes part of a complete conditional distribution.

Make a prediction, then check

Does a triangular attention mask alone prevent copying unshifted targets?

Choose one answer

Learning objectives

  • Prove future-token isolation layer by layer.
  • Distinguish visibility from label shifting and padding.
  • Build masks using absolute cache positions.

Prerequisites & connections

Explore related knowledge →

References

  1. Attention Is All You Need (v5)
    Ashish Vaswani; Noam Shazeer; Niki Parmar; Jakob Uszkoreit; Llion Jones; Aidan N. Gomez; Łukasz Kaiser; Illia Polosukhin · 2017
  2. openai/gpt-2: src/model.py @9b63575
    openai/gpt-2 contributors

Version1 · Editorial status: Recorded technical checks completed

View technical check record (AI)

Codex · 2026-09-20 · Single AI author checked Attention v5 sections3.1/3.2.3 and fixed GPT-2 mask/cache code. Six paired equations and four explained exercises; original allowed-key probability calculation, shifted residual counterexample, multilayer future isolation, padding and absolute rectangular masks. No language training or real-world causality claim.

  • Single AI author checked Attention v5 sections3.1/3.2.3 and fixed GPT-2 mask/cache code. Six paired equations and four explained exercises; original allowed-key probability calculation, shifted residual counterexample, multilayer future isolation, padding and absolute rectangular masks. No language training or real-world causality claim.
  • Four computed SVG variants per topic. Fifteen numeric/geometry tests and36 responsive cases passed; twelve final Chinese-mobile/English-desktop screenshots actually inspected. Initial text-coordinate precision assertion and visual-label refinements preserved. Full article acceptance recorded separately.

Source locations checked:

  • Attention Is All You Need (v5) · Reused identical Source object; additionally read v5 section3.1 shifted decoder inputs and section3.2.3 masking. Original cache and new reading scope recorded in source-evidence-012h.md.
  • openai/gpt-2: src/model.py @9b63575 · Read58-110,123-173: lower-right cache mask, QKV cache, pre-norm/residuals, offset positions and tied output weights. Modified MIT license opening only; no upstream execution or copying.

Related topics

No matches. Try a synonym or acronym.

0 results shown

Wrap the whole query in double quotes for a phrase match.