10. Attention

Why this layer exists

Chapter 9’s model reads a fixed window of nn tokens. Every slot looks its token up in the same embedding table, but the concatenation then gives each slot its own (d, h) block of W1\mathbf{W}_1: one for the current token, one for the token before, and so on. What the block for “one back” learns about how a token affects the prediction does not transfer to the block for “two back”; only the shared embedding does. Nothing outside the window reaches the model at all. Widening the window adds another dhdh weights per slot and does not change the arrangement: each position still reads its neighbours at fixed offsets, whatever they contain. Text does not put the information a prediction needs at a fixed offset. The subject that fixes a verb’s agreement, the name a pronoun refers to, the opening bracket a closing one must match: each can be any distance back, and which earlier token matters depends on what the tokens are.

Attention replaces fixed offsets with a lookup by content. Every position computes three vectors from its own embedding: a query, what it is looking for; a key, what it offers to be found by; and a value, what it hands over when found. Position tt scores every position it can see by the dot product of its query with that position’s key, turns the scores into weights with a softmax, and takes the weighted sum of the values. Chapter 2 introduced the dot product as the similarity attention uses and read it as a weighted sum; both readings are here, the first for the scores and the second for the output. The weights are computed from the data, so the same three projection matrices serve every distance, and the parameter count does not depend on how far back the model reads.

In the models you run, each transformer block’s attention stores its projections as GGUF tensors named blk.N.attn_q.weight, blk.N.attn_k.weight and blk.N.attn_v.weight, with N the block number; some architectures store the three fused as attn_qkv, and attn_output is the projection chapter 11 adds after the heads. When llama-server processes a prompt, it computes the keys and values of every position in every layer and keeps them: that is its KV cache, which chapter 12 builds. (What this chapter says about llama.cpp and llama-server is as of llama.cpp commit da89bb3, 2026-09-29.) A new token needs the keys and values of all the positions before it and nothing else from them, so the cache holds two vectors per position, per head, per layer, and grows linearly with the context. For a model with 32 layers of 32 heads of width 128, at 2 bytes per number (llama-server’s default cache type, f16, set by --cache-type-k and --cache-type-v), that is 2×32×32×128×2=524,2882 \times 32 \times 32 \times 128 \times 2 = 524{,}288 bytes, 512 KiB, per token of context, and 16 GiB for 32,768 tokens. The -c you pass llama-server is a memory budget for this.

The chapter builds tinygpt.attention: a softmax Tensor op with its backward rule, the causal mask, scaled dot-product attention, and one causal attention head, gradient-checked as chapter 5 promised.

Mechanism

A lookup written as a sum

A dictionary maps keys to values. Store SS pairs (kj,vj)(\mathbf{k}_j, \mathbf{v}_j) and look up a query q\mathbf{q}: the answer is the vj\mathbf{v}_j whose key equals q\mathbf{q}. Written as arithmetic, with the Iverson bracket [P][P] equal to 1 when PP holds and 0 otherwise,

lookup(q)=∑j=1S[kj=q]vj. \mathrm{lookup}(\mathbf{q}) = \sum_{j=1}^{S} [\mathbf{k}_j = \mathbf{q}]\, \mathbf{v}_j .

If exactly one key matches, one term survives and the sum is that key’s value. As a layer in a network this has two defects. Keys computed from data never equal a query exactly, so the sum is almost always zero. And the bracket is a step function of q\mathbf{q} and the kj\mathbf{k}_j, with derivative zero wherever it is defined, so no gradient reaches the queries or keys and they cannot be learned.

Both are fixed by replacing the bracket with a graded weight. Score each key by its similarity to the query, zj=q⋅kjz_j = \mathbf{q} \cdot \mathbf{k}_j, large when the two point the same way, and turn the scores into weights with the softmax of chapter 4:

wj=ezj∑i=1Sezi,attend(q)=∑j=1Swjvj. w_j = \frac{e^{z_j}}{\sum_{i=1}^{S} e^{z_i}} , \qquad \mathrm{attend}(\mathbf{q}) = \sum_{j=1}^{S} w_j\, \mathbf{v}_j .

The weights are positive and sum to 1, so the output is a weighted average of the values, a point in their convex hull. Every step is differentiable. Two limits connect this to the lookup it replaces.

  • Sharp scores recover the hard lookup. Multiply every score by β>0\beta > 0. If key mm has the strictly largest score, then for j≠mj \ne m, wj/wm=eβ(zj−zm)→0w_j / w_m = e^{\beta (z_j - z_m)} \to 0 as β→∞\beta \to \infty, so wm→1w_m \to 1 and the output tends to vm\mathbf{v}_m. test_sharp_attention_is_a_lookup builds keys 30ej30\,\mathbf{e}_j, 30 times the standard basis vectors of length 4, and queries equal to keys 2 and 0. The query’s score against its own key is 900/4=450900 / \sqrt{4} = 450 and against the others 0, so the other weights are e−450e^{-450} relative to it and the output is value 2, then value 0, to within 10−610^{-6}.
  • Equal scores average. If all SS scores are equal, every weight is 1/S1/S and the output is the mean of the values. test_equal_scores_average_the_values makes the query zero, so every score is 0 whatever the keys.

Between the limits the output blends the values of the keys that match best, and the gradient says how to move the query, the keys and the values to make the blend better.

Queries, keys and values from one sequence

In self-attention all three come from the same sequence. The input is the batch of hidden states, (B, T, d_model), one vector per position. Three Linear layers without bias project it:

Q=XWQ,K=XWK,V=XWV, \mathbf{Q} = \mathbf{X}\mathbf{W}_Q , \qquad \mathbf{K} = \mathbf{X}\mathbf{W}_K , \qquad \mathbf{V} = \mathbf{X}\mathbf{W}_V ,

with X\mathbf{X} of shape (B, T, d_model), each W\mathbf{W} of shape (d_model, d) and each result of shape (B, T, d). Row tt of Q\mathbf{Q} is position tt’s query qt\mathbf{q}_t, and likewise for keys and values. One matrix product computes every score at once:

Z=QK⊤d, \mathbf{Z} = \frac{\mathbf{Q}\mathbf{K}^\top}{\sqrt{d}} ,

where K⊤\mathbf{K}^\top swaps the last two axes of K\mathbf{K}, (B, d, T), and Z\mathbf{Z} has shape (B, T, T): Zts=qt⋅ks/dZ_{ts} = \mathbf{q}_t \cdot \mathbf{k}_s / \sqrt{d}, the score of key position ss for query position tt. The division by d\sqrt{d} is derived next. A softmax along the last axis turns each row into weights, A=softmax(Z)\mathbf{A} = \mathrm{softmax}(\mathbf{Z}), shape (B, T, T), and

