Attention mechanism

core 12 minarchitecturesattentiontransformers

Builds on:Forward passDot product, norms, and similarityEmbeddings

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.

Attention(Q,K,V)=softmax ⁣(QK⊤dk)V\mathrm{Attention}(Q, K, V) = \mathrm{softmax}\!\left( \frac{QK^\top}{\sqrt{d_k}} \right) V

Shapes (worth reciting in interviews): for nn queries against mm key-value pairs, Q∈Rn×dkQ \in \mathbb{R}^{n \times d_k}, K∈Rm×dkK \in \mathbb{R}^{m \times d_k}, V∈Rm×dvV \in \mathbb{R}^{m \times d_v}; scores QK⊤QK^\top are n×mn \times m; softmax is applied row-wise; output is n×dvn \times d_v. In self-attention, Q,K,VQ, K, V are three learned linear projections of the same sequence; in cross-attention the queries come from another sequence. Causal masking sets forbidden scores to −∞-\infty pre-softmax so their weights land at exactly 0.

Why the dk\sqrt{d_k}: with unit-variance components, q⋅kq \cdot k has variance dkd_k (a sum of dkd_k independent unit-variance products), so at dk=64d_k = 64 raw scores have standard deviation 8. Softmax over scores that spread is essentially argmax — near one-hot weights whose gradients p(1−p)p(1-p) 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 O(n2d)O(n^2 d) arithmetic and naively materializes an O(n2)O(n^2) 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, dk=2d_k = 2, so scale 2≈1.414\sqrt{2} \approx 1.414. Query and keys:

q=(1,0),k1=(1,0),k2=(0,1),k3=(−1,0)q = (1, 0), \qquad k_1 = (1, 0), \quad k_2 = (0, 1), \quad k_3 = (-1, 0)

with (scalar, for clarity) values v1=10v_1 = 10, v2=0v_2 = 0, v3=−10v_3 = -10.

PositionRaw score q⋅kq \cdot kScaled /2/\sqrt{2}escoree^{\text{score}}Weight
1110.7070.7072.0282.0280.5760.576
200001.0001.0000.2840.284
3−1-1−0.707-0.7070.4930.4930.1400.140

(Weights = each exponential over the sum 3.5213.521.) Output:

0.576⋅10+0.284⋅0+0.140⋅(−10)=5.76−1.40=4.360.576 \cdot 10 + 0.284 \cdot 0 + 0.140 \cdot (-10) = 5.76 - 1.40 = 4.36

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 dk=64d_k = 64 unscaled scores would spread with standard deviation 8 — take scores (8,0,−8)(8, 0, -8): weights ∝(e8,1,e−8)=(2981,1,0.000335)\propto (e^8, 1, e^{-8}) = (2981, 1, 0.000335), i.e. (0.99966,0.00034,0.0000001)(0.99966, 0.00034, 0.0000001). Effectively a hard, frozen argmax with vanishing gradients — after scaling by 64=8\sqrt{64} = 8 the scores become (1,0,−1)(1, 0, -1), right back in the soft regime above.

Cheat sheet

Formula: Attention(Q,K,V)=softmax ⁣(QK⊤/dk)V\mathrm{Attention}(Q,K,V) = \mathrm{softmax}\!\left(QK^\top / \sqrt{d_k}\right) V, softmax row-wise.

ObjectShapeMeaning
QQn×dkn \times d_kwhat each of nn tokens seeks
KKm×dkm \times d_kwhat each of mm tokens advertises
VVm×dvm \times d_vwhat each token contributes
QK⊤QK^\topn×mn \times mall pairwise relevance scores
outputn×dvn \times d_vper-token blended values