Part II ยท Ch. 11 โ€” The Transformer

Part II ยท Chapter 11 of 20

The Transformer

Stacking attention into a thinking machine


The machine, so far

Back in Chapter 9 we made a promise: there exists a machine that eats "the cat sat on the" and hands back $p(\text{next} \mid \text{context})$ โ€” a probability for every token it knows. Ever since, we have treated that machine as a box. But we have not been idle: in Chapter 10 we built its beating heart, attention. This chapter assembles the rest of the box around that heart. And here is the promise for today, one I intend to keep in full: by the last paragraph the box will have no unexplained parts. Every component you meet is something you already own โ€” matrices, adds, bends, softmax. Not one new kind of math is coming.

Start by taking honest inventory. One pass of attention is powerful, but on its own it still lacks four things a real language machine needs:

  • Gap 1 โ€” it can't see word order. Attention scores are built from dot products of queries and keys, and "the cat sat" and "sat cat the" produce the same dot products. The machine cannot yet tell who came first.
  • Gap 2 โ€” it asks only one kind of question. Our toy head in Chapter 10 asked "who did it?" But a sentence needs many questions asked at once โ€” who did it, what came just before, which adjective modifies me.
  • Gap 3 โ€” after gathering, a token never gets to think. Attention lets a token collect information from its neighbors, but then nothing digests what it heard.
  • Gap 4 โ€” one pass of anything is shallow. Real understanding needs the whole arrangement repeated, deeply, without forgetting what came before.

The machine that closes all four gaps has a name. The transformer fixes them with exactly four ideas, and the next four sections take them in order: position stamps close Gap 1, multiple heads close Gap 2, MLP blocks close Gap 3, and a residual stream closes Gap 4. One honest diagram at a time โ€” let's build it.

Stamping the seats

A confession first, then the fix. In Chapter 10 we quietly skipped a step. Attention scores travel with the words, not the seats: the dot product $\mathbf{q} \cdot \mathbf{k}$ contains nothing about who sat down first. Shuffle the sentence and every single dot product comes out identical. To a bare attention layer, "man bites dog" and "dog bites man" are the same news story (figure below). The only order-aware piece we met was the causal mask โ€” the no-peeking-forward rule โ€” and a crude "you may not look right" is nowhere near enough to carry grammar.

Two horizontal bands. Top band 'without seat stamps': three token chips reading the, cat, sat on the left; the same three chips scrambled as sat, cat, the on the right; a large equals sign between them with the caption 'same dot products'; identical small clusters of tiny arrows sit beneath each group. Bottom band 'with seat stamps': the same two chip groups, but each chip now carries a small blue seat badge numbered by position, so 'the' wears badge 1 on the left group and badge 3 on the right; a large not-equals sign between them with the caption 'different vectors now'; the arrow clusters beneath the two groups now visibly differ.
Attention scores travel with the words, not the seats. Without position information, "the cat sat" and "sat cat the" hand the machine identical dot products (top). Adding a seat stamp to each embedding makes the same word a different vector in a different seat (bottom) โ€” and order becomes something attention can ask about.

The fix is almost embarrassingly direct: before anything else happens, we add a position vector โ€” a seat stamp โ€” to each token's embedding. Seat 1 has its own stamp vector, seat 2 has another, and so on. The same word sitting in two different seats now enters the machine as two genuinely different vectors. That is Gap 1, closed.

Worked example

Let's stamp with toy integers โ€” invented stamps, chosen so you can check the sum by hand. Cat's embedding is $\begin{bmatrix} 0 \\ 1 \\ 0 \end{bmatrix}$. Sitting in seat 2, it picks up that seat's stamp $\begin{bmatrix} 2 \\ 0 \\ 0 \end{bmatrix}$, and the vector that actually enters the machine is the sum:

$$\mathbf{x}_{\text{cat, seat 2}} = \begin{bmatrix} 0 \\ 1 \\ 0 \end{bmatrix} + \begin{bmatrix} 2 \\ 0 \\ 0 \end{bmatrix} = \begin{bmatrix} 2 \\ 1 \\ 0 \end{bmatrix}$$