Attention(Q,K,V)=AV,(B,T,T)×(B,T,d)→(B,T,d), \mathrm{Attention}(\mathbf{Q}, \mathbf{K}, \mathbf{V}) = \mathbf{A}\mathbf{V} , \qquad (B, T, T) \times (B, T, d) \to (B, T, d) ,

row tt being ∑sAtsvs\sum_s A_{ts} \mathbf{v}_s. That is Vaswani and colleagues’ scaled dot-product attention. Nothing in it needs the keys and the queries to come from the same sequence: attention(q, k, v) takes queries of shape (..., T, d) against SS keys and values of shapes (..., S, d) and (..., S, d_v), and returns (..., T, d_v). Bahdanau, Cho and Bengio’s translation model, which brought this kind of attention to translation, has the decoder’s state query the encoder’s states. test_attention_shapes uses T=4T = 4 and S=6S = 6.

Why three separate projections rather than using X\mathbf{X} directly? With Q=K=X\mathbf{Q} = \mathbf{K} = \mathbf{X} the score of a position against itself, ∥xt∥2\lVert \mathbf{x}_t \rVert^2, beats its score against any position whose vector is no longer, since by Cauchy–Schwarz xt⋅xs≤∥xt∥∥xs∥\mathbf{x}_t \cdot \mathbf{x}_s \le \lVert \mathbf{x}_t \rVert \lVert \mathbf{x}_s \rVert, so a position tends to find itself; and the scores are symmetric: tt scores ss as highly as ss scores tt. Separate WQ\mathbf{W}_Q and WK\mathbf{W}_K make the score xtWQWK⊤xs⊤\mathbf{x}_t \mathbf{W}_Q \mathbf{W}_K^\top \mathbf{x}_s^\top, a learned bilinear form that can be asymmetric, so what a verb looks for can differ from what it offers. A separate WV\mathbf{W}_V decouples what a position is found by from what it passes on.

Why divide by d\sqrt{d}

Take the entries of q\mathbf{q} and k\mathbf{k} to be independent with mean 0 and variance 1. Each term of q⋅k=∑i=1dqiki\mathbf{q} \cdot \mathbf{k} = \sum_{i=1}^{d} q_i k_i is a product of two independent mean-zero variables, so, exactly as in chapter 9’s derivation for a layer’s output,

E[qiki]=E[qi]E[ki]=0,Var(qiki)=E[qi2]E[ki2]=1. \mathbb{E}[q_i k_i] = \mathbb{E}[q_i]\,\mathbb{E}[k_i] = 0 , \qquad \mathrm{Var}(q_i k_i) = \mathbb{E}[q_i^2]\,\mathbb{E}[k_i^2] = 1 .

The dd terms are independent, since no two share a variable, and variances of independent terms add:

Var(q⋅k)=d,Var(q⋅kd)=dd=1. \mathrm{Var}(\mathbf{q} \cdot \mathbf{k}) = d , \qquad \mathrm{Var}\!\left(\frac{\mathbf{q} \cdot \mathbf{k}}{\sqrt{d}}\right) = \frac{d}{d} = 1 .

A constant cc scales a variance by c2c^2, which is why the divisor is d\sqrt{d} and not dd. Without it the scores’ standard deviation grows as d\sqrt{d}: 32 at d=1024d = 1024.

That matters because of what large scores do to the softmax’s derivative. Write s=softmax(z)\mathbf{s} = \mathrm{softmax}(\mathbf{z}) for one row, both of shape (S,), and Σ=∑kezk\Sigma = \sum_k e^{z_k}. Then si=ezi/Σs_i = e^{z_i} / \Sigma, ∂ezi/∂zj=δijezi\partial e^{z_i} / \partial z_j = \delta_{ij} e^{z_i} and ∂Σ/∂zj=ezj\partial \Sigma / \partial z_j = e^{z_j}, and the quotient rule gives

∂si∂zj=δijeziΣ−eziezjΣ2=siδij−sisj=si(δij−sj). \frac{\partial s_i}{\partial z_j} = \frac{\delta_{ij} e^{z_i}\, \Sigma - e^{z_i} e^{z_j}}{\Sigma^2} = s_i \delta_{ij} - s_i s_j = s_i (\delta_{ij} - s_j) .

As a matrix, the Jacobian is J=diag(s)−ss⊤\mathbf{J} = \mathrm{diag}(\mathbf{s}) - \mathbf{s}\mathbf{s}^\top, shape (S, S), symmetric. Now let s\mathbf{s} approach a one-hot vector, all weight on key mm. The diagonal entry sm(1−sm)→1⋅0s_m(1 - s_m) \to 1 \cdot 0; every other diagonal entry si(1−si)→0s_i(1 - s_i) \to 0 because si→0s_i \to 0; and every off-diagonal entry −sisj-s_i s_j has at least one factor going to 0. The whole Jacobian goes to zero. A saturated softmax, like a saturated tanh in chapter 9, passes back almost no gradient: the scores that decide which key wins stop receiving any signal about whether it should.

Measured over 2,000 random queries against S=64S = 64 keys, entries N(0,1)N(0, 1), with the Frobenius norm ∥J∥F=(∑ijJij2)1/2\lVert \mathbf{J} \rVert_F = (\sum_{ij} J_{ij}^2)^{1/2} as the size of the Jacobian:

dd 16 64 256 1024
variance of unscaled scores 15.76 63.80 254.83 1026.21
mean largest weight, unscaled 0.5757 0.7882 0.8950 0.9475
mean ∥J∥F\lVert \mathbf{J} \rVert_F, unscaled 0.2926 0.2147 0.1270 0.0700
mean largest weight, scaled 0.1064 0.1071 0.1062 0.1080
mean ∥J∥F\lVert \mathbf{J} \rVert_F, scaled 0.1820 0.1834 0.1829 0.1842

Scaled, the weights look the same at every width, with a largest weight near 0.11 among 64 keys. Unscaled, the largest weight climbs toward 1 and, past the moderate sharpness of d=16d = 16 (where the Jacobian is larger than the scaled one: a row split between a few keys has bigger entries than a nearly uniform one, whose ∥J∥F\lVert \mathbf{J} \rVert_F is 0.124 here), the Jacobian shrinks, to 0.070 at d=1024d = 1024 and toward zero beyond. The division by d\sqrt{d} makes the sharpness at initialisation independent of the head width, and training can still sharpen a row where it helps by growing WQ\mathbf{W}_Q and WK\mathbf{W}_K.

