The Math Behind the Machine/ Unit 18 · Attention and Transformers Checks 0/31
Unit 18 of 20 · by Prof. Saurabh

Attention and Transformers

In Unit 17 a translator squeezed a whole sentence into one small note, and long sentences got lost. Here we remove that bottleneck. First the translator learns to look back at every word it read before it writes each word. Then every word asks every other word a question, all at once: a dot product from Unit 3 scores the answers, softmax from Unit 14 turns the scores into shares, and each word takes a weighted blend of what the others offer. That is attention. Add positions, shortcuts and a small network, and you have the transformer — the engine inside BERT, GPT and every modern language model.

≈ 150 min read + play 18 interactive widgets · 4 in 3D · an attention lab to type your own sentence 31 inline checks 🧾 18 proofs, folded away — open "if you want the algebra" when you are ready ✍ 16 solved practice problems

← Unit 17 · Machines with Memory

every word asks every word · drag to orbit
1

The bottleneck, and the fix: look back

Imagine this

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: h1\mathbf h_1 after "I", h2\mathbf h_2 after "drink", h3\mathbf h_3 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.

  1. 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 q\mathbf q with the note.
  2. Turn the scores into shares with softmax (Unit 14). The shares are positive and add up to 1. They are called the attention weights.
  3. 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: hI=(1,0,0)\mathbf h_{\text{I}}=(1,0,0), hdrink=(0,1,0)\mathbf h_{\text{drink}}=(0,1,0), htea=(0,0,1)\mathbf h_{\text{tea}}=(0,0,1). (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, q=(0, 0.5, 2)\mathbf q=(0,\ 0.5,\ 2).

scores: q⋅h=(0, 0.5, 2)softmax: (e0, e0.5, e2)1+1.649+7.389≈(0.100, 0.164, 0.736)context: 0.100 hI+0.164 hdrink+0.736 htea=(0.100, 0.164, 0.736)\begin{aligned}\text{scores: }&\mathbf q\cdot\mathbf h=(0,\ 0.5,\ 2)\\ \text{softmax: }&\frac{(e^{0},\ e^{0.5},\ e^{2})}{1+1.649+7.389}\\ &\approx(0.100,\ 0.164,\ 0.736)\\ \text{context: }&0.100\,\mathbf h_{\text{I}}+0.164\,\mathbf h_{\text{drink}}\\ &\quad+0.736\,\mathbf h_{\text{tea}}\\ &=(0.100,\ 0.164,\ 0.736)\end{aligned}

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".

The interpreter looks backTop: the English notes the encoder wrote. Bottom: the Hindi the decoder writes, one word at a time. Gold beams: where the decoder looks before each word — the thicker the beam, the bigger the share. Right: the alignment map fills one row per word, and the context vector is the blend. All numbers are hand-made.

Try: Press ▶ translate and watch the four Hindi words appear. Before each word the beams reach back to the notes, and one more row of the map lights up — see it bend at चाय and पीता. Click चाय and push how sure to 2: the share of "tea" climbs to 0.936. Then switch to no attention (Unit 17): every word gets the same summary, and there is no map at all.

word being written
1
Why does this work?

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.

scoreformulaextra weightsin plain words
dot (Luong, 2015)q⋅h\mathbf q\cdot\mathbf hnone"how much do we agree?" — needs q\mathbf q and h\mathbf h of the same length
general (Luong, 2015)qTWh\mathbf q^{\mathsf T}W\mathbf hone matrix WWfirst re-express the note with WW, then agree
additive (Bahdanau, 2015)vTtanh⁡(W1h+W2q)\mathbf v^{\mathsf T}\tanh(W_1\mathbf h+W_2\mathbf q)W1, W2, vW_1,\ W_2,\ \mathbf va tiny one-layer network judges the match

An additive score by hand. Take W1=W2=IW_1=W_2=I, v=(1,1)\mathbf v=(1,1), a decoder state q=(0.5, −0.5)\mathbf q=(0.5,\ -0.5) and three notes (1,0)(1,0), (0,1)(0,1), (1,1)(1,1). Both matrices are II, so W1h+W2qW_1\mathbf h+W_2\mathbf q is just h+q\mathbf h+\mathbf q: add the state to each note: (1.5, −0.5)(1.5,\ -0.5), (0.5, 0.5)(0.5,\ 0.5), (1.5, 0.5)(1.5,\ 0.5). Squash each entry with tanh: (0.905, −0.462)(0.905,\ -0.462), (0.462, 0.462)(0.462,\ 0.462), (0.905, 0.462)(0.905,\ 0.462). Now v=(1,1)\mathbf v=(1,1) simply adds the two entries: the scores are (0.443, 0.924, 1.367)(0.443,\ 0.924,\ 1.367), and softmax turns them into the weights (0.195, 0.315, 0.490)(0.195,\ 0.315,\ 0.490).

Rule of thumb. The dot product is the cheapest, and it is the one the transformer uses (with the d\sqrt d 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.

Trap

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.

The realization

αtj=softmax⁡j(score⁡(qt,hj))ct=∑jαtj hj\begin{gathered}\alpha_{tj}=\operatorname{softmax}_j\big(\operatorname{score}(\mathbf q_t,\mathbf h_j)\big)\\ \mathbf c_t=\sum_j\alpha_{tj}\,\mathbf h_j\end{gathered}

Before writing word tt, score every note hj\mathbf h_j against the decoder's state qt\mathbf q_t, turn the scores into shares αtj\alpha_{tj}, and blend the notes into the context ct\mathbf c_t. Keep every note and look back, instead of carrying one summary and hoping it holds everything.

Pause & predict

In the worked example you make the decoder's state for चाय twice as long: q=(0, 1, 4)\mathbf q=(0,\ 1,\ 4). What happens to the three attention weights?

Pause & predict

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
Prove it · the blame reaches every note in one hop

Claim. With dot-product scores sj=q⋅hjs_j=\mathbf q\cdot\mathbf h_j, shares αj\alpha_j and context c=∑jαjhj\mathbf c=\sum_j\alpha_j\mathbf h_j, the slope of the context with respect to one note is ∂c/∂hj=αj(I+(hj−c) qT)\partial\mathbf c/\partial\mathbf h_j=\alpha_j\big(I+(\mathbf h_j-\mathbf c)\,\mathbf q^{\mathsf T}\big). The blame reaches note jj directly, scaled by its own share — however long ago the note was written.

1
Note jj moves c\mathbf c in two ways: directly, through its own term αjhj\alpha_j\mathbf h_j, and through the scores — sjs_j changes, so every share changes: ∂c∂hj=αjI+∑ihi ∂αi∂hj.\frac{\partial\mathbf c}{\partial\mathbf h_j}=\alpha_jI+\sum_i\mathbf h_i\,\frac{\partial\alpha_i}{\partial\mathbf h_j}. Only the score sjs_j contains hj\mathbf h_j, and ∂sj/∂hj=qT\partial s_j/\partial\mathbf h_j=\mathbf q^{\mathsf T}.
2
The slope of softmax is ∂αi/∂sj=αi(δij−αj)\partial\alpha_i/\partial s_j=\alpha_i(\delta_{ij}-\alpha_j) (the drawer of §4). So ∑ihi αi(δij−αj) qT=(αjhj−αjc)qT=αj(hj−c) qT.\begin{aligned}&\textstyle\sum_i\mathbf h_i\,\alpha_i(\delta_{ij}-\alpha_j)\,\mathbf q^{\mathsf T}\\ &=\big(\alpha_j\mathbf h_j-\alpha_j\mathbf c\big)\mathbf q^{\mathsf T}\\ &=\alpha_j(\mathbf h_j-\mathbf c)\,\mathbf q^{\mathsf T}.\end{aligned} ∑iαihi\sum_i\alpha_i\mathbf h_i is the context c\mathbf c itself.
3
Add the two parts: αjI+αj(hj−c)qT=αj(I+(hj−c)qT)\alpha_jI+\alpha_j(\mathbf h_j-\mathbf c)\mathbf q^{\mathsf T}=\alpha_j\big(I+(\mathbf h_j-\mathbf c)\mathbf q^{\mathsf T}\big). No long product of step-by-step slopes appears: one hop. ∎ In Unit 17 the blame for an early note passed through one slope matrix for every later step of the relay, and a long product of them fades (Unit 17). Here the note of "tea", with share 0.736, gets its blame at 0.736 strength, wherever it sits.

The road ahead. The unit has four acts.

  1. Look back instead of remembering (§1–§2): the decoder's look-back, and attention as a soft lookup.
  2. Every word asks every word (§3–§7): self-attention by hand, why we divide by d\sqrt d, one word with many meanings, an attention lab where you type your own sentence, and many heads.
  3. Order and depth (§8–§9): three ways to tell the model where each word stands, and the transformer block.
  4. How transformers learn (§10–§14): the mask that trains every next word at once; BERT, GPT and the encoder–decoder; the n2n^2 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.

2

Attention is a soft lookup

Imagine this

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):

chai: e2e2+e0=7.3898.389≈0.881coffee: e0e2+e0=18.389≈0.119\begin{aligned}\text{chai: }&\frac{e^{2}}{e^{2}+e^{0}}=\frac{7.389}{8.389}\approx0.881\\ \text{coffee: }&\frac{e^{0}}{e^{2}+e^{0}}=\frac{1}{8.389}\approx0.119\end{aligned}

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: 0.881×10+0.119×20≈11.190.881\times10+0.119\times20\approx11.19 — ₹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.

The strict shopkeeper and the kind oneFour drinks sit on a "taste map": right = more milky, up = more strong. Each drink's position is its key. Its colour and price are its value. Your wish is the orange query arrow, q.

Try: Drag the orange arrow around the map. In strict mode the cup snaps from one drink to another. In kind mode the cup's colour and price change smoothly. Push how picky to 6: the kind shopkeeper becomes the strict one. Pull it to 0: every drink gets 0.25 and the cup costs the plain average, ₹18.75.

1.5
1
1
Why does this work?

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 bringa key to match exactlya query
it comparesequal or not equala dot product with every key
you get backone valuea blend of all the values
when nothing matchesan error: "not found"still a blend — with equal scores, the plain average
can it learn?no slope: the winner just flipsyes: 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.

Trap

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.

The realization

output=∑iwi vi,wi=e q⋅ki∑je q⋅kj\begin{gathered}\text{output}=\sum_i w_i\,\mathbf v_i,\\ w_i=\frac{e^{\,\mathbf q\cdot\mathbf k_i}}{\sum_j e^{\,\mathbf q\cdot\mathbf k_j}}\end{gathered}

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.

Pause & predict

Three keys give scores 1, 1 and 1 with your query. The values are 3, 6 and 9. What does attention return?

Pause & predict

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
Prove it · the answer is always a blend, never outside the values

Claim. The shares wi=esi/∑jesjw_i=e^{s_i}/\sum_je^{s_j} are all positive and add up to 1. So the answer ∑iwivi\sum_iw_i\mathbf v_i always lies "among" the values (inside their convex hull) — never beyond the biggest or below the smallest in any entry.

1
Each esie^{s_i} is positive, whatever the score sis_i. Dividing positives by their positive total gives positives. And ∑iwi=∑iesi∑jesj=1.\sum_iw_i=\frac{\sum_ie^{s_i}}{\sum_je^{s_j}}=1. This is the softmax of Unit 14: scores in, probabilities out.
2
Look at one entry, say the first. Let mm and MM be the smallest and biggest first entries among the values. Then m=∑iwim≤∑iwivi,1≤∑iwiM=M.\begin{aligned}m&=\sum_iw_im\\ &\le\sum_iw_iv_{i,1}\\ &\le\sum_iw_iM=M.\end{aligned} ∎ In the tea-stall example the cup's price is always between ₹10 and ₹20: ₹11.19.
Prove it · very picky attention becomes a strict lookup

Claim. Multiply every score by a pickiness β\beta. If one key has the strictly biggest score s1s_1, then as β→∞\beta\to\infty its share goes to 1 and every other share goes to 0. At β=0\beta=0 all shares are equal.

1
Divide top and bottom by eβs1e^{\beta s_1}: w1=eβs1∑jeβsj=11+∑j≠1e−β(s1−sj).\begin{aligned}w_1&=\frac{e^{\beta s_1}}{\sum_je^{\beta s_j}}\\ &=\frac{1}{1+\sum_{j\ne1}e^{-\beta(s_1-s_j)}}.\end{aligned} Each gap s1−sjs_1-s_j is positive, because s1s_1 is the biggest.
2
As β→∞\beta\to\infty, each e−β(s1−sj)→0e^{-\beta(s_1-s_j)}\to0, so w1→1w_1\to1 and the others →0\to0. At β=0\beta=0, every e0=1e^{0}=1, so every share is 1/n1/n. ∎ With scores 2 and 0: β=1\beta=1 gives 0.881, β=10\beta=10 gives 1/(1+e−20)≈0.9999999981/(1+e^{-20})\approx0.999999998. The attention lab's temperature is 1/β1/\beta.

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.

3

Self-attention: every word asks every word

Imagine this

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.

  1. 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 0.57≈0.00780.5^7\approx0.0078 — less than 1%. With attention the path from word 1 to word 8 is one step long.
  2. 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): 8×8=648\times8=64 questions. We come back to that price in §12.

