Module contents
Lesson 1 of 22Review 70 min

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.

InteractiveA differentiable dictionary
00.10.20.30.40.50.6v=-20.01637v=10.0914v=00.1477v=20.5641v=-10.1804
1.0
Weighted value1.006
Hard argmax (first maximum)2
Gradient norm with respect to q1.094
Drag q and change the temperature. Each key's size and the height of its bar represent its weight; the readout shows the mixture and the norm of its gradient.

From recurrent alignment to queries, keys, and values

In Bahdanau’s additive attention, the encoder produces states h1,…,hS\vb{h}_1,\ldots,\vb{h}_S. At step tt, the query is the previous decoder state st−1\vb{s}_{t-1}; each encoder state serves as both key and value. An alignment network computes a score eti=a(st−1,hi)e_{ti}=a(\vb{s}_{t-1},\vb{h}_i), for example

eti=va⊤tanh⁡(Wsst−1+Whhi),αti=eeti∑jeetj,ct=∑iαtihi.e_{ti}=\vb{v}_a\T\tanh(\mat{W}_s\vb{s}_{t-1}+\mat{W}_h\vb{h}_i),\qquad \alpha_{ti}=\frac{e^{e_{ti}}}{\sum_j e^{e_{tj}}},\qquad \vb{c}_t=\sum_i\alpha_{ti}\vb{h}_i.

The context ct\vb{c}_t 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 eti=st⊤Wahie_{ti}=\vb{s}_t\T\mat{W}_a\vb{h}_i. The query can be viewed as q=Wa⊤st\vb{q}=\mat{W}_a\T\vb{s}_t and the key as ki=hi\vb{k}_i=\vb{h}_i; the value remains hi\vb{h}_i. 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 st\vb{s}_t used in this formulation with the previous state in the additive formulation above.

With s(q,k)=q⊤ks(\vb{q},\vb{k})=\vb{q}\T\vb{k} and scalar values, sensitivity can be calculated exactly. If o=∑ipivio=\sum_i p_i v_i, the softmax derivative gives

∇qo=1τ∑ipi(vi−o)ki.\grad_{\vb{q}}o=\frac{1}{\tau}\sum_i p_i(v_i-o)\vb{k}_i.

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 τ>0\tau>0, but does not guarantee a large gradient: at low temperature it can saturate away from boundaries; at high temperature the factor 1/τ1/\tau also reduces it. With fixed weights, the output is linear in the values; nonlinearity with respect to the query comes from the weights.

Let mm be the maximum score before division by temperature. Subtracting mm 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 τ→0+\tau\to0^+ all the losing ratios exp⁡((si−m)/τ)\exp((s_i-m)/\tau) tend to zero and the output tends to the winning value. If rr maxima are tied, the limit is their mean, rather than an arbitrary selection. As τ→∞\tau\to\infty, 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 (xi,yi)(x_i,y_i) and want to estimate a response at xx. The Nadaraya-Watson smoother is

f^(x)=∑iKh(x,xi)yi∑jKh(x,xj).\hat f(x)=\frac{\sum_i K_h(x,x_i)y_i}{\sum_j K_h(x,x_j)}.

For a positive kernel Kh(x,xi)=exp⁡(s(x,xi))K_h(x,x_i)=\exp(s(x,x_i)), its normalized weights are exactly the softmax of the scores. In particular, K=exp⁡(q⊤k)K=\exp(\vb{q}\T\vb{k}) 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.

InteractiveNadaraya-Watson is attention
  • data, point size represents weight
  • regression
0.40
0.7
Prediction0.293
Move the query and bandwidth. Point size shows its weight for that query; enable projection to change distances in feature space.

The figure uses nine fixed abscissas, values sin⁡(2xi)\sin(2x_i) plus fixed perturbations, and the Gaussian kernel exp⁡(−∥ϕ(x)−ϕ(xi)∥2/(2h2))\exp(-\|\phi(x)-\phi(x_i)\|^2/(2h^2)). Without projection ϕ(x)=x\phi(x)=x; when enabled, ϕ(x)=w1x+w3x3\phi(x)=w_1x+w_3x^3. The row (w1,w3)(w_1,w_3) is a matrix fitted by least squares to the nine pairs with features (x,x3)(x,x^3). 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 xx can become close in the learned representation. On expanding the square, for a fixed query the term −∥ϕ(x)∥2/(2h2)-\|\phi(x)\|^2/(2h^2) 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 hh is very large, all weights approach 1/S1/S and the curve loses detail. When hh 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 ϕ\phi: an honest evaluation needs separate test data and a bandwidth-selection procedure that does not consult them.