The backward rule, without the Jacobian

softmax is a new Tensor op with its own backward pass, as chapter 8’s cross_entropy fused its log-softmax. Chapter 6’s rule for an op is: given g=∂L/∂s\mathbf{g} = \partial L / \partial \mathbf{s}, shape (S,), add ∂L/∂z\partial L / \partial \mathbf{z} into the input’s gradient. By the chain rule,

∂L∂zj=∑i∂L∂si∂si∂zj=∑igisi(δij−sj)=gjsj−sj∑igisi=sj(gj−g⋅s). \frac{\partial L}{\partial z_j} = \sum_i \frac{\partial L}{\partial s_i} \frac{\partial s_i}{\partial z_j} = \sum_i g_i\, s_i (\delta_{ij} - s_j) = g_j s_j - s_j \sum_i g_i s_i = s_j \big(g_j - \mathbf{g} \cdot \mathbf{s}\big) .

In vector form, with ⊙\odot the elementwise product,

∂L∂z=s⊙(g−(g⋅s)1), \frac{\partial L}{\partial \mathbf{z}} = \mathbf{s} \odot \big(\mathbf{g} - (\mathbf{g} \cdot \mathbf{s})\,\mathbf{1}\big) ,

the vector–Jacobian product J⊤g\mathbf{J}^\top \mathbf{g} (which equals Jg\mathbf{J}\mathbf{g}, J\mathbf{J} being symmetric). It costs one dot product and two elementwise operations, O(S)O(S) per row, where forming J\mathbf{J} and multiplying would cost O(S2)O(S^2) per row and, for the (B, T, T) scores, an array of BT3B T^3 numbers. For the whole array, g⋅s\mathbf{g} \cdot \mathbf{s} is (g * s).sum(axis=-1, keepdims=True), one number per row broadcast back across it. The formula also shows two properties the chapter uses. If g\mathbf{g} is the same in every entry, g−(g⋅s)1=0\mathbf{g} - (\mathbf{g} \cdot \mathbf{s})\mathbf{1} = \mathbf{0}, because s\mathbf{s} sums to 1: adding a constant to every output’s gradient changes nothing, which is why the lab’s tests weight the output by random numbers before summing, since ∑jsj=1\sum_j s_j = 1 has zero gradient and would check nothing. And wherever sj=0s_j = 0, the gradient to zjz_j is exactly 0.

The forward pass subtracts each row’s maximum before exponentiating. Softmax is unchanged by adding a constant cc to every score, since ezi+c/∑kezk+c=ecezi/(ec∑kezk)e^{z_i + c} / \sum_k e^{z_k + c} = e^{c} e^{z_i} / (e^{c} \sum_k e^{z_k}), so the shifted computation is exact, and the largest exponent is e0=1e^0 = 1, so nothing overflows: test_softmax_matches_numpy_and_sums_to_one feeds it the scores 1000 and 0, where e1000e^{1000} is infinite in float64. The backward pass needs no term for the shift, because the output does not depend on it.

The causal mask

A language model predicts the token at t+1t + 1 from positions 0,…,t0, \ldots, t. In training it makes all TT predictions of a window in one pass, so position tt must not read positions after tt: they contain the answer. The causal mask is a (T, T) array, 0 where the key position s≤ts \le t and −∞-\infty where s>ts > t, added to the scores before the softmax:

