AI Wiki中文/EN

Self-attention

自注意力

Track information flow within a sequence, derive permutation equivariance, and verify that a causal mask blocks future tokens.

On this pageIntuitionMathematics & methodImplementationLimitationsExercisesResearch connections

Each position reads the sequence for a different purpose

Take three scalar token representations: 1, 2, and -1. Let each representation serve as its own query, key, and value. The first position scores the sequence as [1,2,−1][1,2,-1], while the second scores it as [2,4,−2][2,4,-2]. They therefore retrieve different weighted mixtures from the same input.

“Self” means the queries, keys, and values originate in the same sequence. It does not mean a token can only look at itself. Different learned projections usually create those three roles, so self-attention also does not require numerically identical queries, keys, and values. D2L, Section 11.6.1

Projection, mixing, and position

For row-oriented input XX with nn positions and representation width dd, one head computes:

Q=XWQ,K=XWK,V=XWV,F(X)=softmax⁡rows(QK⊤dk+M)V.Q=XW_Q,\qquad K=XW_K,\qquad V=XW_V,\qquad F(X)=\operatorname{softmax}_{\mathrm{rows}}\left(\frac{QK^\top}{\sqrt{d_k}}+M\right)V.

WQ,WKW_Q,W_K have shape d×dkd\times d_k; WVW_V has shape d×dvd\times d_v. The mask MM is zero for allowed pairs and negative infinity for forbidden ones in the mathematical notation. Scores are indexed by query row and key column. For causal attention, row ii permits columns j≤ij\le i, including itself. Vaswani et al., Sections 3.2.2–3.2.3

Consider unmasked attention without positional information. If PP permutes input rows, projected queries, keys, and values receive the same permutation. Its score matrix becomes P(QK⊤)P⊤P(QK^\top)P^\top. Row softmax permutes accordingly, giving:

F(PX)=PF(X).F(PX)=P F(X).

This is permutation equivariance: changing token order changes output order in the same way. It is not permutation invariance, which would leave the output unchanged. The operation can distinguish token contents but cannot obtain an absolute position merely from which array slot stores a row. Position encodings or other order-sensitive structure supply that information. D2L, Section 11.6.3

A fixed causal mask breaks arbitrary permutation symmetry because earlier and later positions have different permitted connections. During next-token training, causality must hold for the whole computation. A causal attention layer cannot undo leakage already introduced by a future-aware preprocessing or earlier layer. Targets must also be shifted correctly.

Change the future and test the past

The complete program uses one-dimensional identity projections to expose the mixing step. It verifies equivariance for unmasked attention. It then changes the final token from -1 to 100 and checks that earlier causal outputs remain unchanged. Every causal row includes its own key, so no row is fully masked.

import math

def scalar_self_attention(tokens, causal=False):
    if not tokens or any(not math.isfinite(x) for x in tokens):
        raise ValueError("nonempty finite scalar tokens required")
    outputs, matrix = [], []
    for i,q in enumerate(tokens):
        permitted = list(range(i+1 if causal else len(tokens)))
        scores = [q*tokens[j] for j in permitted]
        if not all(math.isfinite(s) for s in scores):
            raise ArithmeticError("nonfinite score")
        maximum = max(scores)
        raw = [math.exp(s-maximum) for s in scores]
        total = sum(raw)
        weights = [0.0]*len(tokens)
        for j,r in zip(permitted,raw):
            weights[j] = r/total
        outputs.append(sum(w*v for w,v in zip(weights,tokens)))
        matrix.append(weights)
    return outputs, matrix

x = [1.0,2.0,-1.0]
full, weights = scalar_self_attention(x)
permutation = [2,0,1]
reordered,_ = scalar_self_attention([x[j] for j in permutation])
assert all(abs(a-full[j]) < 1e-12 for a,j in zip(reordered,permutation))
causal, mask_weights = scalar_self_attention(x,True)
changed,_ = scalar_self_attention([1.0,2.0,100.0],True)
assert causal[:2] == changed[:2]
assert causal[0] == 1.0
assert all(row[j] == 0 for i,row in enumerate(mask_weights) for j in range(i+1,3))
assert all(math.isclose(sum(row),1) for row in weights+mask_weights)
assert abs(scalar_self_attention([1.0,2.0,100.0])[0][0]-full[0]) > 90
assert scalar_self_attention([3.0],True) == ([3.0],[[1.0]])

