6.1 — Attention as a soft, differentiable dictionary lookup
Goal: Build the attention operation from first principles, starting from a hard dictionary lookup and softening it through softmax until we reach attn(q, K, V) = Σᵢ softmax(s(q, kᵢ)) vᵢ.
1. Why this session exists
Chapter 5.6 ended with three structural requirements for the operator that would replace recurrence:
- Unbounded conditioning — no fixed-length window.
- Constant-length gradient paths — no exponential decay over distance.
- Parallel forward pass — every position computable in one batched matrix multiply.
Together with the fourth desideratum from 4.3 §5 — content-addressed mixing, where weights depend on the tokens themselves — these four properties almost uniquely specify the operation we are about to build.
This session derives the shape of attention from a single starting point: the dictionary lookup, a fundamental operation in computer science. Softening it into a differentiable function gives us attention. The specific similarity score and the batched matrix form come in 6.2.[2, 3, 4]
2. A hard dictionary lookup
A dictionary stores key-value pairs. A lookup with query returns the value whose key exactly matches :
If no key matches, the lookup returns nothing (or a default). This is what every hash map, Python dict, and database does.
For a neural network, hard lookup is useless for two reasons:
- It is discrete. has zero gradient almost everywhere. Backprop cannot pass through it.
- It assumes exact match. In a learned model, the query and keys are continuous vectors. We need graded matching — "this key is somewhat like this query" — not exact equality.
We need a continuous, gradient-friendly relaxation.
3. Softening the lookup
Replace "the single best matching key" with "a weighted average over all keys, weighted by how well each key matches the query."
First, replace exact equality by a continuous similarity score : large when the query and key are close, small (or negative) when they disagree. The specific functional form of is a design choice — 6.2 will pick the scaled dot product. For now, is any function we like.
Next, turn the similarity scores into a probability distribution over keys with softmax (see 1.7):
The weights satisfy and . They are a soft assignment of the query to the keys: if key stands out, if all keys look similar.
Finally, return the weighted average of values:
That is attention. The query produces a distribution over keys via softmax of similarities, and the output is the values, averaged under that distribution.
4. Reading the formula
Three useful ways to see what this does:
(a) Soft argmax. As scales up (multiply every similarity by a large constant), softmax sharpens. In the limit, , where , and attention reduces to the hard lookup. Attention is the differentiable version of "pick the best key, return its value."
(b) Convex combination. with (the probability simplex). The output always lies in the convex hull of the values . It cannot extrapolate beyond what the values express — it can only mix them.
(c) Kernel smoothing. If , the weights are exactly the kernel weights of Nadaraya–Watson regression (Nadaraya, 1964; Watson, 1964) with a Gaussian kernel. Attention is, structurally, kernel-smoothing regression where the kernel is parameterised by the score function and the data are the pairs. The connection is more than analogy: many recent papers re-derive attention from this nonparametric-regression view.
5. Why this satisfies our four desiderata
Look at the four requirements from §1 against the attention formula:
- Unbounded conditioning. The sum is over all keys; nothing is fixed-length. To make the input prefix available at position , we will set keys and values from positions through , and the entire prefix participates in computing the output.
- Constant-length gradient paths. The output at any query position is a single weighted sum of all values. Backprop from the output to any traverses exactly one multiplicative step (the weight ) and one softmax derivative. There is no exponential decay with .
- Parallel forward pass. When we batch the formula across queries simultaneously — say — it becomes two matrix multiplies and one softmax (the derivation is in 6.2). One large GEMM, fully parallelisable on the GPU.
- Content-addressed mixing. The weights depend on what is in and , not on any fixed offset. This is the structural shift from convolution that 4.3 §4 anticipated.
All four properties come "for free" from the soft-lookup formulation. Attention is not designed to satisfy them one by one — it satisfies them simultaneously by being the right shape.
6. The roles: query, key, value
Three slots, each with its own job:
- Query . The "what am I looking for?" vector. Produced by the position that is receiving information.
- Key . The "what do I represent?" vector. Produced by the position that is being looked at. The query–key inner product is the similarity score.
- Value . The "what should I contribute if selected?" vector. The output is a weighted sum of values.
In a hard dictionary, keys and values are tied: the key identifies a slot and the value is the slot's content. In attention, they are decoupled. The same source token will produce one vector for the matching role and a separate vector for the content role, via two different learnable linear projections (6.3). This separation is what gives the attention layer the flexibility to express different patterns at different layers — a token can be a strong "match target" without contributing strongly to the output, and vice versa.[1]
7. The cost of softmax
The softmax in attention is the only non-trivially non-linear operation in the layer (everything else is matrix multiplies). It has three structural consequences worth noting now and revisiting later:
(a) Quadratic memory. Computing for all pairs of queries and keys requires the matrix of similarity scores in memory. This is the memory cost that all "efficient attention" variants in 6.13 (coming in Part 2) attack.
(b) Saturation risk. Softmax saturates: if one similarity score is much larger than the others, the corresponding and the rest . Gradients with respect to the "losing" keys go to zero. The scaling in 6.2 is the design choice that keeps softmax in its non-saturated regime by default.
(c) Always nonzero. A perfect "hard match" (zero weight on all non-matching keys) is unattainable for finite scores. Attention always mixes in a little bit of every value. This is a feature for differentiability — gradients flow everywhere — and a cost for capacity, because no single value can be selected exactly.
8. What we keep going forward
The shape of attention is fixed:
What remains is to specify three things:
- The similarity function (6.2 — scaled dot product).
- Where come from (6.3 — three learned linear projections of the same input, for self-attention).
- The autoregressive / parallelism wiring (6.4 multi-head, 6.5 causal mask, 6.6 positional info, 6.7 RoPE) plus the per-position non-linearity (6.8 FFN).
By the end of Part 1 (session 6.8) you will have every piece of one Transformer block in matrix form. Part 2 stacks the blocks, adds normalisation and residuals, and walks through nanoGPT line by line.
(a) Show that softmax with similarity scores approaches a hard argmax as . What happens as ? Use the two limits to argue that softmax interpolates between "uniform mixture" and "hard lookup."
(b) Suppose the query matches key exactly, , and all other keys score . Compute in closed form for . How close is to ?
(c) Show that the attention output always lies in the convex hull of . What does this imply about the geometric reach of a single attention layer in the value space?
(d) Identify the four desiderata from §1 in the attention formula. For each one, point to the specific piece of the formula that delivers it.
(e) In a hard dictionary, the lookup of an unmatched query returns nothing. In soft attention, what is the output when no key strongly matches the query (all approximately equal)? Interpret this behaviour geometrically.
References
- [1]
Press, O., & Wolf, L. (2017). "Using the output embedding to improve language models". EACL. arXiv:1608.05859 — Weight tying between input embedding and output projection (5.2 §6.1).
↩ - [2]
Prince, S. J. D. (2023). Understanding Deep Learning, §12 (Sequence-to-Sequence Models) and §13 (Transformers). MIT Press. — Attention as soft lookup (6.1), scaled dot-product attention (6.2), multi-head attention (6.4).
↩ - [3]
Bahdanau, D., Cho, K., & Bengio, Y. (2014). "Neural machine translation by jointly learning to align and translate". arXiv:1409.0473 — First "neural attention" paper; additive attention as a precursor to scaled dot-product (6.1, 6.2).
↩ - [4]
3Blue1Brown. "But what is a GPT? Visual intro to Transformers" and "Attention in transformers, step-by-step". 3blue1brown.com — Visual introduction to attention (6.1, 6.2).
↩