A=softmax(QK⊤d+M),Mts={0s≤t−∞s>t \mathbf{A} = \mathrm{softmax}\!\left(\frac{\mathbf{Q}\mathbf{K}^\top}{\sqrt{d}} + \mathbf{M}\right) , \qquad M_{ts} = \begin{cases} 0 & s \le t \\ -\infty & s > t \end{cases}

with M\mathbf{M} broadcast over the batch. A masked score contributes e−∞=0e^{-\infty} = 0 to its row’s numerator and denominator, so its weight is exactly 0 and the others renormalise among the visible keys. By the backward rule, a zero weight also gets zero gradient: nothing flows back to a future position’s key through a masked score. test_softmax_gradcheck_with_masked_entries checks the gradients with a mask in place.

Masking after the softmax, by zeroing the weights above the diagonal, is wrong in two ways. Take query position 1 of 4 with scores (1,2,0.5,3)(1, 2, 0.5, 3), keys 2 and 3 in its future. The softmax gives (0.0854,0.2321,0.0518,0.6308)(0.0854, 0.2321, 0.0518, 0.6308), and zeroing the future leaves weights summing to 0.3174: the output is no longer an average of the visible values but a third of one. Worse, the surviving weights depend on the future scores through the denominator. Change the score of key 3 from 3 to −1-1 and the zeroed row becomes (0.2242,0.6095,0,0)(0.2242, 0.6095, 0, 0): position 1’s output depends on position 3, which is the leak the mask exists to stop. Masking before the softmax gives (0.2689,0.7311,0,0)(0.2689, 0.7311, 0, 0) whatever the future scores are. (Zeroing and then dividing by the row sum also gives this; the additive mask does it in one step.)

The diagonal is never masked, since s=ts = t is allowed. So every row has at least one finite score, the row’s maximum is finite, and the max-shift never computes −∞−(−∞)-\infty - (-\infty), which is NaN. Row 0 has exactly one visible key, itself, so its weight is 1 and its output is its own value, which is what test_attention_with_one_key_returns_its_value checks in the unmasked case. The figure shows the causal weights of the head the lab script builds, and works through one of its rows.

Causal attention weights of the lab's head, and one query row worked through Left: a five by five grid of attention weights, rows the query positions 0 to 4 and columns the key positions 0 to 4, each cell on or below the diagonal shaded in proportion to its weight and each cell above the diagonal crossed out as masked. Row 0 puts all its weight on key 0; row 1 puts 0.944 on key 0; row 2 splits between keys 0 and 2; row 3 puts 0.848 on key 1 and 0.148 on key 3; row 4 puts 0.965 on key 2. Row 3 is outlined and expanded on the right, read top to bottom: the scores z j equal q 3 dot k j divided by the square root of d, for keys 0 to 4, a vector of shape (5,), to which the mask adds minus infinity at key 4. Softmax turns them into the weights 0.003, 0.848, 0.000 and 0.148, with weight 0 on the masked key 4. The output o 3 is the weighted sum of the values v 0 to v 3, each of shape (d,), so o 3 has shape (d,). key position 0 1 2 3 4 0 1 2 3 4 query position shade: weight, 0 to 1 cross: masked, weight exactly 0 row 3: one query against keys 0 to 4 zj = q3 · kj / √d + M3j softmax o3 = Σj wj vj (5,) (5,) (d,) w0 = 0.003 w1 = 0.848 w2 = 0.000 w3 = 0.148 w4 = 0 each weight scales one value vector, shape (d,)

Cost

Per head, QK⊤\mathbf{Q}\mathbf{K}^\top is a (T, d) by (d, T) product: T2dT^2 d multiply-adds. AV\mathbf{A}\mathbf{V} is (T, T) by (T, d): another T2dT^2 d. The projections cost 3Tdmodeld3 T d_{\text{model}} d, linear in TT. So attention’s time is O(T2d)O(T^2 d), and the score matrix it materialises takes O(T2)O(T^2) memory: it grows with the square of the context, where everything else in a layer grows linearly. At T=4096T = 4096 with 32 heads and 2 bytes per score, one layer’s scores take

40962×32×2=1,073,741,824 bytes=1 GiB, 4096^2 \times 32 \times 2 = 1{,}073{,}741{,}824 \text{ bytes} = 1 \text{ GiB} ,

for one sequence, in one layer, before the softmax’s output of the same size.

Nothing forces those scores to exist all at once. Each output row needs its row’s weights only through the sums ∑sezsvs\sum_s e^{z_s}\mathbf{v}_s and ∑sezs\sum_s e^{z_s}, and these can be accumulated block by block over the keys. The only obstacle is the max-shift, which needs the row’s maximum before the first exponential. Keep a running maximum mm, a running sum ℓ=∑ezs−m\ell = \sum e^{z_s - m} and a running unnormalised output o=∑ezs−mvs\mathbf{o} = \sum e^{z_s - m}\mathbf{v}_s over the keys seen so far. When a block of keys with scores zsz_s arrives, the new maximum is m′=max(m,maxszs)m' = \max(m, \max_s z_s); every term already in ℓ\ell and o\mathbf{o} was computed as ez−me^{z - m} and must become ez−m′=ez−mem−m′e^{z - m'} = e^{z - m} e^{m - m'}, so

ℓ′=ℓem−m′+∑s∈blockezs−m′,o′=oem−m′+∑s∈blockezs−m′vs, \ell' = \ell\, e^{m - m'} + \sum_{s \in \text{block}} e^{z_s - m'} , \qquad \mathbf{o}' = \mathbf{o}\, e^{m - m'} + \sum_{s \in \text{block}} e^{z_s - m'}\, \mathbf{v}_s ,

and after the last block the output is o/ℓ\mathbf{o} / \ell, exactly the softmax-weighted sum. Memory per query is one block of scores instead of a row of TT. The running maximum and rescaled sum ℓ\ell are Milakov and Gimelshein’s online normaliser; carrying the output accumulator o\mathbf{o} along with them, so that the weights are never stored, is the core of FlashAttention, which computes exact attention in tiles held in a GPU’s on-chip memory and never writes the (T, T) matrix out to the GPU’s main memory. llama-server’s -fa / --flash-attn option (on, off or auto, by default auto) selects such a fused kernel. The result is the same attention; the difference is memory traffic and footprint.

At generation time the square disappears. A new token is one query against the TT cached keys: TT scores, O(Td)O(Td) work per head, and no (T, T) matrix. The T2T^2 belongs to training and to processing a prompt, where all TT queries are present at once.

Order blindness

Without the mask, attention has no idea of order. Let P\mathbf{P} be a (T, T) permutation matrix, so PX\mathbf{P}\mathbf{X} reorders the rows of X\mathbf{X} and P⊤P=I\mathbf{P}^\top\mathbf{P} = \mathbf{I}. The projections act on each row separately, so (PX)WQ=PQ(\mathbf{P}\mathbf{X})\mathbf{W}_Q = \mathbf{P}\mathbf{Q}, and likewise PK\mathbf{P}\mathbf{K} and PV\mathbf{P}\mathbf{V}. The scores become

(PQ)(PK)⊤d=PQK⊤dP⊤=PZP⊤, \frac{(\mathbf{P}\mathbf{Q})(\mathbf{P}\mathbf{K})^\top}{\sqrt{d}} = \mathbf{P}\,\frac{\mathbf{Q}\mathbf{K}^\top}{\sqrt{d}}\,\mathbf{P}^\top = \mathbf{P}\mathbf{Z}\mathbf{P}^\top ,

the same scores with rows and columns reordered by the same permutation. The row softmax commutes with both: permuting rows moves whole rows, each normalised on its own, and permuting the entries within a row permutes its softmax the same way, since each weight depends only on its own score and the row’s sum, which a reordering leaves unchanged. So softmax(PZP⊤)=PAP⊤\mathrm{softmax}(\mathbf{P}\mathbf{Z}\mathbf{P}^\top) = \mathbf{P}\mathbf{A}\mathbf{P}^\top, and the output is

PAP⊤PV=PAV. \mathbf{P}\mathbf{A}\mathbf{P}^\top \mathbf{P}\mathbf{V} = \mathbf{P}\mathbf{A}\mathbf{V} .

Reordering the input reorders the output the same way and changes nothing else: attention is permutation-equivariant. As far as unmasked attention can tell, dog bites man and man bites dog are the same bag of three tokens. The lab script checks this numerically.

The causal mask breaks the symmetry only partly. PMP⊤≠M\mathbf{P}\mathbf{M}\mathbf{P}^\top \ne \mathbf{M} for every permutation but the identity, so the derivation above fails; but the output at position tt is still ∑s≤tAtsvs\sum_{s \le t} A_{ts}\mathbf{v}_s with weights computed from qt\mathbf{q}_t and the keys, a function of xt\mathbf{x}_t and the unordered set {x0,…,xt}\{\mathbf{x}_0, \ldots, \mathbf{x}_t\}. Swap positions 0 and 1 of a five-position input and a causal head’s outputs at positions 2, 3 and 4 are unchanged, checked numerically; only positions 0 and 1 differ. A causal head can tell which tokens came before, and roughly how many (a lone token at position 0 always gets weight 1), but not in what order. Chapter 11 gives the model positions: a learned vector per position added to the input, and rotary encodings, which rotate the queries and keys by angles that depend on position so that the scores depend on relative offsets.

Checking the gradients

Chapter 5 promised that this chapter would check its attention layer with numerical gradients. test_self_attention_layer_gradcheck builds SelfAttention(6, 4, rng) and a loss that installs four inputs, an input x of shape (2, 5, 6) and three (6, 4) weight matrices, runs the causal head and sums its (2, 5, 4) output weighted by fixed random numbers. gradcheck computes the gradient with respect to all four by backpropagation, then perturbs each of the 60+3×24=13260 + 3 \times 24 = 132 entries by ±10−6\pm 10^{-6}, recomputes the loss for each, 264 forward passes, and requires every central difference to match the backpropagated entry within an absolute 10−610^{-6} plus a relative 10−410^{-4}. The path from the loss to x runs through every op of the chapter: the three projections, the transpose, the scaled product, the mask addition, the softmax and the product with the values, with x reaching the output by three routes that chapter 6’s accumulation must add. test_attention_gradcheck does the same for attention with separate q, k and v, and the softmax tests check the new op alone, along three axes and with masked entries.

A gradient check cannot see a missing mask: attention without a mask is also differentiable, and its gradients match its numbers. test_self_attention_is_causal covers that. It changes positions 3 and 4 of the input and requires the outputs at positions 0 to 2 to stay the same, and those at 3 and 4 to change.

Walkthrough

The reference module is py/tinygpt/attention.py.

def softmax(x, axis=-1):
    """Tensor softmax along axis, with the fused backward dx = s * (g - sum(g * s))."""
    z = x.data - x.data.max(axis=axis, keepdims=True)
    e = np.exp(z)
    s = e / e.sum(axis=axis, keepdims=True)
    out = Tensor(s, (x,), "softmax")

    def backward():
        g = out.grad
        x.grad += s * (g - (g * s).sum(axis=axis, keepdims=True))

    out._backward = backward
    return out

The forward pass is the max-shifted softmax along axis. The output tensor records x as its one parent, and backward is the vector–Jacobian product derived above: (g * s).sum(axis=axis, keepdims=True) is g⋅s\mathbf{g} \cdot \mathbf{s} for every row at once, with the reduced axis kept so it broadcasts back against g. The closure keeps s, the forward result, so the backward pass needs no recomputation. The op works along any axis, which test_softmax_gradcheck checks for axes −1-1, 0 and 1; attention uses the last.

Chapter 6’s ops could compose this from exp, sum and division, and chapter 6’s gradcheck would pass it. The fused op records one node instead of several (B, T, T) intermediates, and its backward pass is the three-operation formula instead of the chain of backward passes of its parts.

def causal_mask(T):
    """(T, T) additive mask: 0 where key position <= query position, -inf above the diagonal."""
    return np.triu(np.full((T, T), -np.inf), k=1)

np.triu(..., k=1) keeps the entries strictly above the diagonal of a (T, T) array of −∞-\infty and sets the rest to 0. It is a plain numpy array, not a Tensor: it has no parameters and needs no gradient. When attention adds it to the scores, chapter 6’s _lift wraps it, and _unbroadcast sums the gradient it receives over the batch into a gradient nobody reads.

def attention(q, k, v, mask=None):
    """Scaled dot-product attention. q (..., T, d), k (..., S, d), v (..., S, d_v) -> (..., T, d_v).

    mask, if given, is an array broadcastable to (..., T, S) added to the scores before softmax.
    """
    d = q.shape[-1]
    scores = (q @ k.transpose()) * (1.0 / np.sqrt(d))  # (..., T, S)
    if mask is not None:
        scores = scores + mask
    weights = softmax(scores, axis=-1)                  # each row sums to 1 over the S keys
    return weights @ v

k.transpose() swaps the last two axes, (..., S, d) to (..., d, S), and chapter 6’s batched @ multiplies the last two axes of each operand, so q @ k.transpose() is (..., T, S) over any leading axes. The scale is a multiplication by the constant 1/d1/\sqrt{d}, where dd is read from the query’s last axis. The mask, if given, is anything that broadcasts to (..., T, S): the (T, T) causal mask broadcasts over any leading axes, a batch axis or an axis of heads. weights @ v is (..., T, S) by (..., S, d_v).

class SelfAttention:
    """One causal attention head: every position reads from itself and earlier positions."""

    def __init__(self, d_model, d_head, rng):
        self.query = Linear(d_model, d_head, rng, bias=False)
        self.key = Linear(d_model, d_head, rng, bias=False)
        self.value = Linear(d_model, d_head, rng, bias=False)

    def parameters(self):
        return self.query.parameters() + self.key.parameters() + self.value.parameters()

    def __call__(self, x):
        T = x.shape[-2]                                   # x: (B, T, d_model)
        q, k, v = self.query(x), self.key(x), self.value(x)  # each (B, T, d_head)
        return attention(q, k, v, causal_mask(T))         # (B, T, d_head)

One head: three bias-free Linear layers from chapter 9, drawn from rng in the order query, key, value, and the causal mask sized to the input’s second-to-last axis. parameters() lists the three weight matrices in that order. The head maps (B, T, d_model) to (B, T, d_head), and chapter 11’s multi-head layer computes HH such heads at once, with (d_model, d_model) projections split into heads, then concatenates the heads’ outputs and projects back to d_model with the matrix GGUF files name attn_output.

Exercises

(a) One query q=(1,1,1,1)\mathbf{q} = (1, 1, 1, 1) attends to three keys, k0=(1,−1,0,0)\mathbf{k}_0 = (1, -1, 0, 0), k1=(1,1,0,0)\mathbf{k}_1 = (1, 1, 0, 0) and k2=(1,1,1,1)\mathbf{k}_2 = (1, 1, 1, 1), with values v0=(1,0)\mathbf{v}_0 = (1, 0), v1=(0,1)\mathbf{v}_1 = (0, 1) and v2=(2,2)\mathbf{v}_2 = (2, 2). Compute the output by hand, then check it with attention.

Answer

Here d=4d = 4, so d=2\sqrt{d} = 2. The dot products are q⋅k0=0\mathbf{q} \cdot \mathbf{k}_0 = 0, q⋅k1=2\mathbf{q} \cdot \mathbf{k}_1 = 2 and q⋅k2=4\mathbf{q} \cdot \mathbf{k}_2 = 4, and the scaled scores are (0,1,2)(0, 1, 2). The softmax denominator is e0+e1+e2=1+2.7183+7.3891=11.1073e^0 + e^1 + e^2 = 1 + 2.7183 + 7.3891 = 11.1073, so the weights are (0.0900,0.2447,0.6652)(0.0900, 0.2447, 0.6652). The output is

0.0900⋅(1,0)+0.2447⋅(0,1)+0.6652⋅(2,2)=(0.0900+1.3305,0.2447+1.3305)=(1.4205,1.5752). 0.0900 \cdot (1, 0) + 0.2447 \cdot (0, 1) + 0.6652 \cdot (2, 2) = (0.0900 + 1.3305,\; 0.2447 + 1.3305) = (1.4205, 1.5752) .
import numpy as np

from tinygpt.attention import attention
from tinygpt.autograd import Tensor

q = np.array([[1.0, 1, 1, 1]])                                   # (1, 4)
k = np.array([[1.0, -1, 0, 0], [1, 1, 0, 0], [1, 1, 1, 1]])      # (3, 4)
v = np.array([[1.0, 0], [0, 1], [2, 2]])                         # (3, 2)
print(attention(Tensor(q), Tensor(k), Tensor(v)).data)
[[1.42051248 1.57521038]]

(b) Derive the Jacobian of log-softmax, ℓ=logsoftmax(z)\ell = \log \mathrm{softmax}(\mathbf{z}), shape (S,), and its vector–Jacobian product. Use it to recover the cross-entropy gradient softmax(z)−ey\mathrm{softmax}(\mathbf{z}) - \mathbf{e}_y of chapter 6.

Answer

With s=softmax(z)\mathbf{s} = \mathrm{softmax}(\mathbf{z}), shape (S,), each entry is ℓi=zi−log∑kezk\ell_i = z_i - \log \sum_k e^{z_k}. The first term’s derivative with respect to zjz_j is δij\delta_{ij}, and the second’s is ezj/∑kezk=sje^{z_j} / \sum_k e^{z_k} = s_j by the chain rule, so

∂ℓi∂zj=δij−sj,J=I−1s⊤, \frac{\partial \ell_i}{\partial z_j} = \delta_{ij} - s_j , \qquad \mathbf{J} = \mathbf{I} - \mathbf{1}\mathbf{s}^\top ,

shape (S, S). Unlike the softmax’s Jacobian it is not symmetric: every row is the same −s⊤-\mathbf{s}^\top plus a 1 on the diagonal. Each row sums to 1−∑jsj=01 - \sum_j s_j = 0, so adding a constant to every score changes no log-probability. Given g=∂L/∂ℓ\mathbf{g} = \partial L / \partial \ell, shape (S,),

∂L∂zj=∑igi(δij−sj)=gj−sj∑igi,∂L∂z=g−(1⋅g)s, \frac{\partial L}{\partial z_j} = \sum_i g_i (\delta_{ij} - s_j) = g_j - s_j \sum_i g_i , \qquad \frac{\partial L}{\partial \mathbf{z}} = \mathbf{g} - (\mathbf{1} \cdot \mathbf{g})\, \mathbf{s} ,

one sum and 2S2S elementwise operations per row, the same O(S)O(S) as the softmax’s rule. The cross-entropy of target yy is L=−ℓyL = -\ell_y, so g=−ey\mathbf{g} = -\mathbf{e}_y and 1⋅g=−1\mathbf{1} \cdot \mathbf{g} = -1, which gives ∂L/∂z=−ey+s=softmax(z)−ey\partial L / \partial \mathbf{z} = -\mathbf{e}_y + \mathbf{s} = \mathrm{softmax}(\mathbf{z}) - \mathbf{e}_y. That is the gradient chapter 8’s fused cross_entropy computes directly.

(c) Prove that a causal head’s output at position tt does not change when the inputs at positions 0,…,t−10, \ldots, t - 1 are reordered among themselves, whatever the reordering.

Answer

Let π\pi be a permutation of {0,…,T−1}\{0, \ldots, T - 1\} that maps {0,…,t−1}\{0, \ldots, t - 1\} onto itself and fixes tt, and let the new input be xs′=xπ(s)\mathbf{x}'_s = \mathbf{x}_{\pi(s)}. Positions after tt may be permuted among themselves too; the mask hides them from tt either way.

  1. The projections act row by row, so qs′=qπ(s)\mathbf{q}'_s = \mathbf{q}_{\pi(s)}, ks′=kπ(s)\mathbf{k}'_s = \mathbf{k}_{\pi(s)} and vs′=vπ(s)\mathbf{v}'_s = \mathbf{v}_{\pi(s)}. In particular qt′=qt\mathbf{q}'_t = \mathbf{q}_t, since π(t)=t\pi(t) = t.
  2. Row tt of the mask allows exactly the keys s≤ts \le t. For those, zs′=qt⋅kπ(s)/d=zπ(s)z'_s = \mathbf{q}_t \cdot \mathbf{k}_{\pi(s)} / \sqrt{d} = z_{\pi(s)}, and as ss runs over {0,…,t}\{0, \ldots, t\}, π(s)\pi(s) runs over the same set. The softmax denominator ∑s≤tezs′\sum_{s \le t} e^{z'_s} is the original row’s sum in another order, the same number, so the weights are as′=aπ(s)a'_s = a_{\pi(s)}.
  3. The output is ot′=∑s≤tas′vs′=∑s≤taπ(s)vπ(s)=∑u≤tauvu=ot\mathbf{o}'_t = \sum_{s \le t} a'_s \mathbf{v}'_s = \sum_{s \le t} a_{\pi(s)} \mathbf{v}_{\pi(s)} = \sum_{u \le t} a_u \mathbf{v}_u = \mathbf{o}_t, substituting u=π(s)u = \pi(s).

