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 , the exact query returns , whereas 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 —and converts the scores into convex weights via a softmax. At , the scores for keys and are and , giving weights and , and a weighted value . 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 be a database of key--value pairs with keys and values . Given a query , attention pooling returns a weighted sum of the values:
where and . The output is therefore a convex combination of the values, interpolating between exact lookup (a one-hot weight vector) and average pooling (uniform weights ).
To map arbitrary real-valued compatibility scores to convex weights, we apply the softmax function (Section 3.1):
Because , the weights depend only on score differences and are invariant to adding a constant across all keys. Both the softmax and the linear combination are differentiable with respect to , , and .
As a concrete vector example, take with query , keys , , , and values , , . The scores are , , and , yielding softmax weights and output
Notice two properties illustrated in Figure 10.1.1. First, even though matches exactly, it receives only two-thirds of the weight; scaling the scores by a factor of (to ) concentrates of the weight on . Thus the magnitude of the scores governs how sharply the softmax commits. Second, although adds zero to the sum, its weight still pulls the output toward the origin by diluting the other values.
Soft lookup of the query in three key--value pairs, with keys , , and values , , . The scores become softmax weights that sum to one (left), and the output 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 , 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 ( per head) over 1,024 tokens stores key and value entries per head, or roughly 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 , such as the Gaussian kernel with bandwidth ,
normalizing across keys yields the Nadaraya--Watson estimator:
For any strictly positive kernel, (10.1.5) is softmax attention (10.1.2) with score . For the Gaussian kernel, , which recovers our opening example when . Under regularity conditions on the density and target function, as and at an appropriate rate, converges to the conditional expectation (Mack and Silverman, 1982).
10.1.2.2 The Bandwidth#
To see how the bandwidth controls the estimator, we draw noisy training observations from with on 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_valThe 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_wAs , all weight concentrates on the nearest training point (1-nearest-neighbor interpolation); as , all weights approach (the global sample mean). We plot 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 () overfits individual noisy labels, while a wide bandwidth () oversmooths toward a horizontal line. The intermediate value tracks the true curve closely except near the boundaries, where all neighbors lie on one side. In practice 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, acts as an inverse temperature multiplying the raw scores 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 is a probability distribution over keys, plotting 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 , weight concentrates in a narrow diagonal band around the nearest training inputs; at , weight spreads broadly across the dataset: no weight exceeds about twice the uniform value ; the largest, about , belong to queries at the edges, whose far keys still get only about .
Two caveats apply when inspecting attention heatmaps in deep networks:
- 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 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).
- 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 , whose softmax weights 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 , while working memory grows linearly with . Nadaraya–Watson kernel regression corresponds to attention pooling with a fixed Euclidean similarity kernel whose bandwidth 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#
-
An average of two values. Let the keys be orthonormal and let the score be with the weights of (10.1.2).
- For the query with , compute all weights and show that the output tends to as .
- How large must be for the two selected keys to receive at least 99% of the total weight when ?
- Now let the keys be orthogonal with . Find a query that again averages and , and state what returns instead as .
Adapted from Stanford CS224N, Assignment 4, Problems 1(b) and 1(c).
-
[code] Effective number of keys. For the weights of one query, define the effective number of keys .
- Let the values be with independent noise of variance , and hold the keys fixed. Show that the variance of the estimate (10.1.5) at is .
- Compute at every query in
x_valfrom the weights thatnadaraya_watsonreturns, for each bandwidth insigmas, and plot the three curves. Then redraw the noise iny_train200 times withx_trainfixed, and compare the standard deviation of the estimate at each query with .
-
[code] The gradient of attention. ● Suppose that and that for . Denote by the distribution over keys defined by the softmax normalization (10.1.2).
- Prove that
-
Conclude that this Jacobian is positive semidefinite, and determine for which databases it is the zero matrix.
-
Let for a fixed direction for which exactly one key attains the largest score . Find the limit of the Jacobian as , and state what it implies for training the query by gradient descent.
-
Verify the identity and the limit with automatic differentiation on a random database with and .
-
[code] Soft lookup as retrieval. ● Build a database of keys drawn uniformly from the unit sphere in , with value the one-hot indicator of index , and weight them with the Gaussian kernel of bandwidth normalized as in (10.1.5), so that the output is the vector of weights. Query with a noisy copy of a stored key, with .
- Show that the largest weight goes to the key nearest the query for every , so the bandwidth does not affect which index wins. It does affect how much of the weight the winner takes.
- Without noise, the weight on the correct key is
Approximate for random unit vectors, so that , and derive the bandwidth at which falls to for and for . How must shrink as grows?
-
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 . Sweep from to at and , with the bandwidth from (b) for each , and plot the retrieval accuracy against . Compute the weights as the softmax (10.1.2) of the scores . Explain why a larger lowers the accuracy at fixed although the distance from the query to the correct key is unchanged.
-
[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 inputs uniformly from and labels with standard Gaussian noise, so that only the first coordinate matters. Score a query against a key by
normalize as in (10.1.2), and fit to the leave-one-out error, in which the estimate at excludes the pair . Measure the test error on fresh inputs against the noise-free function.
- Fit the isotropic kernel by a grid search over .
- 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.
- Compare the leave-one-out errors of the learned and the oracle metrics with their test errors, and repeat the comparison at . What does the result say about learning a similarity from a finite sample?
- A full matrix maps queries and keys by the same linear map, whereas learned attention maps them by separate matrices and . State two properties of the score that the shared map guarantees and separate maps lose.