In words: the word's meaning-arrow plus the seat's location-arrow, added component by component like any two vectors from Chapter 1. The very same cat sitting in seat 5, whose stamp is $\begin{bmatrix} 0 \\ 0 \\ 2 \end{bmatrix}$, would instead enter as $\begin{bmatrix} 0 \\ 1 \\ 2 \end{bmatrix}$ โ€” a different arrow for the same word. Now the queries and keys computed from these vectors can ask position-flavored questions: "what's the word right before me?" finally has an answer.

One sentence of honest breadth, no formulas. Some models bake the stamps in as fixed wave patterns; others learn them like any other parameter; the newest models rotate the query and key arrows by a position-dependent angle instead (rotation you already own from Chapter 3). The engineering differs; the job is identical โ€” get seat information into the vectors so attention can use it.

Many spotlights: multi-head attention

Chapter 10's attention asked one kind of question โ€” our toy head asked "who did it?" But a sentence needs many questions asked simultaneously: who did it, what came just before, which adjective modifies me, is there a negation upstream. Each question is its own softmax over the tokens. The transformer's answer to Gap 2 is blunt: run several small attentions in parallel, and call each one a head.

Each head owns its own violet trio of matrices โ€” its own query, key, and value lenses โ€” so each head learns to ask a different question. The figure shows two heads working the same sentence. Head 1 is literally Chapter 10's grid; head 2 shows a different personality on the same words.

Two square attention-share grids side by side over the tokens the, cat, sat, each masked to a lower triangle. Left grid, labeled 'head 1 โ€” asks: who did it?', shows shares: row the 1.00; row cat 0.02 and 0.98; row sat 0.09, 0.67, 0.24. Right grid, labeled 'head 2 โ€” asks: what came just before?', shows shares: row the 1.00; row cat 0.80 and 0.20; row sat 0.10, 0.75, 0.15. Cells are filled with mint at an opacity matching their share.
Same sentence, same mechanism, different learned lenses. Head 1 is Chapter 10's grid โ€” its shares chase the do-er. Head 2 (numbers illustrative) has drifted into a different habit: each word watches the word just before it. A real layer runs dozens of such heads at once and blends all their answers.

Head 1's shares are exactly the masked grid you computed in Chapter 10: the $\to 1.00$; cat $\to 0.02, 0.98$; sat $\to 0.09, 0.67, 0.24$. Head 2's shares ($1.00$; $0.80, 0.20$; $0.10, 0.75, 0.15$) are illustrative numbers, invented to show a "what came just before?" habit โ€” each word putting most of its weight on its immediate predecessor. Same sentence, same mechanism, different learned lenses, different pattern.

