RL for Reasoning

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.

Train a model on its own checked answers

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

Bigger Models Still Answer in One Pass

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.

ModelYearParameters
GPT-220191.5 billion
GPT-32020175 billion
GPT-42023not 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?"

Give the player some lookahead

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.

The road

  1. Test-time compute: a second axis, and its cost per query.
  2. Games: evaluation plus search, from backgammon to poker.
  3. Monte Carlo tree search: how AlphaGo Zero spends its thinking.
  4. Chain of thought: tokens as compute.
  5. Many samples: coverage and the majority vote.
  6. Verifiers: best-of-N, and its blind spot.
  7. o1 and o3: thinking trained by RL, and the cost frontier.
  8. GRPO: the hero's update, derived.
  9. GRPO in full: the clip, the anchor and the DeepSeek-R1 recipe.
  10. The field guide: terms, numbers, code and links.
Why can a large model recall strong chess moves but blunder at tic-tac-toe?

Chapter 1

Test-Time Compute: A Second Axis

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 methodAIME 2024 solved
GPT-4o12% (1.8 of 15)
o1, one sample74% (11.1 of 15)
o1, consensus of 64 samples83% (12.5 of 15)
o1, 1,000 samples re-ranked by a learned scorer93% (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.

Choose: train bigger, or think longer

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.

With the prices above, about how many queries does it take before training the bigger model is cheaper?

Chapter 2

Games: Search Beats Scale

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.

ProgramYearEvaluationSearch
TD-Gammon (backgammon)early 1990sa network trained by self-play2 to 3 moves ahead
Deep Blue (chess)1997written by handalpha-beta, many moves deep
AlphaGo Zero (Go)2017a policy and value networkMonte Carlo tree search
Libratus (poker)2017a blueprint strategy computed offlinesubgame 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.

Say it aloud

N equals b to the d.

N
N the number of positions at the bottom of the search tree.
b
b the branching factor: legal moves per position. About 35 in chess.
d
to the d the depth: how many ply ahead the search looks. Multiply b by itself d times.
In plain words

Each ply multiplies the positions by b. Do it d times. The count is N.

With numbers

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.

Measure a search tree against the clock

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.

12

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.

At best, alpha-beta visits about b to the power d/2 positions. For chess at depth 12, about how many is that?

Chapter 3

Go: Monte Carlo Tree Search

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.

  1. Select. From the root, walk down. At each position pick the move with the highest score from the equation below.
  2. Expand. When you reach a position not yet in the tree, add it.
  3. Evaluate. Score it. Classic MCTS plays random moves to the end. AlphaGo Zero asks its value network.
  4. Back up. On every position along the path, add one visit and update the average result.

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).

Say it aloud

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.

UCB(s,a)
U-C-B of s and a the upper confidence bound: the score used to pick move a at position s.
Q(s,a)
Q of s and a the average result of the simulations that tried move a, from 0 (loss) to 1 (win).
c
c the exploration constant: how strongly the search favours rarely tried moves. 1.4 here.
√
the square root of it makes the bonus shrink slowly as a move gets more visits.
ln N(s)
log N of s the natural log of the visits to position s. It grows slowly as the search runs.
N(s,a)
N of s and a how many simulations have tried move a.
In plain words

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 numbers

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.

Run the search one simulation at a time

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.

1.4

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.

Two moves have the same average result Q. One has 50 visits, the other 5. Which does UCB favour?

Chapter 4

Chain of Thought: Tokens as Compute

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.

DomainLearned partSearch at test time
Backgammonvalue network2 to 3 ply lookahead
Chesshand-written evaluationalpha-beta
Gopolicy and value networkMCTS, 1,600 simulations a move
Pokerblueprint strategysubgame solving
Languagethe trained modela 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.

Answer at once, or write the steps

Drag the number of steps the problem needs. Compare answering in one go with writing each step down.

4

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.

Why does writing intermediate steps help a model on a multi-step problem?

Chapter 5

Many Samples: Coverage and the Majority Vote

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.

Say it aloud

Pass at k equals one minus, one minus p, to the k.

pass@k
pass at k the coverage: the chance that at least one of k samples is right.
1 − p
one minus p the chance that one sample is wrong; p is the chance it is right.
k
to the k multiply by itself k times, once per sample: the chance all k are wrong.
In plain words

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 numbers

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.

Say it aloud

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.

Pmaj
P-maj the chance that the majority vote is right.
Σj > N/2
the sum over j greater than N over 2 one term for each count j of right samples that is a majority of N.
C(N, j)
N choose j the number of ways to choose which j of the N samples are the right ones.
pj
p to the j the chance that those j samples are all right.
(1 − p)N − j
one minus p to the N minus j the chance that the other N minus j samples are all wrong.
In plain words

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 numbers

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.

Watch coverage climb while the vote stalls

Warm is pass@k, blue is the majority vote. Set p and k, then switch how the wrong answers behave.

0.20
16

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.

