CodeRigor

LESSON

Attention: queries, keys and values

Replace the single context vector with a weighted lookup: scaled dot-product attention with masks, then several heads in parallel, matched against PyTorch.

An encoder-decoder that passes a single fixed vector from the encoder to the decoder forces the whole input through that one vector, however long the input is. Attention removes the bottleneck. At every output step the model scores all input positions and takes a weighted average of what they hold. This lesson pairs with Lecture 18 of CMU's 11-785 (Fall 2026), linked under Watch & read. You build scaled dot-product attention with masks, then multi-head self-attention, in NumPy, and check both against PyTorch.

Three roles make up one lookup. A query is the question being asked. Every input position offers a key, which is matched against the query, and a value, which is what comes back. Score each key against the query with a dot product, turn the scores into weights with a softmax, and return the weighted sum of the values: weights = softmax(q Kᵀ / √d) and out = weights V. For Tq queries and Tk keys, q is (Tq, d), K is (Tk, d), V is (Tk, dv) and the weights are (Tq, Tk), one row per query, each row summing to 1. Extra leading axes for batch or heads pass straight through the same matrix products.

The division by √d is there because of how dot products grow. If the entries of q and k are independent with mean 0 and variance 1, then q·k is a sum of d terms and has variance d, so its typical size is √d. Large scores push the softmax towards one key with weight near 1, and there its slope is close to zero, so little gradient flows back. Dividing by √d keeps the scores at about the same size whatever d is.

Python
import numpy as np

rng = np.random.default_rng(0)
for d in (4, 64, 1024):
    a, b = rng.normal(size=(20000, d)), rng.normal(size=(20000, d))
    print(d, (a * b).sum(axis=1).std().round(1))   # about sqrt(d)

q, keys = np.ones(64), np.array([np.full(64, 0.5), np.full(64, 0.25)])
for scale in (1.0, np.sqrt(64)):
    s = keys @ q / scale
    w = np.exp(s - s.max()) / np.exp(s - s.max()).sum()
    print(round(scale, 1), w.round(3).tolist())

The last two lines use d = 64. Without the scale the scores are 32 and 16 and the weights are [1.0, 0.0]. With it the scores are 4 and 2 and the weights are [0.881, 0.119]. The second key still counts.

Causal attention weights for four positions
Each row is one query, each column one key. The hatched cells were set to -inf before the softmax, so they hold exactly 0 and every row still sums to 1. Values are rounded to two places.
Causal attention weights for four positions
Each row is one query, each column one key. The hatched cells were set to -inf before the softmax, so they hold exactly 0 and every row still sums to 1. Values are rounded to two places.

Masks say which keys a query may use, and they act on the scores before the softmax. A padding mask blocks positions that are not real tokens, because batches are padded to one length. A causal mask blocks later positions, so a model that predicts the next token cannot read it. In both cases the disallowed score is set to -inf, exp(-inf) is exactly 0, and the softmax normalises over the allowed keys only. If you zero the weights after the softmax instead, the mass the forbidden keys took is lost and the row no longer sums to 1.

Python
import numpy as np

def softmax(s):
    e = np.exp(s - s.max(axis=-1, keepdims=True))
    return e / e.sum(axis=-1, keepdims=True)

scores = np.array([2.0, 1.0, 0.0, -1.0])
allowed = np.array([True, True, False, False])
before = softmax(np.where(allowed, scores, -np.inf))
after = softmax(scores) * allowed
print(before.round(3).tolist(), before.sum().round(3))
print(after.round(3).tolist(), after.sum().round(3))

x = np.array([[1.0, 0.0], [0.0, 1.0], [1.0, 1.0], [-1.0, 1.0]])   # four positions
causal = np.tril(np.ones((4, 4), dtype=bool))
for row in softmax(np.where(causal, x @ x.T / np.sqrt(2), -np.inf)).round(2).tolist():
    print(row)

A query with no allowed key has nothing to normalise over, so this build raises ValueError for it. PyTorch's functions do not agree on what to return for such a row, and the tests stay clear of the case.

One attention function looks at the input in one way. Multi-head attention runs several in parallel. Project x of shape (N, T, E) with one matrix to get q, k and v, each (N, T, E). Cut the E channels into h heads of size E/h, attend within each head on its own, concatenate the heads and apply an output projection. The scale uses the head size E/h, because that is the length of the dot products being taken.

One multi-head self-attention layer
start / 4
Shapes under each box, with h heads of size d = E / h. The head split is a reshape followed by a transpose.
One multi-head self-attention layer
Shapes under each box, with h heads of size d = E / h. The head split is a reshape followed by a transpose.

The head split is where shapes go wrong. The E channels are laid out head after head, so a reshape to (N, T, h, d) is right, and the transpose that follows puts the head axis in front of time. A single reshape straight to (N, h, T, d) has the right shape and the wrong contents.

Python
import numpy as np

x = np.arange(12).reshape(1, 3, 4)            # 3 positions, 4 channels, 2 heads of size 2
right = x.reshape(1, 3, 2, 2).transpose(0, 2, 1, 3)
wrong = x.reshape(1, 2, 3, 2)
print(right[0, 0].tolist())                   # head 0: channels 0-1 of every position
print(wrong[0, 0].tolist())                   # a mix of positions and channels

The mistakes people make are the ones above. A mask applied after the softmax leaves rows that do not sum to 1. A reshape with no transpose runs fine and gives a plausible number in the right shape. Scaling by √E where the head size belongs flattens every head's weights a little. And the two PyTorch masks use opposite conventions: in F.scaled_dot_product_attention a boolean True means allowed, while in nn.MultiheadAttention it means not allowed.

The tests compare your functions with PyTorch's, with the same four parameters, for 1, 2 and 4 heads, with causal and padding masks alone and together, to about 1e-10. The weights are also checked against a softmax written directly in the test. That shows your code computes the same function as PyTorch's layer for these inputs. It does not show that the layer is useful, that the weights mean anything for a trained model, or that your own batch is padded the way you expect.

Watch & read

Free lectures, talks and readings that cover this skill from another angle. All resources →