Review: from seq2seq attention to differentiable lookup
Review additive and multiplicative attention in recurrent encoder-decoder models, then express attention as differentiable key-value lookup and Nadaraya-Watson kernel smoothing. Compare recurrent, convolutional, and attention layers, and establish the tensor shapes and einsum notation used throughout this module.
After this lesson you can
- Rewrite Bahdanau and Luong attention in terms of queries, keys, and values.
- Interpret attention as soft dictionary lookup and as Nadaraya-Watson regression with an exponential kernel.
- Compare RNNs, CNNs, and self-attention by per-layer cost, sequential operations, and maximum path length.
- Express batched attention operations with einsum and explicit tensor shapes (B, T, d).
Before you start
A memory to query
When translating a sentence, the decoder needs different information for each word it produces. The first recurrent encoder-decoder compressed the entire input into a single vector. The context-vector bottleneck is that this representation must carry all useful information, regardless of sentence length. Bahdanau, Cho and Bengio proposed a soft search over the encoder states at each decoder step.
The idea extends beyond translation: store a collection of key-value pairs and use a query to build a query-dependent mixture. In the figure, the position of each blue point is a key; the number under each bar is its value. Drag the query and watch the mass redistribute. The figure uses five explicit pairs defined in its code, not training results.
From recurrent alignment to queries, keys, and values
In Bahdanau’s additive attention, the encoder produces states . At step , the query is the previous decoder state ; each encoder state serves as both key and value. An alignment network computes a score , for example
The context depends on the query, so it changes as the decoder advances. Encoder states are reused for the same input, although their weights change. The original mechanism calculates the context before the new recurrent state; other architectures may choose a different order.
In the multiplicative attention of Luong, Pham and Manning, an option called general scores . The query can be viewed as and the key as ; the value remains . The dot variant omits the matrix when the dimensions match. Luong also studies a local variant that restricts the states queried, in addition to the global one. Do not confuse the state used in this formulation with the previous state in the additive formulation above.
With and scalar values, sensitivity can be calculated exactly. If , the softmax derivative gives
The figure’s readout calculates this expression. A hard argmax lookup is constant in each region where one key wins, so its gradient is zero there and undefined at tie boundaries. Soft lookup is differentiable for , but does not guarantee a large gradient: at low temperature it can saturate away from boundaries; at high temperature the factor also reduces it. With fixed weights, the output is linear in the values; nonlinearity with respect to the query comes from the weights.
Let be the maximum score before division by temperature. Subtracting before exponentiation leaves softmax unchanged and prevents overflow. This is the same numerical trick as in log-sum-exp. If the maximum is unique, as all the losing ratios tend to zero and the output tends to the winning value. If maxima are tied, the limit is their mean, rather than an arbitrary selection. As , all exponentials tend to one and the output tends to the mean of all values.
Attention as a kernel smoother
In regression, you observe pairs and want to estimate a response at . The Nadaraya-Watson smoother is
For a positive kernel , its normalized weights are exactly the softmax of the scores. In particular, gives dot-product attention. The link with kernel density estimation is the normalized local average, but here we estimate a conditional response rather than a density. Bandwidth selection controls locality and smoothness.
The figure uses nine fixed abscissas, values plus fixed perturbations, and the Gaussian kernel . Without projection ; when enabled, . The row is a matrix fitted by least squares to the nine pairs with features . This is a deliberately small example of learned geometry, not an evaluation of generalization: the same points are used for fitting and visualization. Points far apart in can become close in the learned representation. On expanding the square, for a fixed query the term cancels in softmax, leaving a dot product plus a key-norm bias. Thus a general Gaussian kernel is not equivalent to a bare dot product unless the key norms are equal or that bias is included.
Bandwidth changes the statistical trade-off: when is very large, all weights approach and the curve loses detail. When is small, nearby points in the chosen representation dominate. In a region with few observations, the prediction can still depend on a single distant point, because the weights are normalized even when all kernels are small. Normalization does not by itself provide a measure of confidence. Moreover, the figure’s small fit uses the responses to learn : an honest evaluation needs separate test data and a bandwidth-selection procedure that does not consult them.
To see the correspondence exactly, define and . Then
The last term is the same for all keys in a row and disappears upon normalization. The second does depend on the key: removing it generally changes the distribution. For example, doubling a key increases its dot product with an aligned query, although it can also move it farther away in Euclidean distance. Score geometry is a modeling decision, not an automatic property of softmax.
Paths, parallelism, and cost
An RNN transmits information along the sequential chain: the next step’s state depends on the previous one. A local causal convolution connects each position to positions in the preceding layer. A full attention layer lets one position directly read another. In the animation, a signal starts at the first position; each step represents a recurrent transition or a layer of the indicated network of connections.
For the causal CNN in the figure, dilations are and each layer connects offsets from to times the dilation. After layers it reaches distance ; without dilation it reaches . These are connectivity assumptions, not measured times. The bars show reach, not the strength or quality of information; causal attention can read the past, not the future.
Table 1 of Vaswani et al. compares asymptotic costs per layer, sequential operations, and maximum path length for sequence length , width , and kernel . For dense self-attention it gives , , and ; for recurrence , , and ; for convolution , , and in its configuration. The figure explicitly uses a causal CNN without dilation or with exponential dilation, so its layer formula is a different instance. Q, K, V, and output projections typically add to attention; the term describes interactions. A materialized weight matrix takes memory per head. These bounds do not predict actual latency without considering hardware and kernels.
Batched shapes and contractions
Shape notation distinguishes batch , query positions , key positions , key width , value width , and heads . In this lesson there is no explicit head dimension: has shape , is , and is . The score matrix is and the output . Mathematical indices start at 1 and Python indices at 0.
Einsum notation expresses which index is summed: bqd,bkd->bqk contracts and retains ; bqk,bkv->bqv contracts . Also check the broadcasting rules: a batch dimension of size 1 can be broadcast silently when you expected independent batches. Check shapes before multiplying. Path length and parallelism describe dependencies between operations, not a guarantee of efficiency for a particular implementation.
Lab: Luong and Nadaraya-Watson with NumPy
The first cell computes general Luong attention for two queries and four states. It fixes the seed, displays the shapes, and checks that weight rows sum to one. The second performs the same calculation with batched einsum. The third verifies the Nadaraya-Watson identity with an exponential kernel. These are synthetic data to test the algebra, not a trained translation system.
import numpy as np
rng = np.random.default_rng(18)
states = rng.normal(size=(4, 3))
decoder = rng.normal(size=(2, 2))
W = rng.normal(size=(2, 3))
scores = decoder @ W @ states.T
z = scores - scores.max(axis=-1, keepdims=True)
weights = np.exp(z) / np.exp(z).sum(axis=-1, keepdims=True)
context = weights @ states
print('scores, pesos, contexto:', scores.shape, weights.shape, context.shape)
print('sumas:', weights.sum(axis=-1))Q = np.stack([decoder @ W, decoder @ W + 0.2])
K = np.stack([states, states * 0.8])
V = K.copy()
S = np.einsum('bqd,bkd->bqk', Q, K)
E = np.exp(S - S.max(axis=-1, keepdims=True))
A = E / E.sum(axis=-1, keepdims=True)
O = np.einsum('bqk,bkv->bqv', A, V)
assert np.allclose(O[0], context)
print('Q, K, V, S, O:', Q.shape, K.shape, V.shape, S.shape, O.shape)
print('diferencia primer lote:', np.max(np.abs(O[0] - context)))x = np.array([-1., 0., 1.])
y = np.array([2., -1., 3.])
query = 0.5
kernel = np.exp(query * x)
nw = (kernel @ y) / kernel.sum()
prob = np.exp(query * x - np.max(query * x))
prob /= prob.sum()
attention = prob @ y
assert np.allclose(nw, attention)
print('NW y atención:', nw, attention)xs = np.arange(-2., 2.01, 0.5)
noise = np.array([0.12, -0.08, 0.04, -0.1, 0.07, 0.09, -0.06, 0.03, -0.08])
ys = np.sin(2 * xs) + noise
features = np.column_stack([np.ones(len(xs)), xs, xs**3])
intercept, w1, w3 = np.linalg.lstsq(features, ys, rcond=None)[0]
print('intercepto, matriz de proyección:', intercept, w1, w3)
# El intercepto se cancela en las distancias entre representaciones.Associative memory and limits
If keys are stored patterns, a query close in the score geometry can retrieve a mixture of associated values. In a particular modern Hopfield network, the continuous update rule coincides with an attention operation; Ramsauer et al. study its fixed points and retrieval. The equivalence depends on that rule and parameterization: it does not imply that every arbitrary attention mechanism is a memory that converges or retrieves an exact pattern.
Exercises
import numpy as np
def attend(q, k, v, tau):
passStep 1 of 2. What happens to the ratio of the weight of a loser i to that of the winner m as τ tends to zero from above?