p = 0.2, and wrong samples scatter over 4 wrong answers that are each as likely as the right one. With 16 samples, what are pass@16 and the vote's accuracy?

Chapter 6

Verifiers and Best-of-N

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.

VerifierWhat it scoresExample
A rulethe final answer, exactlycompare the number with the known answer; run the tests
Outcome reward model (ORM)the final answer, as a learned scorea model trained on graded solutions
Process reward model (PRM)each step of the chaina model trained on step-level labels

Pick the best of N with a checker

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.

2.0

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.

Wrong answers scatter. Why does best-of-N with a good verifier beat the majority vote?

Chapter 7

o1 and o3: Thinking Trained by RL

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.

Spend one budget on two models

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.

Accuracy rises 10 points per 10× compute. You are at 40% with 100 units. What does 60% cost?

Chapter 8

GRPO: Score Each Answer Against Its Group

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.

Say it aloud

A-hat-i equals r-i minus the mean of r, divided by the standard deviation of r.

Âi
A-hat-i the advantage of answer i: how far above or below its group it scored.
ri
r-i the reward of answer i: 1 if right, 0 if wrong.
mean(r)
the mean of r the average reward of the G answers in the group.
std(r)
the standard deviation of r the spread of the group's rewards.
In plain words

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.

With numbers

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.

Say it aloud

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.

g
g the update direction for the weights.
(1/G) Σi
one over G times the sum over i the average over the G answers in the group.
Âi
A-hat-i the advantage of answer i, from the equation above.
∇θ
grad-theta the direction in weight space that raises what follows fastest.
log πθ(oi | q)
log pi-theta of o-i given q the log of the chance that the model writes answer o-i to question q.
In plain words

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.

With numbers

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.

Compute the advantages of one group

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).

0.40

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.

G = 8 and 3 answers are right. What is the advantage of a right answer?

Chapter 9

GRPO in Full: the Clip, the Anchor and the R1 Recipe

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.

Say it aloud

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.

J(θ)
J of theta the score the update raises.
(1/G) Σi
one over G times the sum over i the average over the group's answers.
min
the minimum of take the smaller of the two terms: the cautious one.
ρi
rho-i the new chance of answer i divided by its chance under the old policy. 1 means no change. A-hat-i is its advantage.
clip(ρi, 1 − ε, 1 + ε)
clip of rho-i rho-i held inside the band from 1 minus epsilon to 1 plus epsilon. Epsilon is 0.2 here.
β
beta the weight of the anchor: a small number.
DKL(πθ ‖ πref)
the KL divergence of pi-theta from pi-ref how far the new policy has moved from the reference model.
In plain words

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.

With numbers

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.

Find where the clip stops the 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.

1.50
0.20

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.

StageWhat happens
R1-ZeroGRPO 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 startFine-tune on thousands of long chain-of-thought examples first, for readable output.
R1: RL and moreGRPO with rule rewards, plus a reward for staying in one language, then more stages for general use.
DistillationSix 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.

A right answer has advantage +1.29, epsilon = 0.2, and its ratio is 1.5. What is its clipped term?

Chapter 10

The Field Guide

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.

Terms and numbers

TermWhat it isNumber to remember
Test-time computetokens spent before the final answero1 on AIME 2024: 74% (one sample), 93% (1,000 re-ranked)
Branching factor blegal moves per positionabout 35 in chess, 250 in Go
Search tree sizeb to the d positions; alpha-beta at best about b to the d/23512 = 3.4 × 1018; 356 = 1.8 billion
Search in pokersubgame solving at each decision−9.16 (Claudico) to +14.7 (Libratus) big blinds per 100 hands
UCBQ 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 thoughtwritten steps as working memoryPaLM 540B on GSM8K: 17.9% to 56.9%
pass@k1 minus (1 minus p) to the kp = 0.2, k = 16: 97.2%
Majority votethe most common final answerMinerva 540B on MATH: 33.6% to 50.3% with 64 votes
Best-of-Nthe answer with the top verifier scorereaches pass@N only with a perfect verifier
Group advantage(r minus the group mean) over the group spread3 of 8 right: +1.29 and −0.77
Clip bandratio held inside 1 ± epsilonepsilon = 0.2 is a common choice
R1-ZeroGRPO on a base model with rule rewards onlyAIME 2024: 15.6% to 71.0%

When to think fast and when to think hard

QuestionThink fastThink hard
Difficultyeasy, a lookuphard, new
Volumemany queries, cost mattersfew queries, quality matters
Latencyneeds an answer nowcan wait seconds or minutes
Checkinghard to check (a poem)easy to check (maths, code)

Checklist before you train with GRPO

The core in 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.

Open problems

Keep going

The takeaway. Sample several answers, check them, and push the model toward the ones that were right, measured against their own group. Search at answer time and RL on checked answers are the same idea at two speeds.

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.

Credit and sources

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).

CS 224R: RL for LLMs: Reasoning (Noam Brown)
The course site · OpenAI o1 · DeepSeekMath · DeepSeek-R1 · Back to Gleams