Pass the message, or ask directlyOne at a time: the relay of Unit 17 — each word hands the note to the next, and the first word's voice (orange bars) halves at every hand-over. Everyone at once: attention — every word is joined to every word by a direct line.

Try: Press ▶ send the message in the relay and watch the first word's voice shrink on its way: 1, 0.5, 0.25 … 0.0078 at word 8. Switch to everyone at once and press play again: every line lights in the same moment. Then drag the number of words to 10: 9 hand-overs against 100 questions.

8

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 q\mathbf q — "what am I looking for?"
  • a key k\mathbf k — "what do I offer, so that others can find me?"
  • a value v\mathbf v — "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 x\mathbf x (its vector from the table of Unit 16), written as a row. Three learned matrices turn that one row into three:

q=x WQ,k=x WK,v=x WV.\mathbf q=\mathbf x\,W_Q,\quad\mathbf k=\mathbf x\,W_K,\quad\mathbf v=\mathbf x\,W_V.

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 d=2d=2):

k1=(1,0),  k2=(0,1),  k3=(1,1)v1=(2,0),  v2=(0,2),  v3=(1,1)\begin{aligned}&\mathbf k_1=(1,0),\ \ \mathbf k_2=(0,1),\ \ \mathbf k_3=(1,1)\\ &\mathbf v_1=(2,0),\ \ \mathbf v_2=(0,2),\ \ \mathbf v_3=(1,1)\end{aligned}

A word asks with the query q=(2,0)\mathbf q=(2,0). Four small moves:

  1. Score each key with a dot product, then divide by d=2≈1.414\sqrt d=\sqrt2\approx1.414 (§4 says why): q⋅k1=2\mathbf q\cdot\mathbf k_1=2, q⋅k2=0\mathbf q\cdot\mathbf k_2=0, q⋅k3=2\mathbf q\cdot\mathbf k_3=2. Divided: (1.414, 0, 1.414)(1.414,\ 0,\ 1.414).
  2. Turn scores into shares with softmax: e1.414≈4.113e^{1.414}\approx4.113 and e0=1e^{0}=1, total 9.2279.227. Shares ≈(0.446, 0.108, 0.446)\approx(0.446,\ 0.108,\ 0.446).
  3. Blend the values with those shares: 0.446 (2,0)+0.108 (0,2)+0.446 (1,1)0.446\,(2,0)+0.108\,(0,2)+0.446\,(1,1).
  4. Read the answer: ≈(1.337, 0.663)\approx(1.337,\ 0.663).

The query points along the first direction, so it matched keys 1 and 3 equally well and key 2 badly. The answer leans towards v1\mathbf v_1 and v3\mathbf v_3.

One lookup, in spaceThe floor holds the orange query and the three blue keys. Over each key stands a gold pillar: its share (height = 2.2 × share). Above floats a second floor with the three green values. Each value is shrunk by its share and they are laid tip to tail — where the chain ends is the answer.

Try: Press ▶ run the lookup and follow the four moves. Then turn the query with the angle slider to 90°: it now points at k2\mathbf k_2, the tallest pillar moves there and the answer swings to (0.663, 1.337)(0.663,\ 1.337). Set the length to 0: the three pillars become equal (0.333 each) and the answer is the plain average (1, 1)(1,\ 1). Last, pick the three queries of the matrix below one by one.

drag the picture to orbit

0°
2

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 nn words, each a list of dd numbers, is a table XX of shape n×dn\times d. Stack the queries as the rows of Q=XWQQ=XW_Q, the keys as the rows of K=XWKK=XW_K, the values as the rows of V=XWVV=XW_V — each n×dn\times d. Then every lookup happens in one line:

Attention⁡(Q,K,V)=softmax⁡ ⁣(QKTd) V.\operatorname{Attention}(Q,K,V)=\operatorname{softmax}\!\Big(\frac{QK^{\mathsf T}}{\sqrt d}\Big)\,V.

Read it aloud, from the inside out. QKTQK^{\mathsf T}: every question against every label — an n×nn\times n table of agreements. Divide by d\sqrt d: calm the numbers down (§4). Softmax, row by row: each word shares out exactly 100% of its attention. Times VV (n×dn\times d): each word collects its blend of gifts — nn new vectors, one per word. The table of shares is the attention matrix. With the three queries (2,0)(2,0), (0,2)(0,2) and (1,1)(1,1):

A≈(0.4460.1080.4460.1080.4460.4460.2480.2480.503).A\approx\begin{pmatrix}0.446&0.108&0.446\\ 0.108&0.446&0.446\\ 0.248&0.248&0.503\end{pmatrix}.

The answers are (1.337,0.663)(1.337,0.663), (0.663,1.337)(0.663,1.337) and (1,1)(1,1). The third query (1,1)(1,1) likes key 3 most, and its answer is exactly v3\mathbf v_3 — the other two values balance each other.

Why does this work?

The same three matrices WQ,WK,WVW_Q, W_K, W_V 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 nnn−1n-1 hand-overs1 hop
steps that must wait in a rownn1 per layer
what a word seesa fading summary of the words before itevery word, directly
work for nn wordsabout nn stepsn2n^2 scores (§12)

Rule of thumb. When the text fits, attention wins: nothing fades and nothing waits. The n2n^2 bill is what limits how long the text can be.

Trap

QQ, KK and VV 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.

The realization

softmax⁡ ⁣(QKTd)V\operatorname{softmax}\!\Big(\frac{QK^{\mathsf T}}{\sqrt d}\Big)V

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.

Pause & predict

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?

Pause & predict

With the same keys and values, a new query is q=(0,0)\mathbf q=(0,0). What is the answer?

Pause & predict

A sentence has 5 words and d=2d=2. What are the shapes of QKTQK^{\mathsf T} and of the output softmax⁡(QKT/d) V\operatorname{softmax}(QK^{\mathsf T}/\sqrt d)\,V?

If you want the algebra · 2 proofs, step by step
Prove it · the matrix line is every word's lookup at once

Claim. Row ii of softmax⁡(QKT/d) V\operatorname{softmax}(QK^{\mathsf T}/\sqrt d)\,V is exactly the single lookup of §2 for the query qi\mathbf q_i: ∑jAijvj\sum_jA_{ij}\mathbf v_j with Aij=eqi⋅kj/d/∑leqi⋅kl/dA_{ij}=e^{\mathbf q_i\cdot\mathbf k_j/\sqrt d}/\sum_le^{\mathbf q_i\cdot\mathbf k_l/\sqrt d}.

1
The entry (i,j)(i,j) of QKTQK^{\mathsf T} is row ii of QQ times column jj of KTK^{\mathsf T}, which is row jj of KK: (QKT)ij=qi⋅kj.(QK^{\mathsf T})_{ij}=\mathbf q_i\cdot\mathbf k_j. Row times column is a dot product (Unit 1).
2
Softmax is applied to each row on its own, which gives the shares AijA_{ij}. Then row ii of AVAV is ∑jAij (row j of V)=∑jAijvj.\begin{aligned}&\sum_jA_{ij}\,(\text{row }j\text{ of }V)\\ &=\sum_jA_{ij}\mathbf v_j.\end{aligned} ∎ A matrix times VV makes each output row a mix of the rows of VV — the "row picture" of matrix multiplication.
Prove it · attention is Unit 13's kernel vote

Claim. Write κ(q,k)=eq⋅k/d\kappa(\mathbf q,\mathbf k)=e^{\mathbf q\cdot\mathbf k/\sqrt d}. Then attention is a normalised vote: out⁡(q)=∑jκ(q,kj) vj/∑jκ(q,kj)\operatorname{out}(\mathbf q)=\sum_j\kappa(\mathbf q,\mathbf k_j)\,\mathbf v_j\big/\sum_j\kappa(\mathbf q,\mathbf k_j), and κ\kappa is a genuine kernel — a dot product of two feature vectors in a bigger space.

1
The first part is just softmax written out: the shares are κ(q,kj)/∑lκ(q,kl)\kappa(\mathbf q,\mathbf k_j)/\sum_l\kappa(\mathbf q,\mathbf k_l). Each "voter" jj hands over its value, weighted by its similarity to the query. Unit 13's classifier summed αjyj K(xj,x)\alpha_jy_j\,K(\mathbf x_j,\mathbf x): a vote weighted by a kernel similarity (Unit 13).
2
Why is κ\kappa a kernel? Put u=q⋅k/du=\mathbf q\cdot\mathbf k/\sqrt d. The series eu=∑r≥0ur/r!e^{u}=\sum_{r\ge0}u^r/r! is a sum of powers of a dot product with positive weights. Each power (q⋅k)r(\mathbf q\cdot\mathbf k)^r is a polynomial kernel (Unit 13), and a positive sum of kernels is a kernel. ∎ So attention measures similarity in a huge hidden feature space without ever visiting it — the kernel trick, again. The difference from an SVM: the similarity itself is learned, through WQW_Q and WKW_K.

In one sentence: Self-attention drops the relay: every word makes a query, a key and a value with three shared matrices, and softmax⁡(QKT/d) V\operatorname{softmax}(QK^{\mathsf T}/\sqrt d)\,V 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.

4

Why we divide by the square root of d

Imagine this

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 d\sqrt d. What goes wrong without it — and why d\sqrt d, not dd?

A dot product adds up dd little products, one for each entry. More entries means a bigger pile. If the entries of q\mathbf q and k\mathbf k 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 d\sqrt d:

d=2: 2≈1.41d=64: 64=8d=512: 512≈22.6\begin{aligned}d=2&:\ \sqrt2\approx1.41\\ d=64&:\ \sqrt{64}=8\\ d=512&:\ \sqrt{512}\approx22.6\end{aligned}

Why is that bad? Softmax only cares about gaps between scores. Take two scores 8 and 0, a normal gap when d=64d=64. Softmax gives

(e8e8+1, 1e8+1)≈(0.99966, 0.00034).\Big(\frac{e^8}{e^8+1},\ \frac{1}{e^8+1}\Big)\approx(0.99966,\ 0.00034).

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 pp is p(1−p)≈0.00034p(1-p)\approx0.00034, almost zero, so training gets almost no blame through it (the fading blame of Unit 15).

Now divide by 64=8\sqrt{64}=8 first. The scores become 1 and 0, and softmax gives (0.731, 0.269)(0.731,\ 0.269). The slope is 0.731×0.269≈0.1970.731\times0.269\approx0.197 — nearly 600 times bigger. Dividing by d\sqrt d brings the spread back to about 1, whatever dd is.

The spread grows with d — and √d calms itLeft: 2 000 dot products of random query and key vectors of length d. Right: one row of eight scores and its softmax shares. Bottom: how much blame can pass through that row.

Try: Keep divide by √d off and drag dd from 1 to 512: the cloud of scores spreads wider (to about 22.6) and the shares on the right turn into one tall bar. Then switch divide by √d on: the cloud keeps a spread of about 1 for every dd, and the shares stay soft.

64
Why does this work?

For random entries of size 1, the dd little products are independent, so their variances add up: the variance of the pile is dd, and its spread is d\sqrt d (the drawer below proves it). Dividing by d\sqrt d divides the spread by d\sqrt d, 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 d=64d=64.

divide byscores becomesharesslope p(1−p)p(1-p)the row is
nothing8 and 0(0.99966, 0.00034)0.00034spiky and frozen
d=8\sqrt d=81 and 0(0.731, 0.269)0.197soft, decided and alive
d=64d=640.125 and 0(0.531, 0.469)0.249nearly flat: it barely prefers anything

Rule of thumb. Divide by d\sqrt d — the size of the spread. Too little and the rows freeze; too much and they go blind.

Trap

Divide by d\sqrt d, not by dd. Dividing by dd shrinks every score towards 0 when dd is big, and each row becomes almost flat — every word listens to every other word nearly equally, so attention cannot point at anything.

The realization

spread⁡(q⋅k)=d⟹ use q⋅kd\begin{gathered}\operatorname{spread}(\mathbf q\cdot\mathbf k)=\sqrt d\\ \Longrightarrow\ \text{use }\frac{\mathbf q\cdot\mathbf k}{\sqrt d}\end{gathered}

Long vectors make big dot products, and big scores make softmax pick one winner and freeze. Dividing every score by d\sqrt d keeps the scores at a spread of about 1, so the shares stay soft and blame keeps flowing.

