How Large Language Models Work
The Transformer, Visualized
A 37-minute, 14-chapter explainer of how a large language model produces text, following one sentence, "The Eiffel Tower is located in the city of", through every stage of a real model. Every number on screen comes from GPT-2 small (OpenAI, 2019, 124M parameters): its real tokenizer, embeddings, attention heads, MLP neurons, position vectors and predictions. Learning is shown with a real training run of a tiny transformer on Shakespeare. Schematics are labeled as schematics.
Contents
- 1One token at a time2 min
- 2Text into tokens3 min
- 3Tokens into vectors3 min
- 4The plan: refine every vector with context3 min
- 5Attention: letting tokens talk3 min
- 6Attention in matrix form, and many heads5 min
- 7Word order3 min
- 8The MLP: where knowledge lives4 min
- 9Stacking the blocks2 min
- 10From a vector to a prediction3 min
- 11How it learns4 min
- 12Scale3 min
- 13From autocomplete to assistant2 min
- 14Recap1 min
Also on this page: Lecture · Notes and sources · Build the film.
Lecture
The text of each chapter is the film's narration, as it is spoken, so you can read along or revise without the film. The pictures are in the film.
1One token at a time2 min
Type this into a language model: The Eiffel Tower is located in the city of... and ask it what comes next.
It won't answer with a single word. It answers with a probability for every possible next piece of text. Here's what GPT-2, a real model released by OpenAI in 2019, says. Paris is its top guess, at about six percent, with London close behind.
Now pick a token, append it to the text, and ask again. And again. And again.
Today's AI chatbots write every reply exactly like this: one small piece at a time. Predict what comes next, append it, repeat. That's all a large language model does.
So the real question is: how does a pile of arithmetic produce such sensible guesses? The answer is a design called the transformer, introduced in 2017 by researchers at Google, in a paper titled Attention Is All You Need. It's the T in GPT: generative pre-trained transformer.
In this video we'll open the box and follow our sentence through every stage: how text becomes tokens, tokens become vectors, how attention lets those vectors share information, what the MLP layers do, and how it all turns into a prediction.
Every number you'll see comes from GPT-2 small, a model with 124 million parameters. It's tiny by today's standards, but it's built on the same blueprint as today's large language models. Then we'll see how it learns, what changes when you make it bigger, and how a text predictor becomes an assistant.
What it establishes: An LLM outputs a probability for every next token; text is written by predict → append → repeat. Roadmap.; Real data on screen: GPT-2's top-8 next-token distributions for 4 greedy steps ("Paris" 6.4%, then ", France.").
2Text into tokens3 min
Step one. A language model can't read letters. Text first gets chopped into pieces, called tokens.
Common words, like the, or city, get a single token each. And notice that the space in front of a word is usually part of its token. A rarer word, like Eiffel, gets broken into smaller pieces: E, iff, el.
Each token is really just a number: its position in a fixed list, called the vocabulary. GPT-2's vocabulary has 50,257 entries. From here on, the model never sees letters again; only these numbers.
Another example. A long but common word, like unbelievable, gets a token of its own. But ChatGPT didn't exist when this vocabulary was built, in 2019, so it gets split into three pieces.
Why chop text up this way? You could use single characters. Then the vocabulary is tiny, but every sentence becomes a long sequence, and the model has to work harder just to see the words. Or you could use whole words. Sequences are short, but the vocabulary needs every word, name and typo ever written, and anything new is a dead end. Subword tokens are the compromise.
The vocabulary itself is built by an algorithm called byte-pair encoding. Here it is on a tiny, made-up collection of words, each with a count of how often it appears. Start with single characters as the vocabulary.
Now count how often each pair of neighboring symbols appears, weighted by how common each word is. The winner is o followed by w, 30 times. Merge that pair into a new symbol, everywhere it occurs, and add it to the vocabulary.
Then repeat. Now l and o w appear together 21 times, so they merge into low. Next, e and r become e r. Then tow, tower, and slow.
Frequent chunks, like low, tower, and the ending e r, become single tokens, while rarer words get spelled out of smaller pieces. GPT-2's tokenizer starts from the 256 possible bytes and runs 50,000 merges like this over a large body of text. Add one special token that marks the end of a document, and you get its 50,257 tokens.
So our sentence has become a list of integers. But the number 6342 tells the model nothing about what Paris is. The next step is to give every token a much richer description.
What it establishes: Text → subword tokens → integer IDs. Why subwords. Byte-pair encoding, merge by merge. 256 + 50,000 + 1 = 50,257.; Real data on screen: GPT-2's tokenization and IDs (" E", "iff", "el"; "Chat", "G", "PT"); vocabulary entries; BPE run on a toy corpus.
3Tokens into vectors3 min
The first thing the model does with each token is look it up in a giant table, called the embedding matrix. It has one column for every token in the vocabulary, all 50,257 of them, and each column holds 768 numbers.
So the token Paris, number 6342, picks out its column, and becomes these 768 numbers: a vector. Nobody chooses these numbers by hand. They start out random and get tuned during training, like every other number in the model.
Every token in our sentence gets its own vector this way. I'll draw each one as a column of cells, standing in for its 768 numbers.
A list of two numbers can be drawn as an arrow, or a point, in a plane. In the same way, a list of 768 numbers is a point in a space with 768 dimensions. We can't picture that, but we can project it down to two. Here are GPT-2's embeddings of 35 words, flattened onto the two directions in which they vary the most.
Nobody told the model which words belong together. Yet the numbers land together, so do the days of the week, countries, animals, and colors. Words used in similar ways end up with similar vectors.
Directions in this space can carry meaning too. Here's a different slice through the same space, chosen to show this. The step from man to woman is nearly the same as the step from uncle to aunt, and from king to queen.
So try some arithmetic. Take the vector for king, subtract man, and add woman. Then search the whole vocabulary, leaving out the three words we started with, for the token whose vector points most nearly the same way. In GPT-2's real embeddings, the winner is queen.
The same trick takes you from Paris, minus France, plus Japan, to Tokyo. It doesn't work for every pair of words, but it's a striking sign that directions in this space can encode concepts, like gender, or 'capital city of'.
One operation will matter more than any other for the rest of this video: the dot product. Multiply two vectors entry by entry, and add up the results. Geometrically, it measures how much two vectors point the same way.
It's positive when they're aligned, zero when they're perpendicular, and negative when they point in opposite directions. Divide by the two lengths, and you get what's called the cosine similarity.
Measured on GPT-2's embeddings, cat is much more similar to dog and kitten than to banana, or to democracy. So tokens are now vectors, and similar tokens point in similar directions.
What it establishes: Lookup in W_E; vectors as points; clusters; directions carry meaning; dot product and cosine similarity.; Real data on screen: 2D PCA of 35 real embeddings (5 tight clusters); king − man + woman → queen; Paris − France + Japan → Tokyo; cos(cat, ·).
4The plan: refine every vector with context3 min
But there's a problem. In 'we walked along the river bank', and 'we deposited cash at the bank', the token bank gets exactly the same vector, because there's only one entry for it in the table.
Its meaning, though, depends on the words around it: river in one case, cash in the other. The same is true of nearly every word. The vector from the lookup table is only a starting point.
That's what the rest of the network is for. Start with each token's vector. In a transformer, these vectors flow upward through a stack of layers. In each layer, there's first an attention step, where the vectors exchange information with each other.
Then comes a step called an MLP, which processes each vector on its own, without looking at the others.
Crucially, neither step replaces a vector. Each one computes a small adjustment, and adds it to the vector that's already there. Because of this, the column of vectors running up through the network is called the residual stream. Think of it as a shared workspace that every layer reads from and writes to.
GPT-2 small repeats this pair of steps 12 times, each layer with its own learned weights. At the very top, the vector at the last position is used to predict the next token.
One more rule. When the vectors exchange information, each position may only look at itself and at positions before it, never after. We'll see why when we get to training.
We can watch this happen inside GPT-2. Take the vector at the bank position in each of our two sentences, and measure how similar they are, using cosine similarity, after each layer. Before the first layer, they're identical. Then, layer by layer, they drift apart, as each one absorbs its own context.
For comparison, here's bank in a different sentence that also talks about a river. Those two stay almost identical all the way up. The network has pulled the two meanings of bank apart.
So the heart of a transformer is this mixing step. How does bank know to pull information from river, and not from walked? That's the job of attention.
What it establishes: Context problem ("bank"). Attention mixes, MLP processes, both add to the residual stream. Causal rule.; Real data on screen: Similarity of the two "bank" vectors layer by layer: river vs. money drops 1.0 → ≈0, river vs. river stays ≥ 0.89.
5Attention: letting tokens talk3 min
Let's zoom in on a single attention step, from the point of view of the token bank. Bank would like to ask a question: is there anything earlier in the text that tells me what kind of bank I am?
It encodes that question as a vector, called a query, by multiplying its own vector by a matrix, called W Q. The query is shorter: in GPT-2, just 64 numbers.
Meanwhile, every token, including bank itself, produces a key, using a second matrix, W K. Think of a key as an advertisement: here's what I have to offer.
Bank's query is compared with every key, using a dot product. A higher score means a better match. These are real numbers, from one of the attention heads in GPT-2's very first layer, and river has the highest score.
To turn scores into weights, the model uses a function called softmax. It raises e to the power of each score, which makes everything positive and exaggerates the differences, then divides by the total, so the weights add up to one. Now, sixty percent of bank's attention goes to river.
So what actually gets passed along? Each token also produces a third vector, its value, using a third matrix, W V. The value is the information a token hands over to anyone who attends to it.
Bank's update is a weighted sum of all the values, mostly river's value, plus a little of the others. And that update gets added to bank's vector.
In a cartoon picture: if one direction in the space meant money, and another meant riverside, bank's starting vector would sit somewhere in between. The update from attention nudges it toward the riverside meaning.
Every token does this at the same time, each with its own query. Collect all the weights in a grid, and you get what's called an attention pattern. Each row is one token looking back over the text, and each row adds up to one. The bottom row is bank, with river lit up.
The gray triangle is off limits: a token may never look at tokens that come after it. In practice, those scores are set to minus infinity before the softmax, so their weights come out as exactly zero. This is the rule we met earlier, and we'll see why it matters when we get to training.
What it establishes: Query, key, score, softmax, value, weighted sum, update. Attention pattern. Causal mask (−∞).; Real data on screen: A real first-layer head (L0H7): scores, softmax weights (60% on "river"), full 6×6 pattern.
6Attention in matrix form, and many heads5 min
In practice, all of this happens for every token at once. Stack the token vectors as the rows of one matrix, X.
Multiply X by W Q, and you get a matrix Q, holding every token's query in its rows. Likewise for the keys, and the values.
Now compare every query with every key in one go: that's Q times K transpose, a grid of scores with one row and one column for each token.
Then divide by the square root of d k, which we'll come back to in a moment. Add the mask, minus infinity everywhere a token would look ahead. And apply softmax to each row. That gives the attention pattern.
Finally, multiply by V. Each row of the result is one token's weighted sum of values: its update. That's the whole attention formula from the 2017 paper, and now every piece of it should make sense.
So why divide by the square root of d k? d k is the length of each query and key: 64 in GPT-2. A dot product adds up 64 products, and if those are random-ish numbers around one in size, the sum typically lands around plus or minus eight: the square root of 64.
Feed scores that large into softmax, and nearly all the weight piles onto a single token, which makes training slow and unstable. Divide by eight, and the weights stay spread out enough to learn from.
A single attention pattern can only capture one kind of relationship at a time. So each layer runs several attention heads in parallel, each with its own query, key and value matrices. GPT-2 small has 12 heads in every layer. Each works with queries and keys of 64 numbers, and 12 times 64 is 768.
Each head produces its own update for each token. These are placed side by side, and multiplied by one more matrix, W O, which mixes them into a single update, added to the residual stream. With the four matrices W Q, W K, W V and W O, that's about 2.4 million parameters per attention layer.
So what do real heads actually do? Nobody designs them: their matrices start out random, and whatever they end up doing emerges from training. Here are three from GPT-2.
This one, in layer 5, sends almost all of each token's attention to the token immediately before it. It copies information about the previous token into each position. That sounds trivial, but it turns out to be a building block for something cleverer.
Many heads look like this one: nearly all of their attention lands on the very first token. On this sentence, about two thirds of GPT-2's heads put most of their weight there. It seems to be a resting place: since the weights must add up to one, a head with nothing useful to contribute parks its attention on the first token, which contributes very little.
The third is the most interesting. Feed in a short list of words, then repeat it. On the second pass, at each word, this head looks back at the word that came right after that same word's first appearance. When it reaches river the second time, it looks at lamp, the word that followed river last time. It's called an induction head.
Its rule amounts to: if this word appeared before, attend to whatever came after it, and predict that again. It relies on a previous-token head from an earlier layer, like the first one we saw, to know what preceded each word.
Watch what that does to GPT-2's predictions. Here's a random list of 20 words, followed by the same list again. For each word, the bar shows the probability GPT-2 gave it, just before it appeared. The first time through, the words are random, so every bar is tiny.
The second time, it predicts almost every word. It has picked up a pattern from its own context, something it was never explicitly taught. This is a simple form of what's called in-context learning, and induction heads seem to be one of its basic mechanisms.
What it establishes: softmax(QKᵀ/√d_k + M)V built term by term. Why √d_k. Multi-head, W_O, 2.4M params/layer. Three real heads. Induction → in-context learning.; Real data on screen: All 12 heads of L5; previous-token head L4H11; first-token "sink" head L5H1; induction head L5H5 (0-based; shown 1-based on screen); P(next word) on a random 20-word list repeated: ≈0 then ≈0.8.
7Word order3 min
There's a gap in what we've built so far. Nothing in attention knows where a token is: queries, keys and values depend only on each token's vector. Take the sentence 'dog bites man', and look at it from the point of view of the last token, the period. It sees three words, and takes a weighted sum of their values.
Now swap dog and man. The period sees exactly the same three words, with the same values, and a weighted sum doesn't care about order. So at least in the first layer, it computes exactly the same thing, even though the sentences mean very different things.
The fix: give each position its own vector, and add it to the token's vector before the first layer. Now the same word at a different position starts out as a slightly different vector.
In GPT-2, these position vectors are learned during training, just like the token embeddings: one for each of the 1,024 positions the model can handle. Here they are as a heat map, with position running down, and some of the dimensions running across. Training discovered smooth, wave-like patterns.
Now project all 1,024 position vectors onto their three most important directions, and they trace out a smooth spiral. Neighboring positions get similar vectors, so the model can tell both where a token is, and roughly how far apart two tokens are.
Many newer models, including Meta's Llama family, use a different trick, called rotary position embeddings. Instead of adding a position vector, they rotate the queries and keys. Split each query and key into pairs of numbers, and think of each pair as an arrow in a plane.
A query at position m is rotated by m times some angle, and a key at position n by n times that angle. In the dot product, only the angle between the two arrows matters, and that depends only on m minus n.
So slide both tokens along by the same amount: both arrows turn together, and the dot product doesn't change. Attention becomes sensitive to how far apart two tokens are, which is usually what matters in language, rather than to their absolute positions.
Different pairs of numbers rotate at different speeds, like the hands of a clock. Fast pairs distinguish nearby positions; slow pairs keep track of long distances.
So now each vector knows what its token is, where it sits, and, through attention, what's around it. Next: the other half of every layer.
What it establishes: Attention is order-blind (first layer). Learned position vectors. RoPE: rotate q, k; dot product depends on m − n; clock hands.; Real data on screen: GPT-2's learned position embeddings: heat map (waves) and 3D PCA (a helix through 1,024 positions).
8The MLP: where knowledge lives4 min
After attention comes the second kind of step in every layer: a multilayer perceptron, or MLP. Unlike attention, it works on each position separately. The vectors don't talk to each other here. And every position goes through the very same MLP, with the same weights.
An MLP does three things. First, it multiplies the vector by a big matrix, expanding it from 768 numbers to 3,072. Then it applies a simple nonlinear function to each of those numbers. Then a second matrix brings it back down to 768 numbers, and the result is added to the residual stream.
Here's a useful way to read it. Look at a single neuron. Its incoming weights, one row of the first matrix, form a direction in the space. Taking the dot product with it asks a question: how much does this token's vector point that way? Add a bias, and that's the neuron's input.
The nonlinearity, called GELU, squashes negative inputs to nearly zero, and passes positive ones through. So each neuron is either quiet, or firing.
And when neuron i fires, its outgoing weights, one column of the second matrix, are added to the vector, scaled by how strongly it fired. So the whole MLP is a sum: a long list of directions, each one switched on by its own question.
So, in a cartoon version: by the time our prompt reaches some layer, the vector at the word 'of' might encode that the text mentions the Eiffel Tower, and that a city name should come next. A neuron whose question matches that combination fires, and writes a direction meaning Paris into the vector.
Real models are messier: each fact seems to be spread across many neurons, and each neuron takes part in many different things. But experiments that edit or switch off parts of these layers suggest that the MLPs store much of what a model knows.
Here are the real neurons of one of GPT-2's MLP layers, at the last token of our prompt. Out of 3,072, only about one in thirty fires strongly. The rest stay close to zero.
The two matrices hold about 4.7 million parameters per layer: twice as many as attention. In large models, that makes the MLPs home to most of all the weights.
Here's a puzzle. A space with 768 dimensions has room for only 768 directions that are exactly perpendicular to each other. Yet a model seems to know about far more than 768 different things.
Part of the answer is a strange fact about high-dimensional space. Pick random directions in three dimensions, and the angles between them are all over the place. In 30 dimensions, they bunch up around ninety degrees. In 768 dimensions, almost every pair is within a few degrees of perpendicular.
In fact, the number of directions you can fit that are all nearly perpendicular grows exponentially with the dimension. Models appear to take advantage of this, packing many more features than they have dimensions into the same space, each in its own nearly perpendicular direction. Researchers call this superposition, and it's one reason the insides of these models are so hard to read.
What it establishes: Up-project, GELU, down-project. Neurons as questions; columns as answers; MLP = Σ GELU(r·x + b) c. Facts (cartoon). Superposition.; Real data on screen: The 3,072 real GELU activations of the 11th block's MLP (L10) at the last token (~1 in 30 firing); random-direction angle histograms in 3, 30, 768 dims.
9Stacking the blocks2 min
Let's assemble one complete layer, called a transformer block. Picture the residual stream as a line running upward. The attention step branches off, reads the current vectors, and adds its result back in. Then the MLP does the same: it reads, and adds its result back in.
One detail I've skipped: before each branch reads the stream, the vector passes through a layer norm. It shifts each vector so that its numbers average to zero, rescales them to a standard size, then applies a learned scale and shift. This keeps the numbers in a healthy range as they pass through dozens of layers, which makes training much more stable.
A useful summary of the two halves: attention moves information between positions. The MLP processes the information sitting at each position.
Then stack these blocks, one on top of another. GPT-2 small has 12. GPT-3 has 96. Embeddings go in at the bottom, and the prediction comes out at the top.
Now we can count every single parameter in GPT-2 small. The token embedding table: 50,257 tokens times 768 numbers, about 38.6 million. Position embeddings: under a million. Each attention layer: about 2.4 million, each MLP: about 4.7 million, plus a few thousand for the layer norms.
Multiply the per-block numbers by 12, add everything up, and you get 124,439,808 parameters: the 124 million in GPT-2 small's name. Notice that almost a third of this small model is just the embedding table. In bigger models, the blocks dominate.
What it establishes: x ← x + Attn(LN(x)); x ← x + MLP(LN(x)). LayerNorm. Stack of 12.; Real data on screen: Exact parameter tally of GPT-2 small: 124,439,808.
10From a vector to a prediction3 min
At the top of the stack, take the vector at the last position, the one for 'of'. By now, it has absorbed information from the whole prompt. After one last layer norm, it's time to turn it into a prediction.
The vector is compared, by dot product, with a vector for every token in the vocabulary. GPT-2 simply reuses its embedding table for this. The result is 50,257 scores, called logits, one for each possible next token.
Here, GPT-2's raw logits all happen to sit around minus 95. That doesn't matter: adding the same number to every score doesn't change softmax, so only the differences count. Softmax turns them into probabilities, and Paris comes out on top, at about six percent.
In fact, every position in the sequence makes a prediction like this, for the token that follows it. To generate text we only need the last one; during training, as we'll see, all of them are used.
Here's a fun trick, called the logit lens. Nothing stops us from applying this final step early, to the residual stream after any layer, and asking: what would the model predict right now? After the embedding alone, Paris sits at rank 22,947. The early layers mostly guess 'the'.
Around the middle, place names start to appear: England, Rome. After layer 9, Paris is 13th; after layer 10, second; after layer 11, first. You can watch the answer take shape, layer by layer.
To generate text, we have to pick a token from these probabilities. Here's GPT-2's distribution after a more open-ended prompt: once upon a time, there was a... Always picking the top choice is called greedy decoding.
But greedy decoding tends to get stuck in loops: a man who was a man of great wealth and power. He was a man of great wealth and power. He was a man of great wealth and power...
So instead, we usually sample at random, in proportion to the probabilities, after first dividing every logit by a number called the temperature. A temperature below one sharpens the distribution toward the top choices. Above one, it flattens it out, giving unlikely tokens more of a chance.
Here are real samples from GPT-2. At a temperature of 0.7, it writes about a bright star in the sky. At 1, it gets more surprising. At 1.6, the long tail of unlikely tokens takes over, and it dissolves into word salad. Many applications use temperatures somewhere between about 0.7 and 1.
What it establishes: Unembedding (tied), logits, softmax (shift-invariance). Logit lens. Greedy loops. Temperature.; Real data on screen: Real logits (≈ −95) and probabilities; logit lens: rank of "Paris" 22,947 → 1; real samples at T = 0, 0.7, 1.0, 1.6.
11How it learns4 min
Every number we've seen so far, the embeddings, the attention matrices, the MLP weights, all 124 million of them, starts out random. A freshly initialized model has no idea what comes next: its predictions are spread almost evenly, about one in fifty thousand for every token.
To improve, the model needs a score. Take any text, and at each position, look at the probability the model gave to the token that actually came next. The loss is minus the logarithm of that probability. If the model was certain and right, the loss is zero. For our Paris, at six percent, it's 2.75. A model that guesses uniformly scores about 10.8. Averaged over lots of text, this one number is what training tries to make small.
And one piece of text gives a prediction at every position at once. Here are GPT-2's real losses on our sentence. After 'The', the token E was a big surprise. But once it has seen E and iff, the model is certain that el comes next, and then Tower. Paris costs 2.75.
This is why the causal mask matters. Each position's prediction may only use the tokens before it, so all of these predictions can be trained at the same time, in parallel, without any of them getting to see its own answer.
So how do you improve 124 million numbers at once? Measure the loss on a batch of text. For every parameter, calculus tells you how the loss would change if you nudged it slightly; together, these slopes make up the gradient. Move every parameter a small step downhill, and repeat, on fresh text, millions of times. This is gradient descent.
Computing 124 million slopes sounds expensive, but there's a trick: apply the chain rule backwards through the layers, reusing work as you go, and you get all of them for roughly the cost of a couple more forward passes. That algorithm is called backpropagation.
To see learning happen, I trained a tiny transformer from scratch. It's the same design as GPT-2, but with just 0.8 million parameters, four layers, and single characters as tokens, trained on about a million characters of Shakespeare. Here's its real loss curve. It starts at the loss of random guessing, and falls fast.
At step zero, it produces random characters. After a hundred steps, it has learned which letters are common, and that text comes in chunks separated by spaces.
By step 300, there are short real words, line breaks, and made-up names in capitals, followed by a colon, just like the speaker names in a play.
By step 1,000: real words, real names, like Gloucester, and the rhythm of dialogue.
And after 4,000 steps, about a quarter of an hour on four ordinary processor cores, it writes this. It's not great Shakespeare, but nobody told it about spelling, words, names, or line breaks. All of it came from predicting the next character.
GPT-2 learned in exactly the same way, just bigger: predicting the next token across about 40 gigabytes of text from the web.
What it establishes: Random init. Loss = −log p. Every position trains at once (why the mask). Gradient descent, backprop.; Real data on screen: GPT-2's per-token losses on the sentence; a 0.8M-param char-level GPT trained from scratch: loss curve + samples at steps 0, 100, 300, 1000, 4000.
12Scale3 min
Everything so far has been GPT-2 small. OpenAI actually released four sizes of GPT-2, all with the same design, just wider and deeper. Let's give each of them our prompt. The smallest gives Paris six percent. The next one up: 69. The one after that: 60, so it's not perfectly smooth for any single prompt. And the largest, with one and a half billion parameters, puts 93 percent on Paris.
In 2020, researchers at OpenAI measured this systematically, training language models across a huge range of sizes. The loss followed a smooth power law. On a log-log plot, that's a straight line, and it held over many orders of magnitude: in model size, in the amount of training data, and in compute.
Two years later, DeepMind's Chinchilla study refined the recipe: for a fixed compute budget, model size and training data should grow together, at roughly twenty tokens of training text for every parameter. That's how you get the most out of each unit of compute.
Here's how much models have grown, with area showing parameter count. Our GPT-2 small is this speck. The largest GPT-2: 1.5 billion parameters. GPT-3, in 2020: 175 billion parameters, 96 layers, vectors of 12,288 numbers, trained on 300 billion tokens. Meta's Llama 3.1, in 2024, one of the largest models whose details are public: 405 billion parameters, 126 layers, trained on about 15 trillion tokens. Most frontier labs no longer publish these numbers.
A handy rule of thumb for the cost: training takes about six arithmetic operations per parameter, per token of training text: two for the forward pass, and four more for backpropagation. For GPT-3, that's about 3 times 10 to the 23 operations. For Llama 3.1, about 4 times 10 to the 25, which matches what Meta reported.
Modern models also refine many details: rotary positions, which we saw, simpler normalization, gated MLPs, attention heads that share keys and values to save memory, and mixture-of-experts layers, where each token is routed to just a few of many MLPs, so a model can hold far more parameters than it uses for any one token. And context windows have grown from GPT-2's 1,024 tokens to hundreds of thousands. But the blueprint is the one we've just walked through.
What it establishes: Same blueprint, bigger. Power laws. Chinchilla. Model sizes. C ≈ 6ND. Modern refinements.; Real data on screen: P("Paris") for GPT-2 small/medium/large/XL: 6% → 69% → 60% → 93%; Kaplan et al.'s fitted law.
13From autocomplete to assistant2 min
A model trained only to predict text from the internet is not an assistant. It's a document completer. Ask the largest GPT-2 to write a short poem about the ocean, and it continues the document the way such documents often continue: by repeating the instruction. Again, and again.
Ask it a question, and it answers, then invents the next question, as if it were writing a quiz.
A chatbot is the same machine, completing a different kind of document: a transcript, with special tokens marking who's speaking. Your message goes in the user's slot. Then the model predicts what the assistant says, one token at a time, until it predicts a special token that means: end of turn.
Turning a document completer into an assistant takes extra training. First comes everything we've seen: pretraining on enormous amounts of text, which is where the language and the knowledge come from. Then supervised fine-tuning, on example conversations written by people, with the very same next-token loss, now applied to the assistant's replies. Then, learning from feedback: people compare pairs of answers, a separate reward model learns to predict which ones they prefer, and the language model is tuned with reinforcement learning to produce answers that score well.
This matters more than you might think. In OpenAI's 2022 InstructGPT paper, people preferred the answers of a 1.3 billion parameter model trained this way over those of the original GPT-3, which is more than a hundred times larger.
More recently, models are also trained with reinforcement learning on problems whose answers can be checked automatically, like math and programming. Models trained this way learn to write out long chains of reasoning before they answer, and get much better at hard problems. But underneath it's still the same loop: predict the next token, append it, repeat.
That also explains a familiar failure. The model always produces a plausible-sounding continuation, whether or not it happens to be true. So it can state something false with complete fluency, which is why checking claims, and grounding models in reliable sources, is an active area of work.
What it establishes: Base models complete documents. Chat = transcript with role tokens. Pretraining → SFT → RLHF. RL on checkable tasks. Fluent ≠ true.; Real data on screen: Real GPT-2 XL completions (repeats the poem request; answers, then writes the next quiz question).
14Recap1 min
Let's put it all together. Text is chopped into tokens. Each token becomes a vector, plus a vector for its position. Those vectors flow up through a stack of blocks, where attention lets them share information, the MLPs process what each one holds, and every step adds to the residual stream.
At the top, the last vector is compared with every token in the vocabulary, and softmax turns the scores into probabilities. One token is chosen, appended, and the whole thing runs again.
Here's the part I find most remarkable. None of what we found inside GPT-2, the head that links bank to river, the induction heads, Paris emerging layer by layer, was designed by anyone. The architecture fits in a few pages of code. Everything else was learned, from one simple objective: predict the next token.
Working out, in detail, what all those billions of learned numbers are actually doing is still an open scientific problem, and a very active one, called interpretability. You now know the machine they live in.
Thanks for watching.
What it establishes: The whole loop in one picture. Learned, not designed. Interpretability.; Real data on screen: Callbacks to the real heads and logit-lens curve.
Notes and sources
Sources
Fact-check notes and sources
- Transformer: Vaswani et al., Attention Is All You Need, NeurIPS 2017 (Google). Scaled dot-product attention softmax(QKᵀ/√d_k)V; the √d_k motivation (large dot products push softmax into regions with tiny gradients) is theirs.
- GPT-2: Radford et al., Language Models are Unsupervised Multitask Learners, 2019. WebText: ~40 GB of text from ~8M web pages. Sizes 124M/355M/774M/1.5B; 12/24/36/48 layers; widths 768/1024/1280/1600; context 1,024. BPE vocabulary of 50,257 (256 byte tokens + 50,000 merges +
<|endoftext|>). Parameter counts on screen are measured from the checkpoints. - BPE: Sennrich, Haddow & Birch, Neural Machine Translation of Rare Words with Subword Units, ACL 2016.
- Rotary embeddings: Su et al., RoFormer, 2021. Used by Llama 3 (Meta 2024, "RoPE (θ = 500,000)").
- Induction heads / in-context learning: Elhage et al., A Mathematical Framework for Transformer Circuits, 2021; Olsson et al., In-context Learning and Induction Heads, 2022. Previous-token and induction heads in GPT-2 small: Wang et al., Interpretability in the Wild, 2022.
- Attention sinks: Xiao et al., Efficient Streaming Language Models with Attention Sinks, 2023. The video hedges ("seems to be a resting place").
- MLPs as key-value memories / factual recall: Geva et al., Transformer Feed-Forward Layers Are Key-Value Memories, EMNLP 2021; Meng et al., Locating and Editing Factual Associations in GPT (ROME), NeurIPS 2022. The Eiffel-Tower neuron is explicitly a cartoon.
- Superposition: Elhage et al., Toy Models of Superposition, 2022. Near-orthogonality of random high-dimensional vectors (std of the angle ≈ 1/√d rad, ≈ 2° at d = 768) is computed on screen.
- Logit lens: nostalgebraist, interpreting GPT: the logit lens, 2020.
- Scaling laws: Kaplan et al., Scaling Laws for Neural Language Models, 2020, arXiv:2001.08361. Eq. 1.1: L(N) = (N_c/N)^α_N with α_N ∼ 0.076, N_c ∼ 8.8 × 10¹³ non-embedding parameters; trends "spanning more than seven orders of magnitude"; "C ≈ 6N floating point operators per training token". The plotted line is this fitted law, not new data.
- Chinchilla: Hoffmann et al., Training Compute-Optimal Large Language Models, 2022 (≈20 tokens per parameter; 70B model on 1.4T tokens).
- GPT-3: Brown et al., Language Models are Few-Shot Learners, 2020, Table 2.1: 175B, 96 layers, d_model 12,288, 96 heads, context 2,048, "trained for a total of 300 billion tokens"; Table D.1: 3.14 × 10²³ training FLOPs (6 × 174.6B × 300B).
- Llama 3.1 405B: Llama Team, Meta, The Llama 3 Herd of Models, 2024, arXiv:2407.21783: "pre-trained using 3.8 × 10²⁵ FLOPs", "405B trainable parameters on 15.6T text tokens", "126 layers, a token representation dimension of 16,384, and 128 attention heads", RoPE.
- InstructGPT: Ouyang et al., Training language models to follow instructions with human feedback, NeurIPS 2022: "outputs from the 1.3B parameter InstructGPT model are preferred to outputs from the 175B GPT-3, despite having 100x fewer parameters". Pipeline: SFT on demonstrations → reward model on rankings → PPO.
- Reasoning models: OpenAI o1 (Sep 2024); DeepSeek-AI, DeepSeek-R1, Jan 2025 (RL with rule-based, verifiable rewards). Named on screen only as examples.
- Modern refinements (Ch. 12): RMSNorm (Zhang & Sennrich 2019), SwiGLU (Shazeer 2020), grouped-query attention (Ainslie et al. 2023), mixture of experts (Shazeer et al. 2017; Fedus et al. 2021). Context windows of hundreds of thousands of tokens (e.g. 128K for Llama 3.1; longer for some commercial models).
- Tiny Shakespeare:
karpathy/char-rnndata/tinyshakespeare/input.txt(1,115,394 characters of Shakespeare's plays, public domain).
The video describes the field as of October 2026 only in general terms (frontier labs rarely publish sizes; context windows of hundreds of thousands of tokens). No claims are made about undisclosed models.
What is computed and built
| Run | What | Used in |
|---|---|---|
gpt2_small |
All probes of GPT-2 small (~15 s on CPU): tokenization, embeddings, PCA, analogies, residual streams, head patterns and scores, position embeddings, MLP activations, logit lens, logits, samples, per-token losses, parameter counts. | 1–11, 14 |
gpt2_family |
P("Paris") for all four GPT-2 sizes; GPT-2 XL greedy completions. | 12, 13 |
tiny_shakespeare |
explainer/lm/tiny_gpt.py: 4 layers, 4 heads, width 128, context 128, 818,048 parameters, 65 characters as tokens, 4,000 AdamW steps (batch 32) on Tiny Shakespeare (~14 min on 4 CPU cores). |
11 |
Scenes never run a model; they read the cached JSON/NPZ. Every number the
narration states is asserted against the data at render time (e.g. assert steps[0]["argmax"] == " Paris"), so a regenerated dataset that disagrees with
the script fails loudly instead of silently contradicting the voice-over.
Method notes (so the visuals can be reproduced and are not over-read)
- GPT-2 checkpoints:
openai-community/gpt2{,-medium,-large,-xl}via Hugging Facetransformers, eager attention, fp32, CPU. No BOS token is prepended. - Embedding clusters (Ch. 3): plain PCA of the 35 centered input embeddings (W_E rows), top two components.
- Analogy plane (Ch. 3): axes are the mean of the (woman − man, queen − king, aunt − uncle) offsets and the mean of (king − man, queen − woman), orthogonalized; a linear projection, so the drawn sum is exactly the projection of king − man + woman. The nearest-token search is over all 50,257 normalized input embeddings and excludes the three input words; including them, the nearest token is "king" itself (cos 0.78 vs 0.71 for "queen"), as is typical for this test (Nissim et al. 2020).
- "bank" similarity (Ch. 4): cosine similarity of the residual-stream vectors at "bank" after each block, after subtracting each layer's mean residual vector (measured on a fixed reference paragraph, skipping position 0). Without centering, GPT-2's few huge shared dimensions dominate every cosine (Ethayarajh 2019; Timkey & van Schijndel 2021); the qualitative result (different meanings diverge, same meaning stays close) holds either way. Sentences are chosen so "bank" sits at the same position in all three.
- Attention heads: the layer-0 "bank" head (L0H7) was found by searching for heads where "bank" attends to "river"; L4H11 and L5H5 are the strongest previous-token and induction heads by the scores in
gpt2.head_scores(they match the heads reported by Wang et al. 2022). Layer and head numbers on screen are 1-based for a general audience; in the usual 0-based notation, L4H11 is shown as "layer 5, head 12". - First-token fraction (Ch. 6): fraction of the 144 heads whose mean attention to position 0 (from positions ≥ 3) exceeds 0.5 on the example sentence: 68%.
- Position heat map (Ch. 7): every 4th position, the 64 dimensions with the largest variance across positions (mean removed), ordered by dominant frequency then phase. The helix is PCA of all 1,024 position vectors (top 3 components explain 90% of the variance).
- MLP activations (Ch. 8): GELU outputs of block 11 (0-based layer 10), last position; "firing strongly" means > 0.5.
- Logit lens (Ch. 10): residual stream after k blocks → final LayerNorm → tied unembedding.
- Samples (Ch. 10):
gpt2.sample, torch generator seed 3 for every temperature; greedy for T = 0.
Chapter notes
| # | Scene | What it establishes | Real data on screen |
|---|---|---|---|
| 1 | Hook |
An LLM outputs a probability for every next token; text is written by predict → append → repeat. Roadmap. | GPT-2's top-8 next-token distributions for 4 greedy steps ("Paris" 6.4%, then ", France."). |
| 2 | Tokens |
Text → subword tokens → integer IDs. Why subwords. Byte-pair encoding, merge by merge. 256 + 50,000 + 1 = 50,257. | GPT-2's tokenization and IDs (" E", "iff", "el"; "Chat", "G", "PT"); vocabulary entries; BPE run on a toy corpus. |
| 3 | Embeddings |
Lookup in W_E; vectors as points; clusters; directions carry meaning; dot product and cosine similarity. | 2D PCA of 35 real embeddings (5 tight clusters); king − man + woman → queen; Paris − France + Japan → Tokyo; cos(cat, ·). |
| 4 | BigPicture |
Context problem ("bank"). Attention mixes, MLP processes, both add to the residual stream. Causal rule. | Similarity of the two "bank" vectors layer by layer: river vs. money drops 1.0 → ≈0, river vs. river stays ≥ 0.89. |
| 5 | AttentionIdea |
Query, key, score, softmax, value, weighted sum, update. Attention pattern. Causal mask (−∞). | A real first-layer head (L0H7): scores, softmax weights (60% on "river"), full 6×6 pattern. |
| 6 | AttentionMatrix |
softmax(QKᵀ/√d_k + M)V built term by term. Why √d_k. Multi-head, W_O, 2.4M params/layer. Three real heads. Induction → in-context learning. | All 12 heads of L5; previous-token head L4H11; first-token "sink" head L5H1; induction head L5H5 (0-based; shown 1-based on screen); P(next word) on a random 20-word list repeated: ≈0 then ≈0.8. |
| 7 | Position |
Attention is order-blind (first layer). Learned position vectors. RoPE: rotate q, k; dot product depends on m − n; clock hands. | GPT-2's learned position embeddings: heat map (waves) and 3D PCA (a helix through 1,024 positions). |
| 8 | MLP |
Up-project, GELU, down-project. Neurons as questions; columns as answers; MLP = Σ GELU(r·x + b) c. Facts (cartoon). Superposition. | The 3,072 real GELU activations of the 11th block's MLP (L10) at the last token (~1 in 30 firing); random-direction angle histograms in 3, 30, 768 dims. |
| 9 | TransformerBlock |
x ← x + Attn(LN(x)); x ← x + MLP(LN(x)). LayerNorm. Stack of 12. | Exact parameter tally of GPT-2 small: 124,439,808. |
| 10 | NextToken |
Unembedding (tied), logits, softmax (shift-invariance). Logit lens. Greedy loops. Temperature. | Real logits (≈ −95) and probabilities; logit lens: rank of "Paris" 22,947 → 1; real samples at T = 0, 0.7, 1.0, 1.6. |
| 11 | Training |
Random init. Loss = −log p. Every position trains at once (why the mask). Gradient descent, backprop. | GPT-2's per-token losses on the sentence; a 0.8M-param char-level GPT trained from scratch: loss curve + samples at steps 0, 100, 300, 1000, 4000. |
| 12 | Scale |
Same blueprint, bigger. Power laws. Chinchilla. Model sizes. C ≈ 6ND. Modern refinements. | P("Paris") for GPT-2 small/medium/large/XL: 6% → 69% → 60% → 93%; Kaplan et al.'s fitted law. |
| 13 | Assistant |
Base models complete documents. Chat = transcript with role tokens. Pretraining → SFT → RLHF. RL on checkable tasks. Fluent ≠ true. | Real GPT-2 XL completions (repeats the poem request; answers, then writes the next quiz question). |
| 14 | Outro |
The whole loop in one picture. Learned, not designed. Interpretability. | Callbacks to the real heads and logit-lens curve. |
The visual languageColor legend (consistent across every scene)
| Concept | Color |
|---|---|
| token boxes, raw text | light grey |
| token vectors, residual stream | blue |
| position vectors | pink |
| query q, W_Q | yellow |
| key k, W_K | teal |
| value v, W_V, attention updates | red |
| attention scores, weights, patterns, softmax | orange |
| MLP, neurons, GELU | purple |
| logits, probabilities, predictions | green |
| loss | maroon |
| layer norm | grey |
Build the film
python tools/build.py llm # render and assemble the film
EXPLAINER_TTS=silent python tools/qa_scene.py llm Hook # one chapter, silent, with a contact sheet
Scenes: videos/ml/llm. Setup: see the course page. Source of these notes: the README and the scenes' narration.