So position tt sees the multiset of earlier tokens, not their order, which is the claim the text checked numerically for t=2,3,4t = 2, 3, 4 after swapping positions 0 and 1. The outputs at positions before tt can change, because a position whose prefix the permutation reorders sees its tokens in a different order: for the swap of positions 0 and 1, the outputs at 0 and 1. The proof uses no property of xs\mathbf{x}_s beyond being a row that moves with its position; chapter 11’s position encodings break it by making the row depend on the position.

(d) Multiply every query by a constant c>0c > 0. Describe the output and the gradients as c→0c \to 0 and c→∞c \to \infty.

Answer

The scores become czjc\,z_j. As c→0c \to 0 every score tends to 0, every visible weight to 1/St1/S_t for the StS_t keys position tt can see, and the output to the plain mean of those values: the query no longer matters. Each visible value receives 1/St1/S_t of the gradient of position tt’s output, spread evenly. The gradient to the scores is the softmax’s backward rule at uniform weights, which is not zero, but each score is cq⋅kj/dc\,\mathbf{q}\cdot\mathbf{k}_j/\sqrt{d}, so the gradients to the queries and keys carry a factor cc and vanish with it.

As c→∞c \to \infty with a unique largest score, the weights tend to one-hot on that key and the output to its value: the hard lookup. The Jacobian goes to zero as derived in the mechanism, exponentially fast in cc times the gap between the best score and the next (sj≈e−cΔs_j \approx e^{-c\,\Delta} for a key Δ\Delta behind), faster than the factor cc grows, so the gradient to the queries and keys vanishes, and only the selected value gets a gradient. An exact tie is the exception: mm keys tied for the largest share the weight equally, 1/m1/m each, the Jacobian restricted to them tends to diag(1/m)−11⊤/m2\mathrm{diag}(1/m) - \mathbf{1}\mathbf{1}^\top/m^2, which is not zero, and the gradient to the queries and keys grows like cc. Scores computed from data tie with probability zero, so in practice both extremes stop the queries and keys from learning; the 1/d1/\sqrt{d} scaling starts training between them.