At the first causal position, only one value is allowed, so its weight is one and its output is exactly 1. The second position mixes only 1 and 2. The final position can mix all three. Unmasked attention instead lets every row access the changed final token.

Dense score computation costs O(n2dk)O(n^2d_k) and value mixing costs O(n2dv)O(n^2d_v), plus O(nd(dk+dv))O(nd(d_k+d_v)) projection work up to constant factors. Explicit weights use O(n2)O(n^2) memory. The scalar teaching program has O(n2)O(n^2) time and stored weights. Parallelizable within-layer work does not imply that autoregressive generation of unknown future tokens is fully parallel.

Connectivity is not a guarantee of reasoning

One unmasked layer provides a direct computational path between any pair of positions, but it may assign unhelpful weights or learn poor representations. Short paths alone do not prove reliable reasoning, long-context recall, or correct translation.

Padding masks and causal masks solve different problems. Padding marks nonexistent data; causality restricts future access. A source encoder may be bidirectional when its full input is available, while a target decoder remains causal. Confusing these roles can either leak answers or unnecessarily hide useful input.

Position encodings also do not automatically guarantee generalization to longer sequences. Their values, training lengths, attention computation, and task all matter. Multi-head projections, output mixing, residuals, normalization, and feed-forward blocks belong to a full Transformer; the identity-projection example is only a self-attention calculation.

Follow the information boundary

  1. Can the first causal row read the last token? Answer: no; only its own position is allowed in this indexing convention.
  2. Does self-attention require WQ=WK=WVW_Q=W_K=W_V? Answer: no. Their source sequence is shared, but their projections can differ.
  3. Is F(PX)=PF(X)F(PX)=PF(X) invariance or equivariance? Answer: equivariance, because the output is permuted too.
  4. If an earlier layer already mixed future tokens into every row, does adding a causal mask later remove that information? Answer: no. The earlier representations already contain it.

Efficiency changes should preserve a stated information pattern

Sparse patterns restrict which pairs interact. Blocked exact kernels change how permitted interactions are computed and stored. Approximate attention changes the computation itself. Evaluate memory, runtime, numerical agreement, and task behavior separately, and specify whether the method preserves the original dense attention result or intentionally changes it.

Make a prediction, then check

What does “self” mean in self-attention?

Choose one answer

Learning objectives

  • Derive permutation equivariance for unmasked self-attention without positional information.
  • Verify causality by modifying future tokens and distinguish projection roles and mask purposes.

Prerequisites & connections

Explore related knowledge →

References

  1. Attention Is All You Need
    Ashish Vaswani and coauthors · 2017
  2. Dive into Deep Learning — Self-Attention and Positional Encoding
    Aston Zhang; Zachary C. Lipton; Mu Li; Alexander J. Smola · 2023

Version1 · Editorial status: Recorded technical checks completed

View technical check record (AI)

Codex · 2026-09-05 · Codex technical check: cited-source comparison, re-derivation and recalculation, bilingual argument comparison, and executed Python assertions; no independent human peer review.

  • Derived equivariance without masks or positions; 30 random sequence permutations passed, and changing suffixes left causal-prefix outputs unchanged.
  • Executed singleton inputs, self access, zero future weights, and row normalization; distinguished equivariance/invariance, padding/causality, and within-layer parallelism/autoregressive generation.
  • Compared bilingual arguments, conditions, examples, and exercise answers; structural checks separately compare formulas, code, sections, and references. No independent human peer review.

Source locations checked:

Related topics

No matches. Try a synonym or acronym.

0 results shown

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