10.1 Queries, Keys, and Values

A recurrent neural network (Section 8.4) compresses everything it has read into a fixed-size state vector before knowing which details a later prediction will require. For example, a recurrent model with hidden dimension 768 reading 1,024 tokens must summarize all 1,024 positions in 768 numbers.

A database avoids premature compression by storing records verbatim and deciding what to retrieve only when a query arrives. However, an exact database lookup is discontinuous: given key--value pairs D={(2,10),(5,20)}\mathcal{D}=\{(2,10),(5,20)\}, the exact query q=5q=5 returns 2020, whereas q=4q=4 matches no key. To train with gradient descent, we replace hard lookup with a soft lookup that scores every key—say, by negative squared distance a(q,k)=−(q−k)2a(q,k)=-(q-k)^2—and converts the scores into convex weights via a softmax. At q=4q=4, the scores for keys 22 and 55 are −4-4 and −1-1, giving weights e−4/(e−4+e−1)≈0.05e^{-4}/(e^{-4}+e^{-1}) \approx 0.05 and 0.950.95, and a weighted value 0.05⋅10+0.95⋅20≈19.50.05 \cdot 10 + 0.95 \cdot 20 \approx 19.5. The output varies smoothly with the query, scales to any number of stored records, and requires no fixed-size bottleneck prior to querying.

This differentiable key--value lookup is the attention mechanism (Bahdanau et al., 2015). We first formulate attention pooling for vector queries, keys, and values, and then examine its classical nonparametric precursor, Nadaraya--Watson kernel regression, where a single bandwidth parameter controls the sharpness of the lookup.

10.1.1 Attention as Differentiable Lookup#

Let D=def{(k1,v1),…,(km,vm)}\mathcal{D} \stackrel{\textrm{def}}{=} \{(\mathbf{k}_1, \mathbf{v}_1), \ldots, (\mathbf{k}_m, \mathbf{v}_m)\} be a database of mm key--value pairs with keys ki∈Rd\mathbf{k}_i \in \mathbb{R}^{d} and values vi∈Rdv\mathbf{v}_i \in \mathbb{R}^{d_v}. Given a query q∈Rd\mathbf{q} \in \mathbb{R}^{d}, attention pooling returns a weighted sum of the values:

Attention(q,D)=def∑i=1mα(q,ki)vi,(10.1.1)\textrm{Attention}(\mathbf{q}, \mathcal{D}) \stackrel{\textrm{def}}{=} \sum_{i=1}^m \alpha(\mathbf{q}, \mathbf{k}_i) \mathbf{v}_i, \tag{10.1.1}

where α(q,ki)≥0\alpha(\mathbf{q},\mathbf{k}_i) \ge 0 and ∑i=1mα(q,ki)=1\sum_{i=1}^m \alpha(\mathbf{q},\mathbf{k}_i) = 1. The output is therefore a convex combination of the values, interpolating between exact lookup (a one-hot weight vector) and average pooling (uniform weights 1/m1/m).

To map arbitrary real-valued compatibility scores a(q,ki)a(\mathbf{q}, \mathbf{k}_i) to convex weights, we apply the softmax function (Section 3.1):

α(q,ki)=exp⁡(a(q,ki))∑jexp⁡(a(q,kj)).(10.1.2)\alpha(\mathbf{q}, \mathbf{k}_i) = \frac{\exp(a(\mathbf{q}, \mathbf{k}_i))}{\sum_j \exp(a(\mathbf{q}, \mathbf{k}_j))}. \tag{10.1.2}

Because αi=1/(1+∑j≠ieaj−ai)\alpha_i = 1 / \big(1 + \sum_{j \neq i} e^{a_j - a_i}\big), the weights depend only on score differences aj−aia_j - a_i and are invariant to adding a constant across all keys. Both the softmax and the linear combination are differentiable with respect to q\mathbf{q}, ki\mathbf{k}_i, and vi\mathbf{v}_i.

As a concrete vector example, take a(q,k)=−∥q−k∥2a(\mathbf{q}, \mathbf{k}) = -\|\mathbf{q} - \mathbf{k}\|^2 with query q=(1,1)\mathbf{q} = (1, 1), keys k1=(1,1)\mathbf{k}_1 = (1, 1), k2=(2,1)\mathbf{k}_2 = (2, 1), k3=(0,0)\mathbf{k}_3 = (0, 0), and values v1=(1,3)\mathbf{v}_1 = (1, 3), v2=(0,0)\mathbf{v}_2 = (0, 0), v3=(4,1)\mathbf{v}_3 = (4, 1). The scores are 00, −1-1, and −2-2, yielding softmax weights (1,e−1,e−2)/(1+e−1+e−2)≈(0.67,0.24,0.09)(1, e^{-1}, e^{-2}) / (1 + e^{-1} + e^{-2}) \approx (0.67, 0.24, 0.09) and output

