Key takeaways
- The body of a Transformer is one building block stacked L times: token IDs → embedding lookup, giving a tensor of shape (B,T,D) → through L layers → final Norm → LM head gives logits → softmax turns them into a probability table.
- The residual stream is the model's backbone. Every sublayer reads a copy, works out a change, and adds it back. Information can travel straight from the bottom to the top, and gradients can ride the stream straight back down.
- Each layer = attention + a feed-forward network (FFN), with a Norm at the entrance of each branch. That arrangement is called pre-norm. Attention is the only place where positions exchange information, and it only looks backward (the causal mask). The FFN works on each position separately.
- The probability table at position t predicts token t+1, so in training every position in a sentence is a practice question.
- The shape stays (B,T,D) the whole way, which is why the same layer can be stacked again and again.
Opening the black box
In episode 0 we saw what a language model does: give it some text, like "The fat cat sat", and it hands back a probability table for the next word. The box in the middle is called a Transformer, and this episode opens it up.
You might expect a terrifyingly complicated tangle in there. It's actually the opposite: the main body is one kind of building block, stacked layer after layer. The smallest GPT-2 stacks 12 of them; the 8 billion parameter version of Llama 3 stacks 32. Every layer has exactly the same structure. Only the parameters inside differ.
To understand it, we need to answer three questions:
- How does text become numbers?
- What happens to those numbers inside each layer?
- How do they turn back into probabilities at the end?
So we'll follow a single token, say "sat", from the moment it enters the model to the moment it becomes a prediction.
The whole map
Here's the whole pipeline, left to right:
- Input: a sequence of token IDs.
- Token embedding: swaps each ID for a vector. From here on, every token is represented by a list of numbers.
- Residual stream: these vectors flow to the right along one main line.
- Layer after layer: in each layer, attention comes first, letting the tokens swap information with each other. Then a feed-forward network lets each token do some processing on its own. The results of both steps are added back onto the main line. At the entrance to each branch sits a small normalization step, called Norm, which brings the numbers back to a sensible size.
- Exit: a layer like this is stacked L times. After the last one comes one final normalization, and then the LM head gives a score to every token in the vocabulary.
- Softmax turns those scores into probabilities, and we're back to our familiar probability table.
Intuition: A Transformer language model is essentially "turn words into vectors → stack L layers (each = attention + FFN, both with residual connections) → map back onto the vocabulary".
The original Transformer was built for translation and came in two halves: an encoder and a decoder. Today's large language models keep only the decoder half, which is why they're called decoder-only.
Dimension cheat sheet: B, T, D, V, L
Everything flowing through the model is just blocks of numbers. Let's use "The fat cat sat" to meet the letters that describe their size:
- The sentence is split into 4 tokens. The number of tokens in a sequence is T, so here T=4.
- Each token gets a vector, whose length is D, the hidden dimension. To keep the animation small, D is just 4. Stack the 4 vectors row by row and you get a T×D table. Real models have a much bigger D: 768 for GPT-2, and 4096 for the 8 billion parameter Llama 3.
- During training we usually feed in several sentences at once and process them in parallel. The number of sentences is B, the batch size.
- So the data flowing through the model is a three-dimensional block of numbers, B×T×D. A multi-dimensional block of numbers like this is called a tensor.
- V is the vocabulary size (how many tokens the model knows), and L is the number of layers (how many times the building block is stacked).
Later we'll meet the number of heads N, the size of each head H, the width of the feed-forward network F, and a few more. Here's the full cheat sheet to come back to whenever a letter looks unfamiliar:
| Symbol |
Meaning |
| B |
number of sequences in the batch |
| L |
number of layers |
| T |
sequence length (tokens to generate) |
| S |
sequence length (provided context) |
| V |
vocabulary size |
| D |
hidden dimension |
| H |
head dimension |
| F |
MLP hidden dimension, generally F=4D |
| N |
number of query heads, N⋅H=D |
| K |
number of key/value heads, K<N in GQA |
| G |
group size in GQA, G=N/K |
First stop: the embedding
Say our toy vocabulary has just 6 tokens, numbered 0 through 5.
Inside the model is a big table called the embedding matrix, We∈RV×D. Every token in the vocabulary gets one row, and each row is a D-dimensional vector, so the table has V rows and D columns. To turn "sat" into a vector, we take its ID, 3, and copy out row 3 exactly as it is. That's all there is to it: a table lookup.
The numbers in this table start out random and get adjusted, little by little, during training along with all the model's other parameters. So they are parameters too (the animation draws parameters in purple).
A lookup is actually a kind of matrix multiplication. Write "sat" as a one-hot vector: length V, with a 1 in position 3 and 0 everywhere else. Multiply it by the embedding matrix. A row vector times a matrix means: use each of its numbers to weight the matching row, then add everything up. Every other row gets multiplied by 0 and vanishes; only row 3 is multiplied by 1, so the sum is exactly row 3. Of course, no real implementation bothers multiplying by all those zeros. It just grabs the row by its ID, which is faster and cheaper.
Do this for every token in a whole batch of sentences, and you get the initial hidden state, X(0), with shape (B,T,D):
X(0)=We[tokens]∈RB×T×D
Watch out: This step only cares which token it is, not where it sits. "Dog bites man" and "man bites dog" look up exactly the same set of vectors. So position has to be added some other way. The early GPT-2 adds a learnable position vector right here. Most of today's models use rotary position embedding, RoPE, which brings in position inside attention. That's the topic of episode 8.
The residual stream: an information highway
The vectors coming out of the embedding flow into the residual stream. It's the backbone of the whole model, and every position has a stream like this.
Every sublayer along the stream follows the same rule: read a copy from the stream, work out a change, then add that change back onto the stream. As a formula:
x←x+f(x)
The new x is the old x plus whatever the sublayer f computes from it. We add it back; we don't replace x.
Some illustrative numbers: the vector for "sat" is (0.5,−0.1,0.3,0.8), and the change Δ computed by attention is (0.2,0.4,−0.1,−0.3). Add them entry by entry and we get (0.7,0.3,0.2,0.5). Then the feed-forward network adds a change of its own, and the vector shifts again.
Each sublayer only ever adds a small edit. Expand the equations step by step, and something rather beautiful shows up:
x2=x1+Δ2=x0+Δ1+Δ2
Keep expanding all the way, and the final x is just the original embedding x0 plus the sum of every sublayer's change: x0+Δ1+Δ2+⋯. So the backbone works like a highway: information from the bottom layers can travel straight to the top, and each layer just adds a little something along the way.
This matters for training too. Remember from episode 3: an addition node passes the gradient from above to both of its inputs, unchanged. So the gradient coming back from the loss can ride the stream straight down to the very first layer.
Intuition: Without residuals, the gradient has to pass through every single transformation. If each layer multiplied it by 0.5, then after 30 layers only 0.530, about one billionth, would be left, and the bottom layers would barely learn at all.
Inside a layer: attention + feed-forward
Now step inside one layer:
- Right at the entrance, a branch splits off the stream. It copies the vector, normalizes it, and feeds it into attention. The output of attention is added back onto the stream.
- Then the second branch: normalize again, feed it into the feed-forward network, and add the result back onto the stream.
As formulas, that's just two lines, and those two lines are the entire layer:
xx←x+Attn(Norm(x))←x+FFN(Norm(x))
Pre-norm vs post-norm. Notice that Norm only sits on the branches; the stream itself never gets normalized. This arrangement is called pre-norm. The original Transformer from 2017 did it differently: it put Norm after the addition, right on top of the stream. That's post-norm. It means every layer re-normalizes the stream itself, which breaks up the straight-through highway, and once the model gets deep, training tends to become unstable. So starting with GPT-2, pretty much everyone switched to pre-norm. The catch is that nobody tidies up the stream along the way, so a final Norm has to go at the exit. We'll get to that at the finish line.
How the two branches split the work:
- Attention is the only place in the entire model where different positions can exchange information.
- The feed-forward network and Norm work on each position separately.
In short: talk first, then think. And attention's "talking" only points forward in time, a rule we'll come back to shortly.
Norm: bringing the numbers back to size
The most common Norm in modern models is RMSNorm. Let's try it on the vector (4,0,−2,4):
- Compute the root mean square (RMS): square each number, take the average, then take the square root. The squares are 16, 0, 4 and 16; their average is 9; the square root is 3:
RMS=416+0+4+16=9=3
- Divide every number by 3, giving (1.33,0,−0.67,1.33). The RMS of this new vector is exactly 1.
- Multiply each entry by its own learnable scale factor, γ. These are parameters, so the model decides for itself how big each dimension should be.
The general formula (⊙ means element-wise multiplication):
Xˉ=RMS(X)+ϵX⊙γ,RMS(X)=D1i=1∑Dxi2
The ϵ in the denominator is a tiny positive number, something like 10−5, that keeps us from dividing by zero when the vector is all zeros. Each layer has two sets of γ: γattn before attention and γffn before the FFN.
Why multiply by γ at all? The normalization step forces the hidden state to have unit RMS, which wipes out any scale information the model has learned. γ∈RD gives the network back per-feature control over magnitude: γi>1 amplifies dimension i, γi<1 suppresses it, and γi≈0 effectively switches it off.
This way, no matter how big the numbers on the stream get, attention and the feed-forward network always receive vectors of a sensible size. Why this matters so much, and how it differs from LayerNorm, is coming up in episode 9.
Attention: tokens look at each other
The problem: what a token means often depends on its context. In "Apple pie is delicious", Apple is a fruit. In "Apple launched a new phone", Apple is a company. From the vector for "Apple" alone there's no way to tell them apart; you have to look at the words around it.
How it works: each position takes its own (normalized) vector and multiplies it by three different weight matrices, WQ, WK and WV (parameters too), to compute three things:
- a query, q: what am I looking for?
- a key, k: what do I have?
- a value, v: if you pay attention to me, what do I hand you?
Then three steps:
- Take the query for "sat" and compute its dot product with the key at every position. The bigger the dot product, the better the match, and the higher the score. In the toy example, "sat" gives The, fat, cat, sat the scores −0.5, 0.3, 2.0 and 1.0.
- Run softmax over this row of scores, turning them into weights that add up to 1: 0.05, 0.11, 0.61 and 0.23.
- Use these weights to add up the value vectors from every position. About 60 percent of the output for "sat" comes from "cat". That's how it soaks up information from its context.
Every position does the same thing. Put all the scores together and you get a T×T square: row i holds the scores token i gives to every position.
The causal mask. There's one iron rule: each token may only look at itself and the tokens before it, never at the ones after it. During generation, the later words haven't been written yet. During training, the later words are exactly the answers we're trying to guess, so peeking would be cheating.
We enforce it by replacing every score above the diagonal with −∞. Since e−∞=0, those positions get a weight of exactly 0 after softmax. In code it usually looks like this:
scores = scores.masked_fill(~mask, -torch.inf)
The convention is that mask is True wherever a token is allowed to look, and tensor.masked_fill(mask, value) fills in value wherever mask is True. So we first flip the mask with ~, and then every forbidden position gets negative infinity.
In matrix form. The scores A equal Q times K transpose, divided by H, where H is the length of q and k. A single matrix multiplication handles the dot product of every query with every key:
A=HQK⊤∈RB×N×T×S
Then apply the causal mask (set positions with j>i to −∞) and run softmax along each row:
Aij←{Aij−∞j≤ij>i,A=softmax(A)=∑k=1Sexp(Aik)exp(Aij)
Finally multiply by V, taking a weighted sum of the values, to get the output of attention, O=AV.
Watch out: Why divide by H? Without it, dot products get bigger as the dimension grows (roughly like H). Large inputs to softmax make the distribution too peaky, the gradients get small, and training gets hard. Episode 7 works through this properly.
Multi-head attention and reshaping
Real models don't do attention just once. They slice the D dimensions into N chunks of H dimensions each, and every chunk runs its own attention. Each chunk is a head, so N×H=D. Different heads can learn to focus on different relationships: one might always watch the previous word, another the start of the sentence, another might spread its attention fairly evenly.
Tracking the shapes (the key to reading attention code):
| Step |
Shape |
| normalized Xˉ |
(B,T,D) |
| Q=XˉWQ |
(B,T,D) |
| split D into N×H |
(B,T,N,H) |
| swap T and N |
(B,N,T,H) |
| same for K, V |
(B,N,S,H) |
| K⊤ (swap last two) |
(B,N,H,S) |
| scores QK⊤ |
(B,N,T,S) |
| output O=AV |
(B,N,T,H) |
| swap back, join heads |
(B,T,D) |
| multiply by WO |
(B,T,D) |
A few notes:
- After swapping T and N, every head has its own T×H table.
- S is the length of the keys and values. During training S equals T; during generation with a KV cache the two differ, which is a story for episode 12.
- The rule for matrix multiplication: the number of columns in the first must match the number of rows in the second, and that shared size disappears. T×H times H×S gives T×S. Then T×S times S×H gives T×H.
- Finally, one more D×D output matrix, WO, mixes the results from all the heads, and the result goes back onto the residual stream:
Oproj=OWO,X(ℓ)←X(ℓ)+Oproj
After that whole detour, attention's output has exactly the same shape as its input, (B,T,D). That's why it can be added straight back onto the residual stream.
Detail one: grouped-query attention (GQA). Many newer models let several query heads share the same keys and values. The number of key-value heads is K, smaller than N, and each group of G=N/K query heads shares one. In the 8 billion parameter Llama 3, for example, N=32 and K=8, so G=4. The projection matrices therefore have shapes WQ∈RD×D and WK,WV∈RD×KH. K and V go from (B,S,KH) to (B,K,S,H), and before the computation they are simply copied out to N heads, (B,N,S,H). From there it's ordinary multi-head attention. This greatly cuts down how much data has to be cached during generation (more in episode 12).
Detail two: this is where RoPE does its work. Before the dot product, q and k are each rotated by an angle that depends on the token's position m; the later the position, the bigger the turn. For dimension pair i (indices 2i and 2i+1), the angle is mθi with θi=Θ−2i/H:
Rm(i)=[cos(mθi)sin(mθi)−sin(mθi)cos(mθi)],qm←Rmqm,km←Rmkm
That way the dot product carries position information, and it depends only on how far apart the two tokens are. Episode 8 has the details. Also, some models give q and k an extra RMSNorm each, called QK norm, to control the size of the vectors going into the dot product.
Feed-forward: each token thinks it over
The second branch is the feed-forward network (FFN). It's simply the multilayer perceptron from episode 1, applied to each position separately.
It goes wide, then narrow: project the D-dimensional vector up into a wider space of F dimensions, apply a nonlinear activation, then project back down to D. In the classic recipe F is 4 times D; in GPT-2, for example, 768 dimensions widen to 3,072, then shrink back to 768.
Modern models mostly use a gated version called SwiGLU:
- After an RMSNorm, run two projections side by side. One, called up, gives U; the other, called gate, gives G. Both Wup,Wgate∈RD×F.
- G goes through a Swish activation, the SiLU from episode 1: g⋅σ(g).
- Multiply it with U, element by element. After Swish, G acts like a row of valves, deciding how much of each number in U gets through.
- The F×D down matrix Wdown brings it back to D dimensions, and the result is added onto the residual stream.
U=XˉWup,G=XˉWgate
H=Swish(G)⊙U,Swish(G)=G⊙σ(G),F=HWdown,X(ℓ+1)=X(ℓ)+F
The shape goes (B,T,D)→(B,T,F)→(B,T,D). (Here H and F are just names for intermediate results, not the H and F from the cheat sheet.)
The gated version has one extra matrix. To keep the parameter count about the same as the classic 4× version, F is usually set to around eight thirds of D:
3DF=2⋅D⋅4D⇒F=38D
Intuition: In SwiGLU, both G and U contribute content. U provides one learned representation and G provides another, gating U by its own "confidence". Why gating helps is a story for episode 9.
The finish line: final Norm and LM head
After all L layers, the residual stream reaches the finish line:
- One last RMSNorm. In pre-norm the stream itself never gets normalized, and as layer after layer adds to it, the numbers can keep growing. So we tidy everything up once, at the exit.
- The LM head, also called the unembedding: a D×V matrix Wu turns each position's D-dimensional vector into V scores. These scores are called logits.
Xfinal=RMS(X(L))+ϵX(L)⊙γfinal,Z=XfinalWu∈RB×T×V
Back to the toy example. After every layer, the final vector at the "sat" position is (−0.6,1.2,0.3,1.1) (illustrative). Each column of Wu belongs to one token in the vocabulary, and the score for "on" is the dot product of the final vector with the "on" column:
(−0.6)(−0.4)+(1.2)(0.6)+(0.3)(0.2)+(1.1)(0.7)=1.79
Do the same for the other tokens and we get 6 scores, the highest belonging to "on". Softmax turns them into probabilities: "on" gets about 52%. That's exactly where the probability table from episode 0 comes from.
Intuition: Wu here is exactly the transpose of the embedding matrix. That's what GPT-2 does. It's called weight tying, and it saves a big chunk of parameters.
Every position puts out a probability table. The table at position t predicts token t+1. So in training, every position in a sentence is a practice question, and a single pass answers all T of them at once. Average the cross-entropy over those questions and you have the loss for the sentence. (Recall episode 5: with a one-hot target, cross-entropy is just the negative log probability of the correct token; summed over the sentence it's −∑t=1Tlogp(xt∣x<t), and dividing by the number of questions gives the average.)
Watch out: This is exactly why the causal mask is essential. If the "cat" position could see the "sat" that comes after it, it would simply copy the answer.
During generation we only care about the table at the last position. We pick the next token from it, append it to the end, and run the model again. How to pick is the topic of episode 11.
One token's complete journey
Let's put the whole journey together, following "sat" from start to finish and keeping an eye on its shape:
| Stage |
Shape |
| token IDs (integers) |
(B,T) |
| embedding lookup |
(B,T,D) |
| layer 1 … layer L |
(B,T,D) |
| final Norm |
(B,T,D) |
| LM head |
(B,T,V) |
| softmax |
(B,T,V) |
Along the residual stream, each layer only adds its own edits, so the shape stays (B,T,D) the whole way. Because the shape never changes, we can keep stacking blocks as high as we like. At the end, every position gets a probability table over the entire vocabulary, and at the "sat" position the most likely next token is "on". From an ID to a vector, through L layers, and back out as a probability table: The fat cat sat → on.
How big are real models? The smallest GPT-2 has 12 layers and a D of 768. The 8 billion parameter Llama 3 has 32 layers, a D of 4096, and a vocabulary of more than 128,000 tokens.
The parts keep evolving: GPT-2 uses LayerNorm, GELU and learned position vectors; Llama 3 swaps in RMSNorm, SwiGLU, RoPE and GQA. But the skeleton is the same. How many parameters live in all these matrices, and how much compute one pass takes, we'll add up line by line in episode 10.
Deep dive: the full computation for one layer ℓ
All the formulas scattered above, in the order they're computed, for easy comparison with code:
- RMSNorm (before attention): Xˉ(ℓ)=RMS(X(ℓ))+ϵX(ℓ)⊙γattn(ℓ)
- Q/K/V projections: Q=XˉWQ, K=XˉWK, V=XˉWV; optional QK norm; reshape to expose the head dimension (D→N×H) and transpose; for GQA, expand K, V from K heads to N heads.
- RoPE: qm←Rmqm, km←Rmkm.
- Scores: A=QK⊤/H, apply the causal mask, softmax along each row.
- Output: O=AV, reshape back to (B,T,D), Oproj=OWO, residual X(ℓ)←X(ℓ)+Oproj.
- FFN: RMSNorm (with γffn(ℓ)) → U, G → H=Swish(G)⊙U → F=HWdown → residual X(ℓ+1)=X(ℓ)+F.
After all L layers: a final RMSNorm (with γfinal), then Z=XfinalWu gives the logits.
Recap
- Text becomes token IDs, which are looked up in the embedding matrix to give a tensor of shape (B,T,D).
- The residual stream is the backbone. Each sublayer normalizes and reads a copy, then adds its change back; this is pre-norm. Information and gradients both travel straight along the stream.
- Each layer is attention plus a feed-forward network. Attention lets positions exchange information, looking only backward (the causal mask); the FFN lets each position work on its own. Talk first, then think.
- At the exit come a final Norm and the LM head, which produces logits; softmax turns them into probabilities. Position t predicts token t+1.
- The shape stays (B,T,D) the whole way, so the same layer can be stacked again and again.
Next time we take apart the attention we only skimmed today: what Q, K and V are really computing, why we divide by H, and how multiple heads work.