Contents

Deep Dive / /6 min

What Attention Actually Computes

Contents
  1. Queries, keys, and values
  2. The score, and why dk\sqrt${d_k}dk​​
  3. Softmax into weights
  4. The weighted sum of values
  5. Self-attention and the global receptive field
  6. Multi-head attention
  7. Why it replaced recurrence
  8. Further reading
Plate V MNIST Network Drive the instrument →

Imagine a Python dictionary d where you write d[k] and get back the one value stored under the exact key k. The lookup is brutally discrete: ask for a key that is even slightly off and you get nothing. Now soften it. Instead of demanding an exact match, score how well your request resembles every stored key, turn those scores into a probability distribution, and return a blend of all the values weighted by that distribution. You no longer retrieve one value; you retrieve a consensus of values, dominated by the entries whose keys most resemble your request. That soft, differentiable lookup is, almost exactly, what attention computes. The rest is bookkeeping about where the queries, keys, and values come from.

This essay unpacks the single line of algebra at the heart of modern sequence models and shows why it displaced the recurrent networks that preceded it. The nearest live network on this site is Plate V — the MNIST network; attention is the mechanism that lets a network of that kind look sideways at the rest of its input rather than only forward through its layers.

Queries, keys, and values

Suppose we have a sequence of nn tokens, each already turned into a vector by an embedding and earlier layers. Stack them as rows of a matrix XRn×dX \in \mathbb{R}^{n \times d}. From XX we manufacture three different views by three learned linear maps:

Q=XWQ,K=XWK,V=XWV.Q = X W_Q, \qquad K = X W_K, \qquad V = X W_V.

A query qiq_i (row ii of QQ) encodes what position ii is looking for. A key kjk_j encodes what position jj offers as a handle for being found. A value vjv_j encodes the content position jj will actually hand over if attended to.The query/key split is what lets a position advertise itself one way (“I am a verb”) while being retrieved on another (“looking for a subject”). Tying them would collapse this flexibility. These three roles are deliberately decoupled: the criterion by which a position is matched is separate from the content it contributes.

The score, and why dk\sqrt{d_k}

To measure how well query ii matches key jj, take their dot product qikjq_i \cdot k_j. Large when the two vectors point the same way, near zero when orthogonal. Collecting all pairs at once gives the score matrix QKRn×nQK^\top \in \mathbb{R}^{n \times n}, whose (i,j)(i,j) entry is exactly qikjq_i \cdot k_j. These raw scores are the logits of the attention distribution.

Before normalizing, we divide by dk\sqrt{d_k}, where dkd_k is the dimension of the keys and queries. The reason is statistical. If the entries of qiq_i and kjk_j are independent with mean zero and variance one, then qikj=m=1dkqimkjmq_i \cdot k_j = \sum_{m=1}^{d_k} q_{im} k_{jm} is a sum of dkd_k independent terms, so its variance grows like dkd_k and its typical magnitude like dk\sqrt{d_k}.A sum of dkd_k unit-variance independent terms has variance dkd_k; standard deviation is the square root. Dividing by dk\sqrt{d_k} restores unit scale regardless of dimension. For large dkd_k the dot products would otherwise be enormous, pushing the softmax into a regime where it saturates—one entry near 1, the rest near 0—and where its gradients nearly vanish. Dividing by dk\sqrt{d_k} rescales the scores back to roughly unit variance, keeping the distribution responsive and the gradients alive. This is why the operation is called scaled dot-product attention.

Softmax into weights

We turn each row of scores into a probability distribution with the softmax function, applied along the key axis:

aij=exp ⁣(qikj/dk)exp ⁣(qik/dk).a_{ij} = \frac{\exp\!\big(q_i \cdot k_j / \sqrt{d_k}\big)}{\sum_{\ell} \exp\!\big(q_i \cdot k_\ell / \sqrt{d_k}\big)}.

Now aij0a_{ij} \ge 0 and jaij=1\sum_j a_{ij} = 1: row ii is a genuine distribution over the nn positions, expressing how much position ii attends to each position jj. The exponential makes the competition winner-take-most without being winner-take-all—a higher score earns disproportionately more weight, but no position is ever hard-excluded, which is precisely what keeps the whole map differentiable.

The weighted sum of values

The output for position ii is the value vectors averaged under its attention distribution:

outi=jaijvj.\text{out}_i = \sum_j a_{ij}\, v_j.

Each position emits a custom blend of the sequence’s contents, mixed in proportions it chose by matching its query against every key. Assembling all rows at once recovers the canonical formula:

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

Read it left to right: QKQK^\top scores every query against every key; /dk/\sqrt{d_k} tames the scale; softmax normalizes each row into weights; multiplying by VV takes the weighted sums. The whole thing is two matrix multiplications with a softmax between them—and because every step is differentiable, the maps WQ,WK,WVW_Q, W_K, W_V are learned by ordinary backpropagation.

Self-attention and the global receptive field

When QQ, KK, and VV are all derived from the same sequence XX, the operation is self-attention: every position attends to every other position, itself included. Note the structural consequence. After one self-attention layer, the representation at position ii can depend directly on position jj for any jj, no matter how far away. The receptive field is global in a single layer.

Contrast this with a recurrent network, which threads information through a chain of hidden states h1h2hnh_1 \to h_2 \to \cdots \to h_n. For position 1 to influence position nn, its signal must survive n1n-1 sequential update steps—a path along which gradients tend to vanish or explode and along which nothing can be computed in parallel. Self-attention replaces that long serial path with a single O(n2)O(n^2) comparison that any position can make to any other in one shot.The cost is quadratic in sequence length: the n×nn \times n score matrix. Recurrence is linear in length but serial. Much later research trades one against the other.

Multi-head attention

A single attention distribution forces every position to summarize everything it cares about with one set of weights. But a token may need to track several relations at once—syntactic agreement, coreference, local phrasing. Multi-head attention runs hh attention operations in parallel, each with its own learned WQ(),WK(),WV()W_Q^{(\cdot)}, W_K^{(\cdot)}, W_V^{(\cdot)} projecting into a lower-dimensional subspace of size dk=d/hd_k = d/h. The hh outputs are concatenated and passed through a final linear map:

MultiHead(X)=[head1,,headh]WO.\text{MultiHead}(X) = \big[\,\text{head}_1, \ldots, \text{head}_h\,\big]\, W_O.

Each head is free to specialize in a different kind of relationship, and the model gets several distinct attention patterns for the price of one (the per-head dimension shrinks to keep the total compute roughly fixed).

Why it replaced recurrence

Two properties did the work. First, parallelism: the score matrix QKQK^\top is one dense matrix multiply, so an entire sequence is processed simultaneously rather than one timestep at a time—a decisive fit for GPU hardware. Second, direct long-range dependencies: any two positions are one attention step apart, so the path length information must travel is constant in sequence length rather than linear. Stacking these layers, interleaved with feed-forward blocks and residual connections, gives the transformer, the architecture that now underlies essentially all large language models.Attention is permutation-invariant on its own—it sees a set, not a sequence. Order is reintroduced separately through positional encodings added to the embeddings. The idea did not arrive fully formed: it grew out of additive attention introduced to help machine-translation models align source and target words, then was distilled into the pure scaled-dot-product form below.

The line softmax(QK/dk)V\text{softmax}(QK^\top/\sqrt{d_k})\,V is, in the end, a soft dictionary that learns its own keys, learns what to return, and is smooth enough to train end to end. Everything that follows in a modern model is built from stacking that one idea.

Further reading