Key takeaways
- Attention is the only channel tokens use to share information. Each word compares its query q with every word's key k, then takes in their values v according to how well they match.
- Scores come from dot products. Dividing by d keeps their scale from growing with the dimension, and the causal mask sets every "future" score to −∞ so no word can peek ahead.
- Softmax on each row gives the weights, which are used to take a weighted sum of the values. The whole thing fits in one formula: softmax(QK⊤/d+M)V.
- Multi-head attention lets several heads each focus on a different relationship; their outputs are concatenated and mixed by WO.
- The cost grows with the square of the length, O(T2). Sliding windows, sparse attention, MQA and GQA are all ways to save compute and GPU memory.
Same word, different meanings
Does a word always mean the same thing, whatever sentence it's in? In "She fed the mouse", the mouse is a little animal. In "She clicked the mouse", it's the thing on your desk. We tell them apart instantly because we look at the context.
But to the model, at the moment they come in, both are the same token, "mouse", so the lookup hands back exactly the same vector. Think of that vector as a point in space, sitting somewhere between "animals" and "computer gear", with a little of both meanings. We want the model to push the first mouse toward the animals and the second toward the computer gear.
To pull that off, "mouse" has to look at the other words in its sentence and bring in whatever is useful. Once it sees "fed", it knows it's an animal.
Last episode we saw that every Transformer layer has two parts: attention and a feed-forward network. The feed-forward network works on each token by itself, so words never interact there. That makes attention the only place where tokens exchange information. In this episode we take it apart step by step and work through the numbers by hand.
Weighted averages, and q, k, v
How does a word bring information in? The simplest idea: average the vectors of all the words in the sentence and call that the new information for "mouse". But then every word counts the same (25% each): "She" matters exactly as much as "fed". That's clearly not right.
What we want is a weighted average: relevant words get big weights, irrelevant ones small weights. Here "fed" matters most, so the weights might look like 10%, 60%, 20%, 10%. That leaves two questions:
- Where do the weights come from?
- What information should each word hand over?
Attention's answer: every token prepares three vectors, called the query, the key and the value.
Intuition: It's a lot like finding a book in a library. The question in your head is the query. The label on each book's spine is the key. What's written inside the book is the value. The better a label matches your question, the more you take away from that book.
To keep the arithmetic small enough to do by hand, let's switch to a short sentence: The, cat, is, fluffy. The query for "fluffy" might ask, "What am I describing?" and the key for "cat" answers, "I'm a noun, something you can describe." So "fluffy" pays close attention to "cat" and takes its value, the idea of something small and furry that says meow, onto itself.
Watch out: This is just a metaphor to build intuition. In a real model, what q, k and v stand for is learned during training, and it's nowhere near this tidy.
Computing q, k and v
Where do q, k and v come from? Take each token's vector x and multiply it by three different matrices, WQ, WK and WV:
q=WQx,k=WKx,v=WVx
These three matrices are parameters of the model, learned during training, and every token shares the same set.
Let's run it with small numbers. Here x has 4 dimensions and q, k, v have just 2, so each matrix is 2×4. Take "fluffy": multiply the first row of WQ by x, entry by entry, and add it all up:
1×1+(−1)×1+1×1+(−1)×(−1)=2
That's the first number of q. The second row gives 1, so the query for "fluffy" is q=(2,1). Multiply the same x by WK and WV instead and we get its key, k=(1,1), and its value, v=(0,2). Do the same for every token, and each word has its own q, k and v.
In practice, we stack all the (normalized) token vectors as the rows of a matrix Xˉ and compute every word at once: Q=XˉWQ, K=XˉWK, V=XˉWV.
Why not just compare x with x? Why split it into q and k? Because "what am I looking for" and "what am I" are two different questions. "Fluffy" needs to find "cat", but "cat" has no need to go looking for "fluffy". With q and k kept separate, the match can be different in each direction.
The dot product: how well do they match?
Now let "fluffy" ask its question: its q gets compared with the k of every word. How do we measure how well two vectors match? With the dot product: multiply the numbers in matching positions, then add them all up. The q for "fluffy" is (2,1) and the k for "cat" is (2,0):
qfluffy⋅kcat=2×2+1×0=4
The dot product also has a geometric meaning: it equals the lengths of the two arrows multiplied together, times the cosine of the angle between them:
q⋅k=∥q∥∥k∥cosφ
So the more two arrows point the same way, the bigger the dot product. Perpendicular arrows give zero, and opposite arrows give a negative number.
Back to our example. The k for "cat" points almost the same way as the q for "fluffy", and it's fairly long, so its dot product is 4, the biggest. The k for "is" points downward, more than 90 degrees away, so it gets −1. "The" gets 1, and "fluffy" itself gets 3. These four numbers (1, 4, −1, 3) are the scores "fluffy" gives to each word.
Filling in the T×T score table
It's not just "fluffy": every word asks a question, so every word's q gets a dot product with every word's k.
To line things up, stand K on its side so each word's k becomes a column. That's called a transpose, written K⊤. Then fill in a table where row i, column j holds the dot product of word i's q with word j's k:
- The row for "fluffy" (row 4) we just worked out: 1, 4, −1, 3.
- Row 2: the q for "cat" is (1,0). Dot it with the four k's in turn and we get 0, 2, 0, 1.
- Fill in the last two rows and we have a 4×4 table of scores. With T words, the table is T×T.
A row of q on the left, times a column of k on top, lands in the cell where they cross. That's exactly matrix multiplication:
S=QK⊤
Next, we process this table step by step until it becomes the actual attention weights.
Why divide by √d?
Before turning scores into weights, there's one small detail: every score is first divided by d. Here d is the dimension of q and k (the per-head size H from last episode). In our example d=2.
An experiment first. Generate one random q and six random k's, every entry a random number with mean 0 and variance 1, and compute the six dot products. On the left, apply softmax straight away; on the right, divide by d first. With d=2 the two look about the same. Now crank up the dimension (in real models, d per head is usually 64 or 128). On the left the scores spread further and further apart, and softmax piles almost all the weight onto a single word while everything else drops to nearly zero. On the right the bars stay even.
Watch out: That's bad news. When softmax is this sharp, nudging the inputs barely moves the output. The gradients are close to zero, and the model has a hard time learning.
Why do the scores spread out? A dot product is a sum of d terms: q⋅k=q1k1+q2k2+⋯+qdkd. Suppose every entry of q and k is independent, with mean 0 and variance 1 (variance measures how much something wobbles around). Then each term qiki also has mean 0 and variance 1. When you add independent random numbers, their variances add too:
Var(q⋅k)=Var(q1k1)+⋯+Var(qdkd)=1+⋯+1=d
If the variance is d, the typical size of the wobble, the standard deviation, is d. With d=128, that's about 11.
Dividing a number by d divides its variance by d. So after dividing, the variance is back to 1: no matter how big the dimension gets, the scores stay at a steady scale.
The causal mask: no peeking
Back to the score table. Our d is 2, so every score is divided by 2≈1.41.
Next comes a crucial restriction. A language model's job is to predict the next word. In training we feed in the whole sentence at once, and every position practices guessing its own next word, all at the same time. If "cat", while guessing its next word, could peek at the "is" and "fluffy" that come after it, that would be cheating: the answer would be sitting right in front of it.
So the rule is: each word may only look at itself and the words before it. The cells in the upper right of the table (above the diagonal) are all looking into the future. The fix is simple: replace those scores with −∞. This step is called a causal mask.
Why negative infinity? Because the next step takes exponentials, and e−∞=0, so those positions end up with a weight of exactly zero. Notice that "fluffy" is the last word, so it can already see every word; its row doesn't lose a single cell to the mask.
As a formula, we add a mask matrix M to the score table: 0 where looking is allowed, −∞ where it isn't:
Mij={0−∞j≤ij>i
Softmax, row by row: scores become weights
Now each row of scores becomes a row of weights. Weights have to be positive, and each row has to add up to 1. That's exactly what softmax does:
softmax(z)j=∑kezkezj
It works in two steps: raise e to the power of each number, which makes them all positive, then divide by the row's total. Here's the row for "fluffy":
|
The |
cat |
is |
fluffy |
| score ÷2 |
0.71 |
2.83 |
−0.71 |
2.12 |
| exponentiate |
2.03 |
16.92 |
0.49 |
8.34 |
| divide by 27.78 |
0.07 |
0.61 |
0.02 |
0.30 |
After exponentiating, everything is positive and the big numbers got even bigger. "Fluffy" gives 61% of its attention to "cat" and 30% to itself, while "is" is almost completely ignored.
Each row gets its own softmax. The first row can only see itself, so its weight is just 1, and every masked cell gets a weight of zero. This table is the attention weight matrix, written A. Every row adds up to 1.
A weighted sum of the values
Now the final step: use the weights to take a weighted sum of every word's value vector. Again, the row for "fluffy":
ofluffy=0.07v1+0.61v2+0.02v3+0.30v4=(1.29,0.66)
On the plane, each v is shrunk by its weight, and then they're laid out tip to tail. The result comes mostly from the value of "cat", with a bit of "fluffy" itself mixed in.
This output is then multiplied by an output matrix WO, which brings it back to the same size as x, and added onto the original vector for "fluffy" (the residual connection). And just like that, "fluffy" carries a sense of the cat it describes:
xfluffy←xfluffy+WOofluffy
Every word does the same, using its own row of weights. As matrices that's O=AV (4×4 times 4×2 gives 4×2), and each row of the result is one word's output.
The full formula
String the steps together and we get the complete formula for attention:
- QK⊤ gives a T×T table of scores;
- divide by d to keep the scores at a steady scale;
- add the causal mask M to block out the future;
- run softmax on each row, turning scores into weights;
- multiply by V to take a weighted sum of the values.
Attention(Q,K,V)=softmax(dQK⊤+M)V
This is scaled dot-product attention, from the famous 2017 paper "Attention Is All You Need".
Check the shapes: Q is T×d and K⊤ is d×T, so their product is T×T; times V, which is T×d, the output is T×d again, one vector per word. And all the outputs come out of a few matrix multiplications at once, with no waiting in line one word at a time. That's exactly what GPUs do best.
Multi-head attention
So far we've built one attention head. A single head has a limitation: each word gets just one row of weights, so it can only pick out other words by one criterion at a time. But words relate in lots of ways: adjectives describe nouns, pronouns point back to earlier words, verbs need to find their subjects, and so on.
The solution is to run several heads side by side. Each head has its own WQ, WK and WV and computes attention independently. For illustration: one head might specialize in linking adjectives to their nouns, another always looks at the previous word, and another likes to stare at the start of the sentence.
To avoid extra compute, each head works in a smaller dimension: the model dimension D is split evenly across N heads, so each head gets d=D/N. In practice:
- One big matrix computes a D-dimensional q, which is cut into N pieces of d dimensions, one per head. Same for k and v.
- Each head outputs a d-dimensional vector.
- Concatenate the outputs of all N heads to get back to D dimensions, then multiply by the output matrix WO, which mixes together what all the heads found.
| Model |
D |
heads N |
d per head |
| GPT-2 (smallest) |
768 |
12 |
64 |
| Llama 2 7B |
4096 |
32 |
128 |
As for parameters, WQ, WK, WV and WO are each D×D, so 4D2 in total. Episode 10 counts up every parameter in the model.
The code skeleton
Written as code, the core is only a few lines:
def scaled_dot_product_attention(q, k, v, mask):
d_k = q.shape[-1]
scores = (q @ k.transpose(-2, -1)) / math.sqrt(d_k)
scores = scores.masked_fill(~mask, -torch.inf)
return softmax(scores, dim=-1) @ v
- The first line grabs d, the size of each head (called
d_k here).
scores is q times k transpose, divided by d. transpose(-2, -1) swaps the last two dimensions, which is exactly what a transpose is.
- The
masked_fill line fills every forbidden position with negative infinity. The convention is that mask is True where looking is allowed, and masked_fill(mask, value) fills wherever the mask is True, so we flip the mask first with ~.
- Finally, softmax along the last dimension (each row), then multiply by v.
The multi-head part is mostly shuffling shapes around. x has shape B×T×D: a batch of B sentences, T tokens each, every token D-dimensional.
batch_size, seq_len, _ = x.shape
x_norm = self.norm(x)
qkv = self.qkv_proj(x_norm) # (batch, seq_len, 3 * d_model)
qkv = qkv.reshape(batch, seq_len, 3, self.num_heads, self.head_dim)
q, k, v = qkv.unbind(dim=2) # (batch, seq_len, num_heads, head_dim)
q = q.transpose(1, 2) # (batch, num_heads, seq_len, head_dim)
k = k.transpose(1, 2)
v = v.transpose(1, 2)
causal_mask = torch.tril(torch.ones(seq_len, seq_len)).bool()
output = scaled_dot_product_attention(q, k, v, mask)
output = output.transpose(1, 2) # (batch, seq_len, num_heads, head_dim)
output = output.reshape(batch, seq_len, d_model)
output = self.out_proj(output)
return x + output
Step by step:
- Normalize first (pre-norm), then one big linear layer computes q, k and v in one go, so the last dimension becomes 3D.
.reshape() splits that 3D into 3 parts, each holding N heads of d dimensions (num_heads × head_dim). Then .unbind() pulls q, k and v apart.
.transpose() moves the head dimension in front of the length dimension, giving (B,N,T,d). Now each head looks like its own separate batch, so all heads can compute attention together.
- The mask comes from
torch.tril ("lower triangle"): a matrix that's True on and below the diagonal, which is exactly the rule "look only at yourself and what came before".
- After calling the attention function, transpose and reshape back to (B,T,D), pass through the output projection
out_proj (that's WO), and add the result back onto the residual stream.
Watch out: This is the skeleton from the notes, and its variable names don't quite line up: it unpacks batch_size but later uses batch, and it builds causal_mask but passes mask into the function. Each pair means the same thing; just match them up as you read.
The cost: O(T²)
Attention is powerful, but it comes at a price. The score table is T×T: every word is compared with every word. Double the length and you get four times as many cells; double it again, another factor of four (4×4→8×8→16×16).
In big O notation that's O(T2): both the compute and the memory grow with the square of the length. The feed-forward network and the other parts grow only linearly with T.
How big does that get? With a context of 8,192 tokens, the score table for one head in one layer has over 67 million cells. At 128,000 tokens it's over 16 billion cells, and that's before multiplying by the number of heads and layers. That's why long contexts are so expensive. FlashAttention (episode 14) avoids storing the whole table in GPU memory, but the amount of computation is still quadratic.
Sliding windows and sparse attention
The first family of variants gives up a little global view in exchange for linear cost.
Sliding window attention: each word only looks at itself and the last W words. Each word makes at most W comparisons, so the total compute is O(TW) instead of O(T2), growing only linearly with the length.
There's another bonus. During generation, once a word slides out of the window, its k and v can simply be thrown away, so the KV cache stops growing with the sequence length. Mistral 7B, for example, uses sliding window attention with a window of 4096.
Sparse attention: only compute scores at a chosen subset of positions, for example one word out of every few, plus the words right next door.
Intuition: Is everything outside the window lost for good? Not quite. A word at the top only sees the few words in its window on the layer below, but each of those has already looked at even earlier words. Stack up the layers and the field of view widens with every one: after L layers, information can travel roughly L×W words.
In practice, models often mix these ideas: some layers only look at a local window (local attention), others look at everything (global attention), and the two kinds alternate. Gemma 2, for instance, simply alternates one local layer, one global layer, and so on.
MQA and GQA: slimming down the KV cache
The last family of variants goes after GPU memory during text generation.
During generation, every time a new word arrives, its q has to attend to the k's and v's of all the words before it. To avoid recomputing them, the k's and v's are stored once computed. That's the KV cache. In multi-head attention every head has its own k and v, so the more heads and the longer the context, the bigger this cache gets. For long texts it can even outgrow the model weights themselves.
- Multi-query attention (MQA): all the query heads share a single set of k and v (each head still has its own q). The cache instantly shrinks by a factor of N, but the model's quality can suffer.
- Grouped-query attention (GQA): a compromise. Split the query heads into a few groups and let each group share one set of k and v. The 70 billion parameter Llama 2 has 64 query heads but only 8 sets of k and v: the cache shrinks to one eighth, and quality stays very close to full multi-head attention.
In last episode's notation: K<N key-value heads, group size G=N/K, and WK, WV shrink to D×KH. Implementation is simple: copy each group's k and v enough times to match the number of query heads, then run ordinary multi-head attention.
Watch out: Multi-head attention (MHA) → GQA → MQA is a spectrum: ever more memory-efficient, but each head gets less expressive. Sharing k and v across heads costs some representational capacity per head. GQA is the middle ground.
How big the KV cache really gets, how to work it out, and even more aggressive ways to compress it are coming up in episode 12.
Recap
- Attention is how words share information: each word compares its query with the keys and takes in the values according to how well they match. q, k and v all come from x times shared parameter matrices.
- Scores come from dot products. Dividing by d brings their variance back to 1 so softmax doesn't get too sharp, and the causal mask uses −∞ to block out the future.
- Softmax on each row gives the weights; a weighted sum of the values, times WO, is added back to the residual stream. All of it is softmax(QK⊤/d+M)V.
- Multi-head attention runs several heads, each of size d=D/N, on different relationships; their outputs are concatenated and mixed by WO. That's 4D2 parameters.
- The cost is O(T2). Sliding windows and sparse attention save compute; MQA and GQA shrink the KV cache.
One puzzle to end on: without any position information, a dot product only looks at what two vectors contain, not how far apart they sit. Squeeze 100 words between "cat" and "fluffy" and their dot product is still 4, exactly the same. But word order clearly matters. So most modern models rotate q and k by an angle that depends on their positions, right before the dot product. That's the star of the next episode: rotary position embedding, or RoPE.