10. Attention
Why this layer exists
Chapter 9’s model reads a fixed window of 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 : 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 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 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 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 pairs and look up a query : the answer is the whose key equals . Written as arithmetic, with the Iverson bracket equal to 1 when holds and 0 otherwise,
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 and the , 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, , large when the two point the same way, and turn the scores into weights with the softmax of chapter 4:
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 . If key has the strictly largest score, then for , as , so and the output tends to .
test_sharp_attention_is_a_lookupbuilds keys , 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 and against the others 0, so the other weights are relative to it and the output is value 2, then value 0, to within . - Equal scores average. If all scores are equal, every weight is and the output is the mean of the values.
test_equal_scores_average_the_valuesmakes 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:
with of shape (B, T, d_model), each of shape (d_model, d) and each result of shape (B, T, d). Row of is position ’s query , and likewise for keys and values. One matrix product computes every score at once:
where swaps the last two axes of , (B, d, T), and has shape (B, T, T): , the score of key position for query position . The division by is derived next. A softmax along the last axis turns each row into weights, , shape (B, T, T), and
row being . 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 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 and .
Why three separate projections rather than using directly? With the score of a position against itself, , beats its score against any position whose vector is no longer, since by Cauchy–Schwarz , so a position tends to find itself; and the scores are symmetric: scores as highly as scores . Separate and make the score , a learned bilinear form that can be asymmetric, so what a verb looks for can differ from what it offers. A separate decouples what a position is found by from what it passes on.
Why divide by
Take the entries of and to be independent with mean 0 and variance 1. Each term of is a product of two independent mean-zero variables, so, exactly as in chapter 9’s derivation for a layer’s output,
The terms are independent, since no two share a variable, and variances of independent terms add:
A constant scales a variance by , which is why the divisor is and not . Without it the scores’ standard deviation grows as : 32 at .
That matters because of what large scores do to the softmax’s derivative. Write for one row, both of shape (S,), and . Then , and , and the quotient rule gives
As a matrix, the Jacobian is , shape (S, S), symmetric. Now let approach a one-hot vector, all weight on key . The diagonal entry ; every other diagonal entry because ; and every off-diagonal entry 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 keys, entries , with the Frobenius norm as the size of the Jacobian:
| 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 , unscaled | 0.2926 | 0.2147 | 0.1270 | 0.0700 |
| mean largest weight, scaled | 0.1064 | 0.1071 | 0.1062 | 0.1080 |
| mean , 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 (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 is 0.124 here), the Jacobian shrinks, to 0.070 at and toward zero beyond. The division by makes the sharpness at initialisation independent of the head width, and training can still sharpen a row where it helps by growing and .
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 , shape (S,), add into the input’s gradient. By the chain rule,
In vector form, with the elementwise product,
the vector–Jacobian product (which equals , being symmetric). It costs one dot product and two elementwise operations, per row, where forming and multiplying would cost per row and, for the (B, T, T) scores, an array of numbers. For the whole array, 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 is the same in every entry, , because 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 has zero gradient and would check nothing. And wherever , the gradient to is exactly 0.
The forward pass subtracts each row’s maximum before exponentiating. Softmax is unchanged by adding a constant to every score, since , so the shifted computation is exact, and the largest exponent is , so nothing overflows: test_softmax_matches_numpy_and_sums_to_one feeds it the scores 1000 and 0, where 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 from positions . In training it makes all predictions of a window in one pass, so position must not read positions after : they contain the answer. The causal mask is a (T, T) array, 0 where the key position and where , added to the scores before the softmax:
with broadcast over the batch. A masked score contributes 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 , keys 2 and 3 in its future. The softmax gives , 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 and the zeroed row becomes : position 1’s output depends on position 3, which is the leak the mask exists to stop. Masking before the softmax gives 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 is allowed. So every row has at least one finite score, the row’s maximum is finite, and the max-shift never computes , 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.
Cost
Per head, is a (T, d) by (d, T) product: multiply-adds. is (T, T) by (T, d): another . The projections cost , linear in . So attention’s time is , and the score matrix it materialises takes memory: it grows with the square of the context, where everything else in a layer grows linearly. At with 32 heads and 2 bytes per score, one layer’s scores take
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 and , 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 , a running sum and a running unnormalised output over the keys seen so far. When a block of keys with scores arrives, the new maximum is ; every term already in and was computed as and must become , so
and after the last block the output is , exactly the softmax-weighted sum. Memory per query is one block of scores instead of a row of . The running maximum and rescaled sum are Milakov and Gimelshein’s online normaliser; carrying the output accumulator 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 cached keys: scores, work per head, and no (T, T) matrix. The belongs to training and to processing a prompt, where all queries are present at once.
Order blindness
Without the mask, attention has no idea of order. Let be a (T, T) permutation matrix, so reorders the rows of and . The projections act on each row separately, so , and likewise and . The scores become
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 , and the output is
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. for every permutation but the identity, so the derivation above fails; but the output at position is still with weights computed from and the keys, a function of and the unordered set . 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 entries by , recomputes the loss for each, 264 forward passes, and requires every central difference to match the backpropagated entry within an absolute plus a relative . 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 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 , 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 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 , where 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 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 attends to three keys, , and , with values , and . Compute the output by hand, then check it with attention.
Answer
Here , so . The dot products are , and , and the scaled scores are . The softmax denominator is , so the weights are . The output is
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, , shape (S,), and its vector–Jacobian product. Use it to recover the cross-entropy gradient of chapter 6.
Answer
With , shape (S,), each entry is . The first term’s derivative with respect to is , and the second’s is by the chain rule, so
shape (S, S). Unlike the softmax’s Jacobian it is not symmetric: every row is the same plus a 1 on the diagonal. Each row sums to , so adding a constant to every score changes no log-probability. Given , shape (S,),
one sum and elementwise operations per row, the same as the softmax’s rule. The cross-entropy of target is , so and , which gives . That is the gradient chapter 8’s fused cross_entropy computes directly.
(c) Prove that a causal head’s output at position does not change when the inputs at positions are reordered among themselves, whatever the reordering.
Answer
Let be a permutation of that maps onto itself and fixes , and let the new input be . Positions after may be permuted among themselves too; the mask hides them from either way.
- The projections act row by row, so , and . In particular , since .
- Row of the mask allows exactly the keys . For those, , and as runs over , runs over the same set. The softmax denominator is the original row’s sum in another order, the same number, so the weights are .
- The output is , substituting .
So position sees the multiset of earlier tokens, not their order, which is the claim the text checked numerically for after swapping positions 0 and 1. The outputs at positions before 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 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 . Describe the output and the gradients as and .
Answer
The scores become . As every score tends to 0, every visible weight to for the keys position can see, and the output to the plain mean of those values: the query no longer matters. Each visible value receives of the gradient of position ’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 , so the gradients to the queries and keys carry a factor and vanish with it.
As 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 times the gap between the best score and the next ( for a key behind), faster than the factor grows, so the gradient to the queries and keys vanishes, and only the selected value gets a gradient. An exact tie is the exception: keys tied for the largest share the weight equally, each, the Jacobian restricted to them tends to , which is not zero, and the gradient to the queries and keys grows like . Scores computed from data tie with probability zero, so in practice both extremes stop the queries and keys from learning; the 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 = 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 matrix per query head, since each query head scores its own queries against the keys it reads: 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, bytes per position and 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 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 and .
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 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 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 projections replace the MLP’s first layer.
- At the MLP’s first layer grows to 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 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
gradcheckleft installed. After the check, the layer holds the matrices passed to it, drawn from , notLinear’s initialisation, whose variance is . 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 . That is the regime the 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; withcausal_mask(5)passed to both calls, the same check printsFalse.
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 .
- 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 (footnote 4), and masking by setting the illegal scores to (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.