A bigram model predicts from the latest token alone, and a table indexed by longer contexts is too large to fill (Section 9.6). The book’s model takes a different route. At each position it forms a weighted average of vectors computed from the earlier tokens, and the weights are themselves computed from the tokens: each position decides how much to draw on each earlier one. That operation is attention. Its parameters are a few matrices whose sizes do not depend on how many tokens came before, so the same parameters serve every context length.
This chapter defines attention and the variants that the book’s model uses: scaled dot products, the causal mask, several heads and position embeddings. Each comes with a mathematical reason. Dividing the scores by the square root of the length of the vectors keeps the softmax away from the region where its derivatives vanish. The causal mask stops each position from drawing on later ones, so each prediction depends only on the past, and work done for earlier positions can be stored and reused. Position embeddings are needed because attention without them ignores the order of the tokens. The chapter ends with the derivative of attention, which shows how gradients pass through it, and with its cost.
10.1 Attention as a lookup
A lookup table (a dictionary, in programming) stores pairs of a key and a value, and answers a query by returning the value whose key equals the query. A model that wants to use earlier tokens could store, for each earlier position, a key describing it and a value carrying its information, and give the current position a query describing what it needs, to be matched against the keys. An exact lookup cannot be trained by gradient descent: moving the query slightly either changes nothing or jumps to a different value, so its derivative with respect to the query is zero wherever it exists. Attention replaces the exact match by a graded one.
Take a query \(\mathbf{q} = (1, 1, 1, 1)\) and three keys \(\mathbf{k}_1 = (1, 1, 0, 0)\), \(\mathbf{k}_2 = (1, -1, 0, 0)\), \(\mathbf{k}_3 = (0, 0, 1, -1)\), stored with values \(\mathbf{v}_1 = (1, 0)\), \(\mathbf{v}_2 = (0, 1)\), \(\mathbf{v}_3 = (0, 0)\). Score each key by its dot product with the query: \(2, 0, 0\). Divide the scores by \(2\) (the square root of the width 4; Section 10.2 explains why), giving \(1, 0, 0\). The softmax of Definition 8.5, \(\operatorname{softmax}(\mathbf{s})_j = e^{s_j}/\sum_r e^{s_r}\), turns the scores into weights that are positive and sum to 1, \[
\frac{(e, 1, 1)}{e + 2} \approx (0.576, 0.212, 0.212),
\] and the answer is the weighted average of the values, \(\bigl(e/(e+2),\, 1/(e+2)\bigr) \approx (0.576, 0.212)\). The first key matches the query best, and its value dominates without taking over completely. Every step is differentiable, so a small change in the query, a key or a value changes the answer a little.
Definition 10.1 (Attention) Let \(\mathbf{q}\in\mathbb{R}^{d_h}\) be a query, \(\mathbf{k}_1, \dots, \mathbf{k}_T\in\mathbb{R}^{d_h}\)keys and \(\mathbf{v}_1, \dots, \mathbf{v}_T\in\mathbb{R}^{d_v}\)values. The scores and attention weights are \[
s_j = \frac{\mathbf{q}\cdot\mathbf{k}_j}{\sqrt{d_h}}, \qquad
\mathbf{a} = \operatorname{softmax}(\mathbf{s}),
\quad\text{so}\quad
a_j = \frac{e^{s_j}}{\sum_{r=1}^{T} e^{s_r}} ,
\] and the output of attention is \[
\operatorname{Attn}(\mathbf{q}; \mathbf{k}_{1:T}, \mathbf{v}_{1:T})
= \sum_{j=1}^{T} a_j\mathbf{v}_j .
\tag{10.1}\] In matrix form, let \(K\) be the \(T\times d_h\) matrix with rows \(\mathbf{k}_j^\top\) and \(V\) the \(T\times d_v\) matrix with rows \(\mathbf{v}_j^\top\). For queries \(\mathbf{q}_1, \dots, \mathbf{q}_m\), the rows of an \(m\times d_h\) matrix \(Q\), \[
\operatorname{Attn}(Q, K, V) = A V, \qquad
A = \operatorname{softmax}\Bigl(\frac{QK^\top}{\sqrt{d_h}}\Bigr),
\tag{10.2}\] where softmax acts on each row separately.
In Equation 10.2, row \(t\) of \(Q\) is query \(t\), and row \(j\) of \(K\) and row \(j\) of \(V\) are the key and the value stored together as item \(j\). Entry \((t, j)\) of the \(m\times T\) matrix \(QK^\top/\sqrt{d_h}\) is the score of key \(j\) for query \(t\). After the softmax, row \(t\) of the \(m\times T\) matrix \(A\) holds the weights that query \(t\) gives to the \(T\) keys, so each row sums to 1, and row \(t\) of \(AV\) is the output for query \(t\). (In this chapter \(V\) is the matrix of values. The vocabulary, which Definition 9.1 also calls \(V\), does not appear by name in this chapter.)
The weights are positive and sum to 1, so the output is a convex combination of the values, a weighted sum with non-negative weights that add up to 1. Each component of the output therefore lies between the smallest and largest values of that component. In a model the query, keys and values come from three different linear maps, so “matching” can mean whatever training makes it mean.
Attention was introduced for translation (Bahdanau et al. 2014), where the query comes from the sentence being written and the keys and values from the sentence being translated. The scaled dot-product form of Definition 10.1 is from Vaswani et al. (2017).
10.2 Why the scores are scaled
The dot product of two vectors of width \(d_h\) is a sum of \(d_h\) terms, so it tends to grow with the width. For vectors with random entries the growth can be measured exactly. Let each component of \(\mathbf{q}\) and \(\mathbf{k}\) be \(1\) or \(-1\), each with probability \(\tfrac12\), independently. With \(d_h = 2\) the dot product \(q_1k_1 + q_2k_2\) is a sum of two terms that are each \(\pm1\) with probability \(\tfrac12\), so it equals \(2\), \(0\) or \(-2\) with probabilities \(\tfrac14\), \(\tfrac12\), \(\tfrac14\). Its mean is \(0\) and its variance is \(\tfrac14\cdot4 + \tfrac12\cdot0 + \tfrac14\cdot4 = 2\). The variance equals the width, and the next theorem shows that this is no coincidence. So the standard deviation of an unscaled score, its typical size, grows like \(\sqrt{d_h}\), and dividing by \(\sqrt{d_h}\) undoes the growth.
The proof uses the probability of Section 6.1: random variables on a finite probability space with their expectations and variances (Definition 6.1 and Definition 6.3), and independence (Definition 6.2). It also uses four facts proved there. Expectation is linear by Theorem 6.1, and functions of independent random vectors are independent by Lemma 6.1. The expectation of a product of independent random variables is the product of the expectations by Theorem 6.2, and \(\operatorname{Var}[X] = \mathbb{E}[X^2] - \mathbb{E}[X]^2\) and \(\operatorname{Var}[cX] = c^2\operatorname{Var}[X]\) for every real \(c\) by Lemma 6.2.
Theorem 10.1 (Size of a random dot product) Let \(\mathbf{q}\) and \(\mathbf{k}\) be independent random vectors in \(\mathbb{R}^{d_h}\) on a finite probability space. Suppose that every component \(q_i\) and \(k_i\) has mean \(0\) and variance \(1\), and that for \(i \ne j\) the components \(q_i\) and \(q_j\) are independent, and so are \(k_i\) and \(k_j\). Then \[
\mathbb{E}[\mathbf{q}\cdot\mathbf{k}] = 0, \qquad
\operatorname{Var}[\mathbf{q}\cdot\mathbf{k}] = d_h ,
\] and the score \(s = \mathbf{q}\cdot\mathbf{k}/\sqrt{d_h}\) has mean \(0\) and variance \(1\).
Proof. Each component has mean \(0\) and variance \(1\), so by Lemma 6.2\(\mathbb{E}[q_i^2] = 1\), and likewise \(\mathbb{E}[k_i^2] = 1\). For \(i \ne j\), \(\mathbb{E}[q_iq_j] = \mathbb{E}[q_i]\,\mathbb{E}[q_j] = 0\) by Theorem 6.2, and likewise \(\mathbb{E}[k_ik_j] = 0\).
Any function of \(\mathbf{q}\) is independent of any function of \(\mathbf{k}\) by Lemma 6.1. So, by linearity of expectation (Theorem 6.1) and Theorem 6.2, \[
\mathbb{E}[\mathbf{q}\cdot\mathbf{k}] = \sum_{i=1}^{d_h}\mathbb{E}[q_ik_i]
= \sum_{i=1}^{d_h}\mathbb{E}[q_i]\,\mathbb{E}[k_i] = 0 .
\] Expanding the square of the dot product and grouping the factors from each vector, \[
\mathbb{E}[(\mathbf{q}\cdot\mathbf{k})^2]
= \sum_{i=1}^{d_h}\sum_{j=1}^{d_h}\mathbb{E}\bigl[(q_iq_j)(k_ik_j)\bigr]
= \sum_{i=1}^{d_h}\sum_{j=1}^{d_h}\mathbb{E}[q_iq_j]\,\mathbb{E}[k_ik_j] .
\] The terms with \(i \ne j\) are \(0\), and the \(d_h\) terms with \(i = j\) are \(1\cdot1\). So \(\operatorname{Var}[\mathbf{q}\cdot\mathbf{k}] = \mathbb{E}[(\mathbf{q}\cdot\mathbf{k})^2] - 0^2 = d_h\). Finally, by Theorem 6.1 and Lemma 6.2 with \(c = 1/\sqrt{d_h}\), the score has mean \(0\) and variance \(d_h/d_h = 1\).
The hypotheses hold in particular when all \(2d_h\) components are drawn independently of one another, as when the entries of a model are initialised at random. The book proves the facts about independence and expectation only on finite probability spaces. As Section 7.5 notes, they hold for random variables with densities too, in the sense of Definition 7.4, including the normal distributions used to initialise the book’s model, and with them the theorem. For any distributions whose variances exist, Billingsley (1995, Theorem 20.2 and eq. (21.18)) proves them using measure theory. The same calculation appears in a footnote of Vaswani et al. (2017).
Why does the size of the scores matter? Compare the softmax of the scores \((1, 0, -1)\) with the softmax of \((8, 0, -8)\). The first gives weights \((0.665, 0.245, 0.090)\); the second gives \((0.99966, 0.00034, 0.0000001)\), essentially all the weight on one key. Gradients reach the scores only through the derivatives of the softmax, and by Theorem 8.4 these are \[
\frac{\partial a_i}{\partial s_j} = a_i\bigl([i = j] - a_j\bigr),
\tag{10.3}\] where \([i = j]\) is \(1\) if \(i = j\) and \(0\) otherwise: entry \((i, j)\) of the Jacobian is the rate at which weight \(i\) changes per unit increase of score \(j\). For the scores \((1, 0, -1)\) the largest entry in absolute value is about \(0.22\); for \((8, 0, -8)\) it is about \(0.0003\). When one weight is close to 1 we say that the softmax saturates, and then every derivative is small.
Lemma 10.1 Let \(\mathbf{s}\in\mathbb{R}^T\) and \(\mathbf{a} = \operatorname{softmax}(\mathbf{s})\), and let \(0 \le \varepsilon \le 1\). If some component satisfies \(a_m \ge 1 - \varepsilon\), then every entry of the Jacobian of softmax at \(\mathbf{s}\) has absolute value at most \(\varepsilon\).
Proof. The weights are positive and sum to 1, so every \(a_i\) with \(i \ne m\) is at most \(1 - a_m \le \varepsilon\). By Equation 10.3, the diagonal entry for \(i\) is \(a_i(1 - a_i)\), which is at most \(1 - a_m \le \varepsilon\) when \(i = m\) and at most \(a_i \le \varepsilon\) otherwise. An off-diagonal entry is \(-a_ia_j\) with \(i \ne j\), so at least one of \(i\), \(j\) differs from \(m\), and \(|a_ia_j| \le \varepsilon\).
The effect shows in Table 10.1, for random queries and keys with independent standard normal components, \(T = 8\) keys, and 20,000 random trials for each row, with and without the scale.
Table 10.1: Saturation of the softmax for random scores. The spread is the standard deviation of the scores; the Jacobian entry is the largest absolute entry of the softmax Jacobian in a trial; the last column is the fraction of trials in which one weight exceeds 0.99.
\(d_h\)
scores
spread of scores
mean largest weight
median largest Jacobian entry
largest weight above 0.99
4
unscaled
2.01
0.53
0.23
0.7%
4
scaled
1.00
0.34
0.21
0%
16
unscaled
3.98
0.75
0.17
9.4%
16
scaled
1.00
0.36
0.22
0%
64
unscaled
7.99
0.88
0.03
37.6%
64
scaled
1.00
0.36
0.22
0%
With the scale, the weights and the derivatives look the same at every width. Without it, at \(d_h = 64\) (the head width of Vaswani et al. (2017)) more than a third of the trials have one weight above 0.99, and the typical largest derivative is less than a sixth of its scaled value, so gradient steps barely change the queries and keys. The book’s model has \(d_h = 4\), where the unscaled spread is only 2 and the effect is mild; the scale matters for wider heads, and the model keeps it to follow the standard design.
Why divide by \(\sqrt{d_h}\) and not by some other power of \(d_h\), such as \(d_h\) itself? Under the hypotheses of Theorem 10.1, the score \(\mathbf{q}\cdot\mathbf{k}/d_h^{\alpha}\) has variance \(d_h/d_h^{2\alpha} = d_h^{1-2\alpha}\), which is the same for every width only when \(\alpha = \tfrac12\). A smaller power lets the scores grow with the width, and the softmax saturates as in the table. A larger power makes them shrink. Dividing by \(d_h\) gives scores of variance \(1/d_h\), so for wide heads every score is close to \(0\) and every weight close to \(1/T\), whatever the query and the keys. At \(d_h = 64\) with \(T = 8\) keys these scores have standard deviation \(1/8\), and in 20,000 random trials like those of the table the largest weight averages about \(0.15\) and the smallest about \(0.10\), on either side of the uniform weight \(1/8 = 0.125\). Attention would then return nearly the plain average of the values, whatever the query. Among the powers of \(d_h\), only \(\sqrt{d_h}\) keeps the scores at variance 1 for every width, neither saturating the softmax nor flattening it.
10.3 Self-attention and the causal mask
In a language model the queries, keys and values all come from the same sequence. The sequence has \(T\) positions, \(t = 1, \dots, T\), and position \(t\) holds the token \(x_t\); the computation at position \(t\) ends in the prediction of the token at position \(t + 1\). Each position holds a vector \(\mathbf{x}_t\in\mathbb{R}^d\). In the book’s model this vector is built from the embedding of the token, the learned vector \(\mathbf{u}_{x_t}\) that is row \(x_t\) of the embedding matrix \(E\) of Definition 9.6, as Section 10.5 describes. Three \(d_h\times d\) matrices \(W_Q\), \(W_K\), \(W_V\) turn it into a query, a key and a value: \[
\mathbf{q}_t = W_Q\mathbf{x}_t, \qquad
\mathbf{k}_t = W_K\mathbf{x}_t, \qquad
\mathbf{v}_t = W_V\mathbf{x}_t .
\] Row \(i\) of \(W_Q\) gives component \(i\) of a query as a linear combination of the \(d\) components of the vector at that position, and likewise for \(W_K\) and \(W_V\); the same three matrices serve every position. If \(X\) is the \(T\times d\) matrix whose row \(t\) is \(\mathbf{x}_t^\top\) (one row per position, one column per component), then the queries are the rows of \(Q = XW_Q^\top\), and similarly \(K = XW_K^\top\) and \(V = XW_V^\top\).
For the smallest example take \(d = d_h = 1\) and all three matrices equal to \(1\), so \(q_t = k_t = v_t = x_t\), and take two positions with \(x_1 = 1\) and \(x_2 = 2\). Position 1 has query \(1\) and keys \(1\) and \(2\), so its scores are \(1\) and \(2\) (the scale \(\sqrt{d_h}\) is \(1\)). Its weights are \((e, e^2)/(e + e^2) \approx (0.27, 0.73)\), and its output is \[
y_1 = \frac{e\cdot1 + e^2\cdot2}{e + e^2} \approx 1.731 .
\]
Definition 10.2 (Self-attention) Let \(\mathbf{x}_1, \dots, \mathbf{x}_T\in\mathbb{R}^d\) and let \(W_Q\), \(W_K\), \(W_V\) be \(d_h\times d\) matrices. The self-attention of \(\mathbf{x}_1, \dots, \mathbf{x}_T\) is the list of outputs \(\mathbf{y}_t = \operatorname{Attn}(\mathbf{q}_t; \mathbf{k}_{1:T}, \mathbf{v}_{1:T})\) for \(t = 1, \dots, T\), with \(\mathbf{q}_t = W_Q\mathbf{x}_t\), \(\mathbf{k}_t = W_K\mathbf{x}_t\) and \(\mathbf{v}_t = W_V\mathbf{x}_t\). They are the rows of \(\operatorname{Attn}(XW_Q^\top, XW_K^\top, XW_V^\top)\).
In self-attention every position sees every other, including later ones, and that is a problem for a language model. In the example, position 1 puts weight \(0.73\) on position 2. A language model predicts the token at position 2 from the vector at position 1. If that vector could see position 2, the model could read the answer instead of predicting it, and the product of its predictions would not be the factorisation of Theorem 9.1, in which the probability of each token is conditioned only on the tokens before it. The causal mask removes the later positions.
Definition 10.3 (Causal mask) Let \(\mathbf{q}_t\), \(\mathbf{k}_t\), \(\mathbf{v}_t\) for \(t = 1, \dots, T\) be as in Definition 10.2, with scores \(s_{tj} = \mathbf{q}_t\cdot\mathbf{k}_j/\sqrt{d_h}\). Causal (or masked) self-attention gives position \(t\) weights only on positions \(j \le t\): \[
a_{tj} = \begin{cases}
\dfrac{e^{s_{tj}}}{\sum_{r=1}^{t} e^{s_{tr}}} & j \le t,\\[2ex]
0 & j > t,
\end{cases}
\qquad
\mathbf{y}_t = \sum_{j=1}^{T} a_{tj}\mathbf{v}_j .
\] The causal mask is the \(T\times T\) matrix \(M\) with entries \(m_{tj} = 0\) for \(j \le t\) and \(m_{tj} = -\infty\) for \(j > t\). With the convention \(e^{-\infty} = 0\), the weight matrix \(A = (a_{tj})\) is the softmax, row by row, of \(S + M\), where \(S = QK^\top/\sqrt{d_h}\) is the matrix of scores \(s_{tj}\).
The weight \(a_{tj}\) is how much position \(t\) draws on position \(j\): the softmax of the scores of positions \(1\) to \(t\), and \(0\) for later positions. The weight matrix \(A\) is lower triangular (row \(t\) has non-zero entries only in columns \(1\) to \(t\)), and each row still sums to 1. Adding \(M\) hides, or masks, the scores of the later positions, which is where the name comes from, and programs compute \(A\) this way. In the example above, position 1 now attends only to itself, and \(y_1 = 1\).
The mask has a consequence that the rest of the book relies on: the output at position \(t\) can be computed from positions \(1\) to \(t\) alone, so the work done for earlier positions never needs redoing when a new token arrives.
Theorem 10.2 (Causal attention needs only the past) Let \(\mathbf{y}_1, \dots, \mathbf{y}_T\) be the outputs of causal self-attention of \(\mathbf{x}_1, \dots, \mathbf{x}_T\) with matrices \(W_Q\), \(W_K\), \(W_V\). For each \(t\):
\(\mathbf{y}_t = \operatorname{Attn}(\mathbf{q}_t; \mathbf{k}_{1:t}, \mathbf{v}_{1:t})\), the unmasked attention of \(\mathbf{q}_t\) over the keys and values of positions \(1, \dots, t\) only;
\(\mathbf{y}_t\) depends only on \(\mathbf{x}_1, \dots, \mathbf{x}_t\): changing the vectors at positions after \(t\), or appending more positions, leaves \(\mathbf{y}_t\) unchanged.
Proof.
In Definition 10.3 the terms with \(j > t\) have weight \(0\), so \(\mathbf{y}_t = \sum_{j=1}^{t} a_{tj}\mathbf{v}_j\), and for \(j \le t\) the weight \(a_{tj}\) is the softmax of the \(t\) scores \(s_{t1}, \dots, s_{tt}\). That is Definition 10.1 with the \(t\) keys \(\mathbf{k}_1, \dots, \mathbf{k}_t\) and values \(\mathbf{v}_1, \dots, \mathbf{v}_t\).
By (a), \(\mathbf{y}_t\) is computed from \(\mathbf{q}_t\) and from \(\mathbf{k}_j\), \(\mathbf{v}_j\) for \(j \le t\), and each of these is a fixed matrix times one of \(\mathbf{x}_1, \dots, \mathbf{x}_t\).
Part (a) is what a key–value cache relies on. To generate text, a model computes position after position. At position \(t\) it computes \(\mathbf{k}_t\) and \(\mathbf{v}_t\), appends them to a list of the keys and values of the earlier positions (the cache), and attends from \(\mathbf{q}_t\) over the list. By part (b), the keys and values already in the list never need recomputing, because adding a position does not change anything at earlier positions. The microgpt program (Karpathy 2026) works exactly this way, during training as well as generation: it processes one position at a time and keeps the keys and values in lists. By Theorem 10.2 this computes the same outputs as applying the mask to all positions at once. The code below does both on random inputs and prints the largest difference.
demo = np.random.default_rng(0)T, d =5, 4X = demo.normal(size=(T, d))WQ, WK, WV = (demo.normal(size=(d, d)) for _ inrange(3))Q, K, V = X @ WQ.T, X @ WK.T, X @ WV.T# All positions at once, with scores above the diagonal set to -inf.S = Q @ K.T / np.sqrt(d)S[np.triu_indices(T, k=1)] =-np.infA = np.exp(S - S.max(axis=1, keepdims=True))Y_masked = (A / A.sum(axis=1, keepdims=True)) @ V# One position at a time, keeping the keys and values seen so far.keys, values, Y_cached = [], [], []for t inrange(T): keys.append(K[t]) values.append(V[t]) s = np.array(keys) @ Q[t] / np.sqrt(d) a = np.exp(s - s.max()) Y_cached.append((a / a.sum()) @ np.array(values))print(np.abs(Y_masked - np.array(Y_cached)).max())
2.220446049250313e-16
The difference is at the level of rounding error in floating-point arithmetic.
The same property makes a causal model a language model in the sense of Definition 9.3, a distribution for the next token given each context. Every other operation in the book’s model acts on each position separately, so the vector at position \(t\), and with it the prediction of the token at position \(t + 1\), depends only on the tokens at positions \(1, \dots, t\).
10.4 Multi-head attention
A single set of attention weights gives each position one way to combine the others, and one set of weights cannot favour two different positions for two different reasons. Take \(d = 4\), the query \(\mathbf{q} = (1, 0, 0, 1)\) and two keys \(\mathbf{k}_1 = (1, 0, 0, 0)\) and \(\mathbf{k}_2 = (0, 0, 0, 1)\). Both dot products are \(1\), so one attention of width 4 gives the weights \((0.5, 0.5)\). Now split every vector into two halves of width 2 and attend separately in each half. In the first halves the query \((1, 0)\) matches \(\mathbf{k}_1\)’s \((1, 0)\) and not \(\mathbf{k}_2\)’s \((0, 0)\); the scores are \(1/\sqrt2\) and \(0\), and the weights are about \((0.67, 0.33)\). In the second halves the roles swap and the weights are about \((0.33, 0.67)\). Each half is called a head, here of width \(d_h = 2\). The two heads draw mainly on different positions, and their outputs are kept side by side.
Definition 10.4 (Multi-head attention) Let \(d = hd_h\) with integers \(h, d_h \ge 1\), let \(\mathbf{x}_1, \dots, \mathbf{x}_T\in\mathbb{R}^d\), and let \(W_Q\), \(W_K\), \(W_V\), \(W_O\) be \(d\times d\) matrices. For each position \(t\) compute \(\mathbf{q}_t = W_Q\mathbf{x}_t\), \(\mathbf{k}_t = W_K\mathbf{x}_t\) and \(\mathbf{v}_t = W_V\mathbf{x}_t\), and split each into \(h\) blocks of \(d_h\) consecutive components, \(\mathbf{q}_t = (\mathbf{q}_t^{(1)}, \dots, \mathbf{q}_t^{(h)})\) and likewise for keys and values. Head\(i\) applies causal self-attention (Definition 10.3) of width \(d_h\) to the \(i\)th blocks: \[
\mathbf{o}_t^{(i)} = \sum_{j\le t} a^{(i)}_{tj}\mathbf{v}_j^{(i)},
\qquad
a^{(i)}_{tj} = \frac{e^{\mathbf{q}^{(i)}_t\cdot\mathbf{k}^{(i)}_j/\sqrt{d_h}}}
{\sum_{r\le t}e^{\mathbf{q}^{(i)}_t\cdot\mathbf{k}^{(i)}_r/\sqrt{d_h}}} .
\] The heads’ outputs are stacked into \(\mathbf{o}_t = (\mathbf{o}_t^{(1)}, \dots, \mathbf{o}_t^{(h)})\in\mathbb{R}^d\), and the output of multi-head attention at position \(t\) is \(\mathbf{y}_t = W_O\mathbf{o}_t\). Without the mask (sums over all \(j\) and \(r\) from \(1\) to \(T\)) this is unmasked multi-head attention.
Block \(i\) of \(\mathbf{q}_t = W_Q\mathbf{x}_t\) is \(W_Q^{(i)}\mathbf{x}_t\), where \(W_Q^{(i)}\) consists of rows \((i-1)d_h + 1\) to \(id_h\) of \(W_Q\). So each head is the single-head attention of Section 10.3 with its own \(d_h\times d\) matrices, and the heads differ only in which rows of \(W_Q\), \(W_K\) and \(W_V\) they use. Each head has its own weights \(a^{(i)}_{tj}\). In the product \(W_O\mathbf{o}_t\), columns \((i-1)d_h + 1\) to \(id_h\) of \(W_O\) multiply the output of head \(i\), so row \(k\) of the \(d\times d\) matrix \(W_O\) gives component \(k\) of \(\mathbf{y}_t\) as a linear combination of the outputs of all the heads: the output matrix\(W_O\) mixes the heads’ results (Exercise 10.8). The scale is \(1/\sqrt{d_h}\) because \(d_h\), the width of a head, is the length of the dot products in each head (Theorem 10.1).
The book’s model has \(d = 16\) and \(h = 4\) heads of width \(d_h = 4\), following microgpt (Karpathy 2026). Its four matrices have \(4\cdot16^2 = 1024\) parameters, the same as one head of width 16 would use: splitting changes how the components are combined, not how many weights there are.
10.5 Order and position
Nothing in Definition 10.1 refers to where a key sits in the list. Return to the example of Section 10.3, with \(q_t = k_t = v_t = x_t\), and use unmasked self-attention. For the inputs \((1, 2)\) the outputs are \[
y_1 = \frac{e\cdot1 + e^2\cdot2}{e + e^2} \approx 1.731, \qquad
y_2 = \frac{e^2\cdot1 + e^4\cdot2}{e^2 + e^4} \approx 1.881 .
\] For the swapped inputs \((2, 1)\) the outputs are \((1.881, 1.731)\): the same two numbers, swapped. Attention saw the same query and the same set of key–value pairs at each token, only listed in a different order, and the order of a sum does not matter.
To state this in general we need a name for reordering. A permutation of \(\{1, \dots, T\}\) is a function \(\pi\) from \(\{1, \dots, T\}\) to itself that takes every value exactly once. It reorders a sequence: the sequence \(\mathbf{x}_{\pi(1)}, \dots, \mathbf{x}_{\pi(T)}\) has at position \(t\) the vector that was at position \(\pi(t)\). Its permutation matrix is the \(T\times T\) matrix \(\Pi\) with \(\Pi_{t,\pi(t)} = 1\) and all other entries \(0\); row \(t\) of \(\Pi\) is \(\mathbf{e}_{\pi(t)}^\top\), so row \(t\) of \(\Pi X\) is row \(\pi(t)\) of \(X\). For \(T = 2\), the swap \(\pi(1) = 2\), \(\pi(2) = 1\) has permutation matrix \(\Pi = \begin{pmatrix} 0 & 1\\ 1 & 0 \end{pmatrix}\), and the example says that \(F(\Pi X) = \Pi F(X)\) when \(F\) is unmasked self-attention and \(X = (1, 2)^\top\). A map \(F\) from \(T\times d\) matrices to \(T\times d\) matrices is permutation equivariant if \(F(\Pi X) = \Pi F(X)\) for every \(T\times T\) permutation matrix \(\Pi\): reordering the rows of the input reorders the rows of the output in the same way.
Theorem 10.3 (Permutation equivariance) Let \(d = hd_h\), let \(W_Q\), \(W_K\), \(W_V\), \(W_O\) be \(d\times d\) matrices, and let \(F\) be unmasked multi-head attention (Definition 10.4) with these matrices, written as the map from the \(T\times d\) matrix \(X\) with rows \(\mathbf{x}_t^\top\) to the \(T\times d\) matrix \(F(X)\) with rows \(\mathbf{y}_t^\top\). Then \(F\) is permutation equivariant: for every \(T\times T\) permutation matrix \(\Pi\) and every \(T\times d\) matrix \(X\), \[
F(\Pi X) = \Pi F(X) .
\]
Proof. Let \(X' = \Pi X\), so \(\mathbf{x}'_t = \mathbf{x}_{\pi(t)}\). The queries, keys and values are computed position by position, so \(\mathbf{q}'_t = \mathbf{q}_{\pi(t)}\), \(\mathbf{k}'_j = \mathbf{k}_{\pi(j)}\) and \(\mathbf{v}'_j = \mathbf{v}_{\pi(j)}\), and the same holds for their blocks. For head \(i\), \[
\mathbf{o}'^{(i)}_t
= \frac{\sum_{j=1}^{T} e^{\mathbf{q}^{(i)}_{\pi(t)}\cdot\mathbf{k}^{(i)}_{\pi(j)}/\sqrt{d_h}}\,\mathbf{v}^{(i)}_{\pi(j)}}
{\sum_{r=1}^{T} e^{\mathbf{q}^{(i)}_{\pi(t)}\cdot\mathbf{k}^{(i)}_{\pi(r)}/\sqrt{d_h}}} .
\] As \(j\) runs over \(1, \dots, T\), so does \(\pi(j)\), each value once, so the sum in the numerator is the same sum as with \(\pi(j)\) replaced by \(j\), and the same holds for the denominator. So \(\mathbf{o}'^{(i)}_t = \mathbf{o}^{(i)}_{\pi(t)}\) for every head, hence \(\mathbf{o}'_t = \mathbf{o}_{\pi(t)}\) and \(\mathbf{y}'_t = W_O\mathbf{o}_{\pi(t)} = \mathbf{y}_{\pi(t)}\). Row \(t\) of \(F(\Pi X)\) is row \(\pi(t)\) of \(F(X)\), which is row \(t\) of \(\Pi F(X)\).
Maps that act on each position separately, such as the MLP of Definition 7.3 applied to every \(\mathbf{y}_t\), also commute with \(\Pi\). So a model built from unmasked attention and such maps, with no information about position, gives the same outputs, reordered, for every reordering of its input. It cannot tell ab from ba. The causal mask breaks this symmetry only partly.
Corollary 10.1 Let \(\mathbf{y}_1, \dots, \mathbf{y}_T\) be the outputs of causal multi-head attention (Definition 10.4) of \(\mathbf{x}_1, \dots, \mathbf{x}_T\), and let \(2 \le t \le T\). Then \(\mathbf{y}_t\) is unchanged when \(\mathbf{x}_1, \dots, \mathbf{x}_{t-1}\) are permuted among themselves.
Proof. By Theorem 10.2(a), applied to each head, \(\mathbf{o}^{(i)}_t\) is the unmasked attention of \(\mathbf{q}^{(i)}_t\) over the keys and values at positions \(1, \dots, t\). Permuting positions \(1, \dots, t-1\) leaves \(\mathbf{x}_t\), and so \(\mathbf{q}^{(i)}_t\), unchanged, and reorders the key–value pairs. The proof of Theorem 10.3 shows that reordering the pairs does not change the sums in Equation 10.1.
The book’s model has a single layer of attention, and every other operation acts on one position at a time. Without position information, its prediction after position \(t\) would depend only on the token at \(t\) and on which tokens came before, not on their order: it would give the same distribution for the letter after emm as after mem. Position embeddings remove this limitation by giving each position a vector of its own, added to the vector of whatever token sits there.
In the example with \(d = 1\), add the number \(p_1 = 0\) at position 1 and \(p_2 = 1\) at position 2. The inputs \((1, 2)\) become \((1, 3)\), and the swapped inputs \((2, 1)\) become \((2, 2)\), which is not a reordering of \((1, 3)\). Unmasked self-attention now gives the outputs \((2.762, 2.995)\) for the first order and \((2, 2)\) for the second, so the two orders are told apart.
Definition 10.5 (Position embeddings) Let \(E\) be a token embedding matrix of width \(d\), as in Definition 9.6, so that token \(a\) has embedding \(\mathbf{u}_a\), row \(a\) of \(E\) written as a column. Let \(T_{\max}\), the context length, be the largest number of positions the model accepts. A position embedding matrix is a \(T_{\max}\times d\) matrix \(E_{\mathrm{pos}}\) with rows \(\mathbf{p}_1^\top, \dots, \mathbf{p}_{T_{\max}}^\top\). The input vector at position \(t\) of a sequence of tokens \(x_1, x_2, \dots\) is the sum of the token embedding and the position embedding, \[
\mathbf{x}_t = \mathbf{u}_{x_t} + \mathbf{p}_t .
\]
Row \(t\) of \(E_{\mathrm{pos}}\) is the vector added at position \(t\), whatever token sits there. Permuting the tokens now moves the vectors \(\mathbf{u}_{x_t}\) but leaves the \(\mathbf{p}_t\) in place, so the new inputs are not a permutation of the old ones, and the conclusion of Theorem 10.3 does not apply to them. The book’s model, like microgpt, learns \(E_{\mathrm{pos}}\) along with the other parameters, with \(T_{\max} = 16\) and \(d = 16\), so 256 parameters; microgpt adds the two embeddings and then normalises the sum (Chapter 11). The original transformer used fixed vectors built from sines and cosines instead, and its authors report that learned position embeddings gave nearly identical results (Vaswani et al. 2017, sec. 3.5).
10.6 How gradients pass through attention
Training needs the derivative of the loss with respect to every parameter, and Chapter 4 computes it by passing adjoints back through each operation. For attention, the derivative with respect to the query shows the pattern. Start with the smallest case: \(d_h = 1\), keys \(k_1 = 1\) and \(k_2 = -1\), values \(v_1 = 1\) and \(v_2 = 0\). At \(q = 0\) both scores are \(0\), the weights are \(\tfrac12\) each, and the output is \(y = \tfrac12\). At \(q = 0.01\) the scores are \(\pm0.01\), the first weight rises to about \(0.505\), and so does \(y\): the output changes at a rate of about \(0.5\) per unit increment of \(q\). The increment raised the score of the key that is above average (\(k_1 = 1\), against the average key \(0\)), and that key’s value is above the average output. The theorem below says that the derivative is always built from these two deviations.
Theorem 10.4 (Jacobian of attention with respect to the query) Fix keys \(\mathbf{k}_1, \dots, \mathbf{k}_T\in\mathbb{R}^{d_h}\) and values \(\mathbf{v}_1, \dots, \mathbf{v}_T\in\mathbb{R}^{d_v}\), the rows of matrices \(K\) and \(V\), and let \(\mathbf{y}(\mathbf{q}) = \operatorname{Attn}(\mathbf{q}; \mathbf{k}_{1:T}, \mathbf{v}_{1:T})\) with weights \(\mathbf{a}\). Then \(\mathbf{y}\) is differentiable at every \(\mathbf{q}\in\mathbb{R}^{d_h}\), and with \(\mathbf{c} = \sum_j a_j\mathbf{k}_j\), the weighted average of the keys, \[
J_{\mathbf{y}}(\mathbf{q})
= \frac{1}{\sqrt{d_h}}\,V^\top\bigl(\operatorname{diag}(\mathbf{a}) - \mathbf{a}\mathbf{a}^\top\bigr)K
= \frac{1}{\sqrt{d_h}}\sum_{j=1}^{T} a_j\,(\mathbf{v}_j - \mathbf{y})(\mathbf{k}_j - \mathbf{c})^\top .
\tag{10.4}\]
The Jacobian is a \(d_v\times d_h\) matrix: entry \((i, l)\) is the rate at which component \(i\) of the output changes per unit increment of component \(l\) of the query. The second form has the shape of a covariance, an average of products of deviations: each position contributes the deviation of its value from the output, times the deviation of its key from the average key, weighted by its attention weight.
Proof. The map \(\mathbf{y}\) is a composition of three maps: \(\mathbf{q}\mapsto\mathbf{s} = K\mathbf{q}/\sqrt{d_h}\), which is linear with Jacobian \(K/\sqrt{d_h}\) (Example 1.6); then \(\mathbf{s}\mapsto\mathbf{a} = \operatorname{softmax}(\mathbf{s})\), with Jacobian \(\operatorname{diag}(\mathbf{a}) - \mathbf{a}\mathbf{a}^\top\) by Theorem 8.4; then \(\mathbf{a}\mapsto V^\top\mathbf{a}\), linear with Jacobian \(V^\top\). By the chain rule, Theorem 2.1, the composition is differentiable and its Jacobian is the product, the first form in Equation 10.4.
For the second form, expand. Since \(V^\top\operatorname{diag}(\mathbf{a})K = \sum_j a_j\mathbf{v}_j\mathbf{k}_j^\top\), \(V^\top\mathbf{a} = \mathbf{y}\) and \(K^\top\mathbf{a} = \mathbf{c}\), the first form is \(\frac{1}{\sqrt{d_h}}\bigl(\sum_j a_j\mathbf{v}_j\mathbf{k}_j^\top - \mathbf{y}\mathbf{c}^\top\bigr)\). Using \(\sum_j a_j = 1\), \[
\sum_j a_j(\mathbf{v}_j - \mathbf{y})(\mathbf{k}_j - \mathbf{c})^\top
= \sum_j a_j\mathbf{v}_j\mathbf{k}_j^\top - \mathbf{y}\mathbf{c}^\top
- \mathbf{y}\mathbf{c}^\top + \mathbf{y}\mathbf{c}^\top ,
\] which is the same matrix.
In the opening example, \(c = 0\), \(y = \tfrac12\), and the formula gives \(\tfrac12\cdot\tfrac12\cdot1 + \tfrac12\cdot(-\tfrac12)(-1) = \tfrac12\), the rate found from the increment. If all keys are equal, \(\mathbf{k}_j = \mathbf{c}\) for every \(j\) and the Jacobian is zero: the weights are uniform for every query. If the weights are concentrated on one position, the Jacobian is small.
Corollary 10.2 Let \(\mathbf{y}(\mathbf{q})\) be attention with keys \(\mathbf{k}_1, \dots, \mathbf{k}_T\in\mathbb{R}^{d_h}\) and values \(\mathbf{v}_1, \dots, \mathbf{v}_T\), and suppose that \(\|\mathbf{k}_j\| \le B_k\) and \(\|\mathbf{v}_j\| \le B_v\) for all \(j\). If at the query \(\mathbf{q}\) some weight satisfies \(a_m \ge 1 - \varepsilon\), with \(0 \le \varepsilon \le 1\), then every entry of \(J_{\mathbf{y}}(\mathbf{q})\) has absolute value at most \(8\varepsilon B_kB_v/\sqrt{d_h}\).
Proof. An entry of a matrix \(\mathbf{u}\mathbf{w}^\top\) is \(u_iw_l\), of absolute value at most \(\|\mathbf{u}\|\,\|\mathbf{w}\|\). The vectors \(\mathbf{y}\) and \(\mathbf{c}\) are convex combinations, so \(\|\mathbf{y}\| \le B_v\) and \(\|\mathbf{c}\| \le B_k\) by the triangle inequality, and so \(\|\mathbf{v}_j - \mathbf{y}\| \le 2B_v\) and \(\|\mathbf{k}_j - \mathbf{c}\| \le 2B_k\). The terms with \(j \ne m\) in Equation 10.4 have weights summing to \(1 - a_m \le \varepsilon\), so together they contribute at most \(4\varepsilon B_kB_v\) to each entry. For \(j = m\), \(\mathbf{v}_m - \mathbf{y} = \sum_{j\ne m} a_j(\mathbf{v}_m - \mathbf{v}_j)\), so \(\|\mathbf{v}_m - \mathbf{y}\| \le 2\varepsilon B_v\), and the term contributes at most \(a_m\cdot2\varepsilon B_v\cdot2B_k \le 4\varepsilon B_kB_v\). Dividing by \(\sqrt{d_h}\) gives the bound.
In reverse mode (Chapter 4) the adjoint of the output, \(\bar{\mathbf{y}} = \partial L/\partial\mathbf{y}\), becomes the adjoint of the query by multiplying by the transpose of the Jacobian: \[
\bar{\mathbf{q}} = J_{\mathbf{y}}^\top\bar{\mathbf{y}}
= \frac{1}{\sqrt{d_h}}\sum_{j=1}^{T} a_j\,\bigl((\mathbf{v}_j - \mathbf{y})\cdot\bar{\mathbf{y}}\bigr)\,(\mathbf{k}_j - \mathbf{c}) .
\] Each position contributes its key’s deviation from the average key, weighted by its attention weight and by how much its value’s deviation from the output agrees with \(\bar{\mathbf{y}}\). A gradient step moves the query by \(-\eta\bar{\mathbf{q}}\), so towards the keys whose values would move the output in the direction that lowers the loss, and away from the others. Corollary 10.2 and Table 10.1 show the same thing from two sides: when the weights saturate, this signal fades. Exercise 10.6 gives the derivatives with respect to the keys and values.
10.7 Cost
How much arithmetic does one layer of attention need, and how does it grow with the number of positions? Count multiplications for multi-head attention on \(T\) positions with width \(d\). The four matrices cost \(d^2\) multiplications per position each, \(4Td^2\) in all. Each head computes \(T^2\) scores, dot products of length \(d_h\), and then \(T\) weighted sums of \(T\) value vectors of length \(d_h\): \(2T^2d_h\) multiplications per head, and \(2T^2d\) over the \(h\) heads. The total is \[
4Td^2 + 2T^2d .
\] The first term grows linearly with \(T\) and the second quadratically, so attention takes \(O(T^2d)\) time (at most a constant multiple of \(T^2d\) operations), on top of the \(O(Td^2)\) for the matrices, and storing the weights takes \(T^2\) numbers per head. The causal mask halves the attention term, since only the \(T(T+1)/2\) pairs with \(j \le t\) are needed. The quadratic term overtakes the linear one when \(T > 2d\). For the book’s model, \(T \le 16\) and \(d = 16\), so the matrices cost \(4\cdot16\cdot16^2 = 16{,}384\) multiplications and the masked attention \(16\cdot17\cdot16 = 4352\): at this size the cost is in the matrices. For long documents the \(T^2\) term dominates, and much work on large models goes into reducing it.
10.8 Notes and further reading
Attention was introduced for translation by Bahdanau et al. (2014), with scores from a small network rather than a dot product. Vaswani et al. (2017) built the transformer from scaled dot-product attention, with several heads, a causal mask for generation and position encodings, and their footnote 4 gives the variance argument of Theorem 10.1. Jurafsky and Martin (2026, ch. 7) explain attention, causal masking and multi-head attention in the setting of language modelling. Karpathy (2026) describes the small model this book rebuilds, including its key–value cache and learned position embeddings. Grinstead and Snell (1997, sec. 6.1 and §6.2) treat expectation, variance and independence for discrete random variables, and Billingsley (1995, sec. 20 and §21) gives the general theory.
10.9 Exercises
Exercise 10.1 Let \(d_h = 1\), \(q = 2\), keys \(k_1 = 1\), \(k_2 = 0\), \(k_3 = -1\) and values \(v_1 = 1\), \(v_2 = 2\), \(v_3 = 3\). Find the attention weights and the output, exactly and to three decimal places.
Exercise 10.2
Show that adding the same vector \(\mathbf{b}\) to every key leaves the attention weights unchanged.
Show that adding the same vector \(\mathbf{w}\) to every value adds \(\mathbf{w}\) to the output.
Exercise 10.3 Fix a query, keys and values, and replace the scores \(s_j\) by \(\lambda s_j\) with \(\lambda > 0\). Let \(M\) be the set of \(j\) with \(s_j\) equal to the largest score. Show that as \(\lambda\to\infty\) the weights tend to \(1/|M|\) for \(j\in M\) and to \(0\) otherwise, so the output tends to the average of the values \(\mathbf{v}_j\) with \(j\in M\). What do the weights tend to as \(\lambda\to0\)?
Exercise 10.4
Generalise Theorem 10.1: keep its hypotheses except that \(\operatorname{Var}[q_i] = \sigma^2\) and \(\operatorname{Var}[k_i] = \tau^2\) for every \(i\), and show that \(\operatorname{Var}[\mathbf{q}\cdot\mathbf{k}] = d_h\sigma^2\tau^2\).
In the book’s model, at initialisation each entry of \(W_Q\) and \(W_K\) is drawn independently from the normal distribution with mean 0 and standard deviation \(0.08\), and after RMS normalisation (Chapter 11) the input vectors to attention have squared norm close to 16. Treat a query \(\mathbf{q} = W_Q\mathbf{x}\) and a key \(\mathbf{k} = W_K\mathbf{x}'\) as coming from fixed vectors with \(\|\mathbf{x}\|^2 = \|\mathbf{x}'\|^2 = 16\). Find the variance of each component of \(\mathbf{q}\) and of \(\mathbf{k}\), and then the variance of a score in a head of width 4. What does this say about the attention weights at the start of training?
Exercise 10.5 A model generates \(T\) tokens one at a time with one head of causal attention. Count the dot products \(\mathbf{q}_t\cdot\mathbf{k}_j\) it computes (a) with a key–value cache, and (b) if at each step it recomputes attention for every position so far from scratch. Evaluate both for \(T = 16\).
Exercise 10.6 In the setting of Theorem 10.4, show that \[
\frac{\partial\mathbf{y}}{\partial\mathbf{v}_j} = a_jI
\qquad\text{and}\qquad
\frac{\partial\mathbf{y}}{\partial\mathbf{k}_j}
= \frac{a_j}{\sqrt{d_h}}\,(\mathbf{v}_j - \mathbf{y})\,\mathbf{q}^\top ,
\] where each is the Jacobian of \(\mathbf{y}\) as a function of \(\mathbf{v}_j\) or \(\mathbf{k}_j\) alone, with everything else fixed.
Exercise 10.7 Take \(T = 2\), \(d = d_h = 1\) and \(W_Q = W_K = W_V = 1\), so \(q_t = k_t = v_t = x_t\). Compute the causal self-attention outputs for the input \((x_1, x_2) = (1, 2)\) and for the swapped input \((2, 1)\), and show that the outputs for the swapped input are not the swapped outputs.
Exercise 10.8 Write \(W_O = \bigl(W_O^{(1)}\ \cdots\ W_O^{(h)}\bigr)\), where \(W_O^{(i)}\) consists of columns \((i-1)d_h + 1\) to \(id_h\). Show that \(W_O\mathbf{o}_t = \sum_{i=1}^{h} W_O^{(i)}\mathbf{o}^{(i)}_t\), so multi-head attention is a sum of \(h\) single-head attentions, each with its own output matrix.
Bahdanau, Dzmitry, Kyunghyun Cho, and Yoshua Bengio. 2014. Neural Machine Translation by Jointly Learning to Align and Translate. https://arxiv.org/abs/1409.0473.
Vaswani, Ashish, Noam Shazeer, Niki Parmar, et al. 2017. “Attention Is All You Need.”Advances in Neural Information Processing Systems 30. https://arxiv.org/abs/1706.03762.