How do the answers rejoin the stream? Each head produces its own small output vector per token (head 1's answer for sat was $\begin{bmatrix} 2.25 \\ 0.85 \end{bmatrix}$, from Chapter 10). The head outputs are laid end to end โ€” two heads with 2 numbers each make one list of 4 โ€” and one more learned violet matrix, the output matrix, mixes that combined list back down to the token's working width. No new math at all: concatenate, then matrix × vector, the move from Chapter 3.

Real-scale numbers, honestly sourced: GPT-3 runs 96 heads per layer, each working with 128-number queries and keys. That is 96 different questions asked about every token, in every layer, at once. Nobody tells head 41 what to ask โ€” its question is whatever the violet lenses drifted into during training.

Private thinking: the MLP block

After attention, each token has gathered โ€” sat now carries its cat. But gathering isn't digesting. The second block type in a transformer lets each token think about what it now holds, privately, with no cross-token traffic at all: the MLP block (also called the feed-forward block). That is Gap 3 closing.

Its anatomy is two matrices with a bend between them โ€” and you were promised exactly this in Chapter 3's bridge: matrices alone stay flat, and two matrices in a row collapse into one, so the bend between them is what buys genuinely new behavior. The bend here is the ReLU โ€” cruder than Chapter 4's smooth sigmoid: anything negative becomes 0, anything positive passes untouched. (Real models use a smoothed cousin called GELU; the shape story is identical.)

Worked example

Every digit, on a fresh 2-number toy stream vector $\begin{bmatrix} 2 \\ 1 \end{bmatrix}$. First expand with $\mathbf{W}_1 = \begin{bmatrix} 1 & 1 \\ 0 & 2 \\ -2 & 1 \end{bmatrix}$ (2 numbers in, 3 out). Each row dots the input from Chapter 2: $1\cdot 2 + 1\cdot 1 = 3$, then $0\cdot 2 + 2\cdot 1 = 2$, then $(-2)\cdot 2 + 1\cdot 1 = -3$. The bend zeroes the negative. Then contract back with $\mathbf{W}_2 = \begin{bmatrix} 1 & 0 & 1 \\ 0 & 1 & -1 \end{bmatrix}$: its rows give $1\cdot 3 + 0\cdot 2 + 1\cdot 0 = 3$ and $0\cdot 3 + 1\cdot 2 + (-1)\cdot 0 = 2$.

$$\mathbf{W}_1 \begin{bmatrix} 2 \\ 1 \end{bmatrix} = \begin{bmatrix} 3 \\ 2 \\ -3 \end{bmatrix} \;\xrightarrow{\text{bend}}\; \begin{bmatrix} 3 \\ 2 \\ 0 \end{bmatrix} \;\xrightarrow{\;\mathbf{W}_2\;}\; \begin{bmatrix} 3 \\ 2 \end{bmatrix}$$

In words: spread the vector into more slots, kill the negative ones, then mix what survives back down. The block's answer for this token is $\begin{bmatrix} 3 \\ 2 \end{bmatrix}$.

Why expand and then contract? The widening gives the block scratch space โ€” room to test many little feature-questions at once ("does this vector look cat-ish and verb-adjacent?"), keep the ones that fired past the bend, and recombine them. Real proportions: the middle is typically 4× the stream width (GPT-3: a 12,288-wide stream expands to a 49,152-slot middle). And a fact worth saying out loud โ€” roughly two-thirds of a big model's parameters live in these MLP blocks. Most of the machine, by weight, is private thinking.

The conveyor: residual stream and layer norm

Now the assembly principle that makes deep stacks workable โ€” and the close of Gap 4. Neither block replaces a token's vector. Each block's answer is added onto it. The running vector that flows through the whole machine, collecting additions, is the residual stream. Blocks are editors scribbling margin notes, never authors rewriting the page.

Worked example (continued)

The stream carried $\begin{bmatrix} 2 \\ 1 \end{bmatrix}$ into the MLP block; the block computed $\begin{bmatrix} 3 \\ 2 \end{bmatrix}$; so the stream leaves as the sum:

$$\begin{bmatrix} 2 \\ 1 \end{bmatrix} + \begin{bmatrix} 3 \\ 2 \end{bmatrix} = \begin{bmatrix} 5 \\ 3 \end{bmatrix}$$

In words: add the block's answer onto the stream that fed it. The original $\begin{bmatrix} 2 \\ 1 \end{bmatrix}$ is still in there โ€” nothing learned upstream is thrown away. That is precisely Gap 4 closing: depth without amnesia.

(One honest forward note, no detail: this add-don't-replace design is also what will let blame flow backward through 96 layers when we train the thing โ€” Part III cashes this in.)

The last small part. Before each block, a layer norm re-centers and re-scales the stream vector so its numbers sit in a standard range. Think volume knob, not thought: after many additions the stream's numbers could drift huge or tiny, and blocks behave predictably only on healthy-sized inputs. We'll skip its arithmetic deliberately โ€” it is bookkeeping, and you lose nothing by reading it as "keep the numbers sane." (Our toy arithmetic above skipped it too.)

Assemble one full layer and the figure below appears: norm, then attention (talk to the other tokens), add to the stream; norm, then MLP (think alone), add to the stream. That unit โ€” two detours off a conveyor โ€” is one layer, and it is the only structural idea left between you and the whole machine.

A thick horizontal residual-stream line runs left to right across the figure, labeled 'token's vector in' on the left and 'out โ€” same width' with an arrowhead on the right. Along it, from left to right: a small 'norm' knob gadget on the stream; a branch dropping to a violet-bordered box reading 'attention โ€” talk to the other tokens' with a mint accent dot, returning up to a plus-sign junction on the stream annotated '+ adds, never replaces'; a second 'norm' knob; a second branch to a violet-bordered box reading 'MLP โ€” think alone' with a blue accent dot, returning to a second plus-sign junction. A thin bracket above the whole run is labeled 'one layer'.
One layer, honestly drawn. The stream flows left to right and is never replaced โ€” each block is a detour whose answer is added back on at a ⊕. Two detours per layer: attention (the only place tokens talk) and the MLP (where each token thinks alone). Norms before each block keep the numbers in a healthy range. Violet borders mark where the learned weights live.

The full stack

Stack that layer and you're done. Read the figure below from the bottom up and you have the whole journey: text becomes tokens (Chapter 7), tokens become embeddings plus seat stamps (Chapter 8 + this chapter), the vectors rise through layer after layer after layer, then one final norm, one final matrix, softmax, probabilities, and a sampled token (Chapter 9). Every stage is a chapter you have already lived.

A single vertical pipeline read from the bottom up. At the bottom, an input chip reads 'the cat sat on the'. Above it, a row of five token chips the, cat, sat, on, the labeled 'tokens โ€” Ch. 7'. Above that, five short mint vector bars each wearing a small blue seat badge numbered 1 to 5, labeled 'embeddings + seat stamps โ€” Ch. 8 + 11'. Above that, a stack of three identical violet-bordered layer boxes each reading 'attn plus mlp plus', with a vertical ellipsis between the second and third and a side note 'x L layers (12 in GPT-2 small, 96 in GPT-3)'. Above the stack, a small 'norm' knob, then a tall thin violet-bordered rectangle labeled 'unembedding โ€” V x d_model' with a sub-caption 'one row per vocabulary token'. Above that, a mini bar chart of five mint bars with the tallest labeled 'mat', captioned 'softmax to p(next given context) โ€” Ch. 9'. At the top, an output chip reading 'mat'. A dashed arrow leaves the output chip and sweeps down the right margin back to the input, labeled 'append and run again'.
The whole machine, no missing pieces. Text becomes tokens, tokens become stamped embedding vectors, the stack of layers does its talking-and-thinking $L$ times, and one final matrix plus softmax turns the last vector into a belief over every token in the vocabulary. Roll the die, append the winner, run it all again โ€” that loop is text generation, entire.

Time to name the width symbol properly. The stream's width โ€” how many numbers each token's vector carries โ€” is called $d_{\text{model}}$ (say it "d-model, the width of the stream"). Our toys used 2 or 3; GPT-3 uses 12,288. And depth in real machines: GPT-2 small stacks 12 layers, GPT-3 stacks 96. Same layer design, photocopied โ€” with its own learned matrices in every copy โ€” then stacked.

The last stop deserves its own beat. After the final layer, the stream vector at the last position is multiplied by one final matrix โ€” the unembedding matrix, which is $V$ rows tall (one row per token in the vocabulary, with $V \approx 50{,}000$ in GPT-class models) and $d_{\text{model}}$ columns wide. Each row dots the stream vector โ€” Chapter 2's move, one last time โ€” producing $V$ logits. Softmax turns them into $p(\text{next} \mid \text{context})$, and the die rolls. Every promise from Chapter 9 is now mechanically redeemed.

And now "$N$-billion parameters" becomes furniture instead of fog. Here is the complete list of where the numbers live: the embeddings ($V \times d_{\text{model}}$ numbers), each layer's attention lenses (the query, key, and value matrices plus the output matrix, per head) and its MLP pair ($\mathbf{W}_1$ and $\mathbf{W}_2$ โ€” the bulk), and the unembedding matrix at the end. That's it. There is no other place a parameter can hide.

Then the generation loop, plainly: sample a token, append it to the context, run the whole stack again for the next one. Word by word, forever โ€” that's the entire show, a loop you have now seen the inside of.

See it move

You have drawn the machine part by part; now watch it get built in motion. The video opens the box from Chapter 9 and rebuilds it from parts โ€” seat stamps, the two detours of one layer, the stack rising, and the final softmax choosing "mat." Every number that moves on screen is one you have met.

Watch (2:29): what to notice โ€” the three-lane residual stream that never gets overwritten, the ⊕ junctions where each block's answer is added, the two mini heat-maps inside the attention block, and the stack rising to a softmax that towers "mat" over the field.

Why the LLM cares

This section usually points forward โ€” but this chapter is the LLM, so let's do the opposite and run the machine once, end to end, in a single breath. "The cat sat on the" arrives; the tokenizer chops it into tokens (7); each token becomes an embedding arrow (8) and picks up its seat stamp (this chapter); then, ninety-six times in a row, every token asks its questions and mixes its neighbors' values (10, via dot products from 2 and matrices from 3), and then thinks privately through two matrices and a bend (3, 4), each result added onto its stream (this chapter); the last token's final vector is dotted against every row of the unembedding matrix (2), softmax spreads the belief (6, 9), the die rolls (6), and "mat" appears. No step in that sentence is hand-waving anymore โ€” each has a chapter number bolted to it.

Now notice what is conspicuously absent, because its absence is the deepest fact about LLMs. There are no grammar rules. No dictionary. No fact tables. No logic engine. Just the architecture you can now draw, run at widths and depths that are hard to picture. Everything an LLM "knows" is encoded in how the violet matrices transform vectors, and nowhere else.

Which sets up the obvious, enormous question for Part III. This chapter's machine, fresh off the drawing board, has every violet entry set to random noise โ€” run it now and it produces confident gibberish. The entire difference between that noise-machine and the assistant you've talked to is the values of the numbers. Where do the right numbers come from? That is Part III โ€” and you already hold its tools: a downhill compass (5) and a way to spread belief (6).

What you now know

  • Attention by itself is order-blind, so the transformer adds a seat stamp โ€” a position vector โ€” to every embedding before the first layer: same word, different seat, different vector.
  • A layer runs many attention heads in parallel, each with its own learned query, key, and value matrices asking its own kind of question; their answers are concatenated and mixed back to stream width by one more learned matrix.
  • The MLP block is where each token thinks privately: expand with one matrix, apply a bend (ReLU: negatives become 0), contract with another โ€” our toy took $\begin{bmatrix} 2 \\ 1 \end{bmatrix}$ to $\begin{bmatrix} 3 \\ 2 \end{bmatrix}$ โ€” and roughly two-thirds of a big model's parameters live in these blocks.
  • Nothing overwrites the residual stream; every block's answer is added on (our stream left as $\begin{bmatrix} 2 \\ 1 \end{bmatrix} + \begin{bmatrix} 3 \\ 2 \end{bmatrix} = \begin{bmatrix} 5 \\ 3 \end{bmatrix}$), with layer norms keeping the numbers healthy before each block.
  • The full machine is: tokens → stamped embeddings → $L$ identical-shaped layers (12 in GPT-2 small, 96 in GPT-3, stream width $d_{\text{model}}$ up to 12,288) → final norm → unembedding matrix ($V$ rows) → softmax → sample → append → repeat.
  • There are no other parts โ€” no grammar module, no fact table. Everything the model knows lives in how its learned matrices transform vectors.

Where we're headed. The machine is assembled โ€” and, fresh off the drawing board, it is an idiot. Every violet matrix starts as random noise, so the first thing a newborn transformer produces is confident gibberish: it will happily assign "the cat sat on the" a next word of "purple" or "quantum." The entire difference between that noise-machine and the model you've talked to is the values of the numbers โ€” and to fix numbers, you first need a score that says how wrong they currently are. One single number, computable for every prediction, honest about degrees of wrongness. Building that score โ€” the loss โ€” is Part III's opening move, and it turns out the logarithm you met in Chapter 4 has been waiting for exactly this job.