The only thing an LLM does
You type on your phone, "I will reach home in", and the keyboard offers "10 minutes". It has not read your mind. It has seen millions of messages, and after "reach home in" a number of minutes usually comes.
Now imagine that keyboard grown enormous. It has read a large part of the internet, and it does not stop at one suggestion. It takes its own suggestion, adds it to the message, and suggests again. And again. That is a chatbot.
The question. When a chatbot writes a whole paragraph for you, what is it actually doing, step by step?
First, a word about words. The model does not read letters or whole words. It reads tokens: common words and pieces of rarer words, cut by the byte-pair method of Unit 16. GPT-2's list of tokens, its vocabulary, has 50 257 of them. In this unit a token is nearly always a whole word, to keep the pictures simple.
Here is everything a large language model (LLM) does. It is one loop of four moves.
- Read. Take every token written so far. Your question, the earlier chat and the part of the reply already written are all one long list of tokens.
- Score every token in the vocabulary. The transformer of Unit 18 reads the list and gives each of the 50 257 tokens a score, called a logit: "how well would you fit next?"
- Turn the scores into probabilities with softmax (Unit 14). They are positive and add up to 1.
- Pick one token, add it to the list, and go back to move 1. Stop when the model picks a special "end" token.
By hand. The text so far is "I drink". To keep it tiny, say the vocabulary has only five tokens: chai, coffee, water, cricket, the. The model gives them the scores . (We made these scores up by hand; a real model computes them.)
Divide each by the total:
Chai gets almost two thirds. Say we pick chai. The text is now "I drink chai", and the whole model runs again, from the start, on these three tokens, to choose the fourth. One run of the model gives one new token. A reply of 300 tokens is 300 runs.
The chain rule. How likely is the whole sentence? Multiply the guesses, each one given everything before it. This is the chain of guesses from Unit 16:
The n-gram model of Unit 16 kept only the last one or two words of the "given" part. An LLM keeps all of them: attention (Unit 18) looks back at every earlier token, and the causal mask (Unit 18) makes sure each guess sees only the past.
The game is simple, but playing it well is not. To guess what comes after "The capital of Japan is", the model must know geography. After "2 + 3 =" it needs arithmetic; after "def add(a, b):" it needs to know how Python code is written. Making the next-token guess good on trillions of tokens forces the weights to soak up grammar, facts and styles — because they all help the guess. And one step at a time is enough to write long, sensible text, because every step reads everything written before, including the words the model itself has just chosen.
Three next-word guessers, side by side. You have now met three machines that play the same game.
| n-gram (Unit 16) | recurrent net (Unit 17) | transformer LLM (Unit 18, this unit) | |
|---|---|---|---|
| what it reads | the last one or two words | one running note of everything so far | every earlier token, directly |
| the start of a long text | forgotten after a few words | fades as the note is rewritten | kept exactly, up to the context length |
| how it learns | counting | one word after another | every position at once (the mask) |
| work for one new token | one look-up in a table | one step of the cell | attention over all earlier tokens (§6 makes it cheaper) |
Rule of thumb. All three compute the same thing: a probability for the next token given the ones before. They differ only in how much of the past they can use. The transformer uses all of it, which is why it won.
The model does not plan the sentence and then type it out. There is no hidden finished answer waiting inside. Each token is chosen given only what is already written. When a reply starts well and then wanders, this is why: every new token becomes part of the "given" for all the tokens after it.
A language model is one function: "given the text so far, a probability for every possible next token". Run it, pick a token, append it, run it again. Multiply the guesses along the way and you get the probability of the whole text.
In the worked example you add 5 to every score: . What does the model do now?
You ask a question 40 tokens long. The model writes a reply of 60 new tokens (the last one is the "end" token). How many times did the model run?
If you want the algebra · 1 proof, step by step
Claim. For any tokens , (for the "given" part is empty: ).
The road ahead. The unit has four acts.
- A machine that guesses the next word (§1–§3): the loop, how a whole sentence is scored, and where the model's millions of numbers live.
- How it writes (§4–§7): picking the word — greedy, temperature, top-k and top-p — then the cache that makes writing fast and the clocks that make long texts possible.
- Training at scale (§8): how loss falls as models and data grow, and how to split a fixed budget.
- From guesser to assistant (§9–§13): copying good answers, fine-tuning with a thin low-rank patch, a reward learned from people's choices, the leash that keeps the model sensible, and a shortcut called DPO.
In one sentence: An LLM is your phone's autocomplete grown huge — read everything so far, give every token a probability, pick one, append it, repeat — and the chain rule multiplies those guesses into the probability of the whole text.
Scoring a whole sentence: likelihood, loss and perplexity
Think of the model as a gambler who starts with ₹1. Before each word it spreads its money over all the words that might come next. When the real word arrives, it keeps only the money it put on that word — and bets all of that again on the next word.
A good gambler ends the sentence with a decent amount left. But one word where it put almost nothing, and it is broke — however well it bet on every other word.
The question. How do we give a language model a score on a whole sentence — and why does every paper about LLMs talk in logarithms?
By hand. The sentence is "we drink hot chai". After "we", the model gave the true next token "drink" a probability of 0.5. After "we drink" it gave "hot" 0.25. After "we drink hot" it gave "chai" 0.8. Five small moves.
- The gambler's money is the probability of the sentence (the chain rule of §1): . Ten paise left of the rupee.
- Take logs, and the product becomes a sum: , which is exactly . This is the log-likelihood.
- Average the surprise. The surprise of one token is (Unit 14). The average is nats per token. This is the cross-entropy loss (Unit 14), the one number an LLM is trained to make small.
- Turn it back into a die. . This is the perplexity, the die of Unit 16: on average the model was as unsure as someone choosing among about 2.15 equally likely words. The same number is : one over the probability, shared out evenly over the three tokens.
- In bits, divide by : bits per token.
Why logarithms? Three reasons. First, the product gets too small for a computer. A text of 1 000 tokens, each with probability 0.5, has probability . At 2 000 tokens a computer's ordinary numbers run out and it says 0. The log is just , no trouble at all. Second, a sum is easy to average, so texts of different lengths can be compared per token. Third, the slope of a sum is the sum of the slopes: every token's surprise can be pushed down on its own, and backprop (Unit 15) does it for all of them in one pass.
This is all of training. Take a huge pile of text, and make the average surprise small at every position. Unit 18's mask (§10) lets one pass grade every position of a text at once.
The surprise punishes confidence in the wrong place much more than it rewards confidence in the right place. At the surprise is only 0.105; at it is 4.6; at it is infinite. So a model that wants a small average loss must never be sure of the wrong thing. It learns to spread its money sensibly: most on the likely words, a little on everything that could happen. That is exactly what we want from a model of language.
Five ways to report the same thing. Papers and dashboards use all of these. They carry the same information.
| number | how | for our sentence | better is | used for |
|---|---|---|---|---|
| probability | multiply the guesses | 0.1 | bigger (at most 1) | the idea; shrinks with every extra word |
| log-likelihood | add the logs | −2.3026 | closer to 0 | comparing answers of the same length |
| loss (nats per token) | average of | 0.7675 | smaller (at least 0) | training — the number gradient descent pushes down |
| bits per token | loss ÷ ln 2 | 1.1073 | smaller | compression: bits needed per token |
| perplexity | 2.1544 | smaller (at least 1) | the feel: "a die with this many faces" |
Rule of thumb. Train on the loss, feel it as perplexity. A model that knows nothing gives every token : its perplexity is exactly , 50 257 for GPT-2's vocabulary. Every good model lives far below that.
Perplexity is per token, so it depends on how the text was cut into tokens. Cut the same sentence into more, smaller pieces, and each piece is easier to guess: the perplexity per piece falls, though the model is no better. Compare perplexities only on the same text with the same tokenizer.
The loss is the average surprise of the true tokens: the log turns the gambler's product into a sum, and the average makes texts of any length comparable. Perplexity turns that average back into "how many equally likely choices".
The model gets better at "hot": it now gives it 0.5 instead of 0.25. "drink" and "chai" stay at 0.5 and 0.8. What is the new perplexity?
A model is graded on 1 000 tokens. It is excellent on 999 of them, but on one token it gave the true word a probability of exactly 0. What is its average loss?
A new model with GPT-2's vocabulary of 50 257 tokens has a loss of nats per token. What does that tell you?
If you want the algebra · 2 proofs, step by step
Claim. With loss , the perplexity is .
Claim. A model that gives every one of tokens the probability has loss and perplexity on any text.
In one sentence: A model is scored like a gambler who keeps only what it bet on each true word — multiply the probabilities for the sentence, take logs to turn the product into a sum, average for the loss, and exponentiate for the perplexity, the number of faces on its die.
Inside the stack, by the numbers
Picture a tall office tower. On the ground floor is a huge dictionary: one row for every token. Above it, floor after floor, every floor has the same two rooms. In the meeting room the words talk to each other — that is attention. In the desk room each word thinks alone — that is the feed-forward network.
Where do most of the people sit? Count the chairs.
The question. "GPT-2 small has 124 million parameters." Where do all those numbers live?
Call the width of the model : every token travels through the tower as a list of numbers. Count the weights in one floor — one transformer block of Unit 18.
- The meeting room (attention) has four matrices: and the output mix . That is numbers, however many heads there are.
- The desk room (feed-forward) widens each token from to numbers and brings it back: a matrix and a matrix, numbers.
- Together: per block. The small extras — biases and the two layer norms — add .
- The ground floor is the token table: numbers, one row per token. With weight tying (Unit 18) the same table also scores the next token at the top, so it is counted once.
GPT-2 small (Radford and colleagues, 2019) has , blocks, a vocabulary of and a context of 1 024 tokens.
That is the "124 million". About 68 % sits in the blocks and 31 % in the token table.
Now make it big. A 7-billion-class model has and . The blocks hold . With one shared table of 32 000 tokens () the count is , about 6.6 billion. Now the blocks are 98 % of the model. (Real 7-billion models come out a little higher: their feed-forward rooms are slightly wider, and many keep a separate output table. But is the right first guess.)
A variant: the mixture of experts. Think of a big hospital. It has eight specialists, but each patient sees only two of them; a receptionist decides which. A mixture-of-experts (MoE) block does the same: it keeps several feed-forward rooms, the experts, and a small router scores them for each token. Only the top two are run.
Say four experts get the router scores . Keep the top two, experts 1 and 2, and softmax just their scores: and . The token's output is (expert 1's answer) (expert 2's answer). Experts 3 and 4 are not computed at all.
With , one expert holds numbers. Eight experts hold per layer, but each token wakes up only two: , a quarter.
Why do the blocks win as models grow? Every matrix inside a block connects all numbers of a token to all (or ) numbers on the other side, so its size is " times ". Double the width and every block gets four times bigger, while the token table only doubles. Small models are mostly dictionary; big models are mostly floors. And why experts? Different tokens need different knowledge — Hindi, Python, chemistry. Experts let a model hold much more knowledge while each token pays only for the two rooms it visits.
Dense against mixture of experts, per layer, at .
| dense feed-forward | 8 experts, top 2 | |
|---|---|---|
| numbers stored | 134 217 728 | 1 073 741 824 (8 ×) |
| numbers used per token | 134 217 728 | 268 435 456 (2 ×) |
| memory needed | small | large: every expert must be loaded |
| extra parts | none | a router ( numbers) and a rule to keep the experts evenly busy |
Rule of thumb. Parameters . For a mixture of experts, quote two numbers: the total you must store, and the active count each token uses. Compute follows the active count; memory follows the total.
Parameters are not sentences stored in a drawer. They are the weights of the matrices above, and knowledge lives spread across all of them. And in a mixture of experts, "total parameters" is not "parameters used per token": the 8-expert tower of the widget stores 36.6 billion numbers but computes like a model of about 10.9 billion — and it still needs the memory of all 36.6 billion.
The floors plus the dictionary. Each block holds in attention and in the feed-forward room. The width enters squared, so as models grow the floors swallow almost everything.
You double the width of a model and keep everything else the same. Roughly how many times more numbers do the blocks hold?
A mixture-of-experts layer has 16 experts, each as big as one dense feed-forward room, and its router picks the top 2 for every token. Compared with the dense room, what happens to the numbers stored and the work done per token?
If you want the algebra · 1 proof, step by step
Claim. A GPT-2 block of width has parameters. With , 12 blocks, , a context of 1 024 and a tied output layer, the total is .
In one sentence: An LLM is a tower of identical floors, each holding 4d² numbers in the meeting room and 8d² at the desks, over a V × d dictionary — so parameters ≈ 12Ld² + Vd, and a mixture of experts stores many desk rooms but sends each token to only two.
Picking the word: greedy and temperature
Picture a dial on the model, like the thermostat on an air conditioner — but this one sets boldness. Turn it cold, and the model always says the most obvious word, like a shy student who only ever gives the textbook answer. Turn it warm, and it takes small chances. Turn it hot, and it gets more and more adventurous — like a friend telling stories at two in the morning — until, at the very hottest, it talks nonsense.
The question. The model hands us a probability for each of 50 000 tokens. Which one do we actually write?
Greedy: always take the top one. It is safe and it gives the same answer every time. It is also dull, and it falls into loops. Here is the tiny character model of Unit 17, writing greedily after "the train to ":
the train to patna will arrive on platform three. the train to patna will arrive on platform three. the train to patna…
— and so on forever. Once a sentence is the most likely thing to say, it stays the most likely thing to say next time too. Beam search (Unit 17) keeps the best few partial sentences instead of one. It is excellent when there is one right answer, as in translation. For open writing it finds text that is too probable — bland and repetitive. So chat models usually sample: they draw the next token at random, each token with its own probability, like a lottery where chai holds 64 tickets out of 100.
Temperature is the boldness dial. Before the softmax, divide every score by a number .
By hand. The scores are for chai, coffee, water, the.
- : the scores stay as they are. Softmax gives .
- (cold): dividing by 0.5 doubles the scores to . Softmax gives . The favourite grows stronger.
- (hot): the scores halve to . Softmax gives . The underdogs catch up.
Read it aloud. The ratio between two tokens' probabilities is , where "gap" is the difference of their scores. Chai against coffee has a gap of 1. At chai is times as likely; at it is times; at only times. Cold stretches the gaps; heat shrinks them. Turn all the way down and every gap becomes huge: all the probability lands on the top token — that is greedy. Turn it all the way up and every gap shrinks to nothing: every token gets .
You have met this dial before: it is the "how picky" knob of Unit 18, turned upside down, and the temperature of Unit 17's talking model.
Softmax turns gaps between scores into ratios between probabilities: a gap of becomes a ratio of . Dividing every score by divides every gap by , so it bends all the ratios at once, in the same direction, without ever swapping two tokens. That is why one dial is enough to move smoothly from "always the obvious word" to "anything goes" — and why it never changes the model's opinion of which token is best, only how strongly it insists.
Ways to pick, side by side.
| method | what it does | good for | risk |
|---|---|---|---|
| greedy | always the top token | short factual answers, code | dull; loops |
| beam search | keeps the best few partial sentences | translation, where one answer is right | bland, repetitive open text |
| sampling, | draws with the model's own probabilities | variety | now and then a strange token (§5) |
| sharpens: favourites grow | careful, focused writing | at the extreme, greedy again | |
| flattens: underdogs catch up | brainstorming, poems | nonsense as grows |
Rule of thumb. For facts and code, stay cold ( near 0, or greedy). For chat, a little under or around 1. For ideas and stories, a little above 1 — and always with the tail cut off, as in the next section.
is not "the most accurate setting". It picks the most probable token at each step, which can still be wrong, and a string of individually most-likely tokens need not be the most likely text. And a high temperature does not make the model more creative in any deep sense: it adds randomness, not knowledge.
Temperature divides the scores before the softmax. Every ratio between two tokens is raised to the power : cold makes the favourite a dictator, heat makes every token equal, and the order never changes.
Scores at . How many times more likely is chai (score 2) than coffee (score 1)?
A bug makes the model double all of its scores before the softmax. Which temperature gives back exactly the probabilities of the model without the bug?
You set for a model with a vocabulary of 50 000 tokens. What will it write?
If you want the algebra · 1 proof, step by step
Claim. With : (a) , so the order of the tokens is the same at every ; (b) as all the probability goes to the top token (if it is unique); (c) as every token gets .
In one sentence: Greedy always takes the top token and ends up in loops, so chat models sample — and temperature, a thermostat on boldness, divides the scores before the softmax: cold stretches every gap until the favourite always wins, heat shrinks every gap until any token can win.
Cutting the tail: top-k and top-p
A wedding buffet has 200 dishes. Most guests fill their plates from the ten favourites. Now suppose you choose your dish by throwing a dart that can land anywhere on the table, with a small chance for every dish. Each strange dish is rare. But there are so many of them that, every few plates, you end up eating a bowl of pickle for dinner.
The question. Sampling makes text lively. So why do good chatbots almost never drop a nonsense word into the middle of a sentence?
The danger is the tail. Say the 20 sensible tokens hold 0.9 of the probability, and the other 50 000-odd tokens share the last 0.1 — each one tiny. Then every step has a 1-in-10 chance of drawing junk. Over a 50-token reply, the chance of never drawing junk is . Almost every reply would contain a pickle.
The fix is to cut the tail off before drawing. There are two popular cuts.
- Top-k: keep the most likely tokens, and share their probability back out so it adds up to 1 again (renormalise).
- Top-p, also called nucleus sampling (Holtzman and colleagues, 2020): go down the list from the top, adding up probabilities, and stop as soon as the running total reaches . Keep those tokens, and renormalise.
By hand. "Every morning I drink hot …": chai 0.40, coffee 0.25, milk 0.15, water 0.10, soup 0.06, oil 0.04.
- Top-k with . Keep chai, coffee, milk: together 0.80. Divide each by 0.80: . Oil is gone for good.
- Top-p with . Running totals: 0.40, 0.65, 0.80, … The total first reaches 0.75 at the third token. Keep 3 tokens — the same three, here.
Where the two differ. Take a flat list: "My favourite colour is …" — blue 0.20, green 0.18, red 0.17, yellow 0.16, pink 0.15, black 0.14. Running totals 0.20, 0.38, 0.55, 0.71, 0.86: top-p 0.75 keeps 5 tokens, because many answers are fine. Now a peaked list: "The capital of India is New …" — Delhi 0.90, York 0.04, Zealand 0.03, Jersey 0.02, Moon 0.01. The first token alone passes 0.75: top-p keeps 1. Top-k 3 keeps 3 in both cases — too few for the colours, and for the capital it keeps "York" and "Zealand" in the draw. Top-p adapts to how sure the model is; top-k does not.
The order, in real samplers. Temperature first, then top-k, then top-p, then renormalise, then draw.
Renormalising is the same as saying: "draw from the model as usual, but if the dart lands in the tail, throw it again". The kept tokens keep their relative odds exactly — chai stays 1.6 times as likely as coffee — so the model's judgement among the good tokens is untouched. Only the long, thin tail, where the model's own numbers are least trustworthy, is removed. And top-p adapts because it counts probability, not tokens: a sure model has its probability packed into a few tokens, an unsure one spreads it over many.
The two cuts, side by side (with the lists above, and ).
| top-k | top-p (nucleus) | |
|---|---|---|
| keeps | always tokens | the fewest top tokens holding at least |
| flat list (colours) | 3 tokens — throws away 0.45 of good answers | 5 tokens |
| peaked list (capital) | 3 tokens — York and Zealand still in the draw | 1 token |
| with temperature | same set at any | heat spreads probability, so more tokens pass |
| setting you will see | = 40 or 50 | = 0.9 or 0.95 |
Rule of thumb. Temperature → top-k → top-p → renormalise → draw. If you set only one, set top-p around 0.9 with near 1: it keeps the variety when many answers are fine and removes the pickle when one answer is right.
Top-p 0.9 does not mean "keep 90 % of the tokens". It means "keep the fewest tokens that together hold 90 % of the probability". For a sure model that can be a single token out of 50 000; for an unsure one, thousands.
Choose a set of good tokens — the top , or the fewest top tokens whose probabilities reach — and share the whole probability out among them in their old proportions. Then draw.
The colour list (0.20, 0.18, 0.17, 0.16, 0.15, 0.14) with top-k 3. How much of the model's probability is thrown away?
The capital list (0.90, 0.04, 0.03, 0.02, 0.01) with top-p 0.95. How many tokens are kept?
You set top-k to 1 and temperature to 2. What does the sampler do?
If you want the algebra · 1 proof, step by step
Claim. Keep a set of tokens with total probability . Drawing from the model and re-drawing whenever the token is outside gives token with probability exactly — the renormalised list.
In one sentence: Thousands of tiny probabilities add up to a real chance of nonsense, so before drawing we cut the tail — top-k keeps a fixed number, top-p keeps the fewest tokens that hold p of the probability — and renormalise, like a buffet where you only throw darts at the good dishes.
The KV cache: never recompute the past
A tailor is stitching a long kurta, one panel at a time. For every new panel she needs the measurements of every panel already stitched. A careless tailor would measure the whole kurta again before each new panel. A sensible tailor writes each measurement in her notebook once, and simply reads it back.
The question. To write token number 1 001, must the model redo all the work it already did for the first 1 000?
Recall how attention works (Unit 18). In every layer, every token makes a query, a key and a value. The new token's query is scored against the keys of all the earlier tokens, and it takes a blend of their values. So the new token needs every earlier key and value, in every layer.
Here is the key fact. Because of the causal mask (Unit 18), an earlier token never looks at anything that came after it. So its keys and values, in every layer, are exactly the same now as when it was written. Nothing new can change them. So keep them: the KV cache — the tailor's notebook of keys and values.
Count the work. Count the rows of keys and values the model computes in one layer.
- Without a cache, run processes all tokens again: rows to write tokens. For : rows.
- With a cache, each run computes one new row and reads the rest from the notebook: rows. Five hundred times less.
The price is memory. For every token the notebook holds a key and a value (that is the 2), in every layer, each numbers long, each number bytes:
for a 7-billion-class model (, , 16-bit numbers of 2 bytes). A conversation of 4 096 tokens needs MiB GiB — just for the notebook of one conversation. (A MiB is bytes; a GiB is .)
Three ways to share the notebook. The model has 32 attention heads, and in plain multi-head attention each head keeps its own keys and values: 2 GiB. In grouped-query attention (GQA), the 32 query heads are split into 8 groups, and each group shares one set of keys and values: 8 sets instead of 32, so MiB. In multi-query attention (MQA), all 32 heads share one set: 64 MiB. Sharing costs a little quality, because the heads can no longer each look for their own kind of key.
Two phases of writing. When you send a prompt, the model first reads it all at once, in parallel, filling the notebook — this is the prefill, and it is Unit 18's "every position at once". Then it decodes: one token per run, and each run reads the whole notebook. Decoding is slow not because of the arithmetic, but because of the reading: for every single token, all the model's weights and the whole notebook must be fetched from memory again. For a long chat, the notebook becomes a big part of that reading.
Because the past is frozen. A token's key and value depend only on the tokens up to it — the mask guarantees that — and those tokens never change once written. So a key computed at run 5 is still exactly right at run 1 000. The cache is not an approximation: the model with the cache computes exactly the same probabilities as the model without it, just without repeating itself.
Sharing keys and values, side by side (32 query heads, , , 2 bytes, 4 096 tokens).
| multi-head (MHA) | grouped-query (GQA) | multi-query (MQA) | |
|---|---|---|---|
| sets of keys and values | 32, one per head | 8, one per group of 4 heads | 1, shared by all |
| notebook size | 2 GiB | 512 MiB | 64 MiB |
| quality | the reference | almost the same | a little lower |
| speed of decoding | slowest: most to read | fast | fastest |
Rule of thumb. Cache memory per token . Most recent open models use grouped-query attention: nearly all the quality of multi-head, at a fraction of the memory.
The cache saves computation, and it costs memory. It grows with every token of every conversation the server is holding at once. For long chats the notebook, not the model's weights, is often what fills the memory.
The mask freezes the past, so every earlier key and value can be written once and read back forever: the work falls from a triangle to a line, and the notebook grows by the same few hundred kilobytes with every token.
Without a cache, how many rows of keys and values (in one layer) does the model compute to write 2 000 tokens?
A model uses grouped-query attention with 8 key-value heads, and its notebook for one long chat is 512 MiB. The designers switch to 4 key-value heads. What happens to the notebook?
If you want the algebra · 2 proofs, step by step
Claim. Writing tokens without a cache computes rows of keys and values per layer.
Claim. In a model with a causal mask, the key and value of token in every layer depend only on tokens . So adding tokens after never changes them, and reading them from a cache gives exactly the same result as recomputing them.
In one sentence: Because the mask freezes the past, the model writes every token's keys and values into a notebook once and reads them back forever — n rows of work instead of n(n+1)/2 — and pays in memory, 2·L·d·b bytes per token, which grouped-query attention shrinks by sharing the notebook between heads.
Longer contexts: rotary positions at full size
A clock with only a seconds hand cannot tell 10:15 from 10:16: the hand is in the same place every minute. Add a minutes hand and an hours hand, and it tells every moment of the day apart. The fast hand sorts out small differences; the slow hands sort out big ones.
A transformer tells positions apart with exactly such a clock — with many hands, turning at many speeds.
The question. How does a model with a context of thousands of tokens tell a word 3 positions back from one 3 000 positions back — and why do models trained on short texts get confused by long ones?
In Unit 18 we met rotary positions (RoPE) with one pair of numbers: the query of the word at position is turned by the angle , the key of the word at position by , and their dot product depends only on the gap . Now the full picture.
- Split the numbers into pairs. Each pair is a little arrow on its own clock face.
- Each pair turns at its own speed. Pair turns by radians per position, for . With there are four pairs: .
- Each speed has its period, the number of positions for one full turn, : about and positions. A seconds hand, a minutes hand, an hours hand and a days hand.
- Score as usual. The dot product of the turned query and the turned key is the sum over the pairs. In each pair only the angle between the two hands, , matters.
By hand. Let every pair of the query and of the key be . The query stands at , the key at , a gap of 2. Pair contributes :
Now move both words 1 000 positions later: , . Every hand has turned a long way, but the angle between each pair of hands is still , and the score is still . Where the two words stand does not matter — only how far apart they are.
Why models break on longer texts. Say a model was trained on texts of at most 2 048 tokens. The slowest pair () has then only ever seen the two hands up to radians apart (about 117°). Ask it to connect words 8 000 positions apart, and that pair shows an angle of 8 radians — more than a full turn, something it never saw in training. The fast pairs are fine: they went round and round during training and have seen every angle.
The fix: position interpolation (Chen and colleagues, 2023). Squeeze the new, longer positions into the trained range. To read 8 192 tokens with a model trained on 2 048, multiply every position by . Position 6 000 is treated as position 1 500, and every angle is back inside what the model knows. The cost: neighbours now look closer than before, so the model gets a short extra training on long texts to get used to it.
Turning both arrows by the same extra angle never changes the angle between them — just as moving a meeting from 3 to 5 o'clock does not change the fact that it lasts an hour. So the score can only see the gap . And using many speeds gives both precision and reach: the fast hands separate "1 back" from "2 back", the slow hands separate "a sentence back" from "a chapter back", and no two gaps inside the trained range look alike on all the clocks at once.
Four ways to handle position and length, side by side.
| method | how it marks position | past the trained length |
|---|---|---|
| learned table (GPT-2) | one learned row per position | no rows exist: it cannot go further |
| clock tags (sinusoidal) | sines and cosines added to the word | defined, but unfamiliar to the model |
| rotary (RoPE) | turns q and k; the score sees only the gap | slow hands meet new angles; quality drops |
| RoPE + interpolation | positions squeezed by trained ÷ new length | angles stay familiar; a short fine-tune restores quality |
Rule of thumb. Pair turns at radians per position. To stretch a model's context by a factor , squeeze positions by (or, in later variants, slow down only the slow hands) and fine-tune briefly on long texts.
Rotary positions turn the queries and keys only — never the values. Position is needed to decide where to look; what is handed over, the value, is just the word's content.
Each pair of numbers is a clock hand turning at its own speed. The score of a query and a key depends only on the gap between them, fast hands give precision, slow hands give reach — and squeezing positions keeps every hand inside the angles the model has learned.
A query at position 40 and a key at position 30 give some score. You move the query to position 540 and the key to 530. What happens to the score?
A model trained on 4 096 tokens must read 16 384. With position interpolation, what is the scale, and where does position 10 000 land?
If you want the algebra · 1 proof, step by step
Claim. With the turn , for any pairs : . It depends on and only through .
In one sentence: Rotary positions give every pair of numbers its own clock hand, turning at 10 000^(−2i/d) radians per step, so a score sees only the gap between two words — fast hands for precision, slow hands for reach — and squeezing positions keeps the slow hands inside the angles the model learned.
Scaling laws: bigger, with more data, predictably better
A school has a fixed budget. It can hire more teachers or buy more books. All teachers and no books, and the teachers have nothing to teach from. A huge library with one teacher, and nobody explains anything. The best school splits the money between the two.
Training an LLM is the same choice. The budget is computing time. The teachers are the model's parameters; the books are the tokens of text it reads.
The question. You have a fixed amount of computing. Should you train a bigger model, or feed a smaller one more text?
What a training run costs. A model with parameters reading tokens needs about
Why 6? In the forward pass each parameter is used once per token for a multiply and an add: 2 operations. The backward pass has two jobs for every weight — pass the blame back to the inputs, and find the weight's own slope (Rules A and B of Unit 15) — each another multiply and add: 4 more. So the backward pass costs about twice the forward. For DeepMind's Chinchilla, billion and trillion: .
How the loss falls. Train many models of different sizes on different amounts of text, and the final loss follows a power law. On log–log axes a power law is a straight line — logs, once again, turn a hard curve into a simple one. Hoffmann and colleagues (2022) fitted
Read it aloud. 1.69 is the floor no model can beat: the randomness of language itself. The second term is what a small model loses by being small; it shrinks as grows. The third is what a model loses by reading too little; it shrinks as grows. Ten times more parameters multiplies the second term by : it roughly halves.
Two real models.
- Gopher: 280 billion parameters, 300 billion tokens. . The formula gives .
- Chinchilla: 70 billion parameters, 1.4 trillion tokens. — about the same budget. The formula gives .
The model four times smaller, fed almost five times more text, wins. Gopher had hired too many teachers and bought too few books.
The rule of thumb: about 20 tokens per parameter, . Then , so
For : billion parameters and billion tokens. (An honest note: the fitted formula itself puts its lowest point at Chinchilla's budget near 32 billion parameters on 3 trillion tokens. Its valley is so flat there that Chinchilla's own split is only 0.007 higher. The paper's two other methods gave about 20 tokens per parameter, and that became the rule everyone quotes.)
Training, in practice. The optimiser is Adam (Unit 11). The learning rate is warmed up from zero over the first few thousand steps, then slowly lowered along a cosine curve. Numbers are stored in 16 bits for speed, with a 32-bit master copy of the weights so small updates are not lost. Each step reads a batch of millions of tokens.
Each ingredient runs into diminishing returns on its own. Make the model ten times bigger and its term only halves, while the data term stays where it was — the loss hits a wall set by too little reading. So spending all the budget on one ingredient wastes it. The best split sits where one more rupee buys the same drop in loss whether it is spent on parameters or on tokens. That balance point moves out steadily as the budget grows, which is why it can be predicted before the expensive run starts.
Two models, one budget.
| Gopher (2021) | Chinchilla (2022) | |
|---|---|---|
| parameters N | 280 billion | 70 billion |
| tokens D | 300 billion | 1.4 trillion |
| tokens per parameter | about 1.07 | 20 |
| compute 6ND | ||
| fitted loss | 1.9933 | 1.9366 — better |
| cost to use | 4 times the parameters on every reply | cheaper for every reply, forever |
Rule of thumb. , and for the best loss per rupee of training, . Models that will answer millions of questions are often trained on even more tokens than that: a smaller model costs less every time it is used.
A scaling law predicts the average loss on text like the training text — not any particular skill. Abilities such as arithmetic can seem to appear suddenly while the loss falls smoothly. And the law is a fitted curve: trust it within the range of sizes it was fitted on, and less far beyond.
Training cost is six operations per parameter per token, and loss falls as a sum of power laws in size and data — straight lines on log–log axes. With a fixed budget, balance the two: roughly twenty tokens for every parameter.
About how many operations does it take to train a 1-billion-parameter model on 20 billion tokens?
You double the compute budget and keep the rule . By how much should the model grow?
In the fitted formula, you make the model 10 times bigger but keep the same number of tokens. What happens to the loss?
If you want the algebra · 2 proofs, step by step
Claim. For a network whose work is mostly matrix products, one training step on one token costs about operations, so reading tokens costs .
Claim. Minimise with . At the best split the two losses are in the ratio , and , .
In one sentence: Training costs about 6ND operations, and loss falls as a floor plus two power laws — one in parameters, one in tokens — so for a fixed budget, like a school choosing between teachers and books, the best split grows both together, about twenty tokens for every parameter.
Teaching it to follow instructions
A new apprentice joins a busy dhaba. He already knows how to chop, fry and knead — he learned that at home, over years. What he does not know is how this kitchen answers an order. So for a few weeks he watches the head cook, and copies how each plate should look when a customer asks for it.
The question. A model trained on internet text only ever learned to continue text. How does it learn to answer?
Ask a freshly trained model "What is the capital of India?" and it may well reply "What is the capital of Nepal? What is the capital of Bhutan?" — it has seen many lists of quiz questions, and continuing the list is a perfectly likely thing to do. It knows the answer; it does not know that you wanted it.
Supervised fine-tuning (SFT) is the apprentice's weeks of copying. People write thousands of pairs: an instruction, and a good answer. The model keeps training with exactly the same next-token loss as before — with one change. Each conversation is laid out as one token list, with special marker tokens for who is speaking (a chat template):
<user>capitalofIndia?<assistant>NewDelhi.
and only the answer tokens count in the loss. This is the loss mask: the question's tokens are read, but the model is never graded on guessing them.
By hand. The model gives the three answer tokens the probabilities 0.5 (New), 0.8 (Delhi) and 0.9 (the full stop).
The question's tokens had probabilities 0.02 (capital), 0.6 (of), 0.1 (India) and 0.7 (?). Without the mask the loss would be the average over all seven tokens, 1.1577 — most of it from guessing what the user would type. The model would spend its effort learning to write users' questions. (In real training the "end" token after the answer is counted too, so the model also learns when to stop.)
The model already has the knowledge and the language; pretraining put them there. Fine-tuning changes a habit: after the marker <assistant>, the most likely continuation becomes a helpful answer instead of another question. Changing a habit needs far less data than learning a language — thousands of good examples, not trillions of tokens — which is why a small, carefully written set of answers can turn a text-continuer into an assistant.
Pretraining and fine-tuning, side by side.
| pretraining | supervised fine-tuning | |
|---|---|---|
| data | trillions of tokens of text from anywhere | thousands to a million conversations written or checked by people |
| loss | next-token surprise on every token | the same surprise, on the answer tokens only |
| it learns | language, facts, ways of reasoning | the manners of an assistant: answer, follow instructions, stop |
| cost | enormous | small |
Rule of thumb. Same loss, same model, a mask, and much better data. What goes into the answers is what comes out of the assistant: a few thousand excellent examples beat many mediocre ones.
Fine-tuning teaches the style of good answers by copying them. It cannot tell the model which of two decent answers people prefer — the more helpful one, the more honest one, the kinder one. For that we need people's choices, not only their examples. That is the next three sections.
is the set of answer positions. The whole conversation is read, but only the assistant's tokens are graded — the apprentice copies the master's plates, not the customers' orders.
You fine-tune a model on chat data but forget the loss mask, so every token of every conversation is graded. What extra thing does the model learn?
A short chat: the user's two tokens get probabilities 0.01 and 0.2; the answer's two tokens get 0.9 and 0.6. What is the SFT loss (with the mask)?
If you want the algebra · 1 proof, step by step
Claim. Write the SFT loss with a mask (1 for answer tokens, 0 otherwise): , where is the softmax at position . Then the blame on the scores at position is : zero at every masked position.
In one sentence: Supervised fine-tuning is an apprentice copying the master's plates — the same next-token loss on written examples of good answers, with a mask so that only the assistant's tokens are graded.
LoRA: fine-tune a giant by changing a thin slice
Clip-on lenses for a phone camera: wide-angle, macro, fish-eye. The phone stays exactly the same. A small lens clipped on top changes what it does, you can swap lenses in seconds, and ten of them fit in a pocket.
The question. To teach a 7-billion-number model a new job — answer like a doctor, write in Hindi, follow a company's style — must we change all 7 billion numbers?
Full fine-tuning updates every weight: . For one matrix, is numbers — and Adam (Unit 11) keeps two more notebooks for every weight it trains, so the memory for training is several times the model.
LoRA, low-rank adaptation (Hu and colleagues, 2021), freezes and learns the change as a product of two thin matrices, with a small rank :
With and : and together hold numbers, against — just 0.39 %.
By hand. Take , : and . Then
Look at the rows: the first is , the second is 0 times it, the third is 2 times it. Every row is a multiple of one row, so has rank 1 (Unit 5). Six numbers describe nine; at full size, 65 536 describe 16.8 million.
How training starts. starts small and random, and starts at zero. So at the first step and the model is exactly the original. Training then grows the change from nothing.
Where the adapters go. A common choice puts one on the query matrix and one on the value matrix of every layer. In a 7-billion-class model (32 layers, , ): trainable numbers — about 0.06 % of the model. One base model can carry many adapters and switch between them; or an adapter can be merged, , so using it costs nothing extra.
Because the change needed to adapt a trained model is nearly low-rank: a new job mostly needs a few new directions, not a whole new matrix. The SVD of Unit 5 writes any change as a sum of rank-1 layers, biggest first, and Eckart–Young says the best rank- copy keeps exactly the first layers, with an error equal to the size of the dropped singular values. When those fall fast, a tiny captures almost everything. Hu and colleagues found ranks as small as 1 to 8 were often enough.
Full fine-tuning against LoRA (one matrix, ).
| full fine-tuning | LoRA | |
|---|---|---|
| numbers trained | 16 777 216 | 65 536 (0.39 %) |
| memory while training | weights + slopes + Adam's two notebooks for all of them | slopes and notebooks for the thin slice only |
| stored per new job | a whole new copy of the model | a small file of and |
| speed when used | normal | normal, once merged into |
| quality | the reference | close for most jobs |
Rule of thumb. A LoRA adapter on a matrix has numbers. Start with on the query and value matrices; raise only if the job is far from what the model already does.
LoRA does not make the model you run any smaller: the full frozen is still there, and after merging is a full matrix again. What LoRA shrinks is what you train and what you store for each new job.
Freeze the giant, and learn its change as a thin product of two matrices. It is Eckart–Young as a training method: bet that the change lives in a few directions, and learn only those.
A weight matrix gets a LoRA adapter with . How many numbers does the adapter train?
LoRA starts with and a random . Before the first training step, what does the fine-tuned model output?
A target change has singular values and a LoRA of rank 2 is trained as well as possible. Which singular values decide the error that is left?
If you want the algebra · 2 proofs, step by step
Claim. If is and is , then .
Claim. Let be its SVD (orthonormal , orthonormal , ). Keeping the first layers leaves an error of size , and by Eckart–Young no rank- matrix does better.
In one sentence: LoRA freezes the giant and learns its change as a thin product BA of rank r — a clip-on lens of 2dr numbers instead of d² — and it works because the change a new job needs lives in a few directions, exactly the ones Eckart–Young says a rank-r copy keeps.
A reward from human choices
A cricket selector cannot give every batter an exact score out of 100. But put two batters in the nets side by side, and she can tell you which one is better. Watch enough pairs, and a ranking appears — even a rating for every player, like the ratings chess players carry.
The question. How can a machine learn what people like, when nobody can write down a formula for "a good answer"?
For one prompt the model writes two answers, and a person picks the better one. This is easy for people — much easier than writing a perfect answer, and much more consistent than giving marks out of 10. Collect many such choices. Then give every answer a hidden score, its reward , and ask the scores to explain the choices.
The Bradley–Terry model. The chance that answer A is preferred to answer B depends only on the difference of their rewards:
is the logistic curve: softmax of Unit 14 with just two choices. Equal rewards give 0.5; a big lead gives nearly 1.
By hand. , .
- The prediction: .
- A person prefers A. The loss is the surprise of that choice: .
- The nudge. The slope of the loss pushes the winner's reward up and the loser's down, by the same amount: the step size times . With a step size of 1: , , and now .
- If the scores were equal, the prediction would be 0.5 and the loss : a coin toss.
The reward model. In practice the rewards come from a network: a copy of the LLM whose last layer is replaced by a single number, the score of a whole answer. It is trained on hundreds of thousands of people's choices with exactly this loss.
The nudge is : the chance the model gave to the choice that did not happen. When the rewards already agree strongly with the person, is near 1 and the nudge is tiny. When they disagree — the model had the order backwards — the nudge is big. So the rewards learn mostly from their mistakes, just like the "prediction − truth" of Unit 15. Over many choices, answers people keep picking drift up, answers they keep rejecting drift down, and the gaps settle where the predicted chances match how often people actually agree.
Three ways to collect human judgement.
| write a good answer | give marks out of 10 | pick the better of two | |
|---|---|---|---|
| effort for people | high | low | low |
| consistency | varies with the writer | poor: one person's 7 is another's 5 | good: comparing is easy |
| teaches | what a good answer looks like (§9) | a noisy score | which answer is better — a reward |
Rule of thumb. Ask people to compare, not to score. The Bradley–Terry loss turns comparisons into rewards, with a nudge of to the winner and the loser.
Only differences of rewards mean anything. Add 10 to every reward and every probability stays the same. So a reward of 3.2 on its own says nothing; "3.2 against 1.1" does.
Give every answer a hidden score, predict each choice with the logistic of the score gap, and nudge the winner up and the loser down by how surprised you were — a selector who rates players only by comparing two at a time.
A reward model gives answer A 1.5 and answer B 0.5. A bug adds 10 to every reward it outputs. What is the new chance that A is preferred to B?
The reward model had the order backwards: for the answer the person preferred, for the other. With step size 1, how much does each reward move?
If you want the algebra · 1 proof, step by step
Claim. For : and , with . And the loss is unchanged if every reward gets the same constant added.
In one sentence: Like a selector comparing two batters at a time, a reward model learns from people's choices — the chance one answer beats another is the logistic of their reward gap, and each choice nudges the winner up and the loser down by how surprised the model was.
Chasing the reward on a leash
On Makar Sankranti the sky fills with kites. The wind pulls each kite up and away; the string holds it near the hand that flies it. Cut the string, and the kite races off wherever the wind blows — and comes down in a tree. Keep the string too short, and the kite never rises at all. Flying well is the balance between the two.
The question. We now have a reward model that scores answers. Why not simply train the LLM to get the highest reward it possibly can?
Because the reward model is not perfect. It learned from a limited set of people's choices, so it has blind spots. Push an LLM hard against it, and the LLM finds strange answers the reward model happens to love — very long answers, flattering phrases, favourite words repeated — that no person would actually prefer. This is reward hacking: the kite with a cut string.
The leash. Keep the tuned model close to the sensible model it started from, the reference (the model after §9). Measure "close" with the KL divergence of Unit 14, and subtract it from the reward:
The first term is the wind: more reward is better. The second is the string: every step away from the old habits costs per unit of KL. This is the objective of RLHF, reinforcement learning from human feedback.
The beautiful answer. For a fixed prompt, the best possible has a closed form:
Read it aloud. Start from the old habits, . Multiply each answer by : high reward, big boost. Divide by the total so everything adds up to 1. It is softmax once again — the rewards act as scores, as the temperature of §4, and the old habits as a head start.
By hand. Three answers: the reference gives them , and their rewards are . Take .
The boosts:
Now change the string. : — the kite flies far towards the best answer. : . : — hugging the old habits. As all the probability goes to the highest-reward answer; as , becomes .
In practice a real model has far too many possible answers to list, so this cannot be computed directly. RLHF uses a reinforcement-learning method called PPO: the model writes answers, the reward model scores them, and the weights are nudged, step by step, towards more reward and less KL. The closed form is the target that PPO is walking towards.
The KL term charges for every bit of surprise between the new habits and the old ones, so the cheapest way to earn reward is to move probability between answers the reference already considered reasonable. An answer the reference would almost never write can only be reached by paying a lot of KL — which is exactly where a flawed reward model's blind spots hide. The string does not stop the kite from rising; it stops it from flying into places no sensible model would go.
Three lengths of string (the example above).
| small β (long string) | medium β | large β (short string) | |
|---|---|---|---|
| π* at β = 0.5 / 1 / 10 | (0.037, 0.163, 0.801) | (0.179, 0.292, 0.529) | (0.465, 0.308, 0.227) |
| reward | high | good | little gain |
| distance (KL) | far from the reference | moderate | almost none |
| risk | reward hacking | the balance | barely changes |
Rule of thumb. The best tuned model is the reference, reweighted by . Choose so the model improves on the reward and on what people actually think — watch both, because the reward alone will keep rising even as the answers get worse.
A larger means a shorter string, not a weaker one: the KL costs more, so the model stays closer to its old habits. Small is the long, loose string that lets reward hacking happen.
Chase the reward, pay for every step away from the old habits, and the best policy is the old habits reweighted by exponentiated reward — a kite as high as the wind can lift it on a string of length set by .
You make very small — almost no leash. Where does put its probability?
Two answers, reference , rewards , . What is ?
One possible answer has reference probability exactly 0 — the old model would never write it — but a huge reward. What does give it?
If you want the algebra · 1 proof, step by step
Claim. Over all probability lists on the answers, is largest at , and there .
In one sentence: Chasing an imperfect reward on its own ends in reward hacking, so RLHF subtracts β times the KL from the reference — and the best policy is then the old habits reweighted by e^(r/β), a kite that rises with the wind but stays on its string.
DPO: skip the reward model
A cook wants to know which of her dishes customers like. She could hire a food critic to score every plate. Or she could notice something simpler: the dishes she has started making more often than she used to are exactly the ones she now thinks are better. Her own change of habits already is a score. She is her own judge.
The question. RLHF needs a reward model, a reference model, the model being tuned, and a delicate reinforcement-learning loop. Is there a simpler way to learn from people's choices?
Turn the closed form around (Rafailov and colleagues, 2023). If , then taking logs and rearranging,
The reward is hiding inside the policy: it is times the log of how much more often the model says than the reference did. Now put this into Bradley–Terry (§11), which only needs the difference for two answers to the same prompt. The awkward is the same for both, so it cancels:
No reward model, no reinforcement learning — one supervised-style loss on pairs of answers, trained with ordinary gradient descent. This is direct preference optimisation, DPO.
By hand. . The reference gave the preferred answer and the rejected answer the probability 0.2 each. After some training, the policy gives 0.3 and 0.1.
At the start, when , the margin is 0 and the loss is : a coin toss. Training has moved it down to 0.6397. Each step pushes up and down, with the weight : big while the model still gets the pair wrong, small once it gets it right.
Because the closed form of §12 is a two-way street. Every reward function has one best leashed policy, and every policy is the best leashed policy for some reward function — the one hiding in its log-ratios (up to a constant for each prompt, which never matters). So instead of fitting a reward and then chasing it, DPO fits the policy directly, using the policy's own log-ratios as the reward in Bradley–Terry. The constant that we could never compute drops out of every comparison.
RLHF against DPO.
| RLHF (reward model + PPO) | DPO | |
|---|---|---|
| models during training | policy, reference, reward model (and a value network) | policy and reference |
| training | write answers, score them, reinforcement-learning steps | one loss on stored pairs, plain gradient descent |
| stability | delicate: many settings to tune | steady, like fine-tuning |
| cost | high | about the cost of fine-tuning |
| new answers during training | yes — it can explore | no — only the stored pairs |
Rule of thumb. With a fixed set of people's choices, DPO is the simple, strong first choice. RLHF earns its extra cost when the model should keep writing fresh answers and be scored on them as it learns.
DPO drops the reward model, not the reference. Every log-ratio needs , so the frozen starting model is still run on every pair — and the leash is still there, built into the loss.
The best leashed policy's log-ratios are a reward. Put them into Bradley–Terry and the unknown constant cancels: learn from people's choices with one loss, the model acting as its own judge.
At the very start of DPO the policy is a copy of the reference. What is the loss on any pair, whatever ?
The policy halves the probability of both answers in a pair. What happens to the DPO loss on that pair?
If you want the algebra · 1 proof, step by step
Claim. If the policy is the best leashed policy for some reward, , then Bradley–Terry's equals , with no left.
In one sentence: DPO turns the leash's closed form around — a policy's log-ratio against the reference is its hidden reward — so plugging it into Bradley–Terry cancels the unknown constant and trains on people's choices with one plain loss, the model acting as its own judge.
What to carry forward
The whole unit fits on thirteen cards. Each has one picture you should be able to draw from memory.
The loop
Read everything, give every token a probability, pick one, append, repeat. One run of the model, one new token.A bet on every word
Multiply the probabilities of the true tokens; take logs; average: loss 0.7675. Perplexity = a die with 2.15 faces.The tower
12Ld² in the floors (4d² attention, 8d² feed-forward) + Vd in the dictionary. GPT-2 small: 124 439 808.The thermostat
Divide the scores by T: cold makes the favourite a dictator (greedy), hot makes every token equal. The order never changes.The nucleus
Keep the fewest top tokens holding p of the probability, renormalise, draw. It adapts: 5 colours, 1 capital.The KV notebook
The mask freezes the past: keep every key and value. n rows of work, not n(n+1)/2 — paid for in memory, 2·L·d·b bytes per token.Clock hands
Pair turns radians per position; the score sees only the gap. Squeeze positions to stretch the context.The budget
C ≈ 6ND. Loss = floor + a power law in N + a power law in D. Balance them: about 20 tokens per parameter.The apprentice
Same next-token loss on good answers, with a mask: only the assistant's tokens are graded.The clip-on lens
Freeze W, learn ΔW = BA of rank r: 2dr numbers instead of d². Eckart–Young says the few top directions carry the change.The selector
P(A beats B) = σ(r_A − r_B). Each choice nudges the winner up and the loser down by 1 − σ. Only gaps matter.The kite
Maximise reward − β·KL. The best policy is π_ref · e^(r/β), normalised. Larger β, shorter string.Its own judge
A policy's log-ratio is its hidden reward. Put it into Bradley–Terry, the constant cancels: DPO, one plain loss.Where every tool came from. Almost nothing in this unit was new mathematics. It was the course's own tools, put to work at enormous scale.
| tool | where you met it | what it does inside an LLM |
|---|---|---|
| dot product | Unit 3 | every attention score, every next-token score |
| SVD, low rank, Eckart–Young | Unit 5 | LoRA: fine-tune with a thin slice (§10) |
| backprop: one backward sweep, two jobs per weight | Unit 7, Unit 15 | the 6 in (§8) |
| Adam | Unit 11 | the optimiser of every training run (§8) |
| softmax, surprise, cross-entropy, KL | Unit 14 | next-token probabilities, the loss, temperature, the leash (§1, §2, §4, §12) |
| prediction − truth | Unit 15 | the blame at every output, masked in SFT (§9) |
| chain of guesses, perplexity, subwords | Unit 16 | the chain rule of the loop, the die (§1, §2) |
| temperature, greedy, beam | Unit 17 | how the next token is picked (§4, §5) |
| attention, mask, rotary positions | Unit 18 | the engine; the cache; long contexts (§3, §6, §7) |
Where this goes next. In this unit a model wrote one token at a time, each one picked from a probability list. Unit 20 asks the same question for pictures: how can a machine create an image that has never existed? It will generate a whole picture at once — by starting from pure noise and removing it, step by small step.
An LLM is a next-token guesser trained on the average surprise of trillions of tokens, written out one token at a time with a sampler, made fast with a cache and long with clocks, and turned into an assistant by copying good answers and then chasing people's preferences on a KL leash.
In one sentence: Inside every chatbot is one loop — a probability for every next token, a sampler that picks one, a notebook of the past — trained to be unsurprised by human text and then taught, with a thin low-rank patch, a reward from people's choices and a leash, to be helpful.
Practice arena — sixteen problems, solved in full
Sixteen problems, in the order of the unit: next-token probabilities, scoring a sentence and reading a perplexity backwards, counting a model's parameters and its experts, temperature and the two tail cuts, the cache's work and memory, clock speeds, a training budget, the loss mask, a LoRA adapter, a preference, the leash and DPO. The tags say which are easy and which are hard. Every number here was checked by machine.
Three habits do most of the work. Work in logs: products of probabilities become sums, and powers become multiplications. Write the shapes and counts first: , , . And check that every list of probabilities adds up to 1 before you use it.
After "the train is", a model gives four tokens the scores late 2, early 0, full 1, banana −2. (a) Find the four probabilities. (b) Which token does greedy decoding write? (c) The model adds 3 to every score. What is the probability of "late" now?
What this tests. One move of the write loop (§1): scores → softmax → pick. Plan. Exponentiate, add, divide. For (c), remember what softmax ignores.
Show the full solution
answers at a glance: (a) . (b) late. (c) still .
Softmax sees only the gaps between scores. Shifting every score by the same amount changes nothing.
A model reads a four-token sentence and gives the true tokens the probabilities 0.5, 0.2, 0.9 and 0.4. Find (a) the probability of the sentence, (b) its log-likelihood, (c) the loss in nats per token, (d) the perplexity, (e) the loss in bits per token.
What this tests. The five ways to report the same thing (§2). Plan. Multiply; take logs; average and flip the sign; exponentiate; divide by .
Show the full solution
answers at a glance: (a) 0.036. (b) . (c) . (d) . (e) .
Perplexity is one over the geometric mean of the probabilities: the one probability that, used for every token, gives the same product.
A three-token sentence has perplexity exactly 2.5. The model gave the first two true tokens 0.5 and 0.8. What probability did it give the third?
What this tests. Reading perplexity backwards (§2). Plan. Perplexity , so the product is .
Show the full solution
answer at a glance: .
Perplexity over tokens means the sentence probability is .
GPT-2 medium has , blocks, a vocabulary of and a learned position table for 1 024 positions. Using per block and a final layer norm of , find (a) the numbers in one block, (b) the total with a tied output layer, (c) the total without tying.
What this tests. Where the parameters live (§3). Plan. Block, times ; then the tables; then decide how many token tables there are.
Show the full solution
answers at a glance: (a) 12 596 224. (b) 354 823 168. (c) 406 286 336.
Parameters ; tying the output to the input table saves one whole table.
A mixture-of-experts layer with has 16 experts, each a feed-forward room of numbers, and a router of numbers that keeps the top 2. For one token the router's first four scores are , and all the others are below 1. Find (a) which experts run and their weights, (b) the numbers stored in the experts, (c) the expert numbers used for this token, (d) the router's numbers.
What this tests. The router and "stored against used" (§3). Plan. Pick the two biggest scores and softmax just those two; then count.
Show the full solution
answers at a glance: (a) experts 2 and 4, weights and . (b) 536 870 912. (c) 67 108 864. (d) 32 768.
With top-2 routing over experts, memory grows with but the work per token only with 2.
Scores . Find (a) the probabilities at , (b) at . (c) At what temperature is the first token exactly twice as likely as the second?
What this tests. Temperature divides the scores (§4), and the ratio rule . Plan. For (c) set the ratio to 2 and solve for .
Show the full solution
answers at a glance: (a) . (b) . (c) .
Temperature raises every ratio to the power . To hit a target ratio, solve .
List A: . List B: . (a) Top-k 2 on A: the renormalised list. (b) Top-p 0.75 on A: how many tokens, and the renormalised list. (c) Top-p 0.8 on B. (d) Top-k 2 on B.
What this tests. The two cuts, on a flat-ish list and a peaked one (§5). Plan. Running totals for top-p; divide the kept ones by their sum.
Show the full solution
answers at a glance: (a) . (b) 3 tokens, . (c) 1 token, probability 1. (d) .
Top-p keeps many tokens when the model is unsure and few when it is sure; top-k keeps the same number either way.
A model has layers, , 40 attention heads and 16-bit numbers (2 bytes). (a) How many bytes of keys and values does it keep per token with multi-head attention? (b) For 8 192 tokens, in GiB? (c) With grouped-query attention using 8 key-value heads? (d) How much memory does the switch save?
What this tests. The cache bill (§6). Plan. With all 40 heads, .
Show the full solution
answers at a glance: (a) 819 200 bytes. (b) 6.25 GiB. (c) 1.25 GiB. (d) 5 GiB.
The cache grows with layers × key-value heads × head size × bytes × tokens; sharing key-value heads divides it directly.
(a) Show that writing tokens without a cache computes rows of keys and values in each layer. (b) Apply it to , and compare with the cache. (c) What is the shortest text for which the work without a cache passes one million rows?
What this tests. The triangle against the line (§6), and turning a formula around. Plan. Run processes tokens; add them up; then solve an inequality by trying values near the square root.
Show the full solution
answers at a glance: (a) . (b) 8 390 656 against 4 096, 2 048.5 times more. (c) .
Without a cache the work grows like ; with it, like . The longer the text, the bigger the win.
Rotary positions with and base 10 000. (a) List the eight speeds . (b) How many positions does the slowest hand need for one full turn? (c) The model was trained on 4 096 tokens. What is the largest gap angle its slowest hand saw? (d) It must now read 16 384 tokens. With interpolation, what is the scale, and what gap angle does the slowest hand show for a gap of 12 000?
What this tests. The clock speeds and interpolation (§7). Plan. ; a full turn is ; angles are gap (times the scale).
Show the full solution
answers at a glance: (a) : 1 … 0.0003162. (b) ≈ 19 869. (c) ≈ 1.295 rad. (d) scale 0.25; ≈ 0.949 rad (not 3.795).
The slow hands decide how far a model can see. Squeezing positions keeps their angles inside what training showed them.
You have a training budget of operations. (a) With and the rule , find and . (b) Use the fitted law to find its loss. (c) A colleague prefers a 100-billion-parameter model on the same budget. How many tokens can it read, and what loss does the law predict?
What this tests. , the 20-to-1 rule, and why balance wins (§8). Plan. ; then plug into the law, term by term.
Show the full solution
answers at a glance: (a) billion, billion. (b) . (c) tokens; .
For a fixed budget, a smaller model that reads more usually beats a bigger model that reads less.
In one fine-tuning chat, the user's three tokens get the probabilities 0.05, 0.3 and 0.6, and the assistant's four answer tokens get 0.7, 0.9, 0.95 and 0.6. (a) What is the SFT loss (with the mask)? (b) What would the loss be over all seven tokens? (c) Which single token contributes the most surprise to (b)?
What this tests. Only the answer is graded (§9). Plan. Surprise for each; average the ones that count.
Show the full solution
answers at a glance: (a) . (b) . (c) the user's first token (2.9957).
The mask keeps the loss about the answer. Without it, the hardest-to-guess user tokens would dominate.
(a) Compute for and , and find its rank. (b) For a matrix, for which ranks does LoRA store fewer numbers than the full change? (c) A model has 80 layers with . Adapters of rank 16 go on the query and value matrices of every layer. How many numbers are trained?
What this tests. and the count (§10). Plan. Multiply; look for a row that is a combination of the others; then compare with .
Show the full solution
answers at a glance: (a) rows (1, 2, 0), (0, 1, −1), (1, 3, −1); rank 2. (b) . (c) 41 943 040.
A rank- adapter on a matrix costs numbers; the saving is huge only because is tiny compared with .
A reward model scores the answer a person preferred at and the rejected one at . (a) What chance did it give the person's choice? (b) What is the loss? (c) With step size 0.5, find the two new rewards. (d) What is the new chance?
What this tests. The preference loss and its nudge (§11). Plan. of the gap; minus its log; then move both rewards by .
Show the full solution
answers at a glance: (a) . (b) . (c) , . (d) .
The nudge is the probability the model gave to the choice that did not happen: large when it was wrong, small when it was right.
Three answers: reference , rewards . (a) Find for . (b) Find the expected reward, the KL and the objective, and check that the objective equals . (c) Find for . Which answer's share changes most between the two?
What this tests. The closed form (§12). Plan. Boost each answer, add the boosts to get , divide.
Show the full solution
answers at a glance: (a) . (b) , , . (c) ; the third answer.
is softmax of with the reference as a head start; the best value of the objective is .
With , the reference gives the preferred answer 0.1 and the rejected answer 0.3. After training, the policy gives them 0.2 and 0.15. (a) Find the two log-ratios. (b) Find the margin and the DPO loss. (c) What was the loss before training? (d) How strongly does the next step push, ?
What this tests. DPO's loss from probabilities (§13). Plan. for each; subtract; multiply by ; then .
Show the full solution
answers at a glance: (a) and . (b) margin , loss . (c) . (d) .
DPO compares how far each answer moved from the reference. The absolute probabilities do not matter — only the two log-ratios.