Pause & predict

A friend builds a model with d=512d=512 and forgets to divide by d\sqrt d. What happens when it trains?

Pause & predict

Two scores are 12 and 0 with d=144d=144. After dividing by d\sqrt d, what share does the first word get?

If you want the algebra · 2 proofs, step by step
Prove it · the spread of a dot product is √d

Claim. If the 2d2d entries of q\mathbf q and k\mathbf k are independent, with mean 0 and variance 1, then q⋅k\mathbf q\cdot\mathbf k has mean 0 and variance dd, so its spread is d\sqrt d — and q⋅k/d\mathbf q\cdot\mathbf k/\sqrt d has variance 1.

1
One product qikiq_ik_i: its mean is E[qi] E[ki]=0\mathbb E[q_i]\,\mathbb E[k_i]=0, and its variance is E[qi2ki2]=E[qi2] E[ki2]=1⋅1=1.\begin{aligned}\mathbb E[q_i^2k_i^2]&=\mathbb E[q_i^2]\,\mathbb E[k_i^2]\\ &=1\cdot1=1.\end{aligned} For independent numbers the mean of a product is the product of the means (Unit 14).
2
The dd products are independent, so their variances add: Var⁡(q⋅k)=d⋅1=d\operatorname{Var}(\mathbf q\cdot\mathbf k)=d\cdot1=d. The spread is d\sqrt d. Dividing by d\sqrt d divides the variance by dd, leaving 1. ∎ d=64d=64: spread 8. d=512d=512: spread ≈22.6\approx22.6. After dividing, spread 1 for every dd.
Prove it · a spiky softmax lets almost no blame through

Claim. The slopes of softmax are ∂pi/∂sj=pi(δij−pj)\partial p_i/\partial s_j=p_i(\delta_{ij}-p_j). When one share is nearly 1 (a spiky row), every slope is nearly 0.

1
Write pi=esi/Zp_i=e^{s_i}/Z with Z=∑leslZ=\sum_le^{s_l}. Then ∂Z/∂sj=esj\partial Z/\partial s_j=e^{s_j}, and by the quotient rule ∂pi∂sj=δijesiZ−esiesjZ2=pi(δij−pj).\begin{aligned}\frac{\partial p_i}{\partial s_j}&=\frac{\delta_{ij}e^{s_i}}{Z}-\frac{e^{s_i}e^{s_j}}{Z^2}\\ &=p_i(\delta_{ij}-p_j).\end{aligned} δij\delta_{ij} is 1 when i=ji=j and 0 otherwise.
2
If p1≈1p_1\approx1 then every other pi≈0p_i\approx0. The slopes with i≠1i\ne1 carry a factor pi≈0p_i\approx0; the slopes of p1p_1 are p1(1−p1)≈0p_1(1-p_1)\approx0 and −p1pj≈0-p_1p_j\approx0. ∎ Scores 8 and 0: p1(1−p1)≈0.00034p_1(1-p_1)\approx0.00034. Scores 1 and 0: ≈0.197\approx0.197.

In one sentence: A dot product of two random length-dd vectors has spread d\sqrt d, which makes softmax spiky and frozen, so attention divides every score by d\sqrt d — like a judge who marks out of 1000 being brought back to marks out of 10 before the prize money is shared.

5

The payoff: one word, many meanings

Imagine this

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 =(2,0)=(2,0), money =(0,2)=(0,2), and bank =(1,1)=(1,1) — 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 (Q=K=V=XQ=K=V=X); a real model would first multiply by WQW_Q, WKW_K and WVW_V.

Sentence one: "river bank". Bank asks with its query (1,1)(1,1):

scores: (1,1)⋅(2,0)=2,(1,1)⋅(1,1)=2÷2: (1.414, 1.414) ⇒ shares (0.5, 0.5)banknew=0.5 (2,0)+0.5 (1,1)=(1.5, 0.5)\begin{aligned}\text{scores: }&(1,1)\cdot(2,0)=2,\quad(1,1)\cdot(1,1)=2\\ \div\sqrt2:\ &(1.414,\ 1.414)\ \Rightarrow\ \text{shares }(0.5,\ 0.5)\\ \text{bank}_{\text{new}}&=0.5\,(2,0)+0.5\,(1,1)=(1.5,\ 0.5)\end{aligned}

Sentence two: "money bank". The same steps give 0.5 (0,2)+0.5 (1,1)=(0.5, 1.5)0.5\,(0,2)+0.5\,(1,1)=(0.5,\ 1.5).

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

cos⁡=(1.5)(0.5)+(0.5)(1.5)2.5 2.5=1.52.5=0.6,\cos=\frac{(1.5)(0.5)+(0.5)(1.5)}{\sqrt{2.5}\,\sqrt{2.5}}=\frac{1.5}{2.5}=0.6,

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 chameleon wordThe plane has two directions: nature (right) and money (up). Grey: "bank" as Unit 16 stored it, the same in every sentence. Each sentence pulls bank along the dotted line towards its neighbour; the thick arrows are bank's new vectors. Gold: the angle between them. Toy vectors, made by hand.

Try: Start with "river bank" and "money bank": the two banks split to (1.5, 0.5) and (0.5, 1.5), cosine 0.6. Change the first neighbour to stream, a stronger nature word: bank slides further, to (2.34, 0.33). Choose money for both sentences: the two banks become one vector again (cosine 1). Then try the: a word that says nothing hardly moves bank's direction.

sentence A: ___ bank
sentence B: ___ bank
Why does this work?

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 wordone, for every sentencea fresh one in every sentence
how you get itlook up a row of a tablerun 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
costone lookupa 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.

Trap

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 realization

xbank ⟶ ∑jAbank,j vj\mathbf x_{\text{bank}}\ \longrightarrow\ \sum_j A_{\text{bank},j}\,\mathbf v_j

The sum runs over the words jj 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.

Pause & predict

In "river bank" you replace river by stream =(3,0)=(3,0), a stronger nature word. What happens to bank's new vector?

Pause & predict

After attention, bank is (1.5,0.5)(1.5,0.5) in "river bank" and (0.5,1.5)(0.5,1.5) in "money bank". What is the cosine between the two?

If you want the algebra · 1 proof, step by step
Prove it · a word slides towards its neighbour

Claim. In a two-word sentence with Q=K=V=XQ=K=V=X, word b\mathbf b after attention is b+σ(g) (a−b)\mathbf b+\sigma(g)\,(\mathbf a-\mathbf b), where a\mathbf a is its neighbour, g=(a⋅b−b⋅b)/dg=(\mathbf a\cdot\mathbf b-\mathbf b\cdot\mathbf b)/\sqrt d and σ(g)=1/(1+e−g)\sigma(g)=1/(1+e^{-g}). So it slides along the straight road from b\mathbf b to a\mathbf a, past halfway exactly when a⋅b>b⋅b\mathbf a\cdot\mathbf b>\mathbf b\cdot\mathbf b.

1
Word b\mathbf b asks with b\mathbf b. Its two scores are sa=a⋅b/ds_a=\mathbf a\cdot\mathbf b/\sqrt d and sb=b⋅b/ds_b=\mathbf b\cdot\mathbf b/\sqrt d. The share of the neighbour is esaesa+esb=11+e−(sa−sb)=σ(g).\begin{aligned}&\frac{e^{s_a}}{e^{s_a}+e^{s_b}}\\ &=\frac{1}{1+e^{-(s_a-s_b)}}=\sigma(g).\end{aligned} Divide the top and the bottom by esae^{s_a}. A softmax of two numbers only sees their gap.
2
The new vector is σ(g) a+(1−σ(g)) b=b+σ(g)(a−b)\sigma(g)\,\mathbf a+\big(1-\sigma(g)\big)\,\mathbf b=\mathbf b+\sigma(g)(\mathbf a-\mathbf b): the point a fraction σ(g)\sigma(g) of the way from b\mathbf b to a\mathbf a. And σ(g)>12\sigma(g)>\tfrac12 exactly when g>0g>0. ∎ River: a⋅b=2=b⋅b\mathbf a\cdot\mathbf b=2=\mathbf b\cdot\mathbf b, so g=0g=0, halfway: (1.5, 0.5)(1.5,\ 0.5). Stream (3,0)(3,0): g=(3−2)/2≈0.707g=(3-2)/\sqrt2\approx0.707, σ≈0.670\sigma\approx0.670, and bank lands at (2.340, 0.330)(2.340,\ 0.330).

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.

6

The attention lab: who looks at whom

Imagine this

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 9×99\times9 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 WQ,WK,WVW_Q, W_K, W_V are hand-set too, so you can see why each share comes out as it does. But the arithmetic — dot products, d\sqrt d, 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.

The attention labType a sentence. The words stand in a row as glowing beads. Click a word to see its query go out as gold beams to every word, brighter where the share is bigger. Switch to the landscape to see the whole map as rows of gold pillars. Hand-made toy weights.

Try: Click "it" and find the brightest beam: "ball", 0.766. Load my mother made chai and click "she" (mother, 0.789), then "it". Switch to head 2: every word looks one word back. Turn on no peeking and the top-right half of the map goes dark. Drag the temperature down to 0.3: ball's share climbs to 0.9999. Last, type your own sentence.

drag the picture to orbit

1

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.

Why does this work?

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.

Trap

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 realization

xi ⟶ xi+∑jAij vj\mathbf x_i\ \longrightarrow\ \mathbf x_i+\sum_j A_{ij}\,\mathbf v_j

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".

Try it, then answer

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?

Try it, then answer

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.

7

Many heads: many questions at once

Imagine this

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 WQ,WK,WVW_Q, W_K, W_V, 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 dd. Cut it into hh equal pieces. Each head's matrices make queries, keys and values of length

dk=dh.d_k=\frac{d}{h}.

Tiny numbers. A common size is d=512d=512 with h=8h=8 heads, so each head works with lists of length 512/8=64512/8=64. The eight answers, each of length 64, are glued side by side back into one list of length 8×64=5128\times64=512. A last matrix WOW_O (size 512×512512\times512) mixes them.

The cost is the same as one big head. One big head needs three 512×512512\times512 matrices. Eight small heads need 8×38\times3 matrices of size 512×64512\times64, which is exactly the same number of weights. Add WOW_O and either way attention has 4d2=4×5122=1 048 5764d^2=4\times512^2=1\,048\,576 weights.

Two heads, one sentenceThe lab's two heads on the same sentence. Arcs above the words: head 1 (meaning). Arcs below: head 2 (the word before). An arc's thickness and brightness is its share. Under the sentence, the shapes: how dd is cut into heads and glued back.

Try: Click different words. For "it", head 1 reaches far back to "ball" (0.77) while head 2 reaches one step back to "because" (0.78). Then drag dd to 768 and the heads to 12: each head gets 64 numbers, and the weight count, 2 359 296, never changes when you change the number of heads.

512
8

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 (d=3d=3, h=3h=3, so dk=1d_k=1). 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.

Each head wears its own glassesLeft: what each word is made of — three hand-made features. A head sees only its own column (the glasses); the rest is dimmed. Right: how much the asking word listens to each word, one column per head. Same words, three heads, three different answers.

Try: With "coffee" asking, click the three heads and compare the three columns of gold bars: drink finds chai and lassi (0.330 each), hot finds sun, coffee and chai, sport gives every word 0.125. Then let "lassi" ask: the drink head still finds the drinks, but the hot head now points the other way — lassi is cold, so it favours the ice.

asking word
Why does this work?

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 dd into pieces keeps the price the same.

One big head against many small ones (d=512d=512).

1 head of 5128 heads of 6464 heads of 8
attention maps per word1864
weights in WQ,WK,WV,WOW_Q,W_K,W_V,W_O1 048 5761 048 5761 048 576
what can go wrongone blend must serve every question— the usual choiceeach head's space is tiny, its scores are crude

Rule of thumb. Keep each head's size dkd_k around 64: BERT-base uses 768/12=64768/12=64, and so does the small GPT-2.

Trap

More heads do not mean more weights. Eight heads of 64 cost exactly what one head of 512 costs: 4d24d^2 either way. What changes is how many different questions can be asked at once, and how small each question's space is.

The realization

head⁡i=Attention⁡(Qi,Ki,Vi)Qi=XWQ(i), Ki=XWK(i),Vi=XWV(i)MultiHead⁡=[head⁡1,…,head⁡h] WO\begin{gathered}\operatorname{head}_i=\operatorname{Attention}(Q_i,K_i,V_i)\\ Q_i=XW_Q^{(i)},\ K_i=XW_K^{(i)},\\ V_i=XW_V^{(i)}\\ \operatorname{MultiHead}\\ =\big[\operatorname{head}_1,\dots,\operatorname{head}_h\big]\,W_O\end{gathered}

