Let the model try several answers, check each one, and make the paths that scored more likely. In the toy below, 7 rounds of 8 checked tries lift the chance of a correct path from 35% to about 90%.
Learn why compute spent at answer time works, from game search to votes and verifiers, and how GRPO turns a checker's verdicts into training.
Press Sample a group. The model writes 8 answers to one maths problem and the checker marks each. Press Update and watch the chances move to the paths that scored. Then press Train. Then we build it piece by piece: search in games, chain of thought, many samples, verifiers and GRPO.
You need a little Python and what a probability is. Policy gradients help in Chapter 8. We build the rest from zero.
Re-taught from the guest lecture by Noam Brown (OpenAI), RL for LLMs: Reasoning, in Stanford CS 224R: Deep Reinforcement Learning. The explanations, toys and toy numbers here are our own.
Illustrative toy. The model is a softmax over 4 reasoning paths, starting at 20%, 35%, 30% and 15%; paths A and D reach the right answer, 7. Each update is one policy gradient step with the group advantage of Chapter 8 and a step size of 1. In 200 simulated runs with groups of 8, the chance of a correct path rose from 35% to about 90% after 7 rounds.
Chapter 0
See what scaling bought, and what a model cannot do when it must answer without looking ahead
Ask a strong language model to play tic-tac-toe. In Brown's example, GPT-4 makes illegal moves and misses blocks that a child sees. The same model writes fluent essays and recalls chess openings. Why does the small game break it?
From 2019 to 2023, progress came mostly from scaling: more parameters, more data and more training compute. Each step made the model know more.
| Model | Year | Parameters |
|---|---|---|
| GPT-2 | 2019 | 1.5 billion |
| GPT-3 | 2020 | 175 billion |
| GPT-4 | 2023 | not published by OpenAI |
Knowing is not looking ahead. A model writes each token in one forward pass: one fixed trip through its layers. Chess notation fills the web, so the model can recall good chess moves. Tic-tac-toe written in words is rare. The game has only 5,478 legal positions, but the model never saw most of them. One pass cannot ask "if I go here, what does my opponent do?"
X is the model and must move. Pick a position, then compare a player that moves by habit with players that search ahead.
Illustrative stand-in. The habit player takes the first free square in a fixed order: centre, then corners from the bottom right, then edges. It stands in for a pattern recalled in one pass. The search players run real minimax. O moved first in each position.
Position 2 shows the gap. X can win at once on square 6, which also blocks O's column. The habit player takes corner 7, and O completes 3, 6, 9 on the next move. A search 2 moves deep finds square 6, because it tries each move and then each reply.
The failure. The symptom is a model that is right on familiar inputs and wrong on rare ones. Measure it on fresh cases it cannot have memorized, beside familiar ones. The fix is compute at answer time: a way to try moves before it commits. That is this lesson.
Chapter 1
Spend compute when the question arrives, and weigh it against compute spent once in training
A hard maths question arrives. You can answer at once, or think for a minute first. People think first. Language models answered at once until 2024.
Training compute is what you spend once to build the model. Test-time compute is what you spend each time it answers: the tokens it writes before the final answer. OpenAI's o1 writes a long hidden chain of reasoning first. OpenAI reports that o1 improves with more reinforcement learning and with more time spent thinking.
| Model and method | AIME 2024 solved |
|---|---|
| GPT-4o | 12% (1.8 of 15) |
| o1, one sample | 74% (11.1 of 15) |
| o1, consensus of 64 samples | 83% (12.5 of 15) |
| o1, 1,000 samples re-ranked by a learned scorer | 93% (13.9 of 15) |
Source: OpenAI, Learning to reason with LLMs (2024). AIME is a 15-problem competition maths exam.
The two costs behave differently. Training is a fixed cost: pay once, use it for every query. Thinking is a variable cost: pay again on every query. So the cheaper choice depends on how many queries you serve.
Both options reach the same accuracy. Drag the number of queries and see which total cost is lower.
Illustrative prices: training the bigger model costs an extra $1,000,000, then $0.001 per query; the smaller model that thinks longer costs $0.05 per query.
With those made-up prices, the costs match when 1,000,000 + 0.001 × Q = 0.05 × Q, where Q is the number of queries. So Q = 1,000,000 / 0.049, about 20.4 million. Below that, thinking longer is cheaper. Above it, the bigger model wins.
The failure: overthinking. The symptom is a bill that rises while easy questions get no better. Measure accuracy and tokens per question, split by difficulty. The fix is to send easy questions to a short answer and keep long thinking for hard ones.
Chapter 2
Follow learned evaluation plus search from backgammon to poker, and count what a search tree costs
Game programs learned this decades ago. A strong program has two parts. An evaluation says how good a position looks. A search tries moves ahead and backs up the best result.
| Program | Year | Evaluation | Search |
|---|---|---|---|
| TD-Gammon (backgammon) | early 1990s | a network trained by self-play | 2 to 3 moves ahead |
| Deep Blue (chess) | 1997 | written by hand | alpha-beta, many moves deep |
| AlphaGo Zero (Go) | 2017 | a policy and value network | Monte Carlo tree search |
| Libratus (poker) | 2017 | a blueprint strategy computed offline | subgame solving at each decision |
Search is costly because the tree grows fast. One ply is one move by one player. Call the number of legal moves in a position the branching factor b, and the number of ply the search looks ahead the depth d.
N equals b to the d.
Each ply multiplies the positions by b. Do it d times. The count is N.
Chess with b = 35 and d = 12: N = 3512, about 3.4 × 1018 positions. At 200 million positions per second, that takes about 535 years.
Alpha-beta pruning skips branches that cannot change the choice. At best it visits about bd/2 positions: 356 = 1.8 billion, about 9 seconds at 200 million per second. IBM described Deep Blue as able to evaluate 200 million positions per second, and it beat Kasparov in 1997.
Pick a game and drag the depth. The marker shows the positions the search must visit, on a ruler marked in time at 200 million positions per second.
Branching factors are typical averages. The pruned count is the best case, about b to the power d/2; real alpha-beta lands between the two markers.
Poker gives Brown's cleanest test. In 2015 Claudico, a Carnegie Mellon bot with no real-time search, lost to top professionals by 9.16 big blinds per 100 hands. In 2017 Libratus, built by Brown and Tuomas Sandholm, added subgame solving: at each decision it re-solved the part of the game it was in. It beat top professionals by 14.7 big blinds per 100 hands. Libratus also had other changes; the lecture credits search as the key one.
The failure. The symptom is a search that cannot reach its depth in time. Measure positions per second against bd. The fix is to prune, or to let a learned evaluation pick which moves to try first. Go needs that fix.
Chapter 3
Grow a search tree one simulation at a time, and give rarely tried moves a bonus
Go has about 250 legal moves per position. Four ply is already about 3.9 billion positions, so full-width search is hopeless. Monte Carlo tree search (MCTS) grows the tree only where it looks promising, one simulation at a time.
After the last simulation, play the move with the most visits. The hard part is step 1: take the move that looks best, or try one you know little about? Call the average result of move a from position s Q(s,a). Call the visits to the position N(s) and the visits to the move N(s,a).
U-C-B of s and a equals Q of s and a, plus c times the square root of log N of s, divided by N of s and a.
Start from the move's average result Q. Add a bonus that is large when the move's visits N of s and a are few compared with the position's visits N of s. Pick the move with the largest total.
With made-up counts: N(s) = 20. Move A has 15 visits and Q = 0.60. Move B has 5 visits and Q = 0.40. With c = 1.4, A scores 0.60 + 1.4 × √(ln 20 / 15) = 1.23 and B scores 0.40 + 1.4 × √(ln 20 / 5) = 1.48. The search tries B next.
Each bar is a move: its height is its share of visits, the dot is its average result Q. Step, then run 200, then set c to 0 and reset.
Illustrative and one level deep: the root's four moves win 45%, 62%, 38% and 55% of random playouts. A real tree repeats this choice at every level.
AlphaGo Zero ran 1,600 simulations per move. It used a variant of this rule that also weighs each move by its policy network's prior. In its paper the raw network alone rated about 3,000 Elo, and the network with search about 5,200. On the Elo scale, a 400-point gap means the stronger side wins about 10 games in 11.
The failure. With c = 0 the search is greedy. The symptom is one move that takes almost every visit after a lucky early result. Measure each move's visit share against its true win rate, as in the device. The fix is a larger c.
Chapter 4
Map the game recipe onto language, and see why writing the steps gives the model room to compute
Brown maps the game recipe onto language models. The trained model plays the part of the evaluation and the policy. The search part is new for language.
| Domain | Learned part | Search at test time |
|---|---|---|
| Backgammon | value network | 2 to 3 ply lookahead |
| Chess | hand-written evaluation | alpha-beta |
| Go | policy and value network | MCTS, 1,600 simulations a move |
| Poker | blueprint strategy | subgame solving |
| Language | the trained model | a chain of thought, many samples, checks |
The simplest search is to show the work. Chain-of-thought (CoT) prompting puts a few worked examples in the prompt, so the model writes its steps before the answer.
Wei et al. (2022) use this problem: "Roger has 5 tennis balls. He buys 2 more cans of tennis balls. Each can has 3 tennis balls. How many tennis balls does he have now?" With CoT the model writes "2 cans of 3 balls is 6. 5 + 6 = 11."
Why does writing help? Each new token costs one forward pass. A written step stores a result, and every later token can read it. The chain is working memory, and each extra token adds computation for this one question.
Drag the number of steps the problem needs. Compare answering in one go with writing each step down.
Illustrative rates: each written step is right 97% of the time. Answering at once fits the first 2 steps; each step beyond 2 halves the chance.
With those made-up rates, a 4-step problem with every step written comes out right 0.974 = 89% of the time. Answered at once it comes out right 0.974 × 0.52 = 22% of the time.
Wei et al. report the real effect for PaLM 540B. On GSM8K maths word problems, accuracy rose from 17.9% to 56.9% with CoT. On SVAMP it rose from 69.4% to 79.0%. The gain appeared only at scale: below about 100 billion parameters, chains were fluent but illogical and did not help.
The failure. The symptom is a chain that reads well and ends at a wrong answer. Measure it by checking each step, not only the last line. The fix is to sample several chains and check them, as Chapters 5 and 6 do.
Chapter 5
Sample many answers, and see why the chance that one is right keeps climbing while the vote can stall
One chain can go wrong. So sample many chains for the same question and combine them. Majority vote, also called self-consistency (Wang et al., 2022), returns the most common final answer. Lewkowycz et al. (2022) report that Minerva 540B scored 33.6% on the MATH benchmark with one sample and 50.3% with a vote over 64.
A second number is coverage: the chance that at least one sample is right. Call the chance that one sample is right p, and the number of independent samples k.
Pass at k equals one minus, one minus p, to the k.
Take the chance one sample is wrong, 1 minus p. Raise it to the k: that is the chance all k samples are wrong. Subtract it from 1.
With p = 0.2 and k = 16: 0.816 = 0.028, so pass@16 = 0.972. A right answer is almost always somewhere in the 16.
Now the vote, in the simplest case: every wrong sample gives the same wrong answer. With N samples (N odd), the vote is right when more than half are right. Call the count of right samples j.
P-maj equals the sum over j greater than N over 2, of N choose j, times p to the j, times one minus p to the N minus j.
For each count j that beats half of N, find the chance of exactly j right samples. Add those chances. The total is P-maj.
With p = 0.6 and N = 5: j = 3, 4 and 5 give 0.346, 0.259 and 0.078, so P-maj = 0.683. With p = 0.4 the same sum is 0.317. The vote lifts a p above one half and buries a p below it.
Warm is pass@k, blue is the majority vote. Set p and k, then switch how the wrong answers behave.
Exact sums for "agree"; 4,000 simulated votes per point for "scatter". A tie gives each tied answer an equal share.
The hard case is p = 0.2 with the wrong samples scattered evenly over 4 wrong answers. Then each wrong answer is as likely as the right one. With 16 samples pass@16 is 97.2%, but the vote is a five-way race between equals and picks the right answer about 20% of the time.
The failure: saturation. The symptom is a vote whose accuracy flattens as you add samples. Measure vote accuracy and pass@k against k. A widening gap means the right answer is there and the selector misses it. The fix is a better selector: a verifier.
Chapter 6
Score each sample with a checker, keep the best, and find where an imperfect checker breaks
Checking is often easier than solving. You can check a proof line by line without the insight that found it. You can run unit tests without writing the code. A verifier turns that gap into accuracy.
Best-of-N samples N answers, scores each with a verifier, and returns the one with the top score. With a perfect verifier, best-of-N reaches pass@N. Verifiers come in three kinds.
| Verifier | What it scores | Example |
|---|---|---|
| A rule | the final answer, exactly | compare the number with the known answer; run the tests |
| Outcome reward model (ORM) | the final answer, as a learned score | a model trained on graded solutions |
| Process reward model (PRM) | each step of the chain | a model trained on step-level labels |
p is 0.2 and wrong answers scatter over 4 values. Drag the checker's skill. Then switch on a blind spot: a few wrong answers the checker likes.
Illustrative simulation, 3,000 trials per point. The checker scores a right answer higher by the skill value on average, plus noise of size 1. With the blind spot on, 5% of wrong answers score 1 point above a right answer on average.
With a perfect checker and N = 16, best-of-N reaches pass@16, 97.2%, while the vote stays near 20%. OpenAI's o1 numbers from Chapter 1 follow the same order. One sample gave 74%, a vote of 64 gave 83%, and re-ranking 1,000 samples with a learned scorer gave 93%.
The failure: reward hacking at selection. A learned verifier is a proxy. As N grows, best-of-N searches harder for answers the verifier likes, and that includes wrong answers it rates high. The symptom is accuracy that rises with N, then falls. Measure accuracy against N on held-out questions with known answers. The fix is a rule-based or stronger verifier, or a cap on N.
Chapter 7
Read the log-linear shape of thinking, and the frontier of accuracy against cost
Chapters 4 to 6 search with a fixed model. o1 goes further: training teaches the model to search inside its own chain of thought. OpenAI writes that its "large-scale reinforcement learning algorithm teaches the model how to think productively using its chain of thought." The model learns to spot and fix its mistakes, to split hard steps into simpler ones, and to try a different approach when one fails.
OpenAI's charts plot o1's AIME accuracy against test-time compute on a log axis, and the points rise steadily. That shape is log-linear: each 10× more compute adds about the same number of points.
With a made-up slope of 10 points per 10×: 1 unit of compute gives 20%, 10 units give 30%, and 100 units give 40%. The step from 20% to 30% costs 9 extra units. The step from 30% to 40% costs 90.
A Pareto frontier is the best accuracy you can buy at each cost. More compute moves you along a frontier. A better model moves the whole frontier up and to the left. OpenAI presented its later o3 model as that kind of move.
Each line is a model's frontier: more compute per problem, more accuracy. Drag the budget and compare what each model buys.
Illustrative frontiers, not real prices. Older model: 20% + 10 points per 10× compute, at $0.01 per unit. Newer model: 35% + 12 points per 10×, at $0.02 per unit. Both capped at 97%.
The failure: diminishing returns. The symptom is a bill that grows 10× for each fixed gain. Measure accuracy against the log of compute and read the slope. The fix is a better model, which lifts the frontier, instead of more compute along the same one.
Chapter 8
Turn a group of checked answers into advantages without a critic, and push the policy toward the winners
To train a model to reason, reward right answers. For maths the reward is a rule: 1 if the final answer matches, 0 if not. GRPO (Group Relative Policy Optimization) comes from DeepSeekMath (Shao et al., 2024). DeepSeek-R1 (2025) used it at scale.
The policy gradient raises the log-probability of each sampled answer in proportion to its advantage: how much better it did than usual. PPO estimates "usual" with a critic, a second network about as large as the policy. GRPO drops the critic. It samples a group of G answers to one question q and compares each answer with the rest.
Call the reward of answer i ri.
A-hat-i equals r-i minus the mean of r, divided by the standard deviation of r.
Subtract the group's average reward from each reward r-i. Divide by the group's spread. A right answer in a mostly wrong group gets a large positive A-hat-i.
G = 8 and 3 answers are right: rewards 1, 1, 1, 0, 0, 0, 0, 0. The mean is 0.375 and the spread is 0.484. A right answer gets (1 − 0.375) / 0.484 = +1.29. A wrong one gets (0 − 0.375) / 0.484 = −0.77. The 8 advantages add to 0.
Call the model's chance of writing answer oi to question q πθ(oi | q), where θ are its weights.
g equals one over G times the sum over i of A-hat-i, times grad-theta of log pi-theta of o-i given q.
For each answer o-i, find the weight change that makes it more likely. Scale that change by A-hat-i. Average over the group, then step the weights along g.
In the group above, the 3 right answers get weight +1.29 each and the 5 wrong ones −0.77 each. 3 × 1.29 = 3.87 and 5 × 0.77 = 3.87, so the push up balances the push down.
Set how often the model is right and the group size, then sample. Purple bars are the advantages. Try a hard question (p near 0.1).
Illustrative: each answer is right with chance p, independently. The spread is the population standard deviation; some code divides by G − 1 instead, which shrinks every advantage by the same factor.
The failure: groups with no signal. If all answers get the same reward, the spread is 0 and every advantage is 0 (code adds a tiny number to avoid dividing by 0). With p = 0.1 and G = 8 that happens 0.98 + 0.18 = 43% of the time. Measure the share of groups with zero spread. Fix it with questions the model solves sometimes.
Chapter 9
Keep each update small with a clip and a KL anchor, then follow DeepSeek-R1 from base model to reasoner
One group's gradient can be large, and a big step can wreck a model. GRPO borrows PPO's guard. It compares the new policy with the old policy that sampled the group. Call the new chance of answer i divided by its old chance ρi (rho-i). Call the half-width of the allowed band ε (epsilon). Call the model before RL the reference, πref.
J of theta equals one over G times the sum over i of the minimum of rho-i A-hat-i and clip of rho-i between one minus epsilon and one plus epsilon, times A-hat-i, minus beta times the KL divergence of pi-theta from pi-ref.
Score each answer by rho-i times A-hat-i. Once rho-i leaves the band in the helpful direction, stop that score from growing. Average over the group, then subtract beta times the distance from the reference.
A right answer has A-hat = +1.29 and epsilon = 0.2. The update raised its chance by half, so rho = 1.5. The plain term is 1.5 × 1.29 = 1.94; the clipped term is 1.2 × 1.29 = 1.55. The minimum, 1.55, is flat in rho, so this answer gets no more push.
The solid purple line is the clipped term; the faint dashed line is the plain term. Drag the ratio and switch between a right and a wrong answer.
The advantages come from Chapter 8's group. In code, take the ratio per token and average it over each answer's tokens.
DeepSeek-R1 put this to work in stages, starting from the base model DeepSeek-V3-Base.
| Stage | What happens |
|---|---|
| R1-Zero | GRPO straight on the base model, with two rule rewards: a right answer, and reasoning placed between think tags. No supervised data first. AIME 2024 accuracy rose from 15.6% to 71.0% during training. |
| R1: cold start | Fine-tune on thousands of long chain-of-thought examples first, for readable output. |
| R1: RL and more | GRPO with rule rewards, plus a reward for staying in one language, then more stages for general use. |
| Distillation | Six smaller Qwen and Llama models (1.5B to 70B) fine-tuned on R1's outputs. |
The failure. R1-Zero shows what pure RL gives: the paper reports poor readability and language mixing. The symptom is a chain that switches language mid-thought. Measure the share of the chain in the target language. The fix is the cold start and the language reward of R1.
Chapter 10
Keep the terms, the numbers, the checklist and the core code in one place
Training gives a model knowledge. Search at answer time gives it a way to use that knowledge on new problems. Games showed the recipe first: a learned evaluation plus search. For language, the search is a chain of thought, many samples and a checker. GRPO trains the model on its own checked samples, so the search moves inside the model.
| Term | What it is | Number to remember |
|---|---|---|
| Test-time compute | tokens spent before the final answer | o1 on AIME 2024: 74% (one sample), 93% (1,000 re-ranked) |
| Branching factor b | legal moves per position | about 35 in chess, 250 in Go |
| Search tree size | b to the d positions; alpha-beta at best about b to the d/2 | 3512 = 3.4 × 1018; 356 = 1.8 billion |
| Search in poker | subgame solving at each decision | −9.16 (Claudico) to +14.7 (Libratus) big blinds per 100 hands |
| UCB | Q plus c times the square root of log N(s) over N(s,a) | c about 1.4; AlphaGo Zero: 1,600 simulations a move |
| Chain of thought | written steps as working memory | PaLM 540B on GSM8K: 17.9% to 56.9% |
| pass@k | 1 minus (1 minus p) to the k | p = 0.2, k = 16: 97.2% |
| Majority vote | the most common final answer | Minerva 540B on MATH: 33.6% to 50.3% with 64 votes |
| Best-of-N | the answer with the top verifier score | reaches pass@N only with a perfect verifier |
| Group advantage | (r minus the group mean) over the group spread | 3 of 8 right: +1.29 and −0.77 |
| Clip band | ratio held inside 1 ± epsilon | epsilon = 0.2 is a common choice |
| R1-Zero | GRPO on a base model with rule rewards only | AIME 2024: 15.6% to 71.0% |
| Question | Think fast | Think hard |
|---|---|---|
| Difficulty | easy, a lookup | hard, new |
| Volume | many queries, cost matters | few queries, quality matters |
| Latency | needs an answer now | can wait seconds or minutes |
| Checking | hard to check (a poem) | easy to check (maths, code) |
pythonimport torch def group_advantages(rewards, eps=1e-6): # rewards: [G], one per answer to the same question mean, std = rewards.mean(), rewards.std(unbiased=False) return (rewards - mean) / (std + eps) # [G]; all 0 when every reward is equal def grpo_loss(logp_new, logp_old, logp_ref, adv, mask, clip=0.2, beta=0.04): # logp_*: [G, T] log-probs of each sampled token; adv: [G]; mask: [G, T], 1 on answer tokens ratio = torch.exp(logp_new - logp_old) # rho, per token a = adv[:, None] surr = torch.minimum(ratio * a, ratio.clamp(1 - clip, 1 + clip) * a) d = logp_ref - logp_new kl = torch.exp(d) - d - 1 # per-token KL estimate used by DeepSeekMath per_tok = surr - beta * kl per_ans = (per_tok * mask).sum(1) / mask.sum(1) # average over each answer's tokens return -per_ans.mean() # minimise the negative of J
The defaults clip = 0.2 and beta = 0.04 are illustrative starting points, not values from this lesson's sources.
Now press Present or Teach and explain three things from memory. Why can one forward pass not look ahead? Why does coverage climb while the vote stalls? How does a group of 8 checked answers become an update? Then go back to the hero, shrink the group to 4, and say why some rounds teach nothing.
This lesson re-teaches the guest lecture RL for LLMs: Reasoning by Noam Brown (OpenAI) in Stanford CS 224R: Deep Reinforcement Learning. The explanations, toys and devices are our own. Published numbers come from these sources. OpenAI, Learning to reason with LLMs; Wei et al., Chain-of-thought prompting; Lewkowycz et al., Minerva; Shao et al., DeepSeekMath; DeepSeek-AI, DeepSeek-R1; Silver et al., AlphaGo Zero (Nature, 2017); and Brown and Sandholm on Libratus (Science, 2018).