Part II · Ch. 11 — The Transformer

Part II · Chapter 11 of 21

The Transformer

Stacking attention into a thinking machine


The machine, so far

Attention lets tokens exchange information. A transformer adds position information, parallel attention units, per-token processing, and a path through many layers. Let's assemble the decoder model behind our next-token predictor.

What attention alone still needs
NeedComponent
Position informationPosition embeddings or position-dependent rotations.
Several matching patternsMultiple attention heads.
Process gathered informationAn MLP at each position.
Build deep computationsResidual additions and normalization.

Stamping the seats

Without position information, query-key scores travel with their tokens when we reorder the input. A causal mask restricts access by order, but explicit position information provides a richer signal.

Without positions a permutation preserves token dot products; with seat stamps the vectors change.
Positions distinguish token orders.

A position embedding adds a seat-specific vector to a token's embedding.

Worked example

We stamp with toy integers, invented 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 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 same cat sitting in seat 5, whose stamp is $\begin{bmatrix} 0 \\ 0 \\ 2 \end{bmatrix}$, enters as $\begin{bmatrix} 0 \\ 1 \\ 2 \end{bmatrix}$, a different arrow for the same word. Queries and keys computed from these vectors can now ask about position, so "what's the word right before me?" has an answer.

Some position vectors are learned; others use fixed wave patterns. Rotary position embeddings instead rotate queries and keys according to position. These are alternative implementations of the position signal.

Many spotlights: multi-head attention

A head computes one attention pattern. Multi-head attention lets several patterns coexist.

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 at an opacity matching their share.
Different heads follow different relations.

Head 1 reuses Chapter 10's masked shares. Head 2 is illustrative: its sat row is 0.10,0.75,0.15. Each head produces its own vector. We concatenate those outputs, then apply a learned output matrix to restore the stream width. Two two-entry outputs become a four-entry list before that projection.

As a historical scale example, GPT-3's largest model has 96 heads per layer, with 128-number keys and queries.

Private thinking: the MLP block

An MLP is a multilayer perceptron. The transformer's MLP block processes each position separately: expand, bend, project back.

Our bend is ReLU. Other models use smooth activations such as GELU or gated feed-forward blocks.

Worked example

Work every digit on a fresh two-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}$.

The intermediate width provides room for feature combinations. A common classic design expands to four times the stream width: GPT-3 uses 12,288 → 49,152 → 12,288. In that design, MLP matrices account for roughly two-thirds of the main layer weights.

The conveyor: residual stream and layer norm

The residual stream carries information through the stack. A residual connection updates that stream by addition.

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}$ contributes directly to the sum.

Addition gives a direct path through the computation and later through its derivatives. It does not guarantee that earlier information remains recoverable: additions can cancel or alter it.

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 box reading 'attention — talk to the other tokens' with an 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 box reading 'MLP — think alone' with an accent dot, returning to a second plus-sign junction. A thin bracket above the whole run is labeled 'one layer'.
Residual branches add to the running stream.

Layer norm centers and rescales a copy of the stream before a block in this pre-norm layout. We skip its arithmetic in the toy example. Other architectures use related normalizations.

A layer contains both detours. Each layer owns its own learned weights.

The full stack

Two columns trace tokens, embeddings and positions, repeated attention and MLP layers, final normalization, unembedding, softmax, and sampling; the output loops back to the input.
Every new token passes through the stack.

The width $d_{\text{model}}$, “d-model,” counts entries in each stream vector. V is vocabulary size and n is the token count. The unembedding matrix has V rows and d-model columns.

Trace one layer and its output by shape
StageIn → outShape
Embedding + positionIDs → stream vectorsn → n × d-model
NormalizationStream → normalized block inputn × d-model, unchanged
Attention + output projectionAcross-token mixing → stream updaten × d-model, unchanged
Residual additionStream + update → streamSame shape on both sides
Norm + MLP + addPer-position processing → streamWiden internally, return to d-model
Final norm + unembeddingLast stream vector → logitsd-model → V
Softmax and selectionLogits → shares → one tokenV → V → 1

GPT-2 small uses 12 layers; the largest GPT-3 uses 96. The figure uses L for layer count; Part III uses L for loss, a different quantity.

Parameters live in embeddings, attention projections and output maps, MLP matrices, normalization scales and offsets, and sometimes biases and learned position embeddings. Input and output embedding weights may be shared. Append the selected token and compute the next prediction.

See it move

Watch the stream acquire each block's update. Follow the last position to the vocabulary scores.

Watch (2:29): follow the residual stream through the additions, inspect the attention heads, and watch the final scores become a distribution.

Why the LLM cares

We can now trace the forward computation: tokens become position-aware vectors, layers exchange and process information, and the final projection produces next-token scores.

The architecture supplies the recipe. The parameter values determine its behavior. Random initial values do not yet make a useful language model; learning must find values that predict well.

What you now know

  • Position information lets attention use sequence location.
  • Heads compute parallel attention patterns and combine their outputs.
  • An MLP processes each position independently.
  • Residual additions connect the stack; normalization prepares block inputs.
  • The final projection produces one logit per vocabulary token.
  • Each layer has learned parameters that training must set.

Where we're headed

The machine is assembled. Next we'll measure prediction error, giving training a number to reduce.