Many heads are many small attentions, each looking at the words through its own projection. Cut dd into hh pieces of size d/hd/h, let each head build its own map, glue the answers back and mix them with WOW_O. You get hh different questions for the price of one.

Pause & predict

A model has d=768d=768 and h=12h=12 heads. How long is each head's query, and how many weights do WQ,WK,WV,WOW_Q, W_K, W_V, W_O have together (no biases)?

Try it, then answer

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
Prove it · h heads cost the same as one

Claim. With hh heads of size dk=d/hd_k=d/h, the matrices WQ(i),WK(i),WV(i)W_Q^{(i)},W_K^{(i)},W_V^{(i)} (each d×dkd\times d_k) and WOW_O (d×dd\times d) hold 4d24d^2 weights — the same for every hh.

1
One head has three matrices of d×dkd\times d_k weights. All hh heads together: 3⋅h⋅d⋅dh=3d2.3\cdot h\cdot d\cdot\frac dh=3d^2. The hh cancels: more heads, each smaller.
2
The glued answer has length h⋅dk=dh\cdot d_k=d, so WOW_O is d×dd\times d: d2d^2 more. Total 4d24d^2. ∎ In fact the hh matrices WQ(i)W_Q^{(i)} placed side by side are just one d×dd\times d matrix, cut into hh column blocks.

In one sentence: Multi-head attention cuts dd into hh heads of size d/hd/h, each looking at the words through its own glasses, then glues the answers and mixes them with WOW_O — a commentary box of experts, hh questions for the same 4d24d^2 weights.

8

Where is each word? Three ways to add position

Imagine this

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 =(2,0)=(2,0), man =(0,2)=(0,2), bites =(1,1)=(1,1), and let each word's query, key and value be its own vector. In "dog bites man" the word dog ends up as (1.723, 0.277)(1.723,\ 0.277). In "man bites dog" it ends up as … (1.723, 0.277)(1.723,\ 0.277). The same. Attention cannot tell who bit whom.

The fix: put the position into the vectors. Give the first word the tag (1,0)(1,0), the middle word (0,0)(0,0) and the last word (0,1)(0,1), and add the tag to each word's vector before attention. Now dog becomes (2.967, 0.019)(2.967,\ 0.019) when it comes first and (1.576, 1.284)(1.576,\ 1.284) when it comes last. Order finally matters.

Shuffle the wordsThree words, their attention answers drawn as arrows. Shuffle the order and see whether any answer changes.

Try: Press shuffle a few times with position tags off: the words move, but each keeps exactly its arrow — dog is always (1.723, 0.277). Turn position tags on and shuffle again: now each word's arrow changes with its place.

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 pp, a clock of speed ω\omega gives the two numbers sin⁡(ωp)\sin(\omega p) and cos⁡(ωp)\cos(\omega p) — where its hand points. The speeds are ωi=1/100002i/d\omega_i=1/10000^{2i/d}. With d=4d=4 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:

PE(1)=(0.8415, 0.5403,  0.0100, 1.0000)PE(2)=(0.9093,−0.4161,  0.0200, 0.9998)PE(3)=(0.1411,−0.9900,  0.0300, 0.9996){\small\begin{aligned}\text{PE}(1)&=(0.8415,\ 0.5403,\ \ 0.0100,\ 1.0000)\\ \text{PE}(2)&=(0.9093,-0.4161,\ \ 0.0200,\ 0.9998)\\ \text{PE}(3)&=(0.1411,-0.9900,\ \ 0.0300,\ 0.9996)\end{aligned}}

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:

PE(1)⋅PE(2)≈1.5403PE(2)⋅PE(3)≈1.5403\begin{aligned}\text{PE}(1)\cdot\text{PE}(2)&\approx1.5403\\ \text{PE}(2)\cdot\text{PE}(3)&\approx1.5403\end{aligned}

The same number. For each clock, sin⁡asin⁡b+cos⁡acos⁡b=cos⁡(a−b)\sin a\sin b+\cos a\cos b=\cos(a-b), and two positions kk apart always have their hands ωk\omega k apart. So PE(p)⋅PE(p+k)=cos⁡k+cos⁡(0.01k)\text{PE}(p)\cdot\text{PE}(p+k)=\cos k+\cos(0.01k): it depends only on the distance kk, 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 mm turns its query arrow by mθm\theta; a word at position nn turns its key arrow by nθn\theta. 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 m−nm-n.

Tiny numbers. Take θ=30∘\theta=30^\circ and q=k=(1,0)\mathbf q=\mathbf k=(1,0). Put the query at position 3 and the key at position 1: the arrows point at 90∘90^\circ and 30∘30^\circ, the angle between them is 60∘60^\circ, and the score is cos⁡60∘=0.5\cos60^\circ=0.5. Move them to positions 5 and 3: arrows at 150∘150^\circ and 90∘90^\circ, still 60∘60^\circ apart, score 0.5. Positions 2 and 0: again 0.5.

Position as a row of clocksClocks: each clock turns at its own speed; the strip below shows the tags of positions 0 to 63 (gold = +, blue = −). Compare: the score between positions pp and p+kp+k, as pp slides along, for the three ways of adding position.

Try: With d=4d=4, drag the position to 1, 2 and 3 and read the tags above. Then open compare the three: the clock tags give 1.5403 for every neighbouring pair and the turned arrows give cos 30° = 0.866 — flat lines — while a learned table (toy random rows) jumps about, and simply stops at position 15, the end of its "training". Drag the gap kk: the two flat lines move, but stay flat.

1
1
Rotary positions: turn the arrowsA glass clock face. The orange query arrow is turned by mθm\theta, the blue key arrow by nθn\theta. The gold arc is the angle between them — the only thing the score sees.

Try: Press ▶ move both forward: both arrows turn together and the score stays 0.5. Then drag only mm to 7 with n=1n=1: the gap is 6, the angle 180°, and the score −1. Turn on three clocks to see a stack of dials turning at different speeds, as in a real model.

drag the picture to orbit

3
1
30°
Why does this work?

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 rowsclock tags (sinusoidal)turns (rotary, RoPE)
howadd a trained row for each positionadd fixed clock-hand tagsturn q\mathbf q and k\mathbf k by position × θ\theta
weights to learnone row per positionnonenone
longer text than in training?no row for ita tag exists for every positiona turn exists for every position
does distance alone decide?not built inthe tags' dot product: yesthe score itself: yes
used inBERT, GPT-2the 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.

Trap

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.

The realization

(Rmθq)⋅(Rnθk)=q⋅R(n−m)θ k\big(R_{m\theta}\mathbf q\big)\cdot\big(R_{n\theta}\mathbf k\big)=\mathbf q\cdot R_{(n-m)\theta}\,\mathbf k

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.

Pause & predict

With RoPE, θ=30∘\theta=30^\circ and q=k=(1,0)\mathbf q=\mathbf k=(1,0): what is the score for query position 7 and key position 1?

Pause & predict

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?

Pause & predict

With the d=4d=4 clock tags, PE(1)⋅PE(2)≈1.5403\text{PE}(1)\cdot\text{PE}(2)\approx1.5403. What is PE(10)⋅PE(11)\text{PE}(10)\cdot\text{PE}(11)?

If you want the algebra · 4 proofs, step by step
Prove it · without positions, attention cannot see order

Claim. Shuffle the rows of XX with a permutation matrix PP. Then the attention answers are shuffled the same way and nothing else changes: Att⁡(PX)=P Att⁡(X)\operatorname{Att}(PX)=P\,\operatorname{Att}(X).

1
Q,K,VQ,K,V are made row by row, so they shuffle too: PQ,PK,PVPQ,PK,PV. The score table becomes (PQ)(PK)T=P (QKT) PT:\begin{aligned}&(PQ)(PK)^{\mathsf T}\\ &=P\,(QK^{\mathsf T})\,P^{\mathsf T}:\end{aligned} the same table with its rows and columns shuffled alike. A row-wise softmax does not care where a row sits, and shuffling the columns of a row just shuffles its shares.
2
So the shares are PAPTPAP^{\mathsf T}, and the answers are PAPT PV=PA (PTP) V=P AVPAP^{\mathsf T}\,PV=PA\,(P^{\mathsf T}P)\,V=P\,AV, because PTP=IP^{\mathsf T}P=I. ∎ A permutation matrix is orthonormal (Unit 3): PTP=IP^{\mathsf T}P=I.
Prove it · with rotary positions the score depends only on the gap

Claim. Let RϕR_\phi turn a 2-D arrow by the angle ϕ\phi. Then (Rmθq)⋅(Rnθk)=q⋅R(n−m)θ k(R_{m\theta}\mathbf q)\cdot(R_{n\theta}\mathbf k)=\mathbf q\cdot R_{(n-m)\theta}\,\mathbf k, which depends on mm and nn only through n−mn-m.

