AI from scratch · Chapter 7
Attention and transformers
Every chatbot you've used is a transformer: a stack of two operations repeated dozens of times. One of them is chapter 3's familiar layer. The other, attention, is the new idea, and it's what lets a model understand that "bank" means something different next to "river" than next to "loan". Here's attention with all the numbers visible.
1. Words are arrows
A model first turns every word into a vector, its embedding: a list of numbers learned so that words used in similar ways end up close together. Real embeddings have hundreds or thousands of directions; here are 16 words in just two, so we can see them. Directions in this space mean something: going from man to woman is about the same move as from king to queen.
Drag words around and the analogy updates. In real models these directions aren't placed by hand; they fall out of training on billions of sentences, because predicting the next word well requires knowing that queens and kings are alike in most ways and different in one.
The math, step by step
A vocabulary of \(V\) words and vectors of size \(d\) make an embedding matrix \(E\) with \(V\) rows and \(d\) columns. "Looking up" word number \(k\) is just taking row \(k\). (Formally: multiply a one-hot vector, all zeros except a 1 at \(k\), by \(E\). It's a matrix like any other, so backprop trains it like any other.) GPT-2 used \(V = 50{,}257\) and \(d = 768\): 38.6 million numbers just for this table.
"Close together" is measured by the angle, with cosine similarity, chapter 1's dot product divided by the lengths:
\[ \cos(a, b) = \frac{a \cdot b}{\lVert a \rVert\, \lVert b \rVert} \in [-1, 1] \]
The analogy is plain vector arithmetic: compute \(\text{king} - \text{man} + \text{woman}\), then find the word whose embedding has the highest cosine with the result (leaving out the three input words, which are usually closest).
Two embeddings point in exactly opposite directions. What is their cosine similarity?
- 0
- −1
- 1
An embedding puts each word at a point, so "used alike" becomes "nearby", and relations become directions.
2. Attention: let the other words weigh in
An embedding is the same for "bank" everywhere. Attention fixes that. Each word asks a question (its query), every word offers an answer tag (its key), and how well they match decides how much attention is paid. The word's new meaning is a weighted average of what the others offer (their values), added to its own. Click a word.
Watch "bank": next to river, its new position slides toward the nature side; next to loan, toward money. Little words like "the" have small vectors, so they barely get attention. The math in the table is chapter 5 again: scores are dot products of query and key (how much they point the same way), divided by √(size), then softmax turns them into weights that add up to 1.
Now tick the causal mask. A language model writes left to right, so a word may only look at words before it. In "i sat by the bank of the river", "bank" can't see "river" yet and stays ambiguous. The later words carry the context forward instead, and that's one reason models need many layers.
The math, step by step
Stack the sentence's \(n\) embeddings as rows of a matrix \(X\) (\(n \times d\)). Three learned matrices turn each word into its query, key and value:
\[ Q = X W_Q, \quad K = X W_K, \quad V = X W_V \]
Then every query is compared with every key (an \(n \times n\) table of dot products), scaled, turned into weights by softmax row by row, and used to average the values:
\[ \operatorname{Attention}(Q, K, V) = \operatorname{softmax}\!\left( \frac{Q K^{\top}}{\sqrt{d_k}} \right) V \]
Why \(\sqrt{d_k}\)? If query and key have \(d_k\) independent random entries of size about 1, their dot product is a sum of \(d_k\) random terms, so its typical size grows like \(\sqrt{d_k}\). Without the division, big models would feed softmax huge scores, it would put all the weight on one word, and its gradient (chapter 5) would vanish. Dividing keeps scores around size 1 at any \(d_k\).
The causal mask sets the score for every later word to \(-\infty\) before the softmax; \(e^{-\infty} = 0\), so those words get exactly zero weight.
Cost. The \(QK^\top\) table has \(n^2\) entries: double the context, four times the work. That's why long context windows are expensive.
A head with \(d_k = 64\). What number are the scores divided by?
With the causal mask on, how does the first word of a sentence attend?
- 100% to itself: it's the only word it may see
- Evenly to all words
- It gets no attention output at all
Attention makes each word a weighted average of the words it finds relevant: queries ask, keys answer, values are what gets mixed.
Why attention is a lookup table you can train
- A Python dict is a lookup: a key that exactly matches the query returns its value, all others return nothing.
- Attention compares the query with every key by a dot product, which measures how well they align (chapter 1), instead of asking "equal or not".
- Softmax turns those scores into weights that add up to 1, and the answer is the weighted average of the values: a lookup that returns a blend when several keys match.
- Make the scores bigger and the softmax hardens toward the single best match: in the limit, a real dict lookup.
- Unlike a dict, every step is smooth, so backprop gets a slope for \(W_Q\) and \(W_K\): the model learns what to ask and what to advertise. A hard lookup has slope 0 almost everywhere and couldn't learn (chapter 4's argmax).
Many heads: several questions at once
One head asks one question. But "bank" wants two answers: what is this sentence about? and which word came right before me? ("the bank" vs "river bank"). So a transformer runs several heads side by side, each with its own \(W_Q\) and \(W_K\), and glues their outputs together.
To give a head something to find positions with, each word gets two more numbers: a point on a circle at angle \(45° \times\) its position. Head 1's matrices read only the meaning numbers, exactly as above. Head 2's read only the position numbers, and its \(W_Q\) is a rotation (chapter 1's matrix as a move) by \(-45° \times k\), scaled up so softmax is decisive. The query of the word at position \(i\) then points straight at the key of position \(i - k\): a head that always looks \(k\) words back, whatever the words are. Click a word above, or here.
Trained models find heads like these on their own: researchers have found "previous-token" heads in nearly every language model, and heads that link a pronoun to its noun. Then one more matrix, \(W_O\), mixes the glued outputs back to the model's width:
\[ \operatorname{MultiHead}(X) = \big[\, \text{head}_1 \;\big|\; \text{head}_2 \;\big|\; \dots \;\big|\; \text{head}_h \,\big]\, W_O \]
Heads cost nothing extra: a model of width 4096 with 32 heads gives each head \(d_k = 4096 / 32 = 128\) numbers, so the total work is the same as one big head, but it can ask 32 different questions.
Causal mask on, head 2 looking back 1 word. Where does the first word's head 2 attend?
- To the word before it
- To itself: it's the only word it may see, so it gets all the weight, even though its query points elsewhere
- Nowhere: its output is zero
Several heads ask several questions at once, for the same cost as one big head.
3. A transformer is attention + a layer, stacked
That's the whole architecture. Each block lets words exchange information (attention), then lets each word think on its own (the per-word layer: matrices and bends, chapter 1). Real models run many attention heads in parallel per block, each with its own query, key and value matrices, so one head can track grammar while another tracks who "he" refers to. Everything is trained exactly as before: predict the next word, measure the surprise (chapter 5), backprop the blame (chapter 4), step downhill (chapter 2), on trillions of words.
The math: one block, and where the parameters live
One block, for a sequence \(X\) of \(n\) vectors of size \(d\):
\[ H = X + \operatorname{Attention}(\operatorname{LN}(X)) \qquad Y = H + W_2\, \operatorname{GELU}(W_1\, \operatorname{LN}(H)) \]
The \(X + \dots\) parts are residual connections: each block adds a correction to its input instead of replacing it, so blame flows straight back through dozens of blocks without fading. LN is layer norm: shift and scale each vector to mean 0 and spread 1, which keeps numbers in a range where training is stable. GELU is a smooth ReLU.
Parameter count per block: \(W_Q, W_K, W_V\) and an output matrix are each \(d \times d\): \(4d^2\). The per-word layer goes from \(d\) up to \(4d\) and back: \(2 \cdot 4d^2 = 8d^2\). About \(12 d^2\) per block. GPT-2 small (\(d = 768\), 12 blocks): \(12 \cdot 12 \cdot 768^2 \approx 85\) million, plus the 38.6 million embedding table: 124 million.
About how many parameters are in one block with \(d = 768\), using \(12 d^2\)?
A transformer alternates two moves, words exchanging information and each word thinking alone, and each move adds a correction to what was there.
Where it breaks: order, length and the middle
- No sense of order on its own. Attention is a weighted average, so shuffling the input words just shuffles the outputs the same way: without position information, "dog bites man" and "man bites dog" give the same set of vectors. Position embeddings (or rotations, as in head 2) are what put order in.
- Length costs the square. The score table has \(n^2\) entries: a 128,000-token context means about 16 billion scores, per head, per layer. Tricks like FlashAttention compute the same thing without storing the table; others look only at a window of recent tokens.
- Lost in the middle. A long context isn't used evenly: models tested on finding one fact in a long document do best when it's near the start or the end, and noticeably worse when it's buried in the middle. Putting what matters near the question helps.
Later on the path: what happens when that next-word machine is allowed to call tools and act. That's agents, with Blip, the companion on this page, as the worked example.
All chapters: AI from scratch. Inspired by 3Blue1Brown's Attention in transformers, visually explained.
Last updated