The idea
A fixed weight matrix mixes inputs the same way for every example. Attention computes its mixing weights from the data, per token — the network decides at runtime which positions to read and how much. The metaphor that survives contact with the math is a soft dictionary lookup: each token emits a query ("what I am looking for"), each token offers a key ("what I contain") and a value ("what I will contribute"). Match strength = dot product of query and key; the returned result is not the single best match but a softmax-weighted blend of all values.
Shapes (worth reciting in interviews): for queries against key-value pairs, , , ; scores are ; softmax is applied row-wise; output is . In self-attention, are three learned linear projections of the same sequence; in cross-attention the queries come from another sequence. Causal masking sets forbidden scores to pre-softmax so their weights land at exactly 0.
Why the : with unit-variance components, has variance (a sum of independent unit-variance products), so at raw scores have standard deviation 8. Softmax over scores that spread is essentially argmax — near one-hot weights whose gradients round to zero — and the attention pattern stops learning. The scaling holds the score distribution at unit variance for any head size.
Cost: standard self-attention performs arithmetic and naively materializes an score matrix per head. FlashAttention avoids that materialization and reduces memory traffic while retaining quadratic arithmetic; KV caching avoids recomputing old keys and values during autoregressive inference. Sparse or linear variants change the computation.
Worked example
One query attending over three positions, , so scale . Query and keys:
with (scalar, for clarity) values , , .
| Position | Raw score | Scaled | Weight | |
|---|---|---|---|---|
| 1 | ||||
| 2 | ||||
| 3 |
(Weights = each exponential over the sum .) Output:
The aligned key dominates but does not monopolize — position 3, pointing opposite the query, still contributes a little negative value. That softness is the point: gradients flow to every projection, so all three roles keep learning.
Now watch saturation, the thing scaling prevents. At unscaled scores would spread with standard deviation 8 — take scores : weights , i.e. . Effectively a hard, frozen argmax with vanishing gradients — after scaling by the scores become , right back in the soft regime above.
Cheat sheet
Formula: , softmax row-wise.
| Object | Shape | Meaning |
|---|---|---|
| what each of tokens seeks | ||
| what each of tokens advertises | ||
| what each token contributes | ||
| all pairwise relevance scores | ||
| output | per-token blended values |
- Scaling derivation in one line: unit-variance components → → divide by to restore unit variance → softmax stays soft, gradients survive.
- Causal mask: scores at set to pre-softmax → exact zero weights.
- Self vs cross: same sequence for Q/K/V vs queries from elsewhere (decoder → encoder, query → retrieved docs).
- Complexity: time, score memory; doubling context 4x-es attention compute.
- KV cache: at generation, reuse cached K, V; only the new token is projected → per step. Cache K and V, never Q. Memory = layers × heads × context × head-dim × 2 × bytes.
- Attention is permutation-equivariant — order information must be injected separately (positional encodings).
- Gotcha: softmax is over the key dimension (each query row sums to 1), not over queries.
- Gotcha: "attention weights = explanation" is contested — treat attention maps as diagnostics, not proof.