1
Write the dot product as a matrix product: (Rmθq)T(Rnθk)=qTRmθTRnθk(R_{m\theta}\mathbf q)^{\mathsf T}(R_{n\theta}\mathbf k)=\mathbf q^{\mathsf T}R_{m\theta}^{\mathsf T}R_{n\theta}\mathbf k. (AB)T=BTAT(AB)^{\mathsf T}=B^{\mathsf T}A^{\mathsf T}.
2
Turning back by mθm\theta undoes a turn by mθm\theta: RmθT=R−mθR_{m\theta}^{\mathsf T}=R_{-m\theta}. And two turns add up: R−mθRnθ=R(n−m)θR_{-m\theta}R_{n\theta}=R_{(n-m)\theta}. ∎ With q=k=(1,0)\mathbf q=\mathbf k=(1,0) the score is cos⁡((n−m)θ)\cos((n-m)\theta): for θ=30∘\theta=30^\circ and a gap of 2 it is cos⁡60∘=0.5\cos60^\circ=0.5 (Unit 4's turns).
Prove it · moving the clock tags along is a fixed turn

Claim. For one clock of speed ω\omega, the tag of position p+kp+k is a fixed rotation of the tag of position pp: (sin⁡ω(p+k),cos⁡ω(p+k))\big(\sin\omega(p+k),\cos\omega(p+k)\big) is obtained from (sin⁡ωp,cos⁡ωp)(\sin\omega p,\cos\omega p) by a matrix that depends only on kk.

1
By the angle-sum rules, sin⁡ω(p+k)=cos⁡ωk sin⁡ωp+sin⁡ωk cos⁡ωp,cos⁡ω(p+k)=−sin⁡ωk sin⁡ωp+cos⁡ωk cos⁡ωp.\begin{aligned}&\sin\omega(p+k)\\ &=\cos\omega k\,\sin\omega p\\ &\quad+\sin\omega k\,\cos\omega p,\\ &\cos\omega(p+k)\\ &=-\sin\omega k\,\sin\omega p\\ &\quad+\cos\omega k\,\cos\omega p.\end{aligned} These are the formulas for sin⁡(a+b)\sin(a+b) and cos⁡(a+b)\cos(a+b).
2
So the new pair is (cos⁡ωksin⁡ωk−sin⁡ωkcos⁡ωk)\begin{pmatrix}\cos\omega k&\sin\omega k\\ -\sin\omega k&\cos\omega k\end{pmatrix} times the old pair — a matrix with no pp in it. ∎ That is why one fixed WQW_Q can make a word ask "who is kk places before me?" — the attention lab's head 2 does exactly this, with k=1k=1.
Prove it · the clock tags' dot product depends only on the distance

Claim. For sinusoidal tags with clock speeds ωi\omega_i, PE(p)⋅PE(p+k)=∑icos⁡(ωik)\text{PE}(p)\cdot\text{PE}(p+k)=\sum_i\cos(\omega_ik) — there is no pp in it.

1
One clock contributes two products, one from its sine and one from its cosine. Write a=ωpa=\omega p and b=ω(p+k)b=\omega(p+k) for the two angles: sin⁡a sin⁡b+cos⁡a cos⁡b.\sin a\,\sin b+\cos a\,\cos b. A dot product pairs up matching entries (Unit 3).
2
By the identity cos⁡(b−a)=cos⁡bcos⁡a+sin⁡bsin⁡a\cos(b-a)=\cos b\cos a+\sin b\sin a, that is cos⁡(b−a)=cos⁡(ωk)\cos(b-a)=\cos(\omega k) — the angle between the two hands. Add over the clocks: ∑icos⁡(ωik)\sum_i\cos(\omega_ik). ∎ For d=4d=4 (speeds 1 and 0.01) and k=1k=1: cos⁡1+cos⁡0.01≈0.5403+0.99995≈1.5403\cos1+\cos0.01\approx0.5403+0.99995\approx1.5403, for every neighbouring pair.

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.

9

The transformer block

Imagine this

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:

  1. Attention — the words talk to each other (§3–§8). Each word collects a blend from the other words.
  2. Add, then steady. Add what attention wrote to the word's own vector: x+Attention⁡(x)\mathbf x+\operatorname{Attention}(\mathbf x). This shortcut is the residual path — a note added, nothing erased. Then layer norm rescales the result to a steady size.
  3. 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 dd.
  4. 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 x+f(x)\mathbf x+f(\mathbf x) is 1+f′1+f', not just f′f'. Even if f′f' 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 x=(1,2,3,6)\mathbf x=(1,2,3,6):

mean=1+2+3+64=3variance=(−2)2+(−1)2+02+324=144=3.5result=x−33.5≈(−1.069, −0.535, 0, 1.604)\begin{aligned}\text{mean}&=\tfrac{1+2+3+6}{4}=3\\ \text{variance}&=\tfrac{(-2)^2+(-1)^2+0^2+3^2}{4}=\tfrac{14}{4}=3.5\\ \text{result}&=\tfrac{\mathbf x-3}{\sqrt{3.5}}\\ &\approx(-1.069,\ -0.535,\ 0,\ 1.604)\end{aligned}

Then two learned lists, a scale γ\boldsymbol\gamma and a shift β\boldsymbol\beta, stretch and move each entry, so the network can undo the steadying where it wants to.

Layer norm: centre, then shrink to spread 1Four numbers of one word as bars. The dashed line is their mean. Layer norm slides the bars so the mean is 0, then scales them so the spread is 1, then applies the scale γ and shift β.

Try: Drag the four numbers. Make them all bigger by the same amount — the result does not change. Double them all — the result does not change either. Set them to 2, 4, 4, 6: the result is (−1.414, 0, 0, 1.414). Then move γ to 2 and β to 1: (−1.828, 1, 1, 3.828).

1
2
3
6
1
0

One word through one block. Take a word with x=(1,0,1,2)\mathbf x=(1,0,1,2) (toy numbers, d=4d=4). Say attention hands back (0,2,2,4)(0,2,2,4). The shortcut adds them: (1,2,3,6)(1,2,3,6). Layer norm gives (−1.069,−0.535,0,1.604)(-1.069,-0.535,0,1.604) — the numbers above. The small network adds its own small change, (0, 0.535, 0.267, 0.802)(0,\ 0.535,\ 0.267,\ 0.802), and a second add-and-steady finishes the block: (−1.166, −0.318, −0.106, 1.590)(-1.166,\ -0.318,\ -0.106,\ 1.590). Follow the page up the tower in 3-D.

A page's ride through one blockThe word's four numbers ride upward as four glowing bars. Glass floors are the stations: talk (attention), add, steady, think (the small network), add, steady. The gold side lane is the residual path: a copy of the page that jumps past each station and is added back on top.

Try: Press ▶ send the word up. Watch the copy take the gold lane and meet the station's output at each "add". Then use next station to go one floor at a time and read the numbers: two stations up the page is (1, 2, 3, 6). Last, pick a model size to count the block's weights: d = 512 gives 3 145 728 weights.

drag the picture to orbit

Counting the weights of one block. Take d=512d=512 and a feed-forward middle of dff=2048d_{ff}=2048 (four times wider, the usual choice).

attention: 4d2=1 048 576feed-forward: 2 d dff=2 097 152weights only=3 145 728\begin{aligned}\text{attention: }4d^2&=1\,048\,576\\ \text{feed-forward: }2\,d\,d_{ff}&=2\,097\,152\\ \text{weights only}&=3\,145\,728\end{aligned}

Biases add 4d=20484d=2048 for attention and dff+d=2560d_{ff}+d=2560 for the feed-forward part, giving 3 150 336. The two layer norms add 2×2d=20482\times2d=2048 more (γ\boldsymbol\gamma and β\boldsymbol\beta 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: LN⁡(x+f(x))\operatorname{LN}(\mathbf x+f(\mathbf x)) — "post-norm". Most models since GPT-2 steady a copy before each station and add the result to the untouched page: x+f(LN⁡(x))\mathbf x+f(\operatorname{LN}(\mathbf x)) — "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 stationLN⁡(x+f(x))\operatorname{LN}(\mathbf x+f(\mathbf x))x+f(LN⁡(x))\mathbf x+f(\operatorname{LN}(\mathbf x))
the residual lanepasses through a layer norm at every stationclean from bottom to top
training a deep stackneeds a slow, careful startsteadier

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.

Why does this work?

Three jobs, three parts. The adds keep every earlier note and give the blame a clean road down (the 1 in 1+f′1+f'). 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.

Trap

Layer norm steadies the numbers of one word — across its dd 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.

The realization

h=LN⁡(x+Attention⁡(x))y=LN⁡(h+FFN⁡(h))\begin{gathered}\mathbf h=\operatorname{LN}\big(\mathbf x+\operatorname{Attention}(\mathbf x)\big)\\ \mathbf y=\operatorname{LN}\big(\mathbf h+\operatorname{FFN}(\mathbf h)\big)\end{gathered}

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.

Pause & predict

What is the layer norm (with γ=1,β=0\gamma=1,\beta=0) of (2,4,4,6)(2,4,4,6)?

Pause & predict

Inside a block the station ff has slope f′=0.01f'=0.01 for some entry. What slope does the blame see across x+f(x)\mathbf x+f(\mathbf x) for that entry — and what happens over 50 such blocks?

If you want the algebra · 3 proofs, step by step
Prove it · layer norm gives mean 0 and spread 1

Claim. For x∈Rd\mathbf x\in\mathbb R^d with mean μ\mu and variance σ2>0\sigma^2>0, the list x^=(x−μ)/σ\hat{\mathbf x}=(\mathbf x-\mu)/\sigma has mean 0 and variance 1, and it does not change if x\mathbf x is shifted by a constant or scaled by a positive number.

1
Mean: 1d∑i(xi−μ)/σ=(μ−μ)/σ=0\frac1d\sum_i(x_i-\mu)/\sigma=(\mu-\mu)/\sigma=0. Variance: 1d∑i(xi−μ)2/σ2=σ2/σ2=1\frac1d\sum_i(x_i-\mu)^2/\sigma^2=\sigma^2/\sigma^2=1. The same standardising as Unit 10, but across the entries of one word, not across examples.
2
Replace x\mathbf x by ax+ca\mathbf x+c with a>0a>0: the mean becomes aμ+ca\mu+c and the spread aσa\sigma, so ax+c−(aμ+c)aσ=x−μσ.\begin{aligned}&\frac{a\mathbf x+c-(a\mu+c)}{a\sigma}\\ &=\frac{\mathbf x-\mu}{\sigma}.\end{aligned} ∎ (1,2,3,6)(1,2,3,6) and (2,4,6,12)(2,4,6,12) and (11,12,13,16)(11,12,13,16) all give (−1.069,−0.535,0,1.604)(-1.069,-0.535,0,1.604).
Prove it · the shortcut gives the blame an express lane

Claim. For y=x+f(x)\mathbf y=\mathbf x+f(\mathbf x), the Jacobian is I+JfI+J_f. Through NN such blocks the blame is multiplied by (I+JN)⋯(I+J1)=I+(terms with at least one J)(I+J_N)\cdots(I+J_1)=I+(\text{terms with at least one }J), so it never has to fade to zero.

1
Differentiate entry by entry: ∂yi/∂xj=δij+∂fi/∂xj\partial y_i/\partial x_j=\delta_{ij}+\partial f_i/\partial x_j. As a matrix, I+JfI+J_f. The Jacobian of x\mathbf x itself is the identity (Unit 6).
2
Blame at the bottom is (I+J1)T⋯(I+JN)T(I+J_1)^{\mathsf T}\cdots(I+J_N)^{\mathsf T} times blame at the top. Multiply the brackets out: one term is I⋅I⋯I=II\cdot I\cdots I=I, which passes the blame unchanged; every other term contains some JJ. ∎ Without shortcuts the product is J1T⋯JNTJ_1^{\mathsf T}\cdots J_N^{\mathsf T}, which fades or explodes like the powers of Unit 17. With them, the identity term keeps a clean line from top to bottom.
Prove it · the weights of one block

Claim. A block with size dd and feed-forward width dffd_{ff} has 4d2+2ddff4d^2+2dd_{ff} weights, 4d+dff+d4d+d_{ff}+d biases and 4d4d layer-norm numbers. For d=512d=512, dff=2048d_{ff}=2048: 3 145 728, then 3 150 336, then 3 152 384.

1
Attention: WQ,WK,WV,WOW_Q,W_K,W_V,W_O are each d×dd\times d in total (§7), so 4d2=1 048 5764d^2=1\,048\,576, plus 4d=20484d=2048 biases. One bias per output entry of each matrix.
2
Feed-forward: W1W_1 is d×dffd\times d_{ff} and W2W_2 is dff×dd_{ff}\times d, so 2ddff=2 097 1522dd_{ff}=2\,097\,152, plus biases dff+d=2560d_{ff}+d=2560. Two layer norms, each with γ,β\boldsymbol\gamma,\boldsymbol\beta of length dd: 4d=20484d=2048. 1 048 576+2 097 152=3 145 728;+2048+2560=3 150 336;+2048=3 152 384.\begin{aligned}&1\,048\,576+2\,097\,152\\ &=3\,145\,728;\\ &+2048+2560\\ &=3\,150\,336;\\ &+2048=3\,152\,384.\end{aligned} ∎ With dff=4dd_{ff}=4d the weights are 4d2+8d2=12d24d^2+8d^2=12d^2: a third in attention, two thirds in the small network.

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.

10

No peeking: the mask, and every guess at once

Imagine this

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 −∞-\infty. Since e−∞=0e^{-\infty}=0, 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 (1,0,0)(1,0,0) and its answer is v1=(2,0)\mathbf v_1=(2,0). Row 2 sees words 1 and 2, with scores 00 and 1.4141.414:

(11+e1.414, e1.4141+e1.414)≈(0.196, 0.804)\begin{aligned}&\Big(\frac{1}{1+e^{1.414}},\ \frac{e^{1.414}}{1+e^{1.414}}\Big)\\ &\approx(0.196,\ 0.804)\end{aligned}

and its answer is 0.196 (2,0)+0.804 (0,2)≈(0.391, 1.609)0.196\,(2,0)+0.804\,(0,2)\approx(0.391,\ 1.609). Row 3 is the last word, so it may see everything, and it is unchanged: (0.248,0.248,0.503)(0.248,0.248,0.503), answer (1,1)(1,1).

Every guess at once. Now the payoff. With the mask, the output at position tt is built only from words 1 to tt — in this layer and in every layer above it. So the output at position tt can be asked to predict word t+1t+1, 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 nn-word sentence gives n−1n-1 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.

Mask the futureEncoder and decoder: the scores, the shares and the answers of the §3 example; in decoder mode the top-right cells become −∞ and their shares exactly 0. Every guess at once: what each position may see, and the word it must guess — one relay step after another, or all in one pass.

Try: Switch from encoder to decoder and watch row 2 re-share its weight between the two cells it may still see: (0.196, 0.804). Press ▶ fill row by row. Then open every guess at once and press play: on “I drink hot chai daily” the relay makes its 4 guesses in 4 steps, one after another; the masked transformer makes the same 4 guesses in one step.

Why does this work?

Row tt of a masked attention map mixes only words 1 to tt, and every later layer keeps the same rule, so the output at position tt has never seen word t+1t+1. Predicting word t+1t+1 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 nn-word sentencen−1n-1n−1n-1
steps that wait in a rownn: each note needs the one before1 per layer: all rows at once
what stops cheatingthe future is not read yet−∞-\infty 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.

Trap

The −∞-\infty 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 −∞-\infty in first lets softmax share out the whole 100% among the allowed words. (And the mask never hides a word from itself.)

The realization

softmax⁡ ⁣(QKTd+M)V,Mij={0j≤i−∞j>i\begin{gathered}\operatorname{softmax}\!\Big(\frac{QK^{\mathsf T}}{\sqrt d}+M\Big)V,\\ M_{ij}=\begin{cases}0&j\le i\\ -\infty&j>i\end{cases}\end{gathered}

Adding −∞-\infty 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.

Pause & predict

With the causal mask, row 1 of any attention map is always the same. What is it, for a 4-word sentence?

Pause & predict

In a masked (decoder) attention you change the value of word 4 in a 5-word sentence. Which words' answers can change?

Pause & predict

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
Prove it · one masked pass is n honest runs

Claim. With the causal mask, the output of any layer at position tt does not depend on anything about the words after tt. So one pass over the whole sentence gives, at every position tt, exactly what a run on the first tt words alone would give.

1
For j>ij>i the masked score is −∞-\infty, so e−∞=0e^{-\infty}=0 and Aij=0A_{ij}=0 exactly — whatever qi⋅kj\mathbf q_i\cdot\mathbf k_j was. In practice a very large negative number such as −109-10^9 is used; its exponential is 0 in computer arithmetic.
2
The shares on j≤ij\le i are esij/∑l≤iesile^{s_{ij}}/\sum_{l\le i}e^{s_{il}}: only keys l≤il\le i appear. The answer ∑j≤iAijvj\sum_{j\le i}A_{ij}\mathbf v_j uses only values j≤ij\le i. The add, the layer norm and the small network work on each word alone, so they keep the rule. Position ii's output in this layer is built from positions 1,…,i1,\dots,i of the layer below.
3
Go up the stack one layer at a time: if the layer below, at positions 1,…,i1,\dots,i, depends only on words 1,…,i1,\dots,i, then so does this layer at position ii. At the bottom that is true (each word's own vector). So the top output at tt is a function of words 1,…,t1,\dots,t only — the same as a run on that beginning alone. ∎ So one masked pass over "I drink chai daily" is three honest guessing games at once: "drink" from "I", "chai" from "I drink", "daily" from "I drink chai".

In one sentence: Setting the scores above the diagonal to −∞-\infty 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.

11

Three families: BERT, GPT and the encoder–decoder

Imagine this

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 0.15×512=76.80.15\times512=76.8, 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.

Who may look at whom — and who is gradedPick a family. The grid is its permission map: a gold cell means the row's word may look at the column's word. A red dot at the end of a row means "this position is graded": the model's guess there enters the loss.

Try: Start with BERT and press new masking a few times: about 15% of the 12 words are chosen (here 2), most become [MASK], and only those places are graded — while the whole grid stays gold. Switch to GPT: the grid becomes a staircase and every position but the last is graded (11 guesses). Open encoder–decoder: three grids, and the cross-attention one is §1's alignment map. The text-length slider starts at 512 tokens: BERT grades 76.8 places, GPT 511. Drag it to 1 024: 153.6 against 1 023 — still about 6.7 times as many.

512
Why does this work?

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-onlydecoder-onlyencoder–decoder
each position seesboth sidesonly the left (the mask)encoder: both sides · decoder: its left + all of the input
training gamefill in ~15% hidden wordsguess the next word, everywherewrite the target text, word by word
graded places in a 512-token textabout 77511one per output word
good atunderstanding: sort, search, tagwriting: chat, stories, codeone text into another: translate, summarise
examplesBERT, RoBERTaGPT-2, GPT-3, LLaMAthe 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.)

Trap

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.

The realization

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.

Pause & predict

BERT is trained on a 256-token text. About how many tokens are chosen for guessing, and about how many of those become [MASK]?

Pause & predict

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?

Pause & predict

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).

12

The price: every pair of words

Imagine this

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 nn words attention builds an n×nn\times n 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 10×10=10010\times10=100 scores.

n=10: 100 scoresn=1 000: 1 000 000 scoresn=100 000: 10 000 000 000 scores\begin{aligned}n=10&:\ 100\text{ scores}\\ n=1\,000&:\ 1\,000\,000\text{ scores}\\ n=100\,000&:\ 10\,000\,000\,000\text{ scores}\end{aligned}

Double the length and the work goes up four times. With 12 heads and 12 layers, 1 000 words need 144144 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 nn steps of work for nn 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.

Handshakes against the relayBoth axes grow by ×10 per step. Gold: the scores attention computes (n2n^2 per head per layer). Blue: the steps a relay must take one after another (nn). Green: the steps attention must take one after another (1 per layer).

Try: Drag the length from 10 to 100 000 words and read the three numbers: at 1 000 words, 1 000 000 scores. Then set 12 heads and 12 layers: 144 000 000 scores, about 288 MB — while the green count is only 12.

1 000
1
1
Why does this work?

Why pay n2n^2 when a relay pays nn? Because the n2n^2 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 nn wordsabout nn stepsn2n^2 scores per head per layer
steps that must wait in a rownn1 per layer
memory for the scoresnonen2n^2 per head per layer
1 000 words, 12 heads, 12 layers1 000 steps in a row144 000 000 scores, all at once

Rule of thumb. Attention wins while the n2n^2 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: nn scores for the new word, not n2n^2. Unit 19 opens that cache.

Trap

The n2n^2 is about work and memory, not weights. A transformer has exactly the same weights for 10 words and for 10 000 words: WQ,WK,WV,WOW_Q, W_K, W_V, W_O and the small network do not depend on nn. A longer text costs time and memory, not a bigger model.

The realization

scores=n2×heads×layerssteps in a row=layers\begin{gathered}\text{scores}=n^2\times\text{heads}\times\text{layers}\\ \text{steps in a row}=\text{layers}\end{gathered}

Attention pays n2n^2 for joining every pair of words directly. A relay pays only nn, 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.

Pause & predict

A model handles 2 000 words. You switch to 8 000 words. By what factor does the number of attention scores grow?

Pause & predict

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 n2n^2 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 nn steps that must wait for each other.

13

A tiny transformer, whole

Imagine this

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?

  1. Look up each word's vector in an embedding table (Unit 16), and add its position vector (§8).
  2. One block: two heads of masked attention, add and layer norm, a small network, add and layer norm (§9–§10).
  3. Score every word of the vocabulary with one more matrix, and turn the scores into probabilities with softmax (Unit 14).
  4. Learn: the loss is the cross-entropy −ln⁡(probability of the true next word)-\ln(\text{probability of the true next word}) (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 d=4d=4, 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

L=12(−ln⁡0.468−ln⁡0.877)≈12(0.76+0.13)≈0.45.\begin{aligned}L&=\tfrac12\big(-\ln0.468-\ln0.877\big)\\ &\approx\tfrac12(0.76+0.13)\approx0.45.\end{aligned}

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.

A tiny transformer, step by stepTwelve steps from words to a guess. Every number is shown. Rows are the two positions, "I" and the second word. Hand-set weights.

Try: Step through with next → and check a few numbers by hand: in step 4 row 2 of head 1 is (0.944, 0.056)(0.944,\ 0.056). At step 12 read the probability of chai, 0.877, and the loss, 0.446. Then switch the sentence to "I play" and jump to the end: cricket, 0.874.

sentence

One more trick: weight tying. Step 11 scores every vocabulary word with a matrix WUW_U of shape d×Vd\times V. Step 1 used an embedding table EE of shape V×dV\times d. Many models simply use the same numbers twice: WU=ETW_U=E^{\mathsf T}. Then the score of word ww is h⋅ew\mathbf h\cdot\mathbf e_w — 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 V=50 000V=50\,000 and d=512d=512, that is 50 000×512=25 600 00050\,000\times512=25\,600\,000 weights. (Our tiny toy is not tied: its WUW_U is set by hand.)

Why does this work?

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.

Trap

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.

The realization

words→embed+position→[block]N→scores→softmax⁡L=−1n∑tln⁡p(next word at t)\begin{gathered}\text{words}\to\text{embed}+\text{position}\\ \to\big[\text{block}\big]^{N}\to\text{scores}\to\operatorname{softmax}\\ L=-\tfrac1n\sum_t\ln p(\text{next word at }t)\end{gathered}

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.

Pause & predict

The true next words were given probabilities 0.5 and 0.25 at the two positions. What is the average cross-entropy loss?

Try it, then answer

In the tiny transformer with "I play", which word gets the highest probability after "play", and about how much?

Pause & predict

A model with a vocabulary of V=32 000V=32\,000 and d=4 096d=4\,096 ties its output matrix to its embedding table. How many weights does that save?

If you want the algebra · 1 proof, step by step
Prove it · with tied weights, a word's score is its agreement with the final vector

Claim. Let the embedding table EE (V×dV\times d) have row ew\mathbf e_w for word ww. If the output matrix is tied, WU=ETW_U=E^{\mathsf T}, then the score of word ww at a position with final vector h\mathbf h is h⋅ew\mathbf h\cdot\mathbf e_w, and the model saves V⋅dV\cdot d weights.

1
The scores are h WU=h ET\mathbf h\,W_U=\mathbf h\,E^{\mathsf T}. Entry ww is h\mathbf h times column ww of ETE^{\mathsf T}, which is row ww of EE: (h ET)w=h⋅ew.(\mathbf h\,E^{\mathsf T})_w=\mathbf h\cdot\mathbf e_w. Row times column is a dot product (Unit 1).
2
An untied WUW_U would have d×Vd\times V numbers of its own. Tied, it has none: it reuses EE. The saving is V⋅dV\cdot d. ∎ V=50 000V=50\,000, d=512d=512: 25 600 00025\,600\,000 weights. In training each row ew\mathbf e_w now gets blame from both ends — when ww is read, and when ww is (or is not) the next word.

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.

14

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 eq⋅k/de^{\mathbf q\cdot\mathbf k/\sqrt d}, 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 dd 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.
The realization

xi ← xi+∑jsoftmax⁡j ⁣(qi⋅kjd) vj\begin{aligned}\mathbf x_i\ \leftarrow\ &\mathbf x_i\\ &+\sum_j\operatorname{softmax}_j\!\Big(\frac{\mathbf q_i\cdot\mathbf k_j}{\sqrt d}\Big)\,\mathbf v_j\end{aligned}

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.

15

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 n2n^2 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: QKTQK^{\mathsf T} 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.

Problem 1easylook back

An encoder wrote three notes h1=(1,0)\mathbf h_1=(1,0), h2=(0,1)\mathbf h_2=(0,1), h3=(1,1)\mathbf h_3=(1,1). The decoder's state is q=(2,1)\mathbf q=(2,1). With dot-product scoring (no d\sqrt d 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
Step 1 — (a) scores. q⋅h1=2\mathbf q\cdot\mathbf h_1=2, q⋅h2=1\mathbf q\cdot\mathbf h_2=1, q⋅h3=2+1=3\mathbf q\cdot\mathbf h_3=2+1=3.
Step 2 — (b) weights. e2≈7.389e^2\approx7.389, e1≈2.718e^1\approx2.718, e3≈20.086e^3\approx20.086; total 30.19330.193. Weights ≈(0.245, 0.090, 0.665)\approx(0.245,\ 0.090,\ 0.665).
Step 3 — (c) context. 0.245 (1,0)+0.090 (0,1)+0.665 (1,1)=(0.245+0.665, 0.090+0.665)≈(0.910, 0.755)0.245\,(1,0)+0.090\,(0,1)+0.665\,(1,1)=(0.245+0.665,\ 0.090+0.665)\approx(0.910,\ 0.755).
Step 4 — (d). Note 3. It agrees with both entries of q\mathbf q, so it has the biggest score, 3, and softmax gives it about two thirds of the attention.

answers at a glance: (a) (2, 1, 3)(2,\ 1,\ 3). (b) ≈(0.245, 0.090, 0.665)\approx(0.245,\ 0.090,\ 0.665). (c) ≈(0.910, 0.755)\approx(0.910,\ 0.755). (d) note 3.

Remember

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.

Problem 2mediumadditive vs dot

Notes (1,0)(1,0), (0,1)(0,1), (1,1)(1,1); decoder state q=(0.5, −0.5)\mathbf q=(0.5,\ -0.5). (a) Find the additive scores vTtanh⁡(W1h+W2q)\mathbf v^{\mathsf T}\tanh(W_1\mathbf h+W_2\mathbf q) with W1=W2=IW_1=W_2=I and v=(1,1)\mathbf v=(1,1). (b) Their weights. (c) The dot-product scores q⋅h\mathbf q\cdot\mathbf h 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
Step 1 — (a). h+q\mathbf h+\mathbf q: (1.5, −0.5)(1.5,\ -0.5), (0.5, 0.5)(0.5,\ 0.5), (1.5, 0.5)(1.5,\ 0.5). tanh of each entry: (0.905, −0.462)(0.905,\ -0.462), (0.462, 0.462)(0.462,\ 0.462), (0.905, 0.462)(0.905,\ 0.462). Add the two entries: (0.443, 0.924, 1.367)(0.443,\ 0.924,\ 1.367).
Step 2 — (b). e0.443≈1.557e^{0.443}\approx1.557, e0.924≈2.519e^{0.924}\approx2.519, e1.367≈3.924e^{1.367}\approx3.924; total ≈8.000\approx8.000: (0.195, 0.315, 0.490)(0.195,\ 0.315,\ 0.490).
Step 3 — (c). q⋅h=(0.5, −0.5, 0)\mathbf q\cdot\mathbf h=(0.5,\ -0.5,\ 0). e0.5≈1.649e^{0.5}\approx1.649, e−0.5≈0.607e^{-0.5}\approx0.607, e0=1e^0=1; total 3.2553.255: (0.506, 0.186, 0.307)(0.506,\ 0.186,\ 0.307).
Step 4 — (d). Additive: note 3 (0.490). Dot: note 1 (0.506). The dot product multiplies, so note 3's second entry meets the state's −0.5-0.5 and costs it. The additive score adds the state to the note first, turning that entry into +0.5+0.5, so note 3 comes out on top.

answers at a glance: (a) (0.443, 0.924, 1.367)(0.443,\ 0.924,\ 1.367). (b) (0.195, 0.315, 0.490)(0.195,\ 0.315,\ 0.490). (c) scores (0.5, −0.5, 0)(0.5,\ -0.5,\ 0), weights (0.506, 0.186, 0.307)(0.506,\ 0.186,\ 0.307). (d) additive: note 3; dot: note 1.

Remember

The scoring function is a design choice, and different scores can prefer different notes. Transformers use the dot product (with d\sqrt d) because it is the cheapest.

Problem 3easyone lookup

Queries and keys have length d=4d=4. The query is q=(2,0,0,0)\mathbf q=(2,0,0,0). Two words have keys k1=(1,0,0,0)\mathbf k_1=(1,0,0,0), k2=(0,1,0,0)\mathbf k_2=(0,1,0,0) and values v1=(4,2)\mathbf v_1=(4,2), v2=(0,6)\mathbf v_2=(0,6). 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 d\sqrt d, softmax, blend. Plan. 4=2\sqrt4=2; then one softmax of two numbers.

Show the full solution
Step 1 — scores. q⋅k1=2\mathbf q\cdot\mathbf k_1=2, q⋅k2=0\mathbf q\cdot\mathbf k_2=0. Divide by 4=2\sqrt4=2: (1, 0)(1,\ 0).
Step 2 — shares. e1≈2.718e^1\approx2.718, e0=1e^0=1, total 3.7183.718: (0.731, 0.269)(0.731,\ 0.269).
Step 3 — blend. 0.731 (4,2)+0.269 (0,6)=(2.924, 1.462+1.614)≈(2.924, 3.076)0.731\,(4,2)+0.269\,(0,6)=(2.924,\ 1.462+1.614)\approx(2.924,\ 3.076).

answers at a glance: (a) (1,0)(1,0). (b) (0.731, 0.269)(0.731,\ 0.269). (c) ≈(2.924, 3.076)\approx(2.924,\ 3.076).

Remember

The keys decide the shares; the values decide what is blended. They can even have different lengths.

Problem 4easythe whole table

Three words have vectors x1=(1,0)\mathbf x_1=(1,0), x2=(0,1)\mathbf x_2=(0,1), x3=(1,1)\mathbf x_3=(1,1), and each word uses its own vector as query, key and value (Q=K=V=XQ=K=V=X, d=2d=2). Find (a) the scaled score table QKT/2QK^{\mathsf T}/\sqrt2, (b) the attention matrix, (c) the three answers.

What this tests. softmax⁡(QKT/d)V\operatorname{softmax}(QK^{\mathsf T}/\sqrt d)V row by row. Plan. All dot products are 0, 1 or 2; divide by 1.414; softmax each row.

Show the full solution
Step 1 — dot products. QKT=(101011112)QK^{\mathsf T}=\begin{pmatrix}1&0&1\\ 0&1&1\\ 1&1&2\end{pmatrix}. Divide by 2\sqrt2: entries 0.7070.707 for 1 and 1.4141.414 for 2.
Step 2 — row 1. Scores (0.707,0,0.707)(0.707,0,0.707): e0.707≈2.028e^{0.707}\approx2.028, total 5.0565.056: shares (0.401, 0.198, 0.401)(0.401,\ 0.198,\ 0.401). Row 2 is the mirror: (0.198, 0.401, 0.401)(0.198,\ 0.401,\ 0.401).
Step 3 — row 3. Scores (0.707,0.707,1.414)(0.707,0.707,1.414): 2.028+2.028+4.113=8.1692.028+2.028+4.113=8.169: shares (0.248, 0.248, 0.503)(0.248,\ 0.248,\ 0.503).
Step 4 — answers. Row 1: 0.401(1,0)+0.198(0,1)+0.401(1,1)=(0.802, 0.599)0.401(1,0)+0.198(0,1)+0.401(1,1)=(0.802,\ 0.599). Row 2: (0.599, 0.802)(0.599,\ 0.802). Row 3: 0.248(1,0)+0.248(0,1)+0.503(1,1)=(0.752, 0.752)0.248(1,0)+0.248(0,1)+0.503(1,1)=(0.752,\ 0.752).

answers at a glance: (a) (0.70700.70700.7070.7070.7070.7071.414)\begin{pmatrix}0.707&0&0.707\\ 0&0.707&0.707\\ 0.707&0.707&1.414\end{pmatrix}. (b) rows (0.401,0.198,0.401)(0.401,0.198,0.401), (0.198,0.401,0.401)(0.198,0.401,0.401), (0.248,0.248,0.503)(0.248,0.248,0.503). (c) (0.802,0.599)(0.802,0.599), (0.599,0.802)(0.599,0.802), (0.752,0.752)(0.752,0.752).

Remember

With Q=KQ=K the score table is symmetric, but the attention matrix need not be: each row is normalised on its own.

Problem 5hardreverse-engineer

Keys k1=(1,0)\mathbf k_1=(1,0), k3=(1,1)\mathbf k_3=(1,1) and a query q=(2,0)\mathbf q=(2,0), d=2d=2. Word 2's key is changed to k2=(c,0)\mathbf k_2=(c,0). (a) Write the three scaled scores in terms of cc. (b) Find cc so that word 2 gets exactly half of all the attention. (c) What are the three shares then? (d) For which cc does word 2 get the biggest share of the three?

What this tests. Running softmax backwards. Plan. "Half" means es2=es1+es3e^{s_2}=e^{s_1}+e^{s_3}.

Show the full solution
Step 1 — (a). q⋅k1=2\mathbf q\cdot\mathbf k_1=2, q⋅k2=2c\mathbf q\cdot\mathbf k_2=2c, q⋅k3=2\mathbf q\cdot\mathbf k_3=2. Divided by 2\sqrt2: (2, 2 c, 2)(\sqrt2,\ \sqrt2\,c,\ \sqrt2).
Step 2 — (b). Half the total means e2c=e2+e2=2e2e^{\sqrt2c}=e^{\sqrt2}+e^{\sqrt2}=2e^{\sqrt2}. Take logs: 2 c=2+ln⁡2\sqrt2\,c=\sqrt2+\ln2, so c=1+ln⁡2/2≈1+0.490=1.490c=1+\ln2/\sqrt2\approx1+0.490=1.490.
Step 3 — (c). Word 2 has 12\tfrac12; words 1 and 3 have equal scores, so they split the rest: (0.25, 0.5, 0.25)(0.25,\ 0.5,\ 0.25).
Step 4 — (d). Word 2 beats words 1 and 3 exactly when its score is bigger: 2c>2\sqrt2c>\sqrt2, that is c>1c>1.

answers at a glance: (a) (1.414, 1.414c, 1.414)(1.414,\ 1.414c,\ 1.414). (b) c=1+ln⁡2/2≈1.490c=1+\ln2/\sqrt2\approx1.490. (c) (0.25,0.5,0.25)(0.25,0.5,0.25). (d) c>1c>1.

Remember

To win a fixed share, a key needs a fixed gap in log space: shares follow escoree^{\text{score}}.

Problem 6harddiagnose a run

A student's model with d=64d=64 stops learning. One attention row has raw scores (40, 32, 8, 0)(40,\ 32,\ 8,\ 0), and those are the numbers that go into softmax. (a) What shares does the row get? (b) What is the slope p(1−p)p(1-p) 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 d\sqrt d scaling from a spiky, frozen row. Plan. Softmax cares only about gaps; the gap 8 is huge.

Show the full solution
Step 1 — (a). Subtract the biggest score: (0,−8,−32,−40)(0,-8,-32,-40). e−8≈0.000335e^{-8}\approx0.000335, the others are tiny: shares ≈(0.99966, 0.00034, 0, 0)\approx(0.99966,\ 0.00034,\ 0,\ 0).
Step 2 — (b). 0.99966×0.00034≈0.0003350.99966\times0.00034\approx0.000335: almost no blame gets through, so the row cannot learn.
Step 3 — (c). The scores were never divided by 64=8\sqrt{64}=8. Fixed: (5,4,1,0)(5,4,1,0). e5≈148.41e^5\approx148.41, e4≈54.60e^4\approx54.60, e1≈2.72e^1\approx2.72, e0=1e^0=1, total 206.73206.73: shares ≈(0.718, 0.264, 0.013, 0.005)\approx(0.718,\ 0.264,\ 0.013,\ 0.005).
Step 4 — (d). 0.718×0.282≈0.2030.718\times0.282\approx0.203 — about 600 times more than before.

answers at a glance: (a) ≈(0.99966,0.00034,0,0)\approx(0.99966,0.00034,0,0). (b) ≈0.000335\approx0.000335. (c) the 1/d1/\sqrt d scaling; ≈(0.718,0.264,0.013,0.005)\approx(0.718,0.264,0.013,0.005). (d) ≈0.203\approx0.203.

Remember

A row that is almost exactly one-hot, with the model not learning, is the classic sign of missing d\sqrt d scaling (or a temperature that is far too low).

Problem 7mediumone word, two meanings

Toy vectors (nature, money): lake =(3,1)=(3,1), cash =(0,3)=(0,3), bank =(1,1)=(1,1). Each word uses its own vector as query, key and value (Q=K=V=XQ=K=V=X), and d=2d=2. (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 b+σ(g)(a−b)\mathbf b+\sigma(g)(\mathbf a-\mathbf b), where g=(a⋅b−b⋅b)/dg=(\mathbf a\cdot\mathbf b-\mathbf b\cdot\mathbf b)/\sqrt d.

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 (1,1)(1,1): score both words, divide by 2\sqrt2, softmax, blend.

Show the full solution
Step 1 — (a). bank·lake =4=4, bank·bank =2=2; divided by 2\sqrt2: (2.828, 1.414)(2.828,\ 1.414). The gap is 1.414, so lake's share is 1/(1+e−1.414)≈0.8041/(1+e^{-1.414})\approx0.804 and bank keeps 0.1960.196. New bank =0.804 (3,1)+0.196 (1,1)≈(2.609, 1)=0.804\,(3,1)+0.196\,(1,1)\approx(2.609,\ 1).
Step 2 — (b). bank·cash =3=3, bank·bank =2=2; divided: (2.121, 1.414)(2.121,\ 1.414); shares (0.670, 0.330)(0.670,\ 0.330). New bank =0.670 (0,3)+0.330 (1,1)≈(0.330, 2.340)=0.670\,(0,3)+0.330\,(1,1)\approx(0.330,\ 2.340).
Step 3 — (c). Dot product 2.609×0.330+1×2.340≈3.2012.609\times0.330+1\times2.340\approx3.201. Lengths 2.6092+1≈2.794\sqrt{2.609^2+1}\approx2.794 and 0.3302+2.3402≈2.363\sqrt{0.330^2+2.340^2}\approx2.363. Cosine ≈3.201/(2.794×2.363)≈0.485\approx3.201/(2.794\times2.363)\approx0.485, about 61∘61^\circ.
Step 4 — (d). g=(4−2)/2≈1.414g=(4-2)/\sqrt2\approx1.414 and σ(1.414)≈0.804\sigma(1.414)\approx0.804: (1,1)+0.804 (2,0)≈(2.609, 1)(1,1)+0.804\,(2,0)\approx(2.609,\ 1). It matches (a).

answers at a glance: (a) ≈(2.609, 1)\approx(2.609,\ 1). (b) ≈(0.330, 2.340)\approx(0.330,\ 2.340). (c) ≈0.485\approx0.485. (d) it matches (a).

Remember

A word slides towards its neighbour, further when the neighbour matches its query better. Two neighbours pull the same word two ways.

Problem 8mediumhead shapes

A model has d=768d=768 and h=12h=12 heads. Find (a) dkd_k; (b) the shape and weight count of one head's WQ(i)W_Q^{(i)}; (c) the weights of WQ,WK,WV,WOW_Q,W_K,W_V,W_O together; (d) the same with one bias per output entry of each of the four matrices.

What this tests. dk=d/hd_k=d/h and the 4d24d^2 count. Plan. One head, then all heads, then WOW_O.

Show the full solution
Step 1 — (a). dk=768/12=64d_k=768/12=64.
Step 2 — (b). WQ(i)W_Q^{(i)} is 768×64768\times64: 49 15249\,152 weights.
Step 3 — (c). 12 heads × 3 matrices × 49 152 =1 769 472=3×7682=1\,769\,472=3\times768^2. Add WOW_O, 7682=589 824768^2=589\,824: total 2 359 296=4×76822\,359\,296=4\times768^2.
Step 4 — (d). Four matrices each have 768 outputs: +4×768=3072+4\times768=3072, giving 2 362 3682\,362\,368.

answers at a glance: (a) 64. (b) 768×64768\times64, 49 152. (c) 2 359 296. (d) 2 362 368.

Remember

More heads means smaller heads. The weight count, 4d24d^2, does not depend on hh.

Problem 9mediumclock tags

Sinusoidal tags: PE(p,2i)=sin⁡(p/100002i/d)\mathrm{PE}(p,2i)=\sin(p/10000^{2i/d}), PE(p,2i+1)=cos⁡(p/100002i/d)\mathrm{PE}(p,2i+1)=\cos(p/10000^{2i/d}). (a) For d=4d=4, write the tag of position p=2p=2. (b) Compute PE(5)⋅PE(6)\mathrm{PE}(5)\cdot\mathrm{PE}(6) for d=4d=4 and compare it with cos⁡1+cos⁡0.01\cos1+\cos0.01. (c) For d=512d=512, what is the speed 1/100002i/d1/10000^{2i/d} of clock i=128i=128? (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 d=4d=4 the speeds are 11 and 10000−1/2=0.0110000^{-1/2}=0.01.

Show the full solution
Step 1 — (a). Clock 0: sin⁡2≈0.909\sin2\approx0.909, cos⁡2≈−0.416\cos2\approx-0.416. Clock 1: sin⁡0.02≈0.020\sin0.02\approx0.020, cos⁡0.02≈1.000\cos0.02\approx1.000.
Step 2 — (b). PE(5)≈(−0.9589, 0.2837, 0.0500, 0.9988)\mathrm{PE}(5)\approx(-0.9589,\ 0.2837,\ 0.0500,\ 0.9988) and PE(6)≈(−0.2794, 0.9602, 0.0600, 0.9982)\mathrm{PE}(6)\approx(-0.2794,\ 0.9602,\ 0.0600,\ 0.9982). The products are 0.2679+0.2724+0.0030+0.9970≈1.54030.2679+0.2724+0.0030+0.9970\approx1.5403 — the same as cos⁡1+cos⁡0.01≈0.5403+1.0000\cos1+\cos0.01\approx0.5403+1.0000, because the two positions are 1 apart.
Step 3 — (c). 2i/d=256/512=122i/d=256/512=\tfrac12, so the speed is 10000−1/2=0.0110000^{-1/2}=0.01 radians per position.
Step 4 — (d). One full turn is 2π2\pi radians: 2π/0.01≈6282\pi/0.01\approx628 positions.

answers at a glance: (a) (0.909, −0.416, 0.020, 1.000)(0.909,\ -0.416,\ 0.020,\ 1.000). (b) ≈1.5403\approx1.5403, equal to cos⁡1+cos⁡0.01\cos1+\cos0.01. (c) 0.01. (d) about 628 positions.

Remember

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.

Problem 10mediumrotary positions

RoPE with θ=30∘\theta=30^\circ, q=(1,0)\mathbf q=(1,0), k=(0,1)\mathbf k=(0,1). The score is (Rmθq)⋅(Rnθk)(R_{m\theta}\mathbf q)\cdot(R_{n\theta}\mathbf k). Find it for (a) m=4,n=1m=4,n=1, (b) m=7,n=4m=7,n=4, (c) m=1,n=4m=1,n=4. (d) Give the general formula in terms of m−nm-n.

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
Step 1 — (a). q\mathbf q turned by 120∘120^\circ: (cos⁡120∘,sin⁡120∘)=(−0.5, 0.866)(\cos120^\circ,\sin120^\circ)=(-0.5,\ 0.866). k=(0,1)\mathbf k=(0,1) points at 90∘90^\circ; turned by 30∘30^\circ it points at 120∘120^\circ too: (−0.5, 0.866)(-0.5,\ 0.866). Dot product 0.25+0.75=10.25+0.75=1.
Step 2 — (b). Same gap 3: arrows at 210∘210^\circ and 90∘+120∘=210∘90^\circ+120^\circ=210^\circ. Score 1.
Step 3 — (c). Arrows at 30∘30^\circ and 90∘+120∘=210∘90^\circ+120^\circ=210^\circ: opposite. Score −1-1.
Step 4 — (d). q\mathbf q points at mθm\theta, k\mathbf k at 90∘+nθ90^\circ+n\theta. The dot product of two unit arrows is the cosine of the angle between them: cos⁡(90∘+(n−m)θ)=sin⁡((m−n)θ)\cos(90^\circ+(n-m)\theta)=\sin((m-n)\theta).

answers at a glance: (a) 1. (b) 1. (c) −1. (d) sin⁡((m−n)θ)\sin((m-n)\theta).

Remember

Rotary scores depend only on m−nm-n: "3 words back" scores the same anywhere in the sentence.

Problem 11mediumlayer norm

Layer-normalise x=(2,4,4,6)\mathbf x=(2,4,4,6) (a) with γ=1,β=0\boldsymbol\gamma=1,\boldsymbol\beta=0, (b) with γ=2,β=1\gamma=2,\beta=1 in every entry. (c) What do you get for x′=(12,14,14,16)\mathbf x'=(12,14,14,16)? (d) A word has x=(1,0,−1,0)\mathbf x=(1,0,-1,0) and attention hands back a=(1,2,1,0)\mathbf a=(1,2,1,0). Find LN⁡(x+a)\operatorname{LN}(\mathbf x+\mathbf a) with γ=1,β=0\gamma=1,\beta=0.

What this tests. Mean, variance (divide by dd), then scale and shift. Plan. Centre first.

Show the full solution
Step 1 — mean and variance. Mean 4; centred (−2,0,0,2)(-2,0,0,2); variance (4+0+0+4)/4=2(4+0+0+4)/4=2; spread 2≈1.414\sqrt2\approx1.414.
Step 2 — (a). (−2,0,0,2)/1.414=(−1.414, 0, 0, 1.414)(-2,0,0,2)/1.414=(-1.414,\ 0,\ 0,\ 1.414).
Step 3 — (b). 2×(a)+1=(−1.828, 1, 1, 3.828)2\times(\text{a})+1=(-1.828,\ 1,\ 1,\ 3.828).
Step 4 — (c). x′=x+10\mathbf x'=\mathbf x+10: the shift disappears when we centre, so the result is the same as (a).
Step 5 — (d). The shortcut first: x+a=(2,2,0,0)\mathbf x+\mathbf a=(2,2,0,0). Mean 1; centred (1,1,−1,−1)(1,1,-1,-1); variance 4/4=14/4=1. So LN⁡=(1, 1, −1, −1)\operatorname{LN}=(1,\ 1,\ -1,\ -1).

answers at a glance: (a) (−1.414,0,0,1.414)(-1.414,0,0,1.414). (b) (−1.828,1,1,3.828)(-1.828,1,1,3.828). (c) (−1.414,0,0,1.414)(-1.414,0,0,1.414). (d) (1,1,−1,−1)(1,1,-1,-1).

Remember

Layer norm forgets the average and the size of a word's numbers; γ\gamma and β\beta let the network put back what it needs.

Problem 12mediuma block's weights

A block has d=256d=256 and dff=1024d_{ff}=1024. 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. 4d2+2ddff4d^2+2dd_{ff}, biases 4d+dff+d4d+d_{ff}+d, layer norms 4d4d. Plan. Add in stages.

Show the full solution
Step 1 — (a). 4×2562=262 1444\times256^2=262\,144.
Step 2 — (b). 2×256×1024=524 2882\times256\times1024=524\,288.
Step 3 — (c). Weights 786 432786\,432, biases 4(256)+1024+256=23044(256)+1024+256=2304: 788 736788\,736.
Step 4 — (d). Two layer norms: 2×(256+256)=10242\times(256+256)=1024: 789 760789\,760.

answers at a glance: (a) 262 144. (b) 524 288. (c) 788 736. (d) 789 760.

Remember

With dff=4dd_{ff}=4d, two thirds of a block's weights are in the feed-forward part.

Problem 13mediumcausal mask

A 3-word decoder has scaled scores S=(210131022)S=\begin{pmatrix}2&1&0\\ 1&3&1\\ 0&2&2\end{pmatrix}. Apply the causal mask and find (a) the masked score table, (b) the attention matrix.

What this tests. −∞-\infty 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
Step 1 — (a). (2−∞−∞13−∞022)\begin{pmatrix}2&-\infty&-\infty\\ 1&3&-\infty\\ 0&2&2\end{pmatrix}.
Step 2 — row 1. Only one allowed cell: (1,0,0)(1,0,0). (The score 2 does not matter.)
Step 3 — row 2. e1≈2.718e^1\approx2.718, e3≈20.086e^3\approx20.086, total 22.80422.804: (0.119, 0.881, 0)(0.119,\ 0.881,\ 0).
Step 4 — row 3. e0=1e^0=1, e2≈7.389e^2\approx7.389 twice, total 15.77815.778: (0.063, 0.468, 0.468)(0.063,\ 0.468,\ 0.468).

answers at a glance: (a) as above. (b) rows (1,0,0)(1,0,0), (0.119,0.881,0)(0.119,0.881,0), (0.063,0.468,0.468)(0.063,0.468,0.468).

Remember

The first row of a masked map is always (1,0,…,0)(1,0,\dots,0). The last row is never changed by the mask.

Problem 14mediumBERT vs GPT

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
Step 1 — (a). 0.15×1 024=153.60.15\times1\,024=153.6, about 154 tokens.
Step 2 — (b). 0.8×153.6=122.880.8\times153.6=122.88 become [MASK]; 0.1×153.6=15.360.1\times153.6=15.36 become a random word; 15.3615.36 stay unchanged — about 123, 15 and 15.
Step 3 — (c). Every position guesses the token after it, except the last: 1 0231\,023.
Step 4 — (d). 1 023/153.6≈6.71\,023/153.6\approx6.7.

answers at a glance: (a) 153.6≈154153.6\approx154. (b) 122.88122.88, 15.3615.36, 15.3615.36 (about 123, 15, 15). (c) 1 023. (d) about 6.7 times.

Remember

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.

Problem 15mediumweight tying

A model with d=768d=768 saves exactly 38 597 376 weights by tying its output matrix to its embedding table. (a) What is its vocabulary size VV? (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 ww is h⋅ew\mathbf h\cdot\mathbf e_w. For h=(1,2)\mathbf h=(1,2), echai=(0.5,1)\mathbf e_{\text{chai}}=(0.5,1) and ecoffee=(1,−1)\mathbf e_{\text{coffee}}=(1,-1), which word scores higher?

What this tests. Weight tying (§13), run backwards to find VV, then used forwards. Plan. The saving is one whole V×dV\times d table.

Show the full solution
Step 1 — (a). V×768=38 597 376V\times768=38\,597\,376, so V=38 597 376/768=50 257V=38\,597\,376/768=50\,257.
Step 2 — (b). Without tying: two tables, 2×38 597 376=77 194 7522\times38\,597\,376=77\,194\,752. With tying: one table, 38 597 37638\,597\,376.
Step 3 — (c). chai: 1(0.5)+2(1)=2.51(0.5)+2(1)=2.5; coffee: 1(1)+2(−1)=−11(1)+2(-1)=-1. Chai scores higher.

answers at a glance: (a) V=50 257V=50\,257. (b) 77 194 752 without, 38 597 376 with. (c) chai, 2.5 against −1.

Remember

With tying, "is ww the next word?" is asked with ww's own look-up vector: the final vector must point where the word's embedding points.

Problem 16mediumthe n² bill

A model reads n=2048n=2048 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 (10910^9 bytes) to keep them all? (d) By what factor does (b) grow at n=4096n=4096?

What this tests. n2×h×Ln^2\times h\times L. Plan. Square, multiply, convert.

Show the full solution
Step 1 — (a). 20482=4 194 3042048^2=4\,194\,304.
Step 2 — (b). 4 194 304×16×24=1 610 612 7364\,194\,304\times16\times24=1\,610\,612\,736.
Step 3 — (c). ×2\times2 bytes =3 221 225 472=3\,221\,225\,472 bytes ≈3.22\approx3.22 GB.
Step 4 — (d). Doubling nn multiplies n2n^2 by 4.

answers at a glance: (a) 4 194 304. (b) 1 610 612 736. (c) ≈3.22\approx3.22 GB. (d) 4 times.

Remember

The attention bill grows with the square of the length. That is why long inputs are expensive.

Next up

Unit 19 · The Maths Inside an LLM — upcoming

Stack these blocks a hundred deep and train them on a huge pile of text to predict the next word. Then learn how the machine picks its words — temperature, top-k, top-p — and how it is steered.

← Unit 17 · Machines with Memory · All units