o=0.67 (1,3)+0.24 (0,0)+0.09 (4,1)≈(1.0,2.1).(10.1.3)\mathbf{o} = 0.67\,(1, 3) + 0.24\,(0, 0) + 0.09\,(4, 1) \approx (1.0, 2.1). \tag{10.1.3}

Notice two properties illustrated in Figure 10.1.1. First, even though k1\mathbf{k}_1 matches q\mathbf{q} exactly, it receives only two-thirds of the weight; scaling the scores by a factor of 1010 (to 0,−10,−200, -10, -20) concentrates 99.995%99.995\% of the weight on k1\mathbf{k}_1. Thus the magnitude of the scores governs how sharply the softmax commits. Second, although v2=(0,0)\mathbf{v}_2 = (0, 0) adds zero to the sum, its 0.240.24 weight still pulls the output toward the origin by diluting the other values.

Figure 10.1.1:

Soft lookup of the query q=(1,1)\mathbf{q} = (1, 1) in three key--value pairs, with keys (1,1)(1, 1), (2,1)(2, 1), (0,0)(0, 0) and values (1,3)(1, 3), (0,0)(0, 0), (4,1)(4, 1). The scores si=−∥q−ki∥2s_i = -\|\mathbf{q} - \mathbf{k}_i\|^2 become softmax weights αi\alpha_i that sum to one (left), and the output o≈(1.0,2.1)\mathbf{o} \approx (1.0, 2.1) is the weighted sum of the values, a point inside the triangle whose corners are the values (right).

The attention rule (10.1.1) applies unchanged to any number of records mm, allowing a single layer to process sequences of arbitrary length without compressing them into a fixed-size state. The cost shifts to memory: whereas a recurrent layer of width 768 keeps 768 numbers, one 12-head attention layer of GPT-2 small (d=64d = 64 per head) over 1,024 tokens stores 2×1,024×64=131,0722 \times 1{,}024 \times 64 = 131{,}072 key and value entries per head, or roughly 1.6×1061.6 \times 10^6 numbers across all 12 heads.

10.1.2 Attention Pooling with Fixed Kernels#

Long before deep learning, Nadaraya--Watson kernel regression (Nadaraya, 1964; Watson, 1964) used (10.1.1) for nonparametric regression, treating training inputs as keys, training labels as values, and a fixed similarity kernel as the scoring rule.

10.1.2.1 Kernels and the Nadaraya--Watson Estimator#

Given a nonnegative similarity kernel K(q,k)K(\mathbf{q}, \mathbf{k}), such as the Gaussian kernel with bandwidth σ>0\sigma > 0,

K(q,k)=exp⁡(−∥q−k∥22σ2),(10.1.4)K(\mathbf{q}, \mathbf{k}) = \exp\left(-\frac{\|\mathbf{q} - \mathbf{k}\|^2}{2\sigma^2}\right), \tag{10.1.4}

normalizing across keys yields the Nadaraya--Watson estimator:

f(q)=∑iviK(q,ki)∑jK(q,kj).(10.1.5)f(\mathbf{q}) = \sum_i \mathbf{v}_i \frac{K(\mathbf{q}, \mathbf{k}_i)}{\sum_j K(\mathbf{q}, \mathbf{k}_j)}. \tag{10.1.5}

For any strictly positive kernel, (10.1.5) is softmax attention (10.1.2) with score a(q,k)=log⁡K(q,k)a(\mathbf{q}, \mathbf{k}) = \log K(\mathbf{q}, \mathbf{k}). For the Gaussian kernel, a(q,k)=−∥q−k∥2/(2σ2)a(\mathbf{q}, \mathbf{k}) = -\|\mathbf{q} - \mathbf{k}\|^2 / (2\sigma^2), which recovers our opening example when 2σ2=12\sigma^2 = 1. Under regularity conditions on the density and target function, as m→∞m \to \infty and σ→0\sigma \to 0 at an appropriate rate, f(q)f(\mathbf{q}) converges to the conditional expectation E[y∣q]\mathbb{E}[y \mid \mathbf{q}] (Mack and Silverman, 1982).