(e) In grouped-query attention several query heads share one key head and one value head. For a layer with 32 query heads of width 128 sharing 8 key-value heads, at TT = 32,768 with 2 bytes per number, compute the memory of the layer’s attention scores and of its keys and values, and compare both with ordinary multi-head attention, which has 32 key-value heads.

Answer

The scores are one T×TT \times T matrix per query head, since each query head scores its own queries against the keys it reads: 327682×32×2=68,719,476,73632768^2 \times 32 \times 2 = 68{,}719{,}476{,}736 bytes, 64 GiB, the same with 8 key-value heads as with 32. Sharing keys does not reduce the number of scores. The keys and values are one width-128 vector each per key-value head per position: with 8 heads, 2×8×128×2=4,0962 \times 8 \times 128 \times 2 = 4{,}096 bytes per position and 4,096×32,768=134,217,7284{,}096 \times 32{,}768 = 134{,}217{,}728 bytes, 128 MiB, for the layer; with 32 heads, 16,384 bytes per position and 512 MiB. Grouping divides the stored keys and values by the group size, here 4, and leaves the quadratic term untouched. That term is the one a fused kernel removes by never materialising the scores; the linear one is what an inference server keeps for every position of every sequence. Chapter 12 builds the store for those keys and values.

(f) Replace chapter 9’s concatenation with attention: embed the last nn tokens, add a learned vector for each slot of the window, run one causal SelfAttention head over the window, and feed the newest slot’s output to the same tanh layer and output layer. Train it on the tiny corpus and compare its held-out loss with the MLP’s, at n=3n = 3 and n=8n = 8.

