Attention from first principles¶
Attention is a differentiable dictionary lookup: every position asks a question, every position advertises an answer, and each position receives a blend of the others' contents weighted by how well they match. One equation — $\operatorname{softmax}(QK^\top/\sqrt{d_k})\,V$ — and almost every idea in modern AI runs through it.
10,000 ft
Before 2017, sequence models read text one step at a time (RNNs and LSTMs), squeezing everything they had seen into one fixed-size state. Attention replaced that bottleneck with direct, content-based access: any position can read any other in a single step, and all positions are computed in parallel, which is what made training on trillions of tokens on GPUs feasible. It is the core of the transformer block; it is repeated in parallel as multi-head attention; its cost, quadratic in sequence length, drives the whole field of KV caches and efficient attention and long context; and the same operation powers vision transformers, retrieval and cross-modal models. If you understand this page exactly, the rest of the track is assembly.
2,000 ft
For a sequence of \(n\) token vectors \(X \in \mathbb{R}^{n \times d}\):
- Project each token three ways: a query \(\mathbf{q}_i\) (what am I looking for?), a key \(\mathbf{k}_j\) (what do I contain?), a value \(\mathbf{v}_j\) (what do I hand over if chosen?). \(Q = XW_Q\), \(K = XW_K\), \(V = XW_V\).
- Score every query against every key with a dot product, scaled by \(1/\sqrt{d_k}\) to keep the numbers in a sensible range: \(S = QK^\top/\sqrt{d_k}\), an \(n \times n\) matrix.
- Mask the scores a position must not see (future tokens in a language model) by setting them to \(-\infty\).
- Normalise each row with softmax, so each query's weights are positive and sum to 1: \(A = \operatorname{softmax}(S)\).
- Mix: each output is the weighted average of the values, \(O = AV\).
Ground level¶
The problem attention solves¶
Consider "I sat on the river bank" and "I paid cash into the bank". The token bank gets the same embedding in both sentences — the embedding table is a lookup, blind to context. For the model to represent which bank, the vector at that position must be updated with information from other positions (river, cash). The question is how.
An RNN does it by passing a running state left to right. That has two costs. First, it is sequential: step \(t\) cannot start before step \(t-1\) finishes, so a GPU with thousands of cores sits mostly idle. Second, it is a bottleneck: in sequence-to-sequence translation, the whole source sentence had to be squeezed into one fixed-length vector before decoding. Bahdanau, Cho and Bengio conjectured that this fixed vector was the bottleneck and let the decoder instead look back over all encoder states, choosing a weighted combination at each output step (arXiv:1409.0473). That weighted look-back is attention. The 2017 transformer paper's move was to drop the recurrence entirely and build the whole network from attention plus per-position feed-forward layers (Vaswani et al., arXiv:1706.03762).
A soft dictionary lookup¶
A Python dictionary maps a query to exactly one stored value: if the query equals a key, return its value. That operation has no gradient — "equals" is either true or false.
Attention makes every piece continuous:
| Hard lookup | Attention |
|---|---|
| query equals key? (0 or 1) | similarity score \(\mathbf{q}\cdot\mathbf{k}_j\) (any real number) |
| return the one matching value | return \(\sum_j a_j \mathbf{v}_j\) |
| weights are one-hot | weights \(a_j = \operatorname{softmax}(\text{scores})_j\), positive, summing to 1 |
If one score is far larger than the rest, softmax is nearly one-hot and attention is a hard lookup. If all scores are equal, attention returns the plain average of the values. Everything in between is a learnable, differentiable blend — so gradient descent can learn what to look for and what to advertise.
bank's query matches the two nature-bearing keys, so its output is 89% "nature" — the bar widths are the softmax weights.Queries, keys and values: why three roles¶
Why not just compare token vectors with each other, \(\operatorname{softmax}(XX^\top)X\)? Two reasons, both visible in that formula.
- The relation would be symmetric. \(\mathbf{x}_i \cdot \mathbf{x}_j = \mathbf{x}_j \cdot \mathbf{x}_i\), but relations in language are not: an adjective looks for its noun; the noun is not looking for the adjective in the same way. With separate projections the score is \(\mathbf{x}_i^\top W_Q W_K^\top \mathbf{x}_j\), a general bilinear form that need not be symmetric.
- Every token would mostly attend to itself. \(\mathbf{x}_i\cdot\mathbf{x}_i = \lVert\mathbf{x}_i\rVert^2\) is usually the largest dot product in its row (by Cauchy–Schwarz it beats any vector of the same norm). Learned \(W_Q, W_K\) let the model look elsewhere.
And the value is separate from the key because what makes a token findable is not the same as what it should contribute. A determiner might be found because of its position but contribute nothing; a name might be found by its type ("person") but contribute its identity.
A worked example: which bank?¶
Give each token a 4-dimensional embedding with readable features — [noun, nature, finance, ambiguous]:
| token | noun | nature | finance | ambiguous |
|---|---|---|---|---|
| river | 1 | 1 | 0 | 0 |
| bank | 1 | 0 | 0 | 1 |
| was | 0 | 0 | 0 | 0 |
| muddy | 0 | 1 | 0 | 0 |
Use \(d_k = 2\) and hand-set projections:
- \(W_Q\) maps only the ambiguous feature to the query \([3, 3]\): an ambiguous word asks "is anyone here about nature, or about finance?"; every other word asks nothing (\(\mathbf{q} = \mathbf{0}\)).
- \(W_K\) maps (nature, finance) to the key: words advertise the senses they carry.
- \(W_V = W_K\): the value is the sense itself.
Then for bank, \(\mathbf{q} = [3,3]\), and the scaled scores against (river, bank, was, muddy) are \(\frac{1}{\sqrt 2}[3, 0, 0, 3] = [2.121, 0, 0, 2.121]\). Softmax: \(e^{2.121} = 8.34\), so the weights are \(8.34 / (8.34 + 1 + 1 + 8.34) = 0.446\) for river and muddy and \(1/18.68 = 0.054\) for the others. The output is \(0.446\,[1,0] + 0.446\,[1, 0] = [0.893, 0]\) — mostly nature, no finance. Swap river for money and the same computation gives \([0.446, 0.446]\): the ambiguity is now honestly represented as a blend.
Running it (the second snippet in Build it) prints:
scores S =
[[0. 0. 0. 0. ]
[2.121 0. 0. 2.121]
[0. 0. 0. 0. ]
[0. 0. 0. 0. ]]
weights A =
[[0.25 0.25 0.25 0.25 ]
[0.446 0.054 0.054 0.446]
[0.25 0.25 0.25 0.25 ]
[0.25 0.25 0.25 0.25 ]]
outputs A@V =
[[0.5 0. ]
[0.893 0. ]
[0.5 0. ]
[0.5 0. ]]
bank's output with 'money' instead of 'river': [0.446 0.446]
Notice rows 1, 3 and 4: a zero query produces uniform weights, so those tokens receive the plain average of all values. A head that "has nothing to ask" still writes something; real models learn to park such attention on a harmless token (the "attention sink" effect, Xiao et al., arXiv:2309.17453).
From scores to weights: softmax¶
Softmax turns a vector of real scores \(\mathbf{s}\) into a probability distribution, \(a_j = e^{s_j} / \sum_\ell e^{s_\ell}\). Three properties matter for attention:
- Shift-invariant: adding a constant to every score changes nothing. (This is why the code subtracts the row maximum before exponentiating: same answer, no overflow — see floating point and log-sum-exp.)
- Scale-sensitive: multiplying the scores by \(\beta\) sharpens (\(\beta > 1\)) or flattens (\(\beta < 1\)) the distribution. As \(\beta \to \infty\) it becomes argmax — hard lookup.
- Never exactly zero: every allowed position gets some weight, which keeps gradients flowing to all of them.
Why divide by √d_k¶
Suppose the components of \(\mathbf{q}\) and \(\mathbf{k}\) are independent with mean 0 and variance 1 (roughly what a well-initialised network produces). The dot product \(\mathbf{q}\cdot\mathbf{k} = \sum_{i=1}^{d_k} q_i k_i\) then has mean 0 and variance \(d_k\) (derived in The maths). With \(d_k = 64\) the scores have standard deviation 8; with \(d_k = 512\), about 22.6. Softmax of numbers that spread out is nearly one-hot — and a nearly one-hot softmax has nearly zero gradient. The transformer paper states it plainly: "for large values of \(d_k\), the dot products grow large in magnitude, pushing the softmax function into regions where it has extremely small gradients" (§3.2.1). Dividing by \(\sqrt{d_k}\) restores unit variance at any width.
Measured on 10,000 random queries, each against 16 random keys (real output of the snippet below):
import numpy as np
rng = np.random.default_rng(0)
def softmax(z):
e = np.exp(z - z.max(-1, keepdims=True)); return e / e.sum(-1, keepdims=True)
n = 16 # keys per query
for d in (4, 64, 512):
q = rng.standard_normal((10_000, d)) # unit-variance components
k = rng.standard_normal((10_000, n, d))
s = np.einsum("bd,bnd->bn", q, k) # raw dot products
for name, z in (("raw ", s), ("scaled", s / np.sqrt(d))):
p = softmax(z)
H = -(p * np.log(p + 1e-30)).sum(-1).mean() # entropy in nats; max is ln 16 = 2.773
# Jacobian of softmax is diag(p) - p p^T; its size tells us how much gradient flows
J = np.einsum("bi,ij->bij", p, np.eye(n)) - np.einsum("bi,bj->bij", p, p)
g = np.linalg.norm(J, axis=(1, 2)).mean()
print(f"d={d:3d} {name} std(score)={z.std():6.2f} max weight={p.max(-1).mean():.3f}"
f" entropy={H:.3f} |dsoftmax|={g:.4f}")
d= 4 raw std(score)= 2.01 max weight=0.428 entropy=1.762 |dsoftmax|=0.3222
d= 4 scaled std(score)= 1.00 max weight=0.236 entropy=2.378 |dsoftmax|=0.2974
d= 64 raw std(score)= 8.00 max weight=0.846 entropy=0.404 |dsoftmax|=0.1753
d= 64 scaled std(score)= 1.00 max weight=0.247 entropy=2.357 |dsoftmax|=0.3047
d=512 raw std(score)= 22.66 max weight=0.947 entropy=0.131 |dsoftmax|=0.0709
d=512 scaled std(score)= 1.00 max weight=0.248 entropy=2.355 |dsoftmax|=0.3055
Without scaling, at \(d_k = 512\) the average query puts 95% of its weight on one key at initialisation, before learning anything, and the softmax Jacobian is 4.3× smaller than with scaling. With scaling, the statistics are identical at every width: the network starts in the same well-conditioned regime whatever \(d_k\) you pick.
√d_k is an initialisation argument, not a law
Once training starts, \(\mathbf{q}\) and \(\mathbf{k}\) are no longer independent unit-variance vectors; the model can and does learn large scores when it wants sharp attention. The scale factor fixes the starting point. In very large models the logits can still grow out of control during training, which is why some recipes also normalise queries and keys ("QK-norm", used for stability in Dehghani et al., arXiv:2302.05442).
Masks: what a position may see¶
A language model is trained to predict token \(t+1\) from tokens \(1..t\). If position \(t\) could attend to position \(t+1\), it would simply copy the answer. The causal mask sets \(S_{ij} = -\infty\) for \(j > i\); since \(e^{-\infty} = 0\), those weights vanish and each row's softmax is taken over the allowed positions only. The weight matrix becomes lower-triangular:
weights (row = query):
[[1. 0. 0. 0. 0. ]
[0.612 0.388 0. 0. 0. ]
[0.301 0.399 0.3 0. 0. ]
[0.27 0.268 0.239 0.223 0. ]
[0.144 0.294 0.171 0.283 0.109]]
Row 1 must put all its weight on itself — it has nothing else to see. Masking is what lets one forward pass over a length-\(n\) sequence produce \(n\) training examples at once (predict token 2 from 1, token 3 from 1–2, …), which is a large part of why transformers train so efficiently. A padding mask works the same way, removing pad tokens in a batch of unequal-length sequences; Llama 3 also masks attention between different documents packed into one training sequence (Llama 3 paper, §3.2).
Self-attention and cross-attention¶
In self-attention, \(Q\), \(K\) and \(V\) all come from the same sequence. In cross-attention, queries come from one sequence and keys/values from another: in the original encoder–decoder transformer, the decoder's queries attend over the encoder's outputs (this is Bahdanau's mechanism, rebuilt); in vision-language models and diffusion models, text or image tokens attend to the other modality. Nothing in the equation changes — only where the rows come from. \(Q\) has shape \(n_q \times d_k\), \(K\) and \(V\) have \(n_k\) rows, and \(A\) is \(n_q \times n_k\).
Attention sees a set, not a sequence¶
Shuffle the input tokens of unmasked self-attention and the outputs are shuffled in exactly the same way — nothing else changes (the snippet in Build it checks this). Attention is permutation-equivariant: it has no idea of order. "Dog bites man" and "man bites dog" contain the same set of tokens. Order has to be injected separately, which is the whole subject of positional encoding. (The causal mask does break the symmetry a little — a position can count how many tokens it sees — and models without any positional encoding can exploit that; see that page.)
What it costs¶
For a sequence of length \(n\) and key width \(d\), the score matrix \(QK^\top\) has \(n^2\) entries, each a \(d\)-term dot product: about \(2n^2d\) FLOPs, and the same again for \(AV\). Memory for the scores is \(n^2\) per head. The transformer paper's Table 1 compares layer types:
| Layer | Work per layer | Sequential steps | Longest path between two positions |
|---|---|---|---|
| Self-attention | \(O(n^2 \cdot d)\) | \(O(1)\) | \(O(1)\) |
| Recurrent | \(O(n \cdot d^2)\) | \(O(n)\) | \(O(n)\) |
| Convolutional (kernel \(k\)) | \(O(k \cdot n \cdot d^2)\) | \(O(1)\) | \(O(\log_k n)\) |
Attention wins on the two columns that matter for learning and hardware: everything is parallel, and any two tokens are one step apart, so gradients don't have to survive a long chain. It loses on the first column once \(n > d\). Concretely, at \(n = 8{,}192\) tokens one head's score matrix in 16-bit floats is \(8192^2 \times 2\) bytes \(= 128\) MiB; with 32 heads, 4 GiB per layer if you materialise it. FlashAttention computes exactly the same result without ever materialising \(S\), by tiling the computation through on-chip memory (Dao et al., arXiv:2205.14135) — see KV cache and efficient attention.
History¶
From alignment in translation to the whole network
1964 — Nadaraya and Watson independently propose kernel regression: predict at a query point by a similarity-weighted average of training targets. It is attention with a fixed similarity function. 2013 — Alex Graves uses a soft, differentiable window over the input text to let an RNN generate handwriting (arXiv:1308.0850); in 2014 Neural Turing Machines add content-based read/write addressing to an external memory (arXiv:1410.5401). 2014 — Bahdanau, Cho and Bengio introduce attention for translation with an additive score, \(\mathbf{w}^\top \tanh(W\mathbf{s} + U\mathbf{h})\) (arXiv:1409.0473). 2015 — Luong, Pham and Manning compare dot-product, "general" bilinear and concatenation scores (arXiv:1508.04025). 2017 — Vaswani et al. scale the dot product by \(1/\sqrt{d_k}\), run it in parallel heads, and remove recurrence (arXiv:1706.03762). The authors note that additive and dot-product attention have similar theoretical cost, but dot-product attention "is much faster and more space-efficient in practice, since it can be implemented using highly optimized matrix multiplication code" — an argument from hardware, not theory, and the reason it won.
First principles¶
Derive attention from what we need, adding one assumption at a time.
1. Each position needs a context-dependent update built from the other positions. The update for position \(i\) is some function \(f(\mathbf{x}_i; \mathbf{x}_1,\dots,\mathbf{x}_n)\).
2. It must handle any \(n\) and treat the other positions as a collection (order comes from elsewhere). The simplest such function is a weighted sum of per-position contributions, \(\sum_j a_{ij}\,\mathbf{v}_j\) with \(\mathbf{v}_j = g(\mathbf{x}_j)\). Any number of terms, and permuting \(j\) just permutes the terms.
3. The weights must depend on content — on both the asker \(i\) and the candidate \(j\) — and we want the output to stay on the same scale whatever \(n\) is. So make the weights positive and normalised: \(a_{ij} = \kappa(\mathbf{x}_i, \mathbf{x}_j) / \sum_\ell \kappa(\mathbf{x}_i, \mathbf{x}_\ell)\) for some positive similarity kernel \(\kappa\). This is exactly the Nadaraya–Watson kernel smoother.
4. The kernel must be learnable, cheap and expressive. Choose \(\kappa(\mathbf{x}_i, \mathbf{x}_j) = \exp(\mathbf{q}_i \cdot \mathbf{k}_j / \tau)\) with learned linear maps \(\mathbf{q} = W_Q^\top\mathbf{x}\), \(\mathbf{k} = W_K^\top\mathbf{x}\):
- the exponential makes every weight positive and turns score differences into weight ratios (\(a_{ij}/a_{i\ell} = e^{(s_{ij} - s_{i\ell})}\)) — a natural, scale-free comparison;
- among all distributions with a given expected score, the softmax distribution has maximum entropy — it commits to nothing beyond what the scores say;
- the dot product of linear projections is one matrix multiplication for all pairs at once, which hardware does at peak speed.
5. Pick \(\tau\) so the scores have unit variance at initialisation: \(\tau = \sqrt{d_k}\).
Every piece of the formula is forced by a reason. Change one and something specific breaks: drop the normalisation and outputs scale with \(n\); use the raw dot product without projections and attention becomes symmetric and self-obsessed; drop the \(\sqrt{d_k}\) and wide models start saturated; replace softmax with a hard argmax and gradients vanish.
Three ways to see the same equation
Retrieval: a differentiable key–value store queried by content. Kernel smoothing: a Nadaraya–Watson estimator with a learned exponential kernel (d2l.ai, ch. 11; Tsai et al., arXiv:1908.11775). Associative memory: one update step of a modern continuous Hopfield network, which retrieves the stored pattern nearest a query (Ramsauer et al., arXiv:2008.02217). Drop the softmax and attention becomes a linear memory that can be updated one token at a time — the bridge to linear attention and state-space models (Katharopoulos et al., arXiv:2006.16236; Schlag et al., arXiv:2102.11174).
The maths¶
Shapes. Input \(X \in \mathbb{R}^{n \times d_\text{model}}\) (one row per token). Parameters \(W_Q, W_K \in \mathbb{R}^{d_\text{model} \times d_k}\), \(W_V \in \mathbb{R}^{d_\text{model} \times d_v}\). Then
where the mask \(M_{ij} = 0\) if position \(i\) may attend to \(j\) and \(-\infty\) otherwise (causal: \(M_{ij} = -\infty\) for \(j > i\)). Row-wise softmax: \(A_{ij} = e^{S_{ij}} / \sum_\ell e^{S_{i\ell}}\). In a batch with \(B\) sequences and \(h\) heads the tensors gain leading axes: \(Q \in \mathbb{R}^{B \times h \times n \times d_k}\), \(A \in \mathbb{R}^{B \times h \times n \times n}\).
Written per query, the output for position \(i\) is
Derivation: the dot product of random vectors has variance d_k
Let \(q_i, k_i\) (\(i = 1..d_k\)) be independent with \(\mathbb{E}[q_i] = \mathbb{E}[k_i] = 0\) and \(\operatorname{Var}(q_i) = \operatorname{Var}(k_i) = 1\). Each term \(q_ik_i\) has mean \(\mathbb{E}[q_i]\mathbb{E}[k_i] = 0\) and variance
The \(d_k\) terms are independent, so variances add: \(\operatorname{Var}(\mathbf{q}\cdot\mathbf{k}) = d_k\), standard deviation \(\sqrt{d_k}\). Therefore \(\operatorname{Var}(\mathbf{q}\cdot\mathbf{k}/\sqrt{d_k}) = d_k / d_k = 1\). This is the paper's footnote 4, with the one-line step filled in.
Derivation: the softmax Jacobian, and why saturation kills gradients
For \(\mathbf{a} = \operatorname{softmax}(\mathbf{s})\), \(a_j = e^{s_j}/Z\) with \(Z = \sum_\ell e^{s_\ell}\). Differentiate:
If \(\mathbf{a}\) is nearly one-hot, \(\mathbf{a} \approx \mathbf{e}_r\), then \(J \approx \operatorname{diag}(\mathbf{e}_r) - \mathbf{e}_r\mathbf{e}_r^\top = 0\). Every entry of \(J\) is bounded by \(a_j(1 - a_j)\) on the diagonal and \(a_ja_m\) off it, all of which go to zero as one weight goes to 1. No gradient reaches the scores, so \(W_Q\) and \(W_K\) stop learning. This is what the \(\sqrt{d_k}\) prevents at initialisation.
Derivation: the backward pass of attention
Let the loss be \(L\) and write \(\bar{Y} = \partial L/\partial Y\). Given \(\bar O\) (shape \(n \times d_v\)), use \(O = AV\), \(A = \operatorname{softmax}(S)\), \(S = QK^\top/\sqrt{d_k}\):
Through the row-wise softmax, using the Jacobian above row by row (\(\bar{\mathbf{s}}_i = J_i^\top \bar{\mathbf{a}}_i\) with \(J_i\) symmetric):
Masked entries have \(A_{ij} = 0\), so they receive no gradient automatically. Finally
and the gradients flow on to the weights by \(\bar W_Q = X^\top \bar Q\) (and likewise for \(W_K\), \(W_V\)). The code below checks \(\bar K\) against finite differences to ten decimal places. FlashAttention's backward pass is these same equations, recomputing \(A\) tile by tile instead of storing it.
FLOPs. Projections: \(3 \cdot 2 n\, d_\text{model} d_k\) (taking \(d_v = d_k\)). Scores: \(2n^2 d_k\). Weighted sum: \(2n^2 d_k\). Softmax: \(O(n^2)\). For a causal model roughly half the score matrix is masked, which optimised kernels skip.
Permutation equivariance. For a permutation matrix \(P\), unmasked attention satisfies \(\operatorname{Attn}(PX) = P\operatorname{Attn}(X)\), because \((PQ)(PK)^\top = P(QK^\top)P^\top\), row-wise softmax commutes with permuting rows and columns together, and \(P A P^\top P V = P A V\) (using \(P^\top P = I\)).
Build it¶
Causal scaled dot-product attention in NumPy, its backward pass, and checks of the properties this page claims. NumPy 2, runs in a fraction of a second.
import numpy as np
rng = np.random.default_rng(42)
def softmax(z):
z = z - z.max(-1, keepdims=True); e = np.exp(z); return e / e.sum(-1, keepdims=True)
def attention(Q, K, V, causal=True):
"""Q: (T_q, d_k) K: (T_k, d_k) V: (T_k, d_v) -> out (T_q, d_v), weights (T_q, T_k)"""
S = Q @ K.T / np.sqrt(Q.shape[-1])
if causal: # position i may only see j <= i
S = np.where(np.tril(np.ones(S.shape, bool)), S, -np.inf)
P = softmax(S)
return P @ V, P
def attention_backward(Q, K, V, P, dO):
"""Gradients of a scalar loss given dL/dO, for the formulas derived on this page."""
dV = P.T @ dO
dP = dO @ V.T
dS = P * (dP - (dP * P).sum(-1, keepdims=True)) # softmax Jacobian, row by row
dQ = dS @ K / np.sqrt(Q.shape[-1])
dK = dS.T @ Q / np.sqrt(Q.shape[-1])
return dQ, dK, dV
T, d_model, d_k = 5, 8, 4
X = rng.standard_normal((T, d_model))
W_Q, W_K, W_V = (rng.standard_normal((d_model, d_k)) / np.sqrt(d_model) for _ in range(3))
Q, K, V = X @ W_Q, X @ W_K, X @ W_V
O, P = attention(Q, K, V)
print("weights (row = query):\n", P.round(3))
print("rows sum to 1:", np.allclose(P.sum(-1), 1), "| upper triangle zero:", np.allclose(np.triu(P, 1), 0))
# Permutation equivariance (no mask): shuffling tokens shuffles outputs the same way
perm = rng.permutation(T)
O_full, _ = attention(Q, K, V, causal=False)
O_perm, _ = attention(Q[perm], K[perm], V[perm], causal=False)
print("permutation-equivariant:", np.allclose(O_perm, O_full[perm]))
# Check the analytic backward pass against finite differences, loss = sum(O * G)
G = rng.standard_normal(O.shape)
dQ, dK, dV = attention_backward(Q, K, V, P, G)
def loss(Q_, K_, V_): return (attention(Q_, K_, V_)[0] * G).sum()
eps, num = 1e-6, np.zeros_like(K)
for idx in np.ndindex(K.shape):
Kp, Km = K.copy(), K.copy(); Kp[idx] += eps; Km[idx] -= eps
num[idx] = (loss(Q, Kp, V) - loss(Q, Km, V)) / (2 * eps)
print("max |dK analytic - numeric| =", np.abs(dK - num).max())
weights (row = query):
[[1. 0. 0. 0. 0. ]
[0.612 0.388 0. 0. 0. ]
[0.301 0.399 0.3 0. 0. ]
[0.27 0.268 0.239 0.223 0. ]
[0.144 0.294 0.171 0.283 0.109]]
rows sum to 1: True | upper triangle zero: True
permutation-equivariant: True
max |dK analytic - numeric| = 4.3966153634444893e-10
The worked "bank" example is the same softmax with hand-set weights:
import numpy as np
np.set_printoptions(precision=3, suppress=True)
def softmax(z, axis=-1):
z = z - z.max(axis=axis, keepdims=True) # stability: softmax is shift-invariant
e = np.exp(z)
return e / e.sum(axis=axis, keepdims=True)
# noun nature finance ambiguous
X = np.array([[1, 1, 0, 0], # river
[1, 0, 0, 1], # bank
[0, 0, 0, 0], # was
[0, 1, 0, 0]], # muddy
dtype=float)
W_Q = np.array([[0, 0], [0, 0], [0, 0], [3, 3]], float) # only an ambiguous word asks a question
W_K = np.array([[0, 0], [1, 0], [0, 1], [0, 0]], float) # keys advertise: nature?, finance?
W_V = np.array([[0, 0], [1, 0], [0, 1], [0, 0]], float) # values carry the sense itself
Q, K, V = X @ W_Q, X @ W_K, X @ W_V
S = Q @ K.T / np.sqrt(K.shape[1])
A = softmax(S)
print("scores S =\n", S)
print("weights A =\n", A)
print("outputs A@V =\n", A @ V)
X2 = X.copy(); X2[0] = [1, 0, 1, 0] # 'river' -> 'money'
A2 = softmax((X2 @ W_Q) @ (X2 @ W_K).T / np.sqrt(2))
print("bank's output with 'money' instead of 'river':", A2[1] @ (X2 @ W_V))
Its output is printed in the worked example above.
In PyTorch (2.0 or later) the whole forward pass is one call, which dispatches to a fused FlashAttention-style kernel when it can:
import torch.nn.functional as F
out = F.scaled_dot_product_attention(q, k, v, is_causal=True) # q, k, v: (B, heads, T, d_k)
Things to try
- Remove the
/ np.sqrt(...)inattention, setd_k = 512, and print the rows ofP: count how many rows have a weight above 0.9. - Set
d_k = d_modeland replace the learned projections with \(W_Q = W_K = I\); check that each row's largest weight is on the diagonal for randomX(unmasked). - Extend the gradient check to
dQanddV. - In the "bank" example, change the 3s in
W_Qto 10 and to 0.3. What happens tobank's output, and why? - Implement cross-attention: queries from a 3-token
Y, keys and values from the 5-tokenX. What are the shapes ofSandO?
Common misconceptions¶
Attention weights are not explanations
It is tempting to read a heat map and say "the model used this word". But values are transformed before and after attention, residual connections bypass it, many heads and layers interact, and Jain and Wallace showed attention distributions can often be swapped for very different ones without changing predictions (arXiv:1902.10186; with a rebuttal on what can be inferred in Wiegreffe and Pinter, arXiv:1908.04626). Attribution needs the tools of mechanistic interpretability.
Quadratic compute does not mean quadratic memory
The \(n \times n\) score matrix is a mathematical object, not something you must store. Tiled kernels compute exact attention in memory linear in \(n\); the \(n^2\) arithmetic remains.
Q, K and V are not three inputs
In self-attention there is one input, \(X\). "Query", "key" and "value" are three learned views of it. They only become separate sources in cross-attention or when reading keys and values from a cache.
Check yourself¶
Why does attention need a softmax rather than raw scores as weights?
Raw scores can be negative and don't sum to anything fixed, so the output's scale would grow with sequence length and with the magnitude of the scores. Softmax makes the weights a probability distribution: positive, summing to 1, so the output is a convex combination of values and stays on the values' scale. It is also smooth, so gradients reach every score.
A query vector is all zeros. What does that position's attention output?
Every score is 0, so softmax gives uniform weights over the allowed positions and the output is the mean of their values (rows 1, 3 and 4 of the worked example).
Show that without the scale factor, the score variance is d_k. What std do you get for d_k = 128?
For independent unit-variance zero-mean components, \(\operatorname{Var}(\sum q_ik_i) = \sum \operatorname{Var}(q_ik_i) = d_k\). For \(d_k = 128\), the standard deviation is \(\sqrt{128} \approx 11.3\).
Why is a causal mask applied before the softmax and not by zeroing weights after it?
Zeroing after softmax would leave the remaining weights summing to less than 1 and would let the forbidden scores influence the normaliser \(Z\) — information about future tokens would leak through the denominator. Setting scores to \(-\infty\) before softmax removes them from both numerator and denominator.
What is the shape of the attention matrix in cross-attention from a 10-token decoder input to a 300-token encoder output?
\(10 \times 300\): one row per query (decoder position), one column per key (encoder position). The output has 10 rows.
Why did dot-product attention beat additive attention in practice when their theoretical cost is similar?
Dot-product attention for all query–key pairs is a single matrix multiplication, \(QK^\top\), which GPUs and TPUs execute at peak throughput; additive attention needs a small network evaluated per pair. The transformer paper made exactly this argument.
Hard: self-attention is permutation-equivariant. Is a causal (masked) self-attention layer also permutation-equivariant?
No. The mask itself depends on order: position \(i\) attends to the first \(i\) positions. Permuting the input changes which tokens each position can see, so the output is not just a permutation of the original output. This is the asymmetry that lets models with no positional encoding still infer position (e.g. position 1 always attends only to itself).
Hard: in the backward pass, why do masked positions automatically receive zero gradient?
\(\bar S_{ij} = A_{ij}(\bar A_{ij} - \sum_\ell \bar A_{i\ell}A_{i\ell})\), and masked positions have \(A_{ij} = 0\) exactly, so \(\bar S_{ij} = 0\). Nothing flows to the keys of future tokens from those entries.
Go deeper¶
Papers
- Attention Is All You Need — Vaswani et al., 2017. Read §3.2 (attention) and §4 with Table 1 (why self-attention); footnote 4 is the √d_k argument.
- Neural Machine Translation by Jointly Learning to Align and Translate — Bahdanau, Cho, Bengio, 2014. Where attention was introduced; the alignment figures are still the clearest intuition.
- Effective Approaches to Attention-based Neural Machine Translation — Luong, Pham, Manning, 2015. The dot-product family of scores.
- Formal Algorithms for Transformers — Phuong & Hutter, 2022. Pseudocode for every variant with exact shapes; the reference to check your understanding against.
- Hopfield Networks is All You Need — Ramsauer et al., 2020. Attention as associative memory retrieval.
- FlashAttention — Dao et al., 2022. Exact attention without the n² memory; read §3.1 after this page.
Videos and lectures
- Attention in transformers, step-by-step — 3Blue1Brown, Deep Learning chapter 6. The best visual intuition for queries, keys and values.
- Let's build GPT: from scratch, in code, spelled out — Andrej Karpathy. Self-attention is derived from "averaging the past" with a lower-triangular matrix-multiply trick, then made data-dependent.
- Stanford CS224N, Lecture 9: Self-Attention and Transformers — John Hewitt, 2021. A rigorous lecture-length treatment.
Articles and blog posts
- The Illustrated Transformer — Jay Alammar. The canonical picture-by-picture walkthrough.
- Attention? Attention! — Lilian Weng, 2018. A survey of the attention family before and after transformers.
-
Understanding and Coding Self-Attention, Multi-Head Attention, Causal-Attention, and Cross-Attention — Sebastian Raschka. Every variant in PyTorch.
-
Transformer Explainer — Georgia Tech Polo Club. Interactive GPT-2 in the browser: watch the attention matrices for your own prompt.
Courses and books
-
Dive into Deep Learning, ch. 11 — Zhang, Lipton, Li, Smola. Builds attention up from Nadaraya–Watson kernel regression, with runnable code. Code
-
The Annotated Transformer — Harvard NLP. The paper, line by line, as runnable PyTorch.
-
karpathy/nanoGPT —
model.py'sCausalSelfAttentionis the 30-line production version of this page.
Where this leads¶
- Multi-head attention — run several attentions in parallel, each in its own subspace, and why that is strictly more expressive than one.
- Positional encoding — attention is blind to order; this is how order is put back.
- The transformer block — attention plus an MLP, residuals and normalisation: the unit that is stacked 32–126 times.
- KV cache, FlashAttention, MQA/GQA/MLA — making the \(n^2\) affordable at inference and training time.
- Beyond transformers — what happens when you remove the softmax and make attention linear.