The transformer: Attention is all you need
In 2017, a team at Google working on machine translation published a paper with an unusually cocky title: Attention Is All You Need . The claim was that the attention mechanism (until then a bolt-on that helped RNNs translate) could replace recurrence entirely. The resulting architecture, the transformer, is the substance of every model in this book. GPT stands for Generative Pre-trained Transformer, and nine years later the architecture is nearly unchanged.
Chapter 2 left a network-shaped hole: something has to read the context’s embedding vectors and produce the next-token logits. This chapter fills it:
- The RNNs that held the job crushed the whole past into one fixed-size vector and processed tokens one at a time. We need a network that keeps every token’s vector and reads them all at once.
- One new primitive does it — attention: a differentiable lookup in which every token fetches what it needs from the tokens before it.
- Alternate attention with Chapter 1’s MLP along a residual stream (a per-token running vector each layer adds to — defined below), stack it deep, and you have a GPT. Everything since is this, scaled.
- The stack ends at a probability distribution, not text. A small loop outside the weights (the sampler) picks each token, and its knobs close the chapter.
The problem attention solves
Recall the RNN’s two flaws:
- Squeezing an arbitrarily long past into one fixed-size hidden state meant long-range information got crushed: by the end of a page, the beginning had been averaged into mush.
- The recurrence itself (each step consuming the previous step’s output) meant the computation was inherently serial: token 1,000 could not be processed until tokens 1 through 999 had been, no matter how much hardware you owned.
Start from what Chapter 2 handed us: after the embedding lookup, the context already is a list of vectors, one per token. The RNN’s defining decision was to fold that list, token by token, into a single running summary; the first flaw is that decision’s direct price: a thousand tokens of detail forced through one keyhole of fixed width (the hidden vector’s dimension — a few thousand numbers). So consider the opposite decision: don’t fold. Keep all vectors, and refine them in rounds. You’ve seen this organization before: Chapter 1’s MLP was built from stacked layers, each one taking the previous layer’s output and transforming it. The transformer keeps the word and scales up the unit: here, a layer takes all token vectors in and hands all vectors back, each one refined (what exactly happens inside a layer is this chapter’s remaining business). Stack a few dozen layers and token 500’s vector stays token 500’s vector all the way up the stack, refined at every layer.
But refusing to summarize creates a problem the RNN never had. If every token keeps its own vector, how does information move between them at all? In “the cat sat … because it was tired,” the vector for “it” is useless until something from “cat” gets into it — and which other tokens matter differs for every token, every sentence. We need a way for each token’s vector to reach into the rest of the context and pull in what’s relevant, selectively, with the selection itself learned. That mechanism is this chapter’s one invention.
The second flaw dies as a side effect of the first decision. Each token’s update depends only on the previous layer’s vectors (never on another token’s output at the same layer), so every position can be computed simultaneously. That quiet property let the architecture absorb all the parallel hardware money could buy: the subject of Chapter 4, and of Chapter 10, where we meet the hardware itself.
Attention: a differentiable lookup
Each token’s current vector is linearly projected into three new vectors, whose names tell you the whole story:
- a query — “what am I looking for?”
- a key — “what can I be found by?”
- a value — “what information do I carry?”
To update a token, take its query and dot it against every earlier token’s key — a big dot product means “relevant to me.” Softmax the scores into weights, then average the earlier tokens’ values using those weights. It’s a hash map with soft lookups: a normal map retrieves exactly one value per key; attention retrieves every value at once, weighted by how well each key matches the query. And because queries, keys, and values are all produced by learned matrices, gradient descent decides what each token should ask for, advertise, and carry.
Here’s the entire lookup with real numbers, small enough to check by hand — watch the pronoun “it” go looking for its noun:
| token | x | k | v | q·k | weight |
|---|---|---|---|---|---|
| the | [0, 1] | [1, 0] | [0, 1] | 0 | 0.04 |
| cat | [2, 0] | [0, 2] | [2, 0] | 4 | 0.73 |
| sat | [1, 1] | [1, 1] | [1, 1] | 2 | 0.18 |
| it | [0, 2] | [2, 0] | [0, 2] | 0 | 0.04 |
In symbols, with all tokens stacked into matrices, the whole thing is one line:
And in code, it’s a handful of matrix multiplies:
def attention(x, W_q, W_k, W_v): # x: (seq_len, d) — d_model in most codebases
Q, K, V = x @ W_q, x @ W_k, x @ W_v
scores = Q @ K.T / math.sqrt(K.shape[-1]) # (seq_len, seq_len)
scores = causal_mask(scores) # -inf above the diagonal
return softmax(scores, axis=-1) @ VTwo things about that snippet deserve their own sections: the causal_mask line, and something the code conspicuously lacks — any notion of where a token sits in the sequence.
Look back, never forward
During training, all positions are computed at once — which means position 5 could “cheat” by attending to position 6 and reading the future it’s supposed to predict. The causal mask prevents it: before the softmax, every score where a token would look forward is set to , so the softmax assigns it exactly zero weight.
This mask is what makes the model autoregressive — a term borrowed from time-series statistics whose etymology is its definition: auto- (self) + regression (the first tool this book reached for, back in Chapter 1). An autoregressive model regresses a sequence on itself — each value predicted from the values before it. Statisticians have fit autoregressive models to stock prices and weather for a century; a GPT is the same idea with a trillion-parameter regressor and tokens for data points. The mask is what enforces the “before”: each token predicts while seeing only its past.
The same mask makes training efficient: every position in the sequence becomes its own training example (predict token 2 from token 1, token 3 from tokens 1–2, …), and all of them are computed in a single parallel pass.
The mask figure’s score matrix also shows the architecture’s famous tax. That score matrix has one cell per query–key pair: tokens means cells, so doubling the context quadruples attention’s cost. This is why models advertise a context window (a maximum sequence length) and why long context is expensive enough that Chapters 5, 10, and 11 all spend time fighting the quadratic.
Many heads, many questions
One soft lookup per token is not enough. Resolving “it” needs one kind of question, tracking whether we’re inside a quotation needs another, and matching a closing bracket in code needs a third. So the mechanism is run many times in parallel: each head gets its own (smaller) learned , does its own lookup, and the results are concatenated. A single attention operation in a frontier model runs on the order of a hundred heads side by side — and the full model, as we’ll assemble in a moment, stacks on the order of a hundred such operations.
Heads learn their jobs the way all network weights do: gradient descent, nothing more. Some of what they learn turns out to be legible after the fact — previous-token heads (heads that always attend to the immediately preceding token) like the one above are among the best-documented circuits (small learned subnetworks with identifiable jobs) in interpretability, the field that reverse-engineers what networks learned (Chapter 6 tells that story).
Attention is a set operation
Look at the code again: beyond the mask’s before/after ordering, nothing in it knows where a token is. Shuffle the keys and values a token is allowed to see and its output is unchanged — attention treats the visible context as a set, not a sequence. “The cat chased the dog” and “the dog chased the cat” would be indistinguishable. Word order has to be injected explicitly.
The fix is unglamorous: make position part of the input. The original paper computed a positional encoding (a vector that depends only on the position number) and added it to each token’s embedding, so “cat as token 2” and “cat as token 9” enter the network as slightly different vectors, and attention can learn to care about the difference. Modern models use a cleverer scheme (RoPE, Rotary Position Embedding) that encodes relative position — “three tokens back” rather than “position #4,821,” which is what sentences actually care about. Its mechanics, and the tricks for stretching positions to million-token contexts, are Chapter 5’s business.
The MLP returns
Attention moves information between tokens, but does surprisingly little computation on it. So after each attention step, every token’s vector is passed (independently, in parallel) through an MLP: the exact architecture from Chapter 1, typically expanding to 4× the model width and back down (a convention from the 2017 paper that simply stuck).
The division of labor: attention routes, the MLP computes. Attention gathers the relevant context into a token’s vector; the MLP is where that vector gets processed — and, as Chapter 6 will show, where most of the model’s factual knowledge appears to live. In a standard transformer the MLPs hold roughly two-thirds of the parameters. When people say “a bigger model knows more,” they are mostly talking about MLP weights.
The computation as a spreadsheet
Here is the machine all those parts make, in a single mental image — the computation as a spreadsheet. One column per token. The top row is the embeddings; each row below is all vectors after one more layer. Watch it build, one cell at a time, and watch what each cell reads:
Every cell looked at exactly one place: the row above, columns up to its own. And notice what no cell ever read — a neighbor in its own row. Nothing within a layer depends on anything else within that layer, so there is nothing to wait for: an entire row can be computed in one parallel shot. Which is how it’s actually done —
The next token always comes from the bottom-right cell — everything else exists to make that one cell smart. And generation just appends a column: the new token’s cells are computed, and no existing cell changes — a finished column is finished forever. Which means each cell’s keys and values can be stored and reused instead of recomputed. That store is the KV cache; Chapter 11 is largely about its economics.
The residual stream
Now zoom in on a single column of that spreadsheet — one token’s vector, followed through the layers:
The “layer” promised at the chapter’s start is one attention step plus one MLP — each preceded by a normalization step that keeps the vectors’ magnitudes stable. That pair is called a block (papers use “block” and “layer” interchangeably): vectors in, refined vectors out. A model is a stack of them: 12 in GPT-2, on the order of a hundred in a frontier model. Each part doesn’t replace the token’s vector; it computes an update and adds it:
Make the addition concrete with the numbers from the attention walkthrough above. The token “it” entered attention as . The lookup returned — mostly cat’s vector. The update adds:
Look at what addition preserved: the original — everything “it” already was (a pronoun, in subject position) — is still in the vector, now joined by cat-ness. If the block had replaced the vector instead, the pronoun would have been overwritten by the cat; because it adds, the token accumulates. The MLP then reads the combined vector and adds its own contribution — perhaps, having seen “pronoun + cat + tired” together, something like sleepy animal. A later block’s attention can read that and route it to other tokens. Each token’s vector only ever gets richer.
That accumulating vector is the residual stream, and the mental model, standard in the interpretability field, is a shared memory bus: one stream per token, flowing up through the stack, with every attention head and every MLP reading from it, computing something, and writing the result back by addition:
Early layers tend to write low-level features, middle layers concepts and facts, late layers whatever converts it all into a concrete prediction.
How residual addition keeps hundred-block stacks trainable
If blocks replaced the vector, backprop would still work — the chain rule composes through anything differentiable. The problem is magnitude. The gradient reaching layer 1 would be a product of a hundred consecutive layer-derivatives, and any systematic shrinkage in those factors compounds exponentially — by the bottom of the stack the signal is numerically zero, and the early layers stop learning (the “vanishing gradient” problem that stalled deep networks for years). With , each block’s derivative is identity plus something: among all the paths the chain rule sums over, there’s always one straight shot of plus signs from the loss to every layer, unattenuated. Hundred-block stacks are trainable because of it.
Suppose the context said, pages ago, “Jack, a tall man with red hair, walked in,” and the model must now continue “Jack’s hair was ___”. A single attention lookup sounds hopeless for this: the token “hair” can attend back to “Jack,” but the token “Jack” is just a name — the redness lives three tokens away, on “red.” How can attending to unprocessed tokens answer a question whose answer is smeared across several of them?
It can’t — and it never has to. After the first block, attention reads the previous layer’s streams, not raw tokens. Somewhere in an early block, a head doing purely local work moved “red” into the stream above “Jack” — the column over that name now contains his hair color. By the time a late block’s query from “hair was” goes looking for facts-about-Jack, the answer has already been computed and parked where the name is; retrieval is one hop because earlier layers did the assembly. That’s what depth buys: each layer attends over the results of every layer below it, so one lookup becomes a pipeline of lookups over its own previous conclusions. The stream above a token is the model’s accumulating dossier on that position, and later layers consult the dossiers.
So here is the entire architecture, end to end:
- Look up each token’s embedding (Chapter 2).
- Pass the sequence through N blocks of attention → MLP, each reading from and writing to the residual stream.
- Project the final vector of the last token onto the vocabulary to get logits, softmax into a distribution (Chapters 1–2), and predict.
That’s it. There is no module labeled “grammar,” no knowledge base, no planner. Everything a frontier model does is implemented in the weights of these identical, repeated blocks — which is either deeply unsatisfying or the most interesting fact in computer science, depending on your mood.
Where do the parameters actually go? GPT-2, counted.
GPT-2 shipped in four sizes; the smallest (plain “GPT-2”, the 124M-parameter one) has width and stacks 12 blocks. Per block: the four attention matrices (, plus one to mix the heads’ outputs back together) are each, about M parameters. Heads, by the way, are free: this model runs 12 heads per block, each working in dimensions. The matrices are simply sliced across them, so slicing reshapes the lookups while the weight count stays fixed. The MLP expands to and back: two matrices totaling M (the MLP is 2× attention, right there). Times 12 blocks ≈ 85M. Add the embedding matrix (50,257 tokens × 768 ≈ 38.6M, shared with the output layer) and you land at ~124M, the number on the tin. Every transformer’s parameter count decomposes this way, and you can now read any model’s config file and check.
The lineage that won
The 2017 paper had two towers: an encoder reading the source sentence (every token attending in both directions — no causal mask, since nothing is being predicted left-to-right), and a decoder — the masked stack this chapter built — writing the translation. The years since sorted their descendants:
BERT -style encoders powered search and classification, and that branch is still very much alive. (An encoder has no causal mask — every token attends in both directions — so it can’t train on next-token prediction: each token would see its “answer” sitting right next to it. BERT’s objective is masked language modeling instead: blank out ~15% of the tokens and predict them from both sides, like a cloze test.) The embedding models behind semantic search today are encoders: their output is a single vector summarizing a whole text, so that similar texts land near each other (Chapter 2’s word embeddings, scaled up to entire documents). The reason falls out of the mask. The causal mask exists for one purpose: to keep next-token prediction honest, so no token peeks at its own future. An embedding model isn’t predicting anything; the full text is already on the table, and the job is to read it as well as possible. Hiding the end of a sentence from its beginning would only make the summary worse — so the mask comes off, and every token attends in both directions.
OpenAI’s GPT line took the decoder-only path: just the causal stack described in this chapter, trained on next-token prediction. GPT-2 (2019) showed one such model could do many tasks without task-specific training; GPT-3 (2020) showed what happens when you scale it 100×, which is Chapter 4’s story. Every frontier LLM today is decoder-only, but the embedding model sitting next to it in a retrieval pipeline is the encoder lineage, still on the job.
From distribution to text
The architecture is complete, but it still ends at a probability distribution: the model never emits text, and every demo you’ve ever seen depends on what happens next. Something outside the weights picks a token, appends it to the context, and runs the stack again; that loop is generation. The two basic moves: take the single most likely token every time (greedy decoding: safe, prone to ruts), or draw a token at random in proportion to its probability (sampling: livelier, occasionally derailed). Every knob on every API navigates between those poles.
The famous knob, temperature, rescales the logits before the softmax:
Dividing by changes the outcome because the exponential turns logit gaps into probability ratios: rescaling the logits rescales every gap, which reshapes every ratio. (Adding a constant to every logit, by contrast, cancels in the normalization — softmax is shift-invariant but scale-sensitive, and temperature lives in that asymmetry.) Run three candidates through it, with logits mat 4.0, sofa 2.0, floor 1.0:
- At : 84% / 11% / 4% — the model’s honest beliefs.
- At every gap doubles, so every ratio squares: 98% / 1.8% / 0.2%, nearly deterministic.
- At every gap halves, every ratio square-roots: 63% / 23% / 14% — the underdogs breathe.
Low temperature is not “more accurate” — it’s more conservative: you’re trading diversity for mode-seeking, always harvesting the distribution’s highest peak. The right trade for extraction tasks, often the wrong one for writing. (Training itself can also prune diversity before temperature gets a say; Chapter 8 names that failure when it builds the training that causes it.)
Why not always take the argmax? Pure greed degenerates into repetition loops (“I really really really really…”), each copy making the next more probable. And why not sample honestly? The long tail: of a frontier model’s ~100,000-token vocabulary, the bottom 90,000 are individually negligible but collectively carry enough mass that a catastrophic token occasionally gets drawn — and one bad token compounds, because generation has no backspace. Call that the autoregressive original sin: a sampled token enters the context permanently, and every later distribution conditions on it as if it were ground truth. Training never prepared the model for its own mistakes — the training context was always real corpus text (a setup called teacher forcing), so the model has only ever practiced continuing good prefixes, and errors compound with length (the textbook name is exposure bias). The fix, from The Curious Case of Neural Text Degeneration , is to amputate the tail: top-k keeps the k most likely tokens; top-p (“nucleus”) keeps the smallest set whose probabilities sum to p — narrow when the model is confident, wide when it isn’t. Modern defaults (temperature ~0.7–1.0 with top-p ~0.9–0.95) are the field’s accumulated scar tissue; nobody derived them.
Frequency and presence penalties subtract from the logit of every token already in the context (in proportion to its count, or a flat amount once), attacking repetition directly. Beam search — the machine-translation era’s standard decoder, which carries the most probable partial sequences instead of committing to one — is essentially never used for open-ended generation: repetition is self-reinforcing, so the highest-probability long sequence is often a loop, and beam search seeks it out even harder than greedy does.
No knob, though, makes the model compute longer on a hard problem, know a fact the weights never learned, or touch anything outside its context — and no temperature makes “valid JSON only” a guarantee. Programming the distribution harder than a knob can (masking it so malformed output is impossible, letting generated tokens trigger your code and searches) is Chapter 12, where the book ends.
We now have an architecture with no linguistic knowledge built in, trained by Chapter 1’s loop (predict, score, backpropagate, step), wired all the way to text. And the chief difference between the toy in this chapter and the model you talked to this morning is… size. That can’t be the whole story — can it? The next chapter is about the discovery that it nearly is: the relationship between size and ability is so lawful you can plan a frontier training run on graph paper, months before you can afford to run it.
Further reading
- Attention Is All You Need — the original. Shorter and more readable than its reputation suggests.
- The Illustrated Transformer — Jay Alammar’s visual walkthrough; the canonical companion to the paper.
- The Annotated Transformer — the paper reimplemented line-by-line in PyTorch.
- Let’s build GPT: from scratch, in code, spelled out — Karpathy building exactly the model in this chapter, in two hours. If you do one piece of homework from this book, make it this.
- nanoGPT — the same model as a clean, hackable repo; reading
model.pyafter this chapter is a genuine victory lap. - The Curious Case of Neural Text Degeneration — nucleus sampling, and the best analysis of why naive decoding fails.