Answer
import pathlib

import numpy as np

from tinygpt.attention import SelfAttention
from tinygpt.autograd import Tensor
from tinygpt.mlp import MLPLM, Adam, Linear, context_windows
from tinygpt.nn import embedding, evaluate, train

tokens = pathlib.Path("data/tiny-corpus.txt").read_text().split()
vocab = sorted(set(tokens))
ids = np.array([vocab.index(t) for t in tokens])
cut = int(0.9 * len(ids))
train_ids, test_ids = ids[:cut], ids[cut:]


class AttentionLM:
    """The last n tokens plus their slot in the window, one causal head, a tanh layer, V logits."""

    def __init__(self, vocab_size, n, d, d_hidden, rng):
        self.n, self.pad = n, vocab_size
        self.embed = Tensor(rng.normal(0.0, 1.0, size=(vocab_size + 1, d)))
        self.slot = Tensor(rng.normal(0.0, 1.0, size=(n, d)))  # one row per slot, oldest first
        self.head = SelfAttention(d, d, rng)
        self.hidden = Linear(d, d_hidden, rng)
        self.out = Linear(d_hidden, vocab_size, rng)
        self.out.weight.data *= 0.1
        self.newest = Tensor(np.eye(n)[-1:])                   # (1, n): selects the last slot

    def parameters(self):
        return ([self.embed, self.slot] + self.head.parameters()
                + self.hidden.parameters() + self.out.parameters())

    def __call__(self, ids):
        ctx = context_windows(ids, self.n, self.pad)[:, :, ::-1]  # (B, T, n), oldest first
        B, T = ctx.shape[:2]
        e = embedding(self.embed, ctx) + self.slot                # (B, T, n, d)
        a = self.head(e.reshape(B * T, self.n, -1))               # (B*T, n, d)
        a = (self.newest @ a).reshape(B, T, -1)                   # (B, T, d): the newest slot
        return self.out(self.hidden(a).tanh())                    # (B, T, V)


for n in [3, 8]:
    for name, make in [("MLP", lambda rng: MLPLM(len(vocab), n, 8, 64, rng)),
                       ("attention", lambda rng: AttentionLM(len(vocab), n, 8, 64, rng))]:
        losses = []
        for seed in range(5):
            rng = np.random.default_rng(seed)
            model = make(rng)
            train(model, Adam(model.parameters(), 0.01), train_ids, 1000, 16, 32, rng)
            losses.append(evaluate(model, test_ids, 64))
        size = sum(p.data.size for p in model.parameters())
        print(f"n={n} {name:9s} {size:5d} params  held-out " + " ".join(f"{x:.4f}" for x in losses)
              + f"  mean {np.mean(losses):.4f}")
n=3 MLP        2849 params  held-out 0.9940 0.9983 0.9948 0.9932 0.9845  mean 0.9930
n=3 attention  2041 params  held-out 0.9721 0.9853 0.9810 0.9984 0.9814  mean 0.9836
n=8 MLP        5409 params  held-out 1.0498 1.0749 1.0727 1.0747 1.0678  mean 1.0680
n=8 attention  2081 params  held-out 1.0599 0.9909 0.9832 0.9787 1.1191  mean 1.0264

