Self-attention
自注意力
Track information flow within a sequence, derive permutation equivariance, and verify that a causal mask blocks future tokens.
self-attentionEach 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 , while the second scores it as . 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 with positions and representation width , one head computes:
have shape ; has shape . The mask 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 permits columns , including itself. Vaswani et al., Sections 3.2.2–3.2.3
Consider unmasked attention without positional information. If permutes input rows, projected queries, keys, and values receive the same permutation. Its score matrix becomes . Row softmax permutes accordingly, giving:
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 and value mixing costs , plus projection work up to constant factors. Explicit weights use memory. The scalar teaching program has 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
- Can the first causal row read the last token? Answer: no; only its own position is allowed in this indexing convention.
- Does self-attention require ? Answer: no. Their source sequence is shared, but their projections can differ.
- Is invariance or equivariance? Answer: equivariance, because the output is permuted too.
- 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?
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
- Attention Is All You Need
Ashish Vaswani and coauthors · 2017 - 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:
- Attention Is All You Need · v7 §§3.2.3, 3.5, 4: same-sequence sources, causal masking, positional information and layer complexity
- Dive into Deep Learning — Self-Attention and Positional Encoding · §11.6.1–11.6.3: self-attention roles, computation, and positional encoding
Related topics