10.1.2.2 The Bandwidth#

To see how the bandwidth σ\sigma controls the estimator, we draw n=40n = 40 noisy training observations from y=2sin⁡(x)+x+ϵy = 2\sin(x) + x + \epsilon with ϵ∼N(0,1)\epsilon \sim \mathcal{N}(0, 1) on [0,5)[0, 5) and evaluate predictions on a dense grid.

n = 40
x_train, _ = torch.sort(torch.rand(n) * 5)
y_train = 2 * torch.sin(x_train) + x_train + torch.randn(n)
x_val = torch.arange(0, 5, 0.1)
y_val = 2 * torch.sin(x_val) + x_val

The implementation computes all pairwise query--key distances, evaluates the Gaussian kernel, normalizes each query row, and multiplies by y_train.

def nadaraya_watson(x_train, y_train, x_val, sigma):
    dists = x_val[:, None] - x_train[None, :]  # (queries, keys)
    k = d2l.exp(-dists**2 / (2 * sigma**2))
    attention_w = k / k.sum(1, keepdims=True)  # Normalize over the keys
    return attention_w @ y_train, attention_w

As σ→0\sigma \to 0, all weight concentrates on the nearest training point (1-nearest-neighbor interpolation); as σ→∞\sigma \to \infty, all weights approach 1/n1/n (the global sample mean). We plot σ∈{0.1,0.5,2.0}\sigma \in \{0.1, 0.5, 2.0\} below.

sigmas = (0.1, 0.5, 2.0)
estimates = [nadaraya_watson(x_train, y_train, x_val, s)[0] for s in sigmas]
d2l.plot([x_val] * 4 + [x_train], estimates + [y_val, y_train], 'x', 'y',
         legend=[rf'$\sigma$ = {s:g}' for s in sigmas] + ['truth'],
         fmts=('-', 'm--', 'g-.', 'k:', 'C7o'), ylim=(-2.5, 9),
         figsize=(5, 3), legend_loc='upper left')

A narrow bandwidth (σ=0.1\sigma = 0.1) overfits individual noisy labels, while a wide bandwidth (σ=2.0\sigma = 2.0) oversmooths toward a horizontal line. The intermediate value σ=0.5\sigma = 0.5 tracks the true curve closely except near the boundaries, where all neighbors lie on one side. In practice σ\sigma can be chosen by leave-one-out cross-validation, which requires only zeroing the diagonal of the weight matrix and renormalizing its rows (Exercise 5).

More broadly, 1/σ21/\sigma^2 acts as an inverse temperature multiplying the raw scores −12(q−k)2-\tfrac{1}{2}(q - k)^2 before the softmax. Scaling scores up stretches pairwise gaps and drives the softmax toward a one-hot lookup; scaling scores down compresses gaps and drives the softmax toward uniform averaging. We will see this same temperature scaling in dot-product attention (Section 10.2).

10.1.3 Attention Weights as a Diagnostic#

Because each row of the attention matrix A\mathbf{A} is a probability distribution over keys, plotting A\mathbf{A} as a heatmap shows which keys each query consults.

w_narrow, w_wide = (nadaraya_watson(x_train, y_train, x_val, s)[1]
                    for s in (0.1, 2.0))
# show_heatmaps takes (rows of panels, columns of panels, queries, keys)
d2l.show_heatmaps(d2l.stack([w_narrow, w_wide])[None],
                  xlabel='training inputs (keys)',
                  ylabel='test inputs (queries)',
                  titles=[r'$\sigma$ = 0.1', r'$\sigma$ = 2'],
                  figsize=(7, 3), cbar='each')

At σ=0.1\sigma = 0.1, weight concentrates in a narrow diagonal band around the nearest training inputs; at σ=2.0\sigma = 2.0, weight spreads broadly across the dataset: no weight exceeds about twice the uniform value 1/40=0.0251/40 = 0.025; the largest, about 0.050.05, belong to queries at the edges, whose far keys still get only about 0.0020.002.

Two caveats apply when inspecting attention heatmaps in deep networks:

  1. Weights show where a layer looks, not what it transmits: A key can receive a large attention weight even if its value vector is zero (as with v2=(0,0)\mathbf{v}_2 = (0, 0) in our vector example) or lies in the null space of downstream projections. Verifying a head's causal role requires interventional experiments (Section 10.7).
  2. Fixed kernels enforce a static similarity metric: In (10.1.5), every query uses the same Euclidean distance in input space. In sequence modeling, however, relevance is context- and task-dependent—a verb may need its syntactic subject several tokens away. Learned attention layers therefore project inputs into trainable query, key, and value spaces before scoring.

