The bottleneck, and the fix: look back
A minister gives a speech in English, and an interpreter must say it in Hindi. The first interpreter listens to the whole speech, holds it in her head, and then speaks. For a short speech this works. For a long one, the details are gone before she opens her mouth.
The second interpreter keeps notes, one line for every phrase. Before each Hindi word she glances back at her notes, and she looks hardest at the line that matters right now. She never has to remember the whole speech. She only has to know where to look.
The question. How can a machine translate a fifty-word sentence if only a handful of numbers may pass from the part that reads to the part that writes?
That was the trouble with the translator of Unit 17. Its encoder reads "I drink tea" one word at a time. After each word it writes a note — a short list of numbers: after "I", after "drink", after "tea". Then it hands the decoder only the last note, the summary. A five-word sentence and a fifty-word sentence must squeeze through the same few numbers. That squeeze is the bottleneck. It is the first interpreter, speaking from memory.
The fix (Bahdanau, Cho and Bengio, 2015) is the second interpreter. Keep every note. Before the decoder writes each word, it makes three small moves.
- Score every note. How well does this note match what I am about to write? The simplest score is the dot product (Unit 3) of the decoder's current state with the note.
- Turn the scores into shares with softmax (Unit 14). The shares are positive and add up to 1. They are called the attention weights.
- Blend the notes with those shares. The blend is the context vector. The decoder uses it, together with its own state, to choose the next word.
By hand. We keep the numbers tiny and make them by hand, so that you can see everything. Each note simply points at its own word: , , . (Real notes are long lists that mix many words together.) The decoder has written मैं (main, "I") and is about to write चाय (chai, "tea"). Its state — the decoder's own running note, as in Unit 17 — is, say, .
Almost three quarters of the attention goes to the note of "tea". The machine is about to write "chai", and it is looking at "tea". Nobody told it to — the scores did.
Do this for every Hindi word and stack the weights as rows. You get the alignment map: one row for each word written, one column for each word read. In "I drink tea" → "मैं चाय पीता हूँ" (main chai peeta hoon) Hindi puts the verb at the end. So the bright cells do not run straight down the diagonal. They bend: चाय looks at "tea", and then पीता (peeta, "drink") looks back at "drink". The last word, हूँ (hoon, "am"), has no single English partner, so it spreads its attention over "I" and "drink".
Two reasons. First, nothing is squeezed. A long sentence simply has more notes, and every note stays exactly as it was written. Second, the blame has a short road. When the decoder writes a wrong word, backprop (Unit 15) sends the blame back through the context vector straight into the notes it used — one hop, in proportion to their shares. In the relay, the blame for an early word had to crawl back through every step, and it faded on the way (Unit 17).
Three ways to score a note. The dot product is not the only way to ask "how well does this note match?". Here are the three classic choices side by side.
| score | formula | extra weights | in plain words |
|---|---|---|---|
| dot (Luong, 2015) | none | "how much do we agree?" — needs and of the same length | |
| general (Luong, 2015) | one matrix | first re-express the note with , then agree | |
| additive (Bahdanau, 2015) | a tiny one-layer network judges the match |
An additive score by hand. Take , , a decoder state and three notes , , . Both matrices are , so is just : add the state to each note: , , . Squash each entry with tanh: , , . Now simply adds the two entries: the scores are , and softmax turns them into the weights .
Rule of thumb. The dot product is the cheapest, and it is the one the transformer uses (with the of §4). Additive scoring came first. Like general, it copes when the decoder state and the notes have different lengths: its matrices first bring both to one size.
There is not one context vector for the sentence. There is a new one for every word the decoder writes: four Hindi words, four context vectors, four rows of the map. The notes stay the same; what changes is where the decoder looks.
Before writing word , score every note against the decoder's state , turn the scores into shares , and blend the notes into the context . Keep every note and look back, instead of carrying one summary and hoping it holds everything.
In the worked example you make the decoder's state for चाय twice as long: . What happens to the three attention weights?
A 30-word English sentence is translated into 35 Hindi words, with attention. How many context vectors does the decoder build, and how many numbers are in the alignment map?
If you want the algebra · 1 proof, step by step
Claim. With dot-product scores , shares and context , the slope of the context with respect to one note is . The blame reaches note directly, scaled by its own share — however long ago the note was written.
The road ahead. The unit has four acts.
- Look back instead of remembering (§1–§2): the decoder's look-back, and attention as a soft lookup.
- Every word asks every word (§3–§7): self-attention by hand, why we divide by , one word with many meanings, an attention lab where you type your own sentence, and many heads.
- Order and depth (§8–§9): three ways to tell the model where each word stands, and the transformer block.
- How transformers learn (§10–§14): the mask that trains every next word at once; BERT, GPT and the encoder–decoder; the price; and a tiny transformer walked end to end.
In one sentence: Instead of squeezing the sentence into one summary, the decoder keeps every note and, before each word it writes, scores the notes, turns the scores into shares and blends them — an interpreter glancing back at the speaker's notes, looking hardest where it matters now.
Attention is a soft lookup
You walk up to a tea stall and say, "Something hot and milky, please."
A strict shopkeeper looks for the one item that matches best and hands you only that. A kind shopkeeper pours you a small cup of each drink, with more of the ones that match your wish better, and mixes them. The first is a lookup. The second is attention.
The question. The decoder of §1 did not pick the best note. It took a blend of all of them. Why a blend — why not simply pick the winner?
First, give the three parts their names, with the help of a library. Your query is what you are looking for: "a cricket book for beginners". Every book has a label on its spine — its key. Inside the book is what you actually take home — its value. A strict librarian hands you the one book whose label matches best. A kind librarian photocopies a few pages from every book, more pages from the books whose labels match your wish better, and staples them into one bundle. That bundle is attention's answer.
In §1 each note played both parts at once: the decoder compared its state with the note (the note as a key) and then blended the notes themselves (the note as a value). Split the two parts and you have the general tool, the soft lookup.
A tiny example. The stall has two drinks. Chai costs ₹10, coffee costs ₹20. Your wish matches chai with a score of 2 and coffee with a score of 0. Turn the scores into shares with softmax (Unit 14):
The two shares add up to 1. Your mixed cup is 88% chai and 12% coffee, so its price is the same blend of the prices: — ₹11.19. A strict lookup would have said ₹10, full stop.
Where does a score come from? From the dot product of Unit 3: write the query and each key as lists of numbers, multiply them entry by entry and add up. Big when they point the same way, zero when they have nothing in common, negative when they disagree.
Because a blend can be nudged. If the answer comes out a little wrong, training can move a little share from one key to another: every share has a slope (Unit 14). A strict pick has no useful slope at all. Nudge the query and nothing changes — until the winner suddenly flips. Backprop gets no hint about which key it should have liked a bit more. The soft lookup is a lookup that can learn.
Strict against soft, side by side.
| strict lookup (a dictionary) | soft lookup (attention) | |
|---|---|---|
| you bring | a key to match exactly | a query |
| it compares | equal or not equal | a dot product with every key |
| you get back | one value | a blend of all the values |
| when nothing matches | an error: "not found" | still a blend — with equal scores, the plain average |
| can it learn? | no slope: the winner just flips | yes: every share has a slope |
Rule of thumb. Inside a network, always go soft. If you want it nearly strict, make the scores big: a very picky soft lookup behaves like a dictionary, and it can still learn.
Attention never says "no match". A query that matches nothing still gets an answer: with equal scores, every key gets the same share and the answer is the plain average of the values. A bad query does not give an empty answer — it gives a vague one.
Attention is a lookup that never says "no match". Every key gets a score by a dot product with the query. Softmax turns the scores into shares that add up to 1. The answer is the blend of all the values with those shares. Make the scores bigger and bigger, and the biggest share swallows the rest: the soft lookup becomes a strict one.
Three keys give scores 1, 1 and 1 with your query. The values are 3, 6 and 9. What does attention return?
In the tiny example, you multiply both scores by 10: chai 20, coffee 0. What happens to the price of your cup?
If you want the algebra · 2 proofs, step by step
Claim. The shares are all positive and add up to 1. So the answer always lies "among" the values (inside their convex hull) — never beyond the biggest or below the smallest in any entry.
Claim. Multiply every score by a pickiness . If one key has the strictly biggest score , then as its share goes to 1 and every other share goes to 0. At all shares are equal.
In one sentence: Attention answers a query with a blend of every value, weighted by softmax of how well the query matches each key — a librarian who staples a few pages from every book, more from the books whose labels match your wish, and so can learn where to look.
Self-attention: every word asks every word
A class of eight students plays "pass the message". The first student whispers to the second, the second to the third, and so on. By the time it reaches the eighth student, the message is faint and mixed up — and it took seven turns.
Now change the rule. Every student may stand up and ask any other student a question directly, and everyone asks at the same time. One turn. Nothing gets lost on the way.
The question. In §1 the decoder looked back at the encoder's notes. But the encoder itself still read the sentence as a relay: the note written after "tea" knows about "I" only because "I" was passed along from hand to hand. Why keep the relay at all? What if every word could look at every other word directly?
That is self-attention: the words of one sentence attend to each other. In 2017 Vaswani and others built a whole translator from it, with no relay at all — the transformer, in a paper called "Attention Is All You Need". The relay of Unit 17 had two problems, and self-attention removes both.
- The relay forgets. The first word's voice is handed along seven times to reach word 8. If each hand-over keeps about half of it, what arrives is — less than 1%. With attention the path from word 1 to word 8 is one step long.
- The relay is slow. Word 8 must wait for word 7, which waits for word 6. A computer with a thousand workers still has to do the steps one after another, so most of the workers sit idle. With attention all the questions are asked at once.
The price is the number of questions. With 8 words, each of the 8 asks all 8 (itself too): questions. We come back to that price in §12.
Three views of every word. For every word to ask every other word, each word needs three things. Think of three badges it wears:
- a query — "what am I looking for?"
- a key — "what do I offer, so that others can find me?"
- a value — "what do I hand over when someone picks me?"
All three are made from the same word. The word starts as one list of numbers (its vector from the table of Unit 16), written as a row. Three learned matrices turn that one row into three:
In this unit queries are orange, keys are blue, values are green and attention weights are gold. Training chooses the three matrices.
One word, worked by hand. Three words already have their keys and values, each a list of two numbers (so ):
A word asks with the query . Four small moves:
- Score each key with a dot product, then divide by (§4 says why): , , . Divided: .
- Turn scores into shares with softmax: and , total . Shares .
- Blend the values with those shares: .
- Read the answer: .
The query points along the first direction, so it matched keys 1 and 3 equally well and key 2 badly. The answer leans towards and .
All the words at once. In a sentence every word asks its own question. Write the shapes first (the habit of Unit 15). A sentence of words, each a list of numbers, is a table of shape . Stack the queries as the rows of , the keys as the rows of , the values as the rows of — each . Then every lookup happens in one line:
Read it aloud, from the inside out. : every question against every label — an table of agreements. Divide by : calm the numbers down (§4). Softmax, row by row: each word shares out exactly 100% of its attention. Times (): each word collects its blend of gifts — new vectors, one per word. The table of shares is the attention matrix. With the three queries , and :
The answers are , and . The third query likes key 3 most, and its answer is exactly — the other two values balance each other.
The same three matrices serve every word in every sentence. So the model never learns "what word 5 should ask". It learns kinds of questions — "which thing am I talking about?", "who did the action?" — that work at any position. That is the sharing trick of the recurrent cell (Unit 17), but without the relay: every answer is one hop away.
The relay against self-attention.
| the relay (Unit 17) | self-attention | |
|---|---|---|
| path from word 1 to word | hand-overs | 1 hop |
| steps that must wait in a row | 1 per layer | |
| what a word sees | a fading summary of the words before it | every word, directly |
| work for words | about steps | scores (§12) |
Rule of thumb. When the text fits, attention wins: nothing fades and nothing waits. The bill is what limits how long the text can be.
, and are not three different words, and not three copies of one vector. They are three views of the same word, made by three different matrices. A word's query and its own key need not agree — a word does not have to pay attention to itself.
Every word turns itself into a question, a label and a gift. Each question is scored against every label by a dot product; softmax makes each row of scores into shares; each word collects the gifts in those shares. One matrix line does it for all the words at once. This is Unit 13's kernel vote: similarity by a dot product, then a weighted sum.
A sentence has 10 words. In the relay each hand-over keeps half of the first word's voice. How much of it reaches word 10 in the relay — and with attention?
With the same keys and values, a new query is . What is the answer?
A sentence has 5 words and . What are the shapes of and of the output ?
If you want the algebra · 2 proofs, step by step
Claim. Row of is exactly the single lookup of §2 for the query : with .
Claim. Write . Then attention is a normalised vote: , and is a genuine kernel — a dot product of two feature vectors in a bigger space.
In one sentence: Self-attention drops the relay: every word makes a query, a key and a value with three shared matrices, and lets every word collect a blend of every value in one hop — students who all ask each other at once instead of passing a whisper down the line.
Why we divide by the square root of d
A judge scores a singing contest out of 10. The scores are close, so the prize money is shared fairly. Now a second judge scores the same singers out of 1000. One singer gets 30 points more than the next — and with scores that big, softmax hands that singer all the money.
Nothing about the singers changed. Only the size of the numbers did. The fix is simple: bring the scores back to a sensible size before you share out the money.
The question. Every score in §3 was divided by . What goes wrong without it — and why , not ?
A dot product adds up little products, one for each entry. More entries means a bigger pile. If the entries of and are random numbers of typical size 1, each little product is about size 1 too, and they add up like coin-toss steps: some push up, some push down, and they partly cancel. The pile's typical size — its spread, the standard deviation of Unit 14 — grows like :
Why is that bad? Softmax only cares about gaps between scores. Take two scores 8 and 0, a normal gap when . Softmax gives
That is nearly one-hot: the word listens to one other word and ignores the rest. Worse, the row is stuck. The slope of a share is , almost zero, so training gets almost no blame through it (the fading blame of Unit 15).
Now divide by first. The scores become 1 and 0, and softmax gives . The slope is — nearly 600 times bigger. Dividing by brings the spread back to about 1, whatever is.
For random entries of size 1, the little products are independent, so their variances add up: the variance of the pile is , and its spread is (the drawer below proves it). Dividing by divides the spread by , leaving 1. So a small model and a huge model hand softmax scores of the same size, and softmax behaves the same way in both. It is the spirit of putting inputs on one scale in Unit 10.
Three choices for the same pair of scores, 8 and 0, with .
| divide by | scores become | shares | slope | the row is |
|---|---|---|---|---|
| nothing | 8 and 0 | (0.99966, 0.00034) | 0.00034 | spiky and frozen |
| 1 and 0 | (0.731, 0.269) | 0.197 | soft, decided and alive | |
| 0.125 and 0 | (0.531, 0.469) | 0.249 | nearly flat: it barely prefers anything |
Rule of thumb. Divide by — the size of the spread. Too little and the rows freeze; too much and they go blind.
Divide by , not by . Dividing by shrinks every score towards 0 when is big, and each row becomes almost flat — every word listens to every other word nearly equally, so attention cannot point at anything.
Long vectors make big dot products, and big scores make softmax pick one winner and freeze. Dividing every score by keeps the scores at a spread of about 1, so the shares stay soft and blame keeps flowing.
A friend builds a model with and forgets to divide by . What happens when it trains?
Two scores are 12 and 0 with . After dividing by , what share does the first word get?
If you want the algebra · 2 proofs, step by step
Claim. If the entries of and are independent, with mean 0 and variance 1, then has mean 0 and variance , so its spread is — and has variance 1.
Claim. The slopes of softmax are . When one share is nearly 1 (a spiky row), every slope is nearly 0.
In one sentence: A dot product of two random length- vectors has spread , which makes softmax spiky and frozen, so attention divides every score by — like a judge who marks out of 1000 being brought back to marks out of 10 before the prize money is shared.
The payoff: one word, many meanings
A chameleon sits on a green leaf and turns green. Put the same chameleon on a brown branch and it turns brown. It is the same animal. The colour it shows depends on where it sits.
"I sat on the bank of the river." "I took a loan from the bank." Same word, same spelling — a different meaning. Which one it is depends on the words sitting around it.
The question. In Unit 16 every word got one vector, the same in every sentence. So "bank" had to sit halfway between rivers and money, and "bat" halfway between cricket and caves. Can attention give a word a different vector in each sentence?
Yes — and you have already seen how. After self-attention a word's new vector is a blend of the values of the words it attends to. Change the neighbours and the blend changes. Watch it happen with numbers.
By hand. Take lists of just two numbers, made by hand: the first number says "how much about nature", the second "how much about money". So river , money , and bank — right in the middle, because Unit 16 had to give it one vector for both meanings. To keep the arithmetic small, let every word use its own vector as its query, key and value (); a real model would first multiply by , and .
Sentence one: "river bank". Bank asks with its query :
Sentence two: "money bank". The same steps give .
The same word now has two different vectors. The first leans towards nature, the second towards money. How different are they? Their cosine (Unit 3) is
an angle of about 53°. Before attention the two "bank"s were one and the same vector, with cosine 1. This is what contextual embeddings means: vectors computed from the whole sentence, not looked up once per word. ELMo (2018) built them with the two-way LSTMs of Unit 17; BERT (2018) built them with attention (§11).
A word's new vector is a blend of its own value and its neighbours' values. Its own share keeps it recognisable — "bank" never turns into "river". The neighbours' shares pull it towards what the sentence is about. And a neighbour that matches the word's query better gets a bigger share, so it pulls harder. Stack a few layers and every word's vector describes that word in this sentence.
One vector per word, against one vector per word in each sentence.
| static vectors (Unit 16) | contextual vectors (this unit) | |
|---|---|---|
| how many per word | one, for every sentence | a fresh one in every sentence |
| how you get it | look up a row of a table | run the sentence through the attention layers |
| "bank" in our two sentences | (1, 1) and (1, 1): cosine 1 | (1.5, 0.5) and (0.5, 1.5): cosine 0.6 |
| cost | one lookup | a whole forward pass |
Rule of thumb. Static vectors are cheap and fine for "which words are alike?". Whenever the meaning depends on the sentence — which in real text is almost always — use contextual vectors.
The contextual vector is not stored anywhere. There is no table row for "bank-near-a-river". The model's lookup table still has exactly one row for "bank" — the first layer is Unit 16's table. The context is computed fresh by the attention layers every time the model reads a sentence.
The sum runs over the words of this sentence. After attention a word's vector is a blend over the words of its own sentence, so the same word gets a different vector in a different sentence. The one fixed vector per word of Unit 16 becomes a vector that knows its company.
In "river bank" you replace river by stream , a stronger nature word. What happens to bank's new vector?
After attention, bank is in "river bank" and in "money bank". What is the cosine between the two?
If you want the algebra · 1 proof, step by step
Claim. In a two-word sentence with , word after attention is , where is its neighbour, and . So it slides along the straight road from to , past halfway exactly when .
In one sentence: Because a word's output is a blend over its own sentence, the same word gets a different vector in each sentence — a chameleon that takes the colour of its neighbours, so "bank" by a river and "bank" with money end up about 53° apart.
The attention lab: who looks at whom
Read this: "The batsman hit the ball because it was loose." What was loose? You did not stop to think. You knew "it" meant the ball, not the batsman. Somewhere in your head, the word "it" reached back and grabbed "ball".
That grab is exactly what attention does. And we can draw it.
The question. What does attention look like on a whole sentence — who looks at whom?
Give every word of the sentence its query, key and value, and work out every row of the attention matrix. With 9 words you get a table. Row "it" says how much "it" listens to each word. Draw the table as a grid of squares, brighter where the share is bigger: that is an attention map.
The lab below does exactly the maths of §3, for any short sentence you type. Its word vectors are toy ones, made by hand — not taken from a trained model. Each word is a list of 12 numbers. Eight of them are labelled features you can read: thing, someone, action, "it"-word, "he/she"-word, describing word, place, small linking word. The other four say where the word stands (§8). The matrices are hand-set too, so you can see why each share comes out as it does. But the arithmetic — dot products, , softmax, the blend — is exactly the real one.
In the lab, head 1 is set up so that an "it"-word asks "which word is a thing?", and every thing answers "I am a thing". So row "it" gives "ball" a share of about 0.766, and each of the other eight words about 0.029.
Look at the bars under the lab. Before attention, "it" is a pure "it"-word: its thing bar is 0. After attention it has collected about 0.77 of ball's value from head 1 (and a little more from head 2), so its thing bar has risen to about 0.82. The word "it" now carries part of the meaning of "ball" — the payoff of §5, in a real sentence. The same word in another sentence would pick up something else.
A query and a key are lists of features, and their dot product adds up the features they share. In head 1 the query of an "it"-word has a big number on the thing feature, and every noun's key carries a 1 there. In this sentence only "ball" is a thing, so row "it" has one big score — and softmax turns one big score into one big share.
A bright cell is not an explanation. It says "this word's value was blended in heavily", not "this is why the model decided". In trained models many heads park their attention on the first word or on full stops when they have nothing to ask. Read attention maps as clues, not as proof.
The attention map is a table of who listens to whom. Each row adds up to 1. After attention each word's vector is its old self plus a blend of what the words it listened to were carrying (keeping the old self is the residual path of §9). So "it" in "the ball … it was loose" ends up close to "ball".
In the lab, head 1, row "it" of the batsman sentence: "ball" gets about 0.766 and the other eight words share the rest equally. What share does each of the other eight get?
In the lab, slide the temperature for head 1 from 1 down to 0.3. (The temperature divides every score.) What happens to the share of "ball" in row "it"?
In one sentence: The attention map shows, row by row, how much each word listens to every other word — "it" grabbing "ball" — and adding the blended values to each word turns fixed word vectors into vectors that carry their sentence.
Many heads: many questions at once
A cricket commentary box has several experts. One watches the batsman's feet. One watches the field placing. One keeps the score. They all watch the same ball, but each asks a different question, and together they tell the full story.
The question. A word often needs two answers at once: "which thing do I mean?" and "what came just before me?". One row of softmax gives one blend. How can one word ask two questions?
Run several attentions side by side. Each one is called a head. Each head has its own , builds its own attention map and makes its own blend.
Here is the trick that keeps it cheap. Do not give each head the full length . Cut it into equal pieces. Each head's matrices make queries, keys and values of length
Tiny numbers. A common size is with heads, so each head works with lists of length . The eight answers, each of length 64, are glued side by side back into one list of length . A last matrix (size ) mixes them.
The cost is the same as one big head. One big head needs three matrices. Eight small heads need matrices of size , which is exactly the same number of weights. Add and either way attention has weights.
Each head wears its own glasses. A head's matrices keep only some directions of the word vectors and throw the rest away — the projection of Unit 12. So the same words can be close together through one pair of glasses and far apart through another. Below, eight words have three hand-made features: is it a drink?, is it hot?, is it a sport? Three heads each keep just one feature (, , so ). Ask about "coffee". The drink head finds chai and lassi. The hot head finds the sun, coffee itself and chai. The sport head has nothing to ask, so it spreads its attention evenly.
One row of softmax can say one thing: one blend. A word that needs two different blends needs two rows — two heads. Because each head looks through its own projection, the same word can be close to "ball" in one head and close to "because" in another, and the glued answer carries both. Cutting into pieces keeps the price the same.
One big head against many small ones ().
| 1 head of 512 | 8 heads of 64 | 64 heads of 8 | |
|---|---|---|---|
| attention maps per word | 1 | 8 | 64 |
| weights in | 1 048 576 | 1 048 576 | 1 048 576 |
| what can go wrong | one blend must serve every question | — the usual choice | each head's space is tiny, its scores are crude |
Rule of thumb. Keep each head's size around 64: BERT-base uses , and so does the small GPT-2.
More heads do not mean more weights. Eight heads of 64 cost exactly what one head of 512 costs: either way. What changes is how many different questions can be asked at once, and how small each question's space is.
Many heads are many small attentions, each looking at the words through its own projection. Cut into pieces of size , let each head build its own map, glue the answers back and mix them with . You get different questions for the price of one.
A model has and heads. How long is each head's query, and how many weights do have together (no biases)?
In the glasses widget, "coffee" asks the sport head. Coffee's sport feature is 0. What shares does it give the eight words?
If you want the algebra · 1 proof, step by step
Claim. With heads of size , the matrices (each ) and () hold weights — the same for every .
In one sentence: Multi-head attention cuts into heads of size , each looking at the words through its own glasses, then glues the answers and mixes them with — a commentary box of experts, questions for the same weights.
Where is each word? Three ways to add position
Tip a bag of word cards onto a table: "dog", "bites", "man". Could it say "dog bites man"? Or "man bites dog"? The bag cannot tell you. The cards are the same; only the order differs — and the order is the whole news story.
The question. "Dog bites man" and "man bites dog" use the same three words. Can attention tell them apart?
Look back at the attention formula. It compares words by dot products and blends their values. Nowhere does it ask "which word came first?". So attention on its own is order-blind. Shuffle the words, and every word gets exactly the same answer as before — the answers just come out in the shuffled order.
A tiny check. Take toy vectors dog , man , bites , and let each word's query, key and value be its own vector. In "dog bites man" the word dog ends up as . In "man bites dog" it ends up as … . The same. Attention cannot tell who bit whom.
The fix: put the position into the vectors. Give the first word the tag , the middle word and the last word , and add the tag to each word's vector before attention. Now dog becomes when it comes first and when it comes last. Order finally matters.
Those three tags were made up for three words. Real models need tags for thousands of positions. There are three standard ways to make them.
1 · Learned position vectors. Keep a second lookup table, exactly like the word table of Unit 16, with one row per position: row 1 for the first word, row 2 for the second, and so on up to the longest text used in training (512 in BERT, 1 024 in GPT-2). Add the row to the word's vector. Training fills the table. It is simple — but the table has no row 513, so a model trained on 512 positions cannot read a longer text.
2 · Clock hands (sinusoidal tags). The first transformer built the tags from clock hands turning at different speeds. Picture a row of clocks. For position , a clock of speed gives the two numbers and — where its hand points. The speeds are . With there are two clocks, of speeds 1 and 0.01. Each tag lists the fast clock's two numbers, then the slow clock's two:
The fast clock tells near positions apart. The slow clock tells far positions apart — the hour hand and the minute hand together tell the time better than either alone. And here is the gem. Take the dot product of two neighbouring tags:
The same number. For each clock, , and two positions apart always have their hands apart. So : it depends only on the distance , never on where the pair sits.
3 · Turn the arrows (rotary positions, RoPE). Many modern models use the clock idea more directly. Instead of adding a tag, they turn the query and the key. Split each into pairs of numbers — little arrows. A word at position turns its query arrow by ; a word at position turns its key arrow by . Turning is the rotation of Unit 4. The dot product of two arrows depends only on the angle between them, and turning both by the same extra amount changes nothing. So the score depends only on the gap .
Tiny numbers. Take and . Put the query at position 3 and the key at position 1: the arrows point at and , the angle between them is , and the score is . Move them to positions 5 and 3: arrows at and , still apart, score 0.5. Positions 2 and 0: again 0.5.
Attention can only compare vectors, so the position has to live inside the vectors. Once two words carry position, their dot product carries a part that depends on where they stand — and with clock tags or turns, only on how far apart they are. So one fixed set of weights can learn "look one word back" and use it at every position of every sentence. The lab's head 2 in §6 does exactly that.
The three ways, side by side.
| learned rows | clock tags (sinusoidal) | turns (rotary, RoPE) | |
|---|---|---|---|
| how | add a trained row for each position | add fixed clock-hand tags | turn and by position × |
| weights to learn | one row per position | none | none |
| longer text than in training? | no row for it | a tag exists for every position | a turn exists for every position |
| does distance alone decide? | not built in | the tags' dot product: yes | the score itself: yes |
| used in | BERT, GPT-2 | the original Transformer (2017) | LLaMA and most new models |
Rule of thumb. For a new model, turn the arrows: nothing to learn, a turn for every position, and "two words back" means the same everywhere. (A model still reads best at the lengths it practised on; stretching it much further needs extra tricks.) Learned rows are the simplest choice when every text has a fixed maximum length.
Adding a position tag does not sort the words. The model still sees an unordered set — now a set of "word + tag" vectors. Order enters only through the way the tags change the dot products.
Attention alone treats a sentence as a bag of words. Positions put the order back in: learned rows, clock-hand tags, or turns of the query and key. With clock tags and turns, what matters is how far apart two words are — "two words back" means the same thing everywhere in the sentence.
With RoPE, and : what is the score for query position 7 and key position 1?
No position information at all. You swap the first and last words of a sentence. What happens to the attention answer of the middle word?
With the clock tags, . What is ?
If you want the algebra · 4 proofs, step by step
Claim. Shuffle the rows of with a permutation matrix . Then the attention answers are shuffled the same way and nothing else changes: .
Claim. Let turn a 2-D arrow by the angle . Then , which depends on and only through .
Claim. For one clock of speed , the tag of position is a fixed rotation of the tag of position : is obtained from by a matrix that depends only on .
Claim. For sinusoidal tags with clock speeds , — there is no in it.
In one sentence: Attention is order-blind, so we put position into the vectors — a learned row per position, clock hands turning at different speeds, or turns of the query and key — and with clocks and turns the score sees only how far apart two words are.
The transformer block
A group project has one shared notebook. It goes round the table. Each student reads everything written so far, then adds a note at the bottom. Nobody tears out a page, and nobody erases a line. At the end the notebook holds the first page and every note added since.
The question. Attention lets words talk to each other. What else does a layer need, so that we can stack dozens of them without the numbers — or the blame — falling apart?
Think of each word's vector as its own page of that notebook. The page rides up through a stack of identical blocks, and every block only ever adds notes to it. This running page is called the residual stream. One block has four stations:
- Attention — the words talk to each other (§3–§8). Each word collects a blend from the other words.
- Add, then steady. Add what attention wrote to the word's own vector: . This shortcut is the residual path — a note added, nothing erased. Then layer norm rescales the result to a steady size.
- Feed-forward — each word thinks on its own. Every word, separately, goes through the same small two-layer network of Unit 15: matrix, bend (ReLU, or its smoother cousin GELU), matrix. Its middle layer is usually four times wider than .
- Add, then steady — again.
So a block is: talk, then think — and after each, add a note and steady the page.
Why the shortcut? Because of the blame. On the way back (Unit 15), the slope of is , not just . Even if is tiny, the "1" carries the blame straight down, block after block. It is the LSTM's express lane from Unit 17, built into every block.
Layer norm, by hand. It makes each word's list have average 0 and spread 1 — the "standardise" of Unit 10, done inside the network, one word at a time. Take :
Then two learned lists, a scale and a shift , stretch and move each entry, so the network can undo the steadying where it wants to.
One word through one block. Take a word with (toy numbers, ). Say attention hands back . The shortcut adds them: . Layer norm gives — the numbers above. The small network adds its own small change, , and a second add-and-steady finishes the block: . Follow the page up the tower in 3-D.
Counting the weights of one block. Take and a feed-forward middle of (four times wider, the usual choice).
Biases add for attention and for the feed-forward part, giving 3 150 336. The two layer norms add more ( and each), for 3 152 384 in all. Two thirds of a block lives in its small network, not in attention.
Where does layer norm go? The first transformer steadied the page after each add: — "post-norm". Most models since GPT-2 steady a copy before each station and add the result to the untouched page: — "pre-norm". Then the residual lane runs from the bottom of the tower to the top without passing through a single layer norm, and deep stacks train more steadily.
| post-norm (2017) | pre-norm (GPT-2 and later) | |
|---|---|---|
| one station | ||
| the residual lane | passes through a layer norm at every station | clean from bottom to top |
| training a deep stack | needs a slow, careful start | steadier |
Rule of thumb. Deep models use pre-norm. The worked numbers in this section use post-norm, because it is the easiest to follow by hand.
Three jobs, three parts. The adds keep every earlier note and give the blame a clean road down (the 1 in ). Layer norm keeps each word's numbers at one size, so block 50 sees the same kind of numbers as block 1. And the feed-forward network adds the bends: attention on its own only mixes values with weights, and a stack of pure mixing stays close to straight lines (Unit 15). The small network lets each word turn what it heard into something new.
Layer norm steadies the numbers of one word — across its entries. It does not average over the words of a sentence, and not over a batch of sentences (that is batch norm). Every word is normalised on its own.
A block is: talk (attention), think alone (a small network), and after each, add the result to the page and steady it with layer norm. The adds are an express lane for the blame; layer norm keeps the numbers at a calm size, block after block.
What is the layer norm (with ) of ?
Inside a block the station has slope for some entry. What slope does the blame see across for that entry — and what happens over 50 such blocks?
If you want the algebra · 3 proofs, step by step
Claim. For with mean and variance , the list has mean 0 and variance 1, and it does not change if is shifted by a constant or scaled by a positive number.
Claim. For , the Jacobian is . Through such blocks the blame is multiplied by , so it never has to fade to zero.
Claim. A block with size and feed-forward width has weights, biases and layer-norm numbers. For , : 3 145 728, then 3 150 336, then 3 152 384.
In one sentence: A transformer block is talk (attention) then think (a small per-word network), each wrapped as "add to the page, then steady it", so the residual stream is a shared notebook that only ever gets notes added — and the blame rides its express lane straight down.
No peeking: the mask, and every guess at once
A teacher writes a sentence on the board, one word per column: "I drink chai daily". She wants the class to practise guessing the next word. The first student may look only at "I" and must guess the second word. The second student may look at "I drink" and must guess the third. And so on.
Nobody waits for anybody. Each student simply covers everything to the right of their own column with a sheet of paper — and the whole class answers at the same moment.
The question. A model that writes must guess the next word without seeing it. How can we train it on a whole sentence at once, without letting it cheat?
While it learns to predict word 3, it must not see word 3. So in the attention map every word may look only at itself and the words to its left. The trick is tiny. Before softmax, set every score above the diagonal to . Since , those words get a share of exactly 0, and softmax spreads the whole share among the allowed words. This is the causal mask — the sheet of paper.
With the numbers of §3. Row 1 may only see word 1, so its shares are and its answer is . Row 2 sees words 1 and 2, with scores and :
and its answer is . Row 3 is the last word, so it may see everything, and it is unchanged: , answer .
Every guess at once. Now the payoff. With the mask, the output at position is built only from words 1 to — in this layer and in every layer above it. So the output at position can be asked to predict word , and it is an honest guess. One pass over "I drink chai daily" makes three guesses at the same time: after "I" → drink, after "I drink" → chai, after "I drink chai" → daily. The loss is the average surprise of all of them (the cross-entropy of Unit 14). An -word sentence gives guesses in one pass.
The recurrent network of Unit 17 also guessed at every word, but it had to walk: word 2's guess waited for word 1's note, word 3's for word 2's. The masked transformer makes all its guesses in one pass through each layer. That is why transformers could be trained on so much text.
Row of a masked attention map mixes only words 1 to , and every later layer keeps the same rule, so the output at position has never seen word . Predicting word from it is a fair test — and it is a fair test at every position at once. One pass gives the same guesses as running the model separately on every beginning of the sentence (the drawer proves it).
Learning to guess the next word: the relay against the masked transformer.
| recurrent network (Unit 17) | masked transformer | |
|---|---|---|
| guesses from an -word sentence | ||
| steps that wait in a row | : each note needs the one before | 1 per layer: all rows at once |
| what stops cheating | the future is not read yet | above the diagonal |
Rule of thumb. To train a writer, use the mask: the same honest guesses as a relay, for the price of one pass.
The goes into the scores, before softmax — not into the shares after it. If you set the shares above the diagonal to 0 after softmax, the rows no longer add up to 1. Putting in first lets softmax share out the whole 100% among the allowed words. (And the mask never hides a word from itself.)
Adding above the diagonal gives the future words a share of exactly zero, so each word's answer is built only from the words before it. Because of that, one pass over a sentence trains every next-word guess at once — word 1 predicting word 2, words 1–2 predicting word 3, and so on — like a class answering together, each student covering the answers to the right.
With the causal mask, row 1 of any attention map is always the same. What is it, for a 4-word sentence?
In a masked (decoder) attention you change the value of word 4 in a 5-word sentence. Which words' answers can change?
A 6-word sentence goes through a masked transformer once, and every position guesses the next word. How many guesses does this one pass train, and how many steps must wait for each other in each layer?
If you want the algebra · 1 proof, step by step
Claim. With the causal mask, the output of any layer at position does not depend on anything about the words after . So one pass over the whole sentence gives, at every position , exactly what a run on the first words alone would give.
In one sentence: Setting the scores above the diagonal to before softmax gives future words exactly zero share, so every position's output is an honest guess of the next word and one pass trains them all at once — the whole class answering together, each student covering the answers to the right.
Three families: BERT, GPT and the encoder–decoder
Three people work with text. A proofreader gets a page with a few smudged words and fills them in; she reads the whole page, both sides of every smudge. A storyteller writes a story one word at a time and never looks ahead — there is nothing ahead yet. An interpreter first listens to a whole speech, then speaks it in another language, glancing back at her notes (§1).
The question. If every modern language model is built from the same transformer blocks, why do some fill in blanks while others write essays?
Because the same blocks can be wired in three ways — and trained with three different games.
1 · Encoder-only: BERT (Google, 2018) — the proofreader. There is no mask: every word sees both sides. The training game is masked-word guessing. Pick 15% of the tokens — the word pieces a text is cut into (Unit 16); think "words"; in a 512-token text that is , about 77 tokens. Of those, 80% are replaced by a special token [MASK] (about 61), 10% by a random word (about 8) and 10% are left as they are (about 8). At each of the ~77 chosen places the model must say what the original token was. (The first BERT also played a second, smaller game — does sentence B really follow sentence A? — which later models such as RoBERTa dropped.) Why not always [MASK]? Because when BERT is used later there are no [MASK] tokens, so it must also learn to check real-looking words. BERT is good at understanding: sorting reviews, finding an answer in a paragraph, tagging the names in a sentence, search.
2 · Decoder-only: GPT (OpenAI, 2018 onward) — the storyteller. It uses the causal mask of §10, and its game is next-word guessing at every position. A 512-token text gives 511 guesses — about 6.7 times as many learning signals as BERT's 77. GPT is good at writing: chat, stories, code.
3 · Encoder–decoder: the original Transformer (2017), T5 (2019) — the interpreter. An encoder reads the input both ways. A decoder writes the output with a causal mask, and every decoder block has one more attention: cross-attention, whose queries come from the decoder and whose keys and values come from the encoder. That is the look-back of §1, rebuilt from attention alone. It is good at turning one text into another: translation, summaries.
Each game fits a job. Take "He said Teddy bears are on sale" and "He said Teddy Roosevelt was a president" (Unit 17). Whether "Teddy" is a name depends on the next word. BERT sees both sides, so it understands such a word better. GPT sees only the left side — which is exactly right for writing, because while you write, the right side does not exist yet. And the encoder–decoder keeps the two jobs apart: understand the input fully, then write the output one word at a time, never peeking ahead.
The three families, side by side.
| encoder-only | decoder-only | encoder–decoder | |
|---|---|---|---|
| each position sees | both sides | only the left (the mask) | encoder: both sides · decoder: its left + all of the input |
| training game | fill in ~15% hidden words | guess the next word, everywhere | write the target text, word by word |
| graded places in a 512-token text | about 77 | 511 | one per output word |
| good at | understanding: sort, search, tag | writing: chat, stories, code | one text into another: translate, summarise |
| examples | BERT, RoBERTa | GPT-2, GPT-3, LLaMA | the original Transformer, T5, BART |
Rule of thumb. To understand, use an encoder. To write, use a decoder. To turn one text into another, use both. (Today's very large decoder-only models are big enough to do all three, by writing the answer out.)
BERT cannot simply write text: it was never trained to guess a word without seeing the words after it. And a GPT vector for a word knows only the words to its left — so for understanding one sentence, a BERT of the same size often does better. Same blocks, different wiring, different talents.
BERT — no mask; grade the ≈ 15% hidden words.
GPT — causal mask; grade every next word.
Encoder–decoder — both, joined by cross-attention.
One kind of block, three wirings. Who may look at whom (the mask) and which positions are graded (the game) decide whether a transformer becomes a proofreader, a storyteller or an interpreter.
BERT is trained on a 256-token text. About how many tokens are chosen for guessing, and about how many of those become [MASK]?
You need a model that marks every name in a sentence — and "Teddy" is a name in "Teddy Roosevelt was a president" but not in "Teddy bears are on sale". Which family fits best?
From the same 1 000-token text, how many graded guesses does GPT get, compared with BERT?
In one sentence: The same blocks become three families — BERT reads both ways and fills in hidden words (the proofreader), GPT reads left to right and guesses every next word (the storyteller), and the encoder–decoder joins the two with cross-attention (the interpreter of §1).
The price: every pair of words
At a party of 10 people, everyone shakes hands with everyone else: 45 handshakes. At a wedding of 1 000 guests the same rule means about half a million handshakes (499 500). The guests have grown only 100 times, but the handshakes have grown more than 10 000 times.
The question. Attention compares every pair of words. What does that cost when the text is a whole book?
For words attention builds an table of scores, in every head of every layer. It counts a little more than the handshakes: every pair from both sides ("it" asks "ball", and "ball" asks "it"), and every word with itself. So 10 words give scores.
Double the length and the work goes up four times. With 12 heads and 12 layers, 1 000 words need such tables: 144 million scores. Stored with 2 bytes each, that is 288 MB — for one text of 1 000 words.
A recurrent network of Unit 17 does only about steps of work for words. Cheaper on paper. But those steps come one after another, so 1 000 words means 1 000 waits in a row. Attention's million scores do not depend on each other, so a graphics card with thousands of little workers computes them all at the same time. That is the trade: more total work, far less waiting.
Why pay when a relay pays ? Because the scores do not wait for each other, and waiting is what really costs. A graphics card is a room of thousands of small calculators: attention keeps all of them busy at once, while a relay can hand them only one small step at a time, so most of them wait. For texts of a few thousand words, the arithmetic is cheaper than the queue.
The bill, side by side.
| relay (recurrent network) | attention | |
|---|---|---|
| work for words | about steps | scores per head per layer |
| steps that must wait in a row | 1 per layer | |
| memory for the scores | none | per head per layer |
| 1 000 words, 12 heads, 12 layers | 1 000 steps in a row | 144 000 000 scores, all at once |
Rule of thumb. Attention wins while the table fits in memory. That is why "long context" is expensive — and a busy research topic.
A preview of Unit 19: the cache. When a model writes, it adds one word at a time. Because of the mask, the keys and values of the earlier words never change. So a writing model keeps them in a key–value cache and computes only the new word's query, key and value: scores for the new word, not . Unit 19 opens that cache.
The is about work and memory, not weights. A transformer has exactly the same weights for 10 words and for 10 000 words: and the small network do not depend on . A longer text costs time and memory, not a bigger model.
Attention pays for joining every pair of words directly. A relay pays only , but in a queue. Attention's work can all happen at once, which is why transformers train so fast on graphics cards — and why very long inputs are costly.
A model handles 2 000 words. You switch to 8 000 words. By what factor does the number of attention scores grow?
You feed a trained transformer a text twice as long as before. What happens to the number of its weights?
In one sentence: Attention computes scores per head per layer — a million for a thousand words, the handshakes of a big wedding counted from both sides — but all at once and with no extra weights, while a relay needs only steps that must wait for each other.
A tiny transformer, whole
A shopkeeper's notebook has a few pages: a page to look up each word, a page for who looks at whom, a page for thinking, and a last page that turns the thinking into a guess for the next word. Nothing on any page is magic. It is all adding and multiplying, done in the right order.
The question. Put every piece together. What does one complete transformer do, number by number, from a sentence to a guess?
- Look up each word's vector in an embedding table (Unit 16), and add its position vector (§8).
- One block: two heads of masked attention, add and layer norm, a small network, add and layer norm (§9–§10).
- Score every word of the vocabulary with one more matrix, and turn the scores into probabilities with softmax (Unit 14).
- Learn: the loss is the cross-entropy (Unit 14), and backprop (Unit 15) sends the blame back through every matrix.
Our toy has a vocabulary of five words — I, drink, play, chai, cricket — lists of length , and two heads of size 2. Its weights are set by hand so that you can read them, not learned. Feed it "I drink". Because of the mask, it makes a guess at every position at once: after "I" it guesses the next word, and after "I drink" it guesses again.
At the end, after "I drink" it gives chai a probability of about 0.877. After "I" it splits between drink and play, about 0.468 each. If the true sentence is "I drink chai", the loss is the average surprise
Change "drink" to "play" and the same machine now says cricket. Nobody told it "drink goes with chai" in a rule — the numbers carry it.
One more trick: weight tying. Step 11 scores every vocabulary word with a matrix of shape . Step 1 used an embedding table of shape . Many models simply use the same numbers twice: . Then the score of word is — how well the final vector agrees with that word's own look-up vector. It makes sense: a word's "look me up" vector and its "am I the next word?" vector ought to agree. And it saves a whole table: with and , that is weights. (Our tiny toy is not tied: its is set by hand.)
Every page of the notebook is a part you already know, and each one is trained against the truth: the mask makes every position's guess honest (§10), the cross-entropy grades every guess, and the residual lanes carry the blame down to every matrix (§9). Repeat the same simple block many times, train on a lot of text, and the numbers come to carry grammar, facts and style.
At every position the model's output is a whole probability list over the vocabulary, not one word. Picking the word — the top one, or a random draw with a temperature (Unit 17) — is a separate decision that comes after the model. Unit 19 is about that choice.
A transformer is a lookup table at the bottom, a stack of blocks in the middle and a softmax over the vocabulary at the top. With the mask, one sentence gives a next-word guess at every position, and the loss scores all of them at once. Training is the backprop of Unit 15 running through all these matrices.
The true next words were given probabilities 0.5 and 0.25 at the two positions. What is the average cross-entropy loss?
In the tiny transformer with "I play", which word gets the highest probability after "play", and about how much?
A model with a vocabulary of and ties its output matrix to its embedding table. How many weights does that save?
If you want the algebra · 1 proof, step by step
Claim. Let the embedding table () have row for word . If the output matrix is tied, , then the score of word at a position with final vector is , and the model saves weights.
In one sentence: A whole transformer is embeddings plus positions, a stack of talk-and-think blocks, and a softmax over the vocabulary — often read out through the embedding table itself — trained on every next-word guess of a sentence at once by cross-entropy and backprop.
What to carry forward
The whole unit fits on twelve cards. Each has one picture you should be able to draw from memory.
Look back
Keep every note. Before each output word, score the notes, softmax, blend: a fresh context vector for every word written.A soft lookup
Score the query against every key, softmax the scores, blend the values. Never "no match" — and it can learn.Q, K, V
Three views of every word from three shared matrices; softmax(QKᵀ/√d)·V lets every word ask every word, in one hop.Divide by √d
Dot products spread like √d. Dividing by √d keeps softmax soft and the blame flowing — not by d, which blinds it.A chameleon word
A word's output is a blend over its own sentence, so "bank" by a river and "bank" with money end up 53° apart.Many heads
Cut d into h heads of size d/h, each looking through its own glasses; glue and mix with W_O. Same 4d² weights.Positions, three ways
Learned rows, clock-hand tags, or turning q and k (RoPE). With clocks and turns, only the distance between two words matters.The block
Talk (attention), think (a small network); after each, add to the page and steady it. The adds are the blame's express lane.The mask
−∞ above the diagonal: no peeking. One pass trains every next-word guess at once — the class answering together.Three families
BERT reads both ways and fills in hidden words. GPT reads left to right and guesses every next word. Encoder–decoder joins the two with cross-attention.The n² price
n² scores per head per layer, all computed at once, with no extra weights. Long texts cost time and memory.A tiny transformer
Embed + position → blocks → scores → softmax, graded at every position; tie the output to the embedding table to save V·d weights.The one idea under it all. Look back at Unit 13. A kernel classifier decided by a vote: every training point voted, with a weight given by its similarity to the new point. Attention is that vote. The similarity is , the voters hand over their values, and softmax makes the weights add up to 1. The dot product of Unit 3 — agreement between two lists — ends up deciding what a machine pays attention to.
Where this goes next.
- Unit 19 · The Maths Inside an LLM. Stack these blocks a hundred deep, make in the thousands, and train a decoder on a huge pile of text to predict the next word. Then the new questions: how the machine picks its word (temperature, top-k, top-p), why it keeps a cache of old keys and values, and how a small add-on (LoRA) can steer a giant model.
- Unit 20 · From Noise to Pictures. The same attention blocks, turned from reading to drawing.
Every word asks every other word a question, scores the answers by a dot product, and adds a softmax-weighted blend of what they carry to itself. Repeat in many heads, with positions, shortcuts and layer norm, block after block, trained on every next word at once — that is a transformer.
In one sentence: Attention is a similarity-weighted vote — dot products, softmax, a weighted sum of values — and a transformer stacks it with positions, residual paths, layer norm and small networks into a machine that reads a whole text at once, looking back wherever it matters.
Practice arena — sixteen problems, solved in full
Sixteen problems, in the order of the unit: the look-back of §1 and two ways to score it, lookups by hand, a key to reverse-engineer and a frozen row to diagnose, one word with two meanings, heads, clocks and turns, layer norm and a block's weights, the mask, BERT against GPT, weight tying and the bill. The tags say which are easy and which are hard. Every number here was checked by machine.
Three habits do most of the work. Write the shapes first: is words × words, and the answer has one row per word. Work row by row: each row of the attention map is its own little softmax. And check that each row of shares adds up to 1 before you blend the values.
An encoder wrote three notes , , . The decoder's state is . With dot-product scoring (no here), find (a) the three scores, (b) the attention weights, (c) the context vector. (d) Which note does the decoder look at most, and why?
What this tests. The three moves of §1: score, softmax, blend. Plan. Dot products first; then one softmax of three numbers; then a weighted sum of the notes.
Show the full solution
answers at a glance: (a) . (b) . (c) . (d) note 3.
A context vector is a blend of the notes, so each of its entries lies between the smallest and the biggest entries of the notes.
Notes , , ; decoder state . (a) Find the additive scores with and . (b) Their weights. (c) The dot-product scores and their weights. (d) Which note wins under each scoring?
What this tests. Two ways to score the same notes (§1) — and that they can disagree. Plan. Additive: add the state to the note, squash each entry with tanh, add the entries. Dot: multiply and add. Then softmax each set.
Show the full solution
answers at a glance: (a) . (b) . (c) scores , weights . (d) additive: note 3; dot: note 1.
The scoring function is a design choice, and different scores can prefer different notes. Transformers use the dot product (with ) because it is the cheapest.
Queries and keys have length . The query is . Two words have keys , and values , . Find (a) the two scaled scores, (b) the two shares, (c) the answer.
What this tests. The four moves of §3: dot product, divide by , softmax, blend. Plan. ; then one softmax of two numbers.
Show the full solution
answers at a glance: (a) . (b) . (c) .
The keys decide the shares; the values decide what is blended. They can even have different lengths.
Three words have vectors , , , and each word uses its own vector as query, key and value (, ). Find (a) the scaled score table , (b) the attention matrix, (c) the three answers.
What this tests. row by row. Plan. All dot products are 0, 1 or 2; divide by 1.414; softmax each row.
Show the full solution
answers at a glance: (a) . (b) rows , , . (c) , , .
With the score table is symmetric, but the attention matrix need not be: each row is normalised on its own.
Keys , and a query , . Word 2's key is changed to . (a) Write the three scaled scores in terms of . (b) Find so that word 2 gets exactly half of all the attention. (c) What are the three shares then? (d) For which does word 2 get the biggest share of the three?
What this tests. Running softmax backwards. Plan. "Half" means .
Show the full solution
answers at a glance: (a) . (b) . (c) . (d) .
To win a fixed share, a key needs a fixed gap in log space: shares follow .
A student's model with stops learning. One attention row has raw scores , and those are the numbers that go into softmax. (a) What shares does the row get? (b) What is the slope of the top share? (c) What was forgotten, and what are the shares after the fix? (d) What is the top share's slope after the fix?
What this tests. Spotting missing scaling from a spiky, frozen row. Plan. Softmax cares only about gaps; the gap 8 is huge.
Show the full solution
answers at a glance: (a) . (b) . (c) the scaling; . (d) .
A row that is almost exactly one-hot, with the model not learning, is the classic sign of missing scaling (or a temperature that is far too low).
Toy vectors (nature, money): lake , cash , bank . Each word uses its own vector as query, key and value (), and . (a) Find bank's new vector in "lake bank". (b) In "cash bank". (c) The cosine between the two new banks. (d) Check (a) with the slide formula , where .
What this tests. Contextual vectors (§5): one word, two sentences, two vectors — and the general formula for a two-word sentence. Plan. Bank asks with : score both words, divide by , softmax, blend.
Show the full solution
answers at a glance: (a) . (b) . (c) . (d) it matches (a).
A word slides towards its neighbour, further when the neighbour matches its query better. Two neighbours pull the same word two ways.
A model has and heads. Find (a) ; (b) the shape and weight count of one head's ; (c) the weights of together; (d) the same with one bias per output entry of each of the four matrices.
What this tests. and the count. Plan. One head, then all heads, then .
Show the full solution
answers at a glance: (a) 64. (b) , 49 152. (c) 2 359 296. (d) 2 362 368.
More heads means smaller heads. The weight count, , does not depend on .
Sinusoidal tags: , . (a) For , write the tag of position . (b) Compute for and compare it with . (c) For , what is the speed of clock ? (d) How many positions does that clock need for one full turn?
What this tests. Reading the clock formula, and the distance property of §8. Plan. For the speeds are and .
Show the full solution
answers at a glance: (a) . (b) , equal to . (c) 0.01. (d) about 628 positions.
Fast clocks separate neighbours, slow clocks separate far-apart positions — and the dot product of two tags depends only on how far apart they are.
RoPE with , , . The score is . Find it for (a) , (b) , (c) . (d) Give the general formula in terms of .
What this tests. That the score depends only on the gap. Plan. Turn both arrows, then take the dot product; spot the pattern.
Show the full solution
answers at a glance: (a) 1. (b) 1. (c) −1. (d) .
Rotary scores depend only on : "3 words back" scores the same anywhere in the sentence.
Layer-normalise (a) with , (b) with in every entry. (c) What do you get for ? (d) A word has and attention hands back . Find with .
What this tests. Mean, variance (divide by ), then scale and shift. Plan. Centre first.
Show the full solution
answers at a glance: (a) . (b) . (c) . (d) .
Layer norm forgets the average and the size of a word's numbers; and let the network put back what it needs.
A block has and . Count (a) the attention weights, (b) the feed-forward weights, (c) the total with all biases, (d) the total with biases and both layer norms.
What this tests. , biases , layer norms . Plan. Add in stages.
Show the full solution
answers at a glance: (a) 262 144. (b) 524 288. (c) 788 736. (d) 789 760.
With , two thirds of a block's weights are in the feed-forward part.
A 3-word decoder has scaled scores . Apply the causal mask and find (a) the masked score table, (b) the attention matrix.
What this tests. above the diagonal, then a row softmax. Plan. Row 1 has one cell, row 2 two cells, row 3 all three.
Show the full solution
answers at a glance: (a) as above. (b) rows , , .
The first row of a masked map is always . The last row is never changed by the mask.
A text has 1 024 tokens. (a) How many tokens does BERT choose for guessing (15%)? (b) How many of those become [MASK], a random word, or stay unchanged (80/10/10)? (c) How many graded next-word guesses does GPT get from the same text? (d) How many times as many as BERT?
What this tests. The two training games of §11. Plan. Percentages of 1 024, then of the chosen tokens; for GPT, one guess at every position except the last.
Show the full solution
answers at a glance: (a) . (b) , , (about 123, 15, 15). (c) 1 023. (d) about 6.7 times.
BERT learns from about 15% of each text and GPT from almost all of it — but BERT sees both sides of every word it guesses.
A model with saves exactly 38 597 376 weights by tying its output matrix to its embedding table. (a) What is its vocabulary size ? (b) How many weights would the embedding table and the output matrix hold together without tying, and with it? (c) With tying, the score of word is . For , and , which word scores higher?
What this tests. Weight tying (§13), run backwards to find , then used forwards. Plan. The saving is one whole table.
Show the full solution
answers at a glance: (a) . (b) 77 194 752 without, 38 597 376 with. (c) chai, 2.5 against −1.
With tying, "is the next word?" is asked with 's own look-up vector: the final vector must point where the word's embedding points.
A model reads tokens with 16 heads and 24 layers. (a) How many scores are in one head's map? (b) How many scores in the whole forward pass? (c) At 2 bytes per score, how many gigabytes ( bytes) to keep them all? (d) By what factor does (b) grow at ?
What this tests. . Plan. Square, multiply, convert.
Show the full solution
answers at a glance: (a) 4 194 304. (b) 1 610 612 736. (c) GB. (d) 4 times.
The attention bill grows with the square of the length. That is why long inputs are expensive.