Each model is trained from five seeds for 1,000 steps with the lab’s other settings; the run takes about a minute and a half. (Captured on talos, chapter 11’s laptop. Straylight, dixie and orion print the same; titan prints 0.9981 for the fourth n=3 attention seed, since another CPU rounds the sums differently, as chapter 16 explains.) The model reads each window as a sequence of nn positions, oldest first, and keeps only the output of the newest one. That row of the causal mask hides nothing, so here the head is plain attention with one query; newest @ a picks the row with a (1, n) selector, since Tensor has no indexing op.

  • At n=3n = 3 the attention model beats the MLP in four of five seeds, mean 0.9836 against 0.9930, with 2,041 parameters to 2,849. The slot vectors tell the head which token is which distance back, so it can weight tokens by their distance as well as by their content, though its output is one weighted average of 8-dimensional values rather than the MLP’s 24-dimensional concatenation; its three 8×88 \times 8 projections replace the MLP’s 24×6424 \times 64 first layer.
  • At n=8n = 8 the MLP’s first layer grows to 64×6464 \times 64 and its held-out loss gets worse: seed 0’s loss on the whole training text, evaluate(model, train_ids, 64), ends at 0.9084 against 1.0498 held out, a model fitting its 11,998 tokens more closely than the grammar allows (chapter 9’s floor is 0.96) and paying for it. The attention model gains only 40 parameters, five more slot vectors of 8, and three of its seeds stay near 0.98. The other two end at 1.0599 and 1.1191: the wider window leaves more ways to learn a worse weighting, and one head, averaging its values into one vector, has to find the few positions that matter among eight. The seed-to-seed spread is the reason to run more than one.

Lab

Implement softmax, causal_mask, attention and SelfAttention in py/labs/ch10/starter.py, following its docstrings; build the three projections in the order query, key, value. Run

make lab CH=10 IMPL=mine

until it passes. Read py/labs/ch10/test_lab.py first. It checks the softmax against numpy and with a huge score, gradchecks it along three axes and with masked entries, pins the mask’s layout, the two limits of the lookup, the one-key case and the d\sqrt{d} scaling, and requires the head to be causal. The acceptance test is test_self_attention_layer_gradcheck: the attention layer passes its gradient check with respect to its input and all three projections.

Then look at a head’s weights and check the symmetry of the mechanism. Save this script outside the repository, for example as /tmp/attention_lab.py:

import numpy as np

from tinygpt.attention import SelfAttention, attention, causal_mask, softmax
from tinygpt.autograd import Tensor, gradcheck

rng = np.random.default_rng(0)
layer = SelfAttention(d_model=8, d_head=4, rng=rng)
x = rng.normal(size=(1, 5, 8))
w = rng.normal(size=(1, 5, 4))


def loss(x, wq, wk, wv):
    layer.query.weight, layer.key.weight, layer.value.weight = wq, wk, wv
    return (layer(x) * w).sum()


gradcheck(loss, [x, rng.normal(size=(8, 4)), rng.normal(size=(8, 4)), rng.normal(size=(8, 4))])
print("gradcheck passed for the input and all three projections")

q, k = layer.query(Tensor(x)), layer.key(Tensor(x))
weights = softmax((q @ k.transpose()) * (1 / np.sqrt(4)) + causal_mask(5)).data[0]
np.set_printoptions(precision=3, suppress=True)
print("attention weights (row = query position, column = key position):")
print(weights)

perm = np.array([3, 0, 4, 1, 2])
q, k, v = (rng.normal(size=(5, 4)) for _ in range(3))
out = attention(Tensor(q), Tensor(k), Tensor(v)).data
out_perm = attention(Tensor(q[perm]), Tensor(k[perm]), Tensor(v[perm])).data
print("unmasked attention is permutation-equivariant:", np.allclose(out_perm, out[perm]))

and run it from py/ with PYTHONPATH=. uv run python /tmp/attention_lab.py. Change the import to from labs.ch10.starter import SelfAttention, attention, causal_mask, softmax to run yours. The reference prints:

gradcheck passed for the input and all three projections
attention weights (row = query position, column = key position):
[[1.    0.    0.    0.    0.   ]
 [0.944 0.056 0.    0.    0.   ]
 [0.476 0.002 0.522 0.    0.   ]
 [0.003 0.848 0.    0.148 0.   ]
 [0.002 0.    0.965 0.033 0.   ]]
unmasked attention is permutation-equivariant: True
  • The weights are the figure’s grid. Every entry above the diagonal is exactly 0, every row sums to 1, and row 0 puts all its weight on itself, the only key it can see.
  • They are sharp because of the weights gradcheck left installed. After the check, the layer holds the matrices passed to it, drawn from N(0,1)N(0, 1), not Linear’s initialisation, whose variance is 1/(3⋅8)=1/241/(3 \cdot 8) = 1/24. With those, the visible scores have a standard deviation of 4.42, and most rows are close to a single key. With the layer’s own initial weights, the same input gives scores with a standard deviation of 0.36 and nearly flat rows: row 4 is (0.212,0.142,0.175,0.358,0.113)(0.212, 0.142, 0.175, 0.358, 0.113). That is the regime the 1/d1/\sqrt{d} scaling and the initialisation aim for, with the Jacobian far from zero.
  • The last line is exercise (c) on one example. It uses the unmasked attention; with causal_mask(5) passed to both calls, the same check prints False.

Further reading

  • Dzmitry Bahdanau, Kyunghyun Cho and Yoshua Bengio, “Neural Machine Translation by Jointly Learning to Align and Translate”, ICLR (2015). Attention as a soft search: the decoder weights the encoder’s states with a softmax over alignment scores and takes their weighted sum. Its scores come from a small feed-forward network of the two states, additive attention, not a dot product.
  • Alex Graves, Greg Wayne and Ivo Danihelka, “Neural Turing Machines” (2014). A network reading and writing an external memory; section 3.3.1, “Focusing by Content”, addresses the memory with a softmax over cosine similarities to a key, sharpened by a learned key strength: the soft lookup of this chapter, with the sharpness a parameter instead of 1/d1/\sqrt{d}.
  • Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit, Llion Jones, Aidan N. Gomez, Łukasz Kaiser and Illia Polosukhin, “Attention Is All You Need”, NeurIPS (2017), section 3.2. Scaled dot-product attention and its equation, the variance argument for 1/dk1/\sqrt{d_k} (footnote 4), and masking by setting the illegal scores to −∞-\infty (section 3.2.3); section 3.2.2 is chapter 11’s multi-head attention.
  • Maxim Milakov and Natalia Gimelshein, “Online normalizer calculation for softmax” (2018). The running maximum and rescaled running sum derived in this chapter’s cost section.
  • Tri Dao, Daniel Y. Fu, Stefano Ermon, Atri Rudra and Christopher Ré, “FlashAttention: Fast and Memory-Efficient Exact Attention with IO-Awareness”, NeurIPS (2022). Exact attention computed in tiles that stay in a GPU’s on-chip memory, with the scores recomputed in the backward pass instead of stored, and an analysis of the memory traffic this saves.

results matching ""

    No results matching ""