Queries, Keys, and Values

Dive into Deep Learning · §10.1

Queries, Keys, and Values: From Nonparametric Smoothing to Attention
differentiable lookup · convex combinations · Nadaraya–Watson kernel regression · bandwidth as temperature

Why Fixed-Size Recurrent States Lose Early Context

Motivation

  • Concrete Capacity Gap: In a GPT-2 small scale model (d = 768) reading n = 1{,}024 tokens, the token representations hold 1{,}024 \times 768 = 786{,}432 numbers, whereas a recurrent state keeps only 768 numbers.
  • Premature Summarization: An RNN writes \mathbf{h}_t at step t without knowing whether token t will be needed 900 steps later.
  • The Database Alternative: Store all m records verbatim in O(md) memory and retrieve relevant values only when a query arrives.

Why Exact Database Lookup Cannot Be Trained

From Hard to Soft Lookup

  • Discontinuous Hard Lookup: Given \mathcal{D} = \{(2, 10), (5, 20)\}, exact query q = 5 returns 20, whereas q = 4 finds no match (or jumps abruptly at midpoint q = 3.5).
  • Zero Gradient Everywhere: Because a piecewise-constant step function is flat away from jumps, its derivative with respect to queries and keys is zero almost everywhere.
  • Differentiable Relaxation: Score every key against the query and return a smooth softmax-weighted average of all stored values.

Worked Example: Soft Lookup on Two Scalar Records

Scalar Soft Lookup

  • Score with Negative Squared Distance: At query q = 4, keys k_1 = 2 and k_2 = 5 score a_1 = -(4-2)^2 = -4 and a_2 = -(4-5)^2 = -1.
  • Normalize via Softmax: Exponentiating and dividing by e^{-4} + e^{-1} yields weights \alpha_1 \approx 0.047 and \alpha_2 \approx 0.953.
  • Convex Value Sum: \textrm{Attention}(q=4, \mathcal{D}) = 0.047(10) + 0.953(20) \approx 19.53

Formalizing Attention Pooling Over Vector Records

Mathematical Formulation

  • Attention Pooling: Over m records \mathcal{D} = \{(\mathbf{k}_i, \mathbf{v}_i)\}_{i=1}^m with \mathbf{q}, \mathbf{k}_i \in \mathbb{R}^d and \mathbf{v}_i \in \mathbb{R}^{d_v}: \textrm{Attention}(\mathbf{q}, \mathcal{D}) \stackrel{\textrm{def}}{=} \sum_{i=1}^m \alpha(\mathbf{q}, \mathbf{k}_i)\,\mathbf{v}_i \in \mathbb{R}^{d_v}
  • Simplex Constraint: \alpha(\mathbf{q}, \mathbf{k}_i) \ge 0 and \sum_{i=1}^m \alpha(\mathbf{q}, \mathbf{k}_i) = 1, confining the output to the convex hull of \{\mathbf{v}_i\}.
  • Interpolation Spectrum: One-hot weights \mathbf{e}_{i^*} recover exact lookup; uniform weights 1/m recover average pooling.

From Compatibility Scores to Softmax Weights

Softmax Normalization

  • Softmax Map: Any real compatibility score a(\mathbf{q}, \mathbf{k}_i) \in \mathbb{R} maps to the simplex via: \alpha(\mathbf{q}, \mathbf{k}_i) = \frac{\exp(a(\mathbf{q}, \mathbf{k}_i))}{\sum_{j=1}^m \exp(a(\mathbf{q}, \mathbf{k}_j))}
  • Shift Invariance: Adding any key-independent constant c(\mathbf{q}) to all scores cancels out, so weights depend only on differences a_j - a_i.
  • Numerical Stability: Subtracting M = \max_j a_j bounds all exponents by 0, preventing overflow or 0/0 underflow.

Worked Example: Vector Soft Lookup in the Plane

2D Vector Lookup

  • Query \mathbf{q} = (1, 1) over 3 Records: Under s_i = -\|\mathbf{q} - \mathbf{k}_i\|^2, keys (1,1), (2,1), and (0,0) score 0, -1, -2 and receive weights (0.67, 0.24, 0.09).
  • Imperfect Commitment: Even exact match \mathbf{k}_1 = \mathbf{q} captures only 67\% of the weight unless scores are scaled up.
  • Zero-Value Dilution: Record 2 has value \mathbf{v}_2 = (0, 0), which adds zero to the sum yet absorbs 24\% of the weight and pulls \mathbf{o} \approx (1.03, 2.09) toward the origin.

Geometric View: Convex Hull of Stored Values

Geometry of Attention

  • Convex Hull Invariant: Because \alpha_i \ge 0 and \sum_{i=1}^m \alpha_i = 1, the output \mathbf{o} is strictly confined to the convex hull of \{\mathbf{v}_1, \ldots, \mathbf{v}_m\} (the triangle with corners (1,3), (0,0), and (4,1)).
  • Score Scaling Sharpens Commitment: Multiplying all scores by 10 (to 0, -10, -20) concentrates 99.995\% of the weight on \mathbf{k}_1, pulling \mathbf{o} onto the vertex \mathbf{v}_1 = (1, 3).
  • No Extrapolation: Softmax attention interpolates among stored values; it can never output a point outside their convex hull.

Soft lookup maps scores to simplex weights and outputs a point inside the triangle of values.

Length Independence vs. Linear Memory Scaling

Systems Scaling

  • Length-Independent Rule: The attention pooling operator \sum_{i=1}^m \alpha(\mathbf{q}, \mathbf{k}_i)\mathbf{v}_i has no parameters tied to the context length m.
  • Linear Key–Value Memory: At m = 1{,}024 in GPT-2 small (d = 768, H = 12, d_h = 64), one head stores 2 \times 1{,}024 \times 64 = 131{,}072 floats (1.57\text{M} floats across 12 heads, vs. 768 in an RNN).
  • Direct 1-Hop Access: Token m scores token 1 directly via \alpha(\mathbf{q}_m, \mathbf{k}_1) without recurrent compression.

Classical Precursor: Nadaraya–Watson Regression

Nonparametric Statistics (1964)

Long before deep learning, Nadaraya (1964) and Watson (1964) formulated nonparametric regression as attention pooling over a training dataset \{(x_i, y_i)\}_{i=1}^n:

f(q) = \sum_{i=1}^n y_i \, \frac{K(q, x_i)}{\sum_{j=1}^n K(q, x_j)}, \qquad K(q, k) = \exp\!\left(-\frac{\|q - k\|^2}{2\sigma^2}\right)

  • Database Identification: Training inputs x_i act as keys, training labels y_i act as values, and the test location q acts as the query.
  • Equivalence to Softmax Attention: For any strictly positive kernel K(q, k) > 0, normalizing K(q, x_i) across keys is identical to softmax attention with score a(q, k) = \log K(q, k) = -\|q - k\|^2 / (2\sigma^2).
  • Statistical Consistency: As n \to \infty and bandwidth \sigma \to 0 at an appropriate rate, f(q) converges to the true conditional expectation \mathbb{E}[y \mid x = q].

Synthetic Benchmark and Vectorized Implementation

Code Implementation

We draw n = 40 noisy observations from y = 2\sin(x) + x + \epsilon with \epsilon \sim \mathcal{N}(0, 1) on [0, 5) and compute all query–key distances via broadcasting:

  • Broadcasted Distance Matrix: x_val[:, None] - x_train[None, :] broadcasts (50, 1) against (1, 40) to form the (50, 40) matrix of pairwise differences q - k_i.
  • Row-Wise Normalization: k / k.sum(1, keepdims=True) normalizes each query row over all 40 keys, and attention_w @ y_train computes all 50 predictions in one matrix–vector product.
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

How Bandwidth Controls the Bias–Variance Trade-Off

Visualizing the Estimator

  • Narrow Bandwidth (\sigma = 0.1): Low bias, high variance; weight concentrates on the closest training point (\to 1-NN interpolation as \sigma \to 0), chasing individual noise spikes.
  • Intermediate (\sigma = 0.5): Tracks the true curve 2\sin(x) + x closely across the interior, lagging only near the boundaries where all neighbors lie on one side.
  • Wide Bandwidth (\sigma = 2.0): High bias, low variance; weights flatten toward 1/n, oversmoothing toward the global sample mean \bar{y}.

Bandwidth as Inverse Softmax Temperature

The Sharpness Dial

  • Inverse Variance as Temperature (\beta = 1/\sigma^2): \alpha_i(q) = \mathrm{softmax}_i\!\left(\frac{1}{\sigma^2} \cdot \left(-\frac{1}{2}\|q - k_i\|^2\right)\right)
  • Low Temperature (\sigma \to 0, large 1/\sigma^2): Stretches pairwise score gaps \Delta a / \sigma^2 \to \infty, driving the softmax toward a one-hot argmax lookup.
  • High Temperature (\sigma \to \infty, small 1/\sigma^2): Compresses score gaps toward zero, driving weights toward uniform 1/n averaging (moving \sigma: 2.0 \to 0.1 multiplies score gaps by 400\times).

Effective Number of Keys and Estimator Variance

Statistical Diagnostics

How many keys effectively contribute to a query’s prediction? If y_i = g(x_i) + \epsilon_i with independent observation noise \textrm{Var}(\epsilon_i) = s^2, the conditional variance of the attention estimate is:

\textrm{Var}\!\left(\sum_{i=1}^n \alpha_i(q)\, y_i \,\middle|\, \mathbf{x}\right) = s^2 \sum_{i=1}^n \alpha_i(q)^2 = \frac{s^2}{n_{\textrm{eff}}(q)}, \qquad n_{\textrm{eff}}(q) \stackrel{\textrm{def}}{=} \frac{1}{\sum_{i=1}^n \alpha_i(q)^2}

  • Effective Sample Size n_{\textrm{eff}}(q) \in [1, n]: Measures how many training values are effectively averaged at query q.
  • One-Hot Limit (\sigma \to 0): \sum_i \alpha_i^2 = 1 \to n_{\textrm{eff}}(q) = 1, leaving the full single-observation noise variance s^2.
  • Uniform Limit (\sigma \to \infty): \alpha_i = 1/n \to \sum_i \alpha_i^2 = 1/n \to n_{\textrm{eff}}(q) = n, reducing noise variance to s^2/n.

Inspecting Attention Weight Heatmaps

Visual Diagnostics

  • Row-Stochastic Matrix: Each row of \mathbf{A} \in \mathbb{R}^{n_q \times n_k} is a probability distribution over keys for one query.
  • Diagonal Band at \sigma = 0.1: Sorted queries and keys form a thin diagonal ridge where each query consults only 2–3 local keys.
  • Diffuse Sheet at \sigma = 2.0: Probability mass spreads across almost all 40 keys, within a factor of about two of the uniform baseline 1/40 = 0.025 (peak \approx 0.05 at the edges).

Pitfall 1: Out-of-Range Queries and Underflow

Numerical & Statistical Pitfalls

  • Convex-Hull Clamping: As q \to \infty beyond [0, 5), the closest boundary key x_{\max} dominates all others, so f(q) \to y_{\max} (a flat asymptote that cannot follow a linear trend).
  • Float32 Underflow to NaN: At q = 15, \sigma = 0.5, exponent -(q - x_i)^2/(2\sigma^2) < -200 underflows float32 \exp(-200) \to 0.0, so k / k.sum() evaluates 0.0 / 0.0 = NaN.
  • Fix: Pass log-scores -(q - k_i)^2/(2\sigma^2) directly to a max-subtracted softmax.

Pitfall 2: Why Fixed Kernels and Heatmaps Mislead

Interpretability & Modeling Limits

Before building deep attention layers, keep two fundamental limitations of fixed-kernel pooling in mind:

  • 1. Attention Weights Show Where a Layer Looks, Not What It Transmits: In our 2D vector example, key \mathbf{k}_2 = (2, 1) captured 24\% of the attention weight even though its value \mathbf{v}_2 = (0, 0) transmitted nothing. In deep networks, a heavily attended token whose value lies in the null space of downstream projections has zero causal effect.
  • 2. Fixed Input-Space Metrics Cannot Capture Syntactic or Task Relevance: Nadaraya–Watson measures Euclidean distance \|q - k\|^2 in raw input coordinates with a single isotropic bandwidth \sigma.
  • Why Deep Networks Learn Projections: In language or vision, a verb seeking its subject or a pronoun seeking its antecedent needs learned query, key, and value projections (\mathbf{W}_q, \mathbf{W}_k, \mathbf{W}_v) so the task defines similarity.

Concept Check: Soft Lookup, Bandwidth, and Scaling

Check Your Understanding

Work out these three questions from the softmax attention equations:

  1. Bandwidth Halving: At bandwidth \sigma, two keys receive attention weights in the ratio \alpha_1 / \alpha_2 = 2 : 1. If we halve the bandwidth to \sigma / 2, what is the new weight ratio \alpha_1' / \alpha_2'?
  2. Orthonormal Key Averaging: Let \mathbf{k}_1, \ldots, \mathbf{k}_m be orthonormal with dot-product score a(\mathbf{q}, \mathbf{k}_i) = \mathbf{q}^\top \mathbf{k}_i. What happens to the attention output for query \mathbf{q} = c\,(\mathbf{k}_1 + \mathbf{k}_2) as c \to \infty?
  3. Vanishing Query Gradient: As c \to \infty and \boldsymbol{\alpha} converges to a one-hot vector on a single winning key, what happens to the gradient \nabla_{\mathbf{q}} \textrm{Attention}(\mathbf{q}, \mathcal{D})?

Answers:

  1. 16 : 1. Halving \sigma multiplies 1/\sigma^2 by 4, so the score difference \Delta becomes 4\Delta and e^{4\Delta} = (e^\Delta)^4 = 2^4 = 16.
  2. It converges to \frac{1}{2}(\mathbf{v}_1 + \mathbf{v}_2). Keys 1 and 2 tie with score c while all other keys score 0, so their weights each approach e^c / (2e^c + m - 2) \to 1/2.
  3. It vanishes (\to \mathbf{0}). Once a single key holds weight 1, small perturbations to \mathbf{q} barely alter the weights, saturating the softmax Jacobian.

Summary: Differentiable Key–Value Lookup

Key Takeaways

  • Soft Convex Pooling: \textrm{Attention}(\mathbf{q}, \mathcal{D}) = \sum_{i=1}^m \alpha(\mathbf{q}, \mathbf{k}_i)\,\mathbf{v}_i where \boldsymbol{\alpha} \in \Delta^{m-1}.
  • Temperature & Effective Keys: Bandwidth \sigma interpolates from nearest-neighbor (\sigma \to 0, n_{\textrm{eff}} \to 1) to uniform mean (\sigma \to \infty, n_{\textrm{eff}} \to m).
  • Max-Subtract Stability: Subtracting m(\mathbf{q}) = \max_j a(\mathbf{q}, \mathbf{k}_j) prevents 0/0 = NaN underflow.