10.1.4 Summary#

Attention pooling computes a convex combination of value vectors ∑iα(q,ki)vi\sum_i \alpha(\mathbf{q}, \mathbf{k}_i)\mathbf{v}_i, whose softmax weights α(q,ki)\alpha(\mathbf{q}, \mathbf{k}_i) interpolate smoothly between exact dictionary lookup and uniform average pooling. Unlike a fixed-size recurrent state, attention accesses all stored key–value pairs directly using a rule independent of the number of pairs mm, while working memory grows linearly with mm. Nadaraya–Watson kernel regression corresponds to attention pooling with a fixed Euclidean similarity kernel whose bandwidth σ\sigma acts as a softmax temperature governing the bias–variance trade-off. Although attention heatmaps visualize query–key alignments, moving beyond fixed input-space distance requires trainable projections and learned scoring functions.

10.1.5 Exercises#

  1. An average of two values. Let the keys k1,…,km\mathbf{k}_1, \ldots, \mathbf{k}_m be orthonormal and let the score be a(q,k)=q⊤ka(\mathbf{q}, \mathbf{k}) = \mathbf{q}^\top \mathbf{k} with the weights of (10.1.2).

    1. For the query q=c (ka+kb)\mathbf{q} = c\,(\mathbf{k}_a + \mathbf{k}_b) with c>0c > 0, compute all mm weights and show that the output tends to 12(va+vb)\tfrac{1}{2}(\mathbf{v}_a + \mathbf{v}_b) as c→∞c \to \infty.
    2. How large must cc be for the two selected keys to receive at least 99% of the total weight when m=10m = 10?
    3. Now let the keys be orthogonal with ∥kb∥=2 ∥ka∥\|\mathbf{k}_b\| = 2\,\|\mathbf{k}_a\|. Find a query that again averages va\mathbf{v}_a and vb\mathbf{v}_b, and state what q=c (ka+kb)\mathbf{q} = c\,(\mathbf{k}_a + \mathbf{k}_b) returns instead as c→∞c \to \infty.

    Adapted from Stanford CS224N, Assignment 4, Problems 1(b) and 1(c).

  2. [code] Effective number of keys. For the weights αi(q)\alpha_i(q) of one query, define the effective number of keys neff(q)=1/∑iαi(q)2n_{\textrm{eff}}(q) = 1 / \sum_i \alpha_i(q)^2.

    1. Let the values be yi=g(xi)+ϵiy_i = g(x_i) + \epsilon_i with independent noise of variance s2s^2, and hold the keys fixed. Show that the variance of the estimate (10.1.5) at qq is s2/neff(q)s^2 / n_{\textrm{eff}}(q).
    2. Compute neffn_{\textrm{eff}} at every query in x_val from the weights that nadaraya_watson returns, for each bandwidth in sigmas, and plot the three curves. Then redraw the noise in y_train 200 times with x_train fixed, and compare the standard deviation of the estimate at each query with 1/neff(q)1 / \sqrt{n_{\textrm{eff}}(q)}.
  3. [code] The gradient of attention. ● Suppose that a(q,ki)=q⊤kia(\mathbf{q}, \mathbf{k}_i) = \mathbf{q}^\top \mathbf{k}_i and that ki=vi\mathbf{k}_i = \mathbf{v}_i for i=1,…,mi = 1, \ldots, m. Denote by p(ki;q)p(\mathbf{k}_i; \mathbf{q}) the distribution over keys defined by the softmax normalization (10.1.2).

    1. Prove that
∇qAttention(q,D)=Covp(ki;q)[ki].(10.1.6)\nabla_{\mathbf{q}} \mathop{\textrm{Attention}}(\mathbf{q}, \mathcal{D}) = \textrm{Cov}_{p(\mathbf{k}_i; \mathbf{q})}[\mathbf{k}_i]. \tag{10.1.6}
  1. Conclude that this Jacobian is positive semidefinite, and determine for which databases it is the zero matrix.

  2. Let q=c u\mathbf{q} = c\,\mathbf{u} for a fixed direction u\mathbf{u} for which exactly one key attains the largest score u⊤ki\mathbf{u}^\top \mathbf{k}_i. Find the limit of the Jacobian as c→∞c \to \infty, and state what it implies for training the query by gradient descent.

  3. Verify the identity and the limit with automatic differentiation on a random database with m=8m = 8 and d=4d = 4.

  4. [code] Soft lookup as retrieval. ● Build a database of mm keys drawn uniformly from the unit sphere in R16\mathbb{R}^{16}, with value vi\mathbf{v}_i the one-hot indicator of index ii, and weight them with the Gaussian kernel of bandwidth σ\sigma normalized as in (10.1.5), so that the output is the vector of weights. Query with a noisy copy q=ki+ϵ\mathbf{q} = \mathbf{k}_i + \boldsymbol{\epsilon} of a stored key, with ϵ∼N(0,τ2I)\boldsymbol{\epsilon} \sim \mathcal{N}(\mathbf{0}, \tau^2 \mathbf{I}).

    1. Show that the largest weight goes to the key nearest the query for every σ>0\sigma > 0, so the bandwidth does not affect which index wins. It does affect how much of the weight the winner takes.
    2. Without noise, the weight on the correct key is
αi=11+∑j≠iexp⁡(−∥ki−kj∥2/2σ2).(10.1.7)\alpha_i = \frac{1}{1 + \sum_{j \neq i} \exp\big(-\|\mathbf{k}_i - \mathbf{k}_j\|^2 / 2\sigma^2\big)}. \tag{10.1.7}

Approximate ki⊤kj≈0\mathbf{k}_i^\top \mathbf{k}_j \approx 0 for random unit vectors, so that ∥ki−kj∥2≈2\|\mathbf{k}_i - \mathbf{k}_j\|^2 \approx 2, and derive the bandwidth at which αi\alpha_i falls to 0.90.9 for m=20m = 20 and for m=200m = 200. How must σ\sigma shrink as mm grows?

  1. A lookup whose output the next layer can use needs most of the weight on one key, not merely the largest share. Call the query retrieved when αi≥0.5\alpha_i \geq 0.5. Sweep τ\tau from 00 to 11 at m=20m = 20 and m=200m = 200, with the bandwidth from (b) for each mm, and plot the retrieval accuracy against τ\tau. Compute the weights as the softmax (10.1.2) of the scores −∥q−kj∥2/2σ2-\|\mathbf{q} - \mathbf{k}_j\|^2 / 2\sigma^2. Explain why a larger mm lowers the accuracy at fixed τ\tau although the distance from the query to the correct key is unchanged.

  2. [extended] A learned metric. ● Kernel regression with a learned distance (Weinberger and Tesauro, 2007) replaces the fixed similarity of (10.1.5) by a learned one. Draw n=200n = 200 inputs xi\mathbf{x}_i uniformly from [0,5]5[0, 5]^5 and labels yi=2sin⁡(xi1)+xi1+ϵiy_i = 2\sin(x_{i1}) + x_{i1} + \epsilon_i with standard Gaussian noise, so that only the first coordinate matters. Score a query against a key by

a(q,k)=−12∥W(q−k)∥2,W=diag(w1,…,w5),(10.1.8)a(\mathbf{q}, \mathbf{k}) = -\tfrac{1}{2} \|\mathbf{W}(\mathbf{q} - \mathbf{k})\|^2, \qquad \mathbf{W} = \textrm{diag}(w_1, \ldots, w_5), \tag{10.1.8}

normalize as in (10.1.2), and fit W\mathbf{W} to the leave-one-out error, in which the estimate at xi\mathbf{x}_i excludes the pair (xi,yi)(\mathbf{x}_i, y_i). Measure the test error on 10001000 fresh inputs against the noise-free function.

  1. Fit the isotropic kernel w1=⋯=w5=1/σw_1 = \cdots = w_5 = 1/\sigma by a grid search over σ\sigma.
  2. Starting from the isotropic solution, fit the five scales by gradient descent. Compare the learned scales with the relevance of each coordinate, and the test error with that of the isotropic kernel and of an oracle that uses only the first coordinate at its best bandwidth.
  3. Compare the leave-one-out errors of the learned and the oracle metrics with their test errors, and repeat the comparison at n=1000n = 1000. What does the result say about learning a similarity from a finite sample?
  4. A full matrix W∈R5×5\mathbf{W} \in \mathbb{R}^{5 \times 5} maps queries and keys by the same linear map, whereas learned attention maps them by separate matrices Wq\mathbf{W}_q and Wk\mathbf{W}_k. State two properties of the score aa that the shared map guarantees and separate maps lose.

Discussions