To see the correspondence exactly, define z=ϕ(x)\vb{z}=\phi(x) and zi=ϕ(xi)\vb{z}_i=\phi(x_i). Then

−∥z−zi∥22h2=z⊤zih2−∥zi∥22h2−∥z∥22h2.-\frac{\norm{\vb{z}-\vb{z}_i}^2}{2h^2} =\frac{\vb{z}\T\vb{z}_i}{h^2}-\frac{\norm{\vb{z}_i}^2}{2h^2}-\frac{\norm{\vb{z}}^2}{2h^2}.

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 kk 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.

InteractiveInformation race
00.20.40.60.81RNN1CNN1Dilated1Attention1
32
3
step 0
RNN / CNN / dilated / attention steps31 / 16 / 5 / 1
Attention terms per layer1024d + 32d²
Play the steps and change T and k. Compare local propagation, dilated propagation, and the direct attention connection.

For the causal CNN in the figure, dilations are 1,2,4,…1,2,4,\ldots and each layer connects offsets from 00 to (k−1)(k-1) times the dilation. After LL layers it reaches distance (k−1)(2L−1)(k-1)(2^L-1); without dilation it reaches L(k−1)L(k-1). 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 TT, width dd, and kernel kk. For dense self-attention it gives O(T2d)O(T^2d), O(1)O(1), and O(1)O(1); for recurrence O(Td2)O(Td^2), O(T)O(T), and O(T)O(T); for convolution O(kTd2)O(kTd^2), O(1)O(1), and O(log⁡kT)O(\log_k T) 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 O(Td2)O(Td^2) to attention; the O(T2d)O(T^2d) term describes interactions. A materialized weight matrix takes O(T2)O(T^2) memory per head. These bounds do not predict actual latency without considering hardware and kernels.

Batched shapes and contractions

Shape notation distinguishes batch BB, query positions TqT_q, key positions TkT_k, key width dkd_k, value width dvd_v, and heads HH. In this lesson there is no explicit head dimension: QQ has shape (B,Tq,dk)(B,T_q,d_k), KK is (B,Tk,dk)(B,T_k,d_k), and VV is (B,Tk,dv)(B,T_k,d_v). The score matrix is (B,Tq,Tk)(B,T_q,T_k) and the output (B,Tq,dv)(B,T_q,d_v). Mathematical indices start at 1 and Python indices at 0.

Einsum notation expresses which index is summed: bqd,bkd->bqk contracts dd and retains b,q,kb,q,k; bqk,bkv->bqv contracts kk. 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.

[ ]Multiplicative attentionBrowser
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))
[ ]The same batched attentionBrowser
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)))
[ ]Exponential kernelBrowser
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)
[ ]Figure projectionBrowser
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

Quiz
At Bahdanau step t, for a fixed input, what changes when another word is produced?
Numeric
For q=1, keys 0, 1, 2 and values 0, 1, 3, calculate the scalar output with score qk and temperature 1.
Numeric
With the same pairs, calculate the output for temperature 0.1.
Code
Implement attend(q, k, v, tau): q has shape (B,Tq,d), k (B,Tk,d), and v (B,Tk,dv). Return the dot-product attention output using stable softmax over Tk. Assume positive tau and compatible shapes.
import numpy as np
def attend(q, k, v, tau):
  pass
Shift+Enter to run
Proof
Prove: With a unique maximum, the output tends to the winning value as τ goes to zero and to the mean of the values as τ goes to infinity.
0
Let the scores s_i and values v_i be fixed and finite.

Step 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?

Key idea
Attention turns compatibility between queries and keys into normalized weights, then uses those weights to mix values. The same calculation is a kernel smoother and a differentiable lookup; its shapes and connectivity pattern determine what is computed and at what cost.