Alignment II: RLVR & GRPO

When a program can check the answer, the checker can be the reward. In a toy run, GRPO lifts checked accuracy from 45.8% to 66.0% in 150 steps, with no critic. Train on a learned judge instead, and the judge's score climbs to 69.6% while checked accuracy falls to 33.0%.

Press Train and watch the policy move toward answers that pass the check. Then switch the reward to the learned judge and train again. Then we build each part from zero, up to the R1, Kimi and Qwen recipes.

You need a probability and a gradient step. Lecture 15's reward models and PPO help, but we build what we use.

Lecture 16 of Stanford CS336, Language Modeling from Scratch (Spring 2025, Percy Liang and Tatsunori Hashimoto). Previous: Lecture 15, Alignment I: SFT and RLHF. Next: Lecture 17, Alignment III: Policy Gradients.

Train a tiny reasoner on a reward

G = 8

Illustrative toy, computed live and seeded. A policy picks one of five answer strategies for 16 made-up problems, from trivial to impossible. Each step draws G answers per problem and makes one GRPO update (group z-score, no critic). The judge's score mixes correctness (40%) with long, confident style (60%). Checked accuracy is the exact chance of a right answer.

Chapter 0

Check the Answer Instead of Judging It

Replace a learned judge with a program that checks the answer, and find what the program can still miss

Lecture 15 trained a reward model on human preferences, then pushed the policy toward high scores. That works up to a point. Past it, the policy finds what the reward model likes but people do not. The lecture calls this overoptimization, and it is why RLHF does not scale cleanly.

Some tasks need no judge. A math problem has a final answer you can compare with a key. A coding problem has unit tests. A verifier is a program that reads a response and returns 1 if it is right and 0 if not. Reinforcement learning with verifiable rewards (RLVR) trains on that 0 or 1.

The hero shows the difference. With the checker, checked accuracy climbs from 45.8% to 66.0%. With the judge, the judge's score rises at every step. Checked accuracy peaks at 54.3% near step 45, then falls to 33.0%: the policy learned to ramble, because the judge likes long, sure text.

A verifier is exact only about what it checks. DeepSeek-R1-Zero used two rule rewards. The accuracy reward checks that the final answer, in a set format, matches the key. The format reward checks that the reasoning sits inside think tags. Its authors avoided neural reward models for reasoning, because these are open to reward hacking at scale. People also game loose rules, so Kimi k1.5 dropped multiple-choice and true/false questions, where a guess can pass.

Score six answers with a checker

The problem is 3x + 7 = 22, key 5. Choose a checker. A red row is a wrong answer that got the reward.

Illustrative responses written for this lesson. The strict checker is the Field Guide's verify, which we ran on these six strings.

Worked number: the loose checker gives the reward to two wrong answers out of six, the hedge "5 or 7" and "7.5". The strict checker parses one value and gives the reward to exactly the two right answers, "5" and "15/3". The last response is right but has no answer tag, so neither rule can find its answer. Making the answer findable is the format reward's job.

Symptom: the training reward climbs, but accuracy on a held-out set does not.

Measure: read 50 high-reward samples by hand, and re-score them with a stricter checker.

Fix: parse one final answer and compare values, not strings. Drop question types that a guess can pass.

The road

  1. Baseline: push answers above average, not above zero.
  2. Group: GRPO scores each answer against its siblings.
  3. No critic: what PPO's value network costs, and why GRPO drops it.
  4. Clip: small steps away from the policy that wrote the answers.
  5. KL: a leash to the reference model, and its estimator.
  6. Biases: length and difficulty, and Dr. GRPO's fix.
  7. R1: R1-Zero, then the full DeepSeek-R1 recipe.
  8. Kimi, Qwen: a length reward, curricula and 3,995 problems.
  9. Showcase: run the whole loop and break it.
  10. Field guide: the table, the code and the habits.
Which reward is verifiable in the RLVR sense?

Chapter 1

The Baseline: Push Above Average, Not Above Zero

Weight each sampled answer by its reward minus a baseline, and watch the noise in the gradient shrink

The policy is the language model, called πθ (pi-theta), with weights θ. For a prompt x it samples a response y, and the verifier returns a reward. We want a higher average reward. But the reward is a 0 or 1 from a program, so no gradient flows through it.

The policy gradient gets around this. It raises the log probability of each sampled answer, weighted by that answer's reward. Lecture 17 derives it; here we need the result and one fix. Call the number of answers we sample for one prompt G, the i-th answer yi and its reward ri. Call b the baseline: a number we subtract from every reward.

Say it aloud

g-hat equals one over G, times the sum over i of r-i minus b, times the gradient of log pi-theta of y-i given x.

ĝ
g-hat our estimate of the direction that raises the average reward. A gradient step adds a small multiple of it to θ.
1/G
one over G divide by the number of sampled answers, so the sum becomes an average.
Σi
the sum over i one term for each sampled answer, 1 to G.
ri
r-i the reward of answer i: 1 if the verifier passes it, 0 if not, plus any bonus such as a format reward.
b
b the baseline. It may depend on the prompt, but never on the answer it scores.
∇θ log πθ(yi | x)
the gradient of log pi-theta of y-i given x the direction in weight space that makes answer y-i more likely. Backpropagation computes it from the answer's tokens.
In plain words

For each answer y-i, find the direction that makes it more likely. Scale it by r-i minus b: up if the answer beat the baseline, down if not. Average the G scaled directions.

With numbers

With made-up rewards 1, 0, 0, 1 and b = 0.5, the weights are +0.5, −0.5, −0.5 and +0.5. With b = 0, the two wrong answers get weight 0 and are never pushed down.

Why is the baseline free? Over the policy's own samples, ∇ log π averages to zero, because the probabilities always add up to 1. So b changes no expected gradient. It changes only the noise.

The noise matters here. R1-Zero adds its accuracy and format rewards with equal weight. Once the model always formats, every reward is at least 1. With no baseline, the update pushes up every sampled answer, right or wrong.

Measure the noise in one gradient

One prompt, four answers, one right: the policy picks it with chance 0.25. Each bar counts batches of 8 answers whose estimate fell there. Add a format bonus, then switch the baseline.

+1

Illustrative toy, 4,000 seeded batches. The estimate is for the right answer's logit; its true gradient is 0.25 × 0.75 = 0.1875.

Worked number, from 200,000 batches in Python, with a bonus of 1. The spread (standard deviation) of the estimate is 0.268 with no baseline and 0.074 with the group mean: 3.6 times smaller. The group mean's average is 0.164, 7/8 of the truth. Leave one out gives 0.1875 exactly, with spread 0.084.

Symptom: the update jumps from step to step, even on a fixed set of prompts.

Measure: the spread of the gradient estimate over a few repeated batches.

Fix: subtract a baseline. PPO learns one (a value network); GRPO takes the average reward of answers to the same prompt.

Four answers get rewards 1, 0, 0, 1 and the baseline is their mean. What happens to answers 2 and 3?

Chapter 2

GRPO: The Group Is the Baseline

Sample several answers to one prompt, and score each against its siblings

PPO learns its baseline: a value network that predicts the reward from the prompt. Group Relative Policy Optimization (GRPO), from the DeepSeekMath paper (Shao et al., 2024), drops that network. For each prompt it samples a group of G answers, scores all of them, and uses the group as the reference.

Call the group's average reward μ (mu) and the spread of its rewards σ (sigma), the standard deviation inside the group. The advantage of answer i says how much better it did than its siblings, in units of the spread:

Say it aloud

A-i equals r-i minus mu, over sigma.

Ai
A-i the advantage of answer i. It takes the place of r − b in the policy gradient, and every token of the answer gets it.
ri
r-i the verifier's reward for answer i, 0 or 1 here.
μ
mu the mean reward of the G answers to this prompt: the group's own baseline.
σ
sigma the standard deviation of the G rewards. Dividing by it puts every prompt's advantages on one scale.
In plain words

Average the G rewards to get mu. Measure their spread, sigma. For each answer, subtract mu from its reward r-i and divide by sigma. That is A-i.

With numbers

Eight answers to 3x + 7 = 22 earn 1, 0, 1, 0, 0, 1, 0, 0. So μ = 3/8 = 0.375 and σ = √(0.375 × 0.625) = 0.484. A right answer gets (1 − 0.375)/0.484 = +1.29; a wrong one gets −0.375/0.484 = −0.775.

Call p the fraction of the group that is right. With 0 or 1 rewards, a right answer gets √((1 − p)/p) and a wrong one −√(p/(1 − p)). A rare right answer gets a big push: 1 right out of 8 gives +2.65. The advantages always add up to zero.

If every answer is right, or every answer is wrong, σ = 0 and every advantage is 0. Code adds a small number to σ (the lecture's tiny implementation uses 0.0001) so nothing divides by zero. The group still teaches nothing. GRPO learns only from prompts it sometimes solves.

Score a group of eight answers

Tap an answer to flip it between right and wrong. Watch the yellow mean and the advantages. Then switch the rule.

Exact arithmetic. σ is the population standard deviation (divide by G). When σ = 0, every advantage is 0.

Symptom: many groups give no learning signal, and accuracy on a hard set stays flat.

Measure: the share of groups whose rewards are all equal.

Fix: drop prompts the model always or never solves, and raise G. Kimi and Qwen 3 both filter by difficulty (Chapter 8).

All 8 answers to a prompt are wrong. What does GRPO learn from this group?

Chapter 3

Why Drop the Critic

Count the models PPO keeps in memory, and see why one reward at the end makes a value network hard to train

PPO for language models runs four networks. The policy and the critic (a value network that predicts the reward) both train. A frozen reference policy supplies the KL penalty, and a frozen reward model supplies the score. The lecture's verdict on PPO: a complicated implementation, and a value model that is memory hungry and needs its own tuning.

DPO (Lecture 15) avoids all of that, but it needs pairs of answers and learns offline. Verifier rewards are not pairs: each answer is right or wrong on its own. GRPO keeps PPO's online loop and drops the critic. With a verifier, the reward model is a program too.

The critic's job is hard here. The reward arrives once, after the last token. The lecture notes that PPO's advantage estimate then works with γ = λ = 1, so a token's advantage is the final reward minus the critic's guess. The critic must guess, at every prefix, how a long answer will end. The group mean estimates the same expected reward by sampling.

What does the critic cost? Count model state in bytes. Mixed-precision training with Adam keeps about 16 bytes per trained parameter (the ZeRO paper's count). That is 2 for bf16 weights, 2 for gradients, and 12 for the fp32 master weights and Adam's two moments. A frozen model in bf16 keeps 2. Call the trained parameters Ntrain and the frozen ones Nfrozen:

Say it aloud

M equals sixteen N-train plus two N-frozen.

M
M bytes of model state, before activations and the cache that rollouts need.
16
sixteen bytes per trained parameter: weights 2, gradients 2, fp32 master copy 4, Adam's two moments 8.
Ntrain
N-train parameters that get gradient updates: the policy, and in PPO the critic too.
2
two bytes per frozen parameter, stored in bf16.
Nfrozen
N-frozen parameters only run forward: the reference policy, and in PPO the reward model.
In plain words

Multiply the trained parameters N-train by 16 bytes. Multiply the frozen ones N-frozen by 2. Add them to get M.

With numbers

With a 7B policy, PPO trains the policy and a 7B critic, so Ntrain = 14B. It freezes a reference and a reward model, so Nfrozen = 14B. M = 224 + 28 = 252 GB. GRPO with a verifier trains 7B and freezes one 7B reference: M = 112 + 14 = 126 GB. That is at least 4 versus 2 GPUs of 80 GB.

Count the bytes PPO and GRPO hold

Each block is one network's state. Purple blocks are learned networks; yellow is the frozen reference. Drag the model size.

7B

Model state only, using 16 bytes per trained and 2 per frozen parameter. Activations, the rollout cache and sharding change real totals. We give the critic and the reward model the policy's size.

Symptom: the job runs out of memory when you add the critic.

Measure: model state per GPU, with the equation above.

Fix: drop the critic and use the group baseline, or shard the state across GPUs (Lecture 8).

What takes the place of PPO's value network V(x) in GRPO?

Chapter 4

The Clip: Small Steps From the Old Policy

Reuse one batch of answers for several updates, and stop each token's probability from moving too far

Generating answers is slow, so trainers often reuse one batch for several gradient steps. After the first step the policy has changed. The answers came from the old policy, πold, but we now update πθ.

The probability ratio ρ (rho) for one token is πθ of that token divided by πold of it. ρ = 1 means no change since sampling. GRPO takes PPO's clipped objective, with a clip width ε (epsilon). For each token of answer i, with advantage A:

Say it aloud

L equals the minimum of rho times A, and clip of rho between one minus epsilon and one plus epsilon, times A.

L
L the objective for one token. Training raises it, so it lowers minus L.
min
the minimum keep the smaller of the two terms: the cautious one.
ρ
rho the probability ratio, πθ over πold, for this token.
A
A the answer's group advantage from Chapter 2, the same for all its tokens.
clip(ρ, 1 − ε, 1 + ε)
clip of rho between one minus epsilon and one plus epsilon rho held inside the band. With ε = 0.2, the band is 0.8 to 1.2.
In plain words

Compute rho times A. Compute it again with rho held inside the band. Keep the smaller. Past the band in the direction A wants, the kept term is flat, so it gives no gradient.

With numbers

With A = +1.29 and ε = 0.2: at ρ = 1.1, L = 1.42 and the update still pushes the token. At ρ = 1.3, ρA = 1.68 but the clipped term is 1.2 × 1.29 = 1.55, the smaller: flat, no push. A wrong answer with A = −0.775 at ρ = 0.7 gets 0.8 × −0.775 = −0.62: flat too.

Move one token's ratio past the band

The pink line is L; the grey dashes are ρA with no clip. Drag ρ and watch where the line goes flat.

1.30
0.20

Exact formula. The advantages are the worked group's from Chapter 2.

The full objective averages L over each answer's tokens, then over the G answers, and subtracts a KL penalty (next chapter). Two settings show the range. DeepSeekMath made a single update per batch, so ρ = 1 and the clip never acted. The lecture calls this online case "just policy gradient with group normalized rewards". R1's 2026 revision reports ε = 10 in its first RL stage: lower values cut off the gradient for too many tokens.

Symptom: reward collapses after several updates on one batch.

Measure: the clip fraction, the share of tokens with ρ outside the band.

Fix: fewer passes over each batch, a smaller learning rate, or a narrower band.

A right answer (A > 0) has a token at ρ = 1.35 with ε = 0.2. What does the clipped objective do to it?

Chapter 5

The KL Leash and Its Estimator

Keep the policy near a reference model, and estimate the distance from samples without going negative

The checker rewards right answers, not readable ones. So GRPO adds a penalty that grows as the policy drifts from a frozen reference policy, πref, usually the starting model. The distance is the KL divergence: the average, over the policy's own tokens, of log(πθ/πref). It is zero when the two agree and positive otherwise.

The exact KL needs a sum over the whole vocabulary at every position. GRPO estimates it from the sampled tokens instead. Call x the ratio πref/πθ for one sampled token. The plain estimate, −log x, is right on average but negative on many tokens. DeepSeekMath uses an estimate from John Schulman's 2020 note on KL approximation, often called k3:

Say it aloud

k-three equals x minus log x minus one, where x is pi-ref over pi-theta.

k3
k-three one token's estimate of the KL. The loss adds β (beta) times its average over tokens.
x
x, pi-ref over pi-theta the reference model's probability of the sampled token, divided by the policy's. x = 1 means they agree.
log x
log x the natural log of the ratio. Minus log x alone is the plain estimate.
1
one with x, it forms x − 1, a term that averages to zero.
In plain words

For each sampled token, divide the reference probability by the policy probability to get x. Take x, subtract log x, subtract 1. Average over tokens.

With numbers

With made-up probabilities πθ = 0.5 and πref = 0.4: x = 0.8, −log x = 0.223, and k3 = 0.8 + 0.223 − 1 = 0.023. Swap them: x = 1.25, −log x = −0.223 (negative), but k3 = 1.25 − 0.223 − 1 = 0.027.

Why does it work? First, it has no bias. For tokens drawn from πθ, the average of x is the sum of πθ × πref/πθ, that is, the sum of πref, which is 1. So x − 1 averages to zero, and k3 has the same mean as −log x. Second, it is never negative: log x ≤ x − 1 for every x > 0, since the log curve lies under its tangent line at 1.

Estimate the KL from sampled tokens

Top: the policy (purple) and the reference (yellow outline) over five tokens. Bottom: 400 one-token estimates for each rule. Drag the drift.

0.50

Illustrative distributions, 400 seeded samples, exact true KL. At drift 0.50, 100,000 samples in Python give means of 0.125 and 0.124 and spreads of 0.50 and 0.091.

The small spread holds while the policy stays near the reference. At drift 1, the policy almost never picks token 5. There, x = 0.15/0.01 = 15. k3's spread (1.19, exact) then passes −log x's (0.83).

DeepSeekMath puts β times the KL in the loss, not in the reward, so the advantages stay clean. It set β = 0.04. R1-Zero's 2026 revision reports β = 0.001, with the reference replaced by the latest policy every 400 steps. One caveat: k3 has no bias only for tokens drawn from πθ. Reused batches come from πold.

Symptom: the KL climbs fast, and outputs repeat or switch languages.

Measure: the mean k3 per token, logged every step.

Fix: raise β, or reward the trait you want directly, as R1's language reward does (Chapter 7).

Why use k3 = x − log x − 1 instead of −log x?

Chapter 6

Two Hidden Biases: Length and Difficulty

Find the two divisions in GRPO that reweight answers and prompts, and remove them as Dr. GRPO does

GRPO's loss divides twice: by the group's σ, and by the answer's length when it averages over tokens. Liu et al. (2025) show that both bias the update. Call the number of tokens in answer i |oi|. Each of its tokens gets the weight:

Say it aloud

w-i equals r-i minus mu, over sigma times the length of o-i.

wi
w-i the weight on each token's gradient in answer i, under GRPO.
ri
r-i the reward of answer i.
μ
mu the group's mean reward.
σ
sigma the group's spread. Dividing by it reweights whole prompts: the difficulty bias.
|oi|
the length of o-i the number of tokens in answer i. Dividing by it reweights answers by length: the length bias.
In plain words

Centre the reward r-i on the group mean mu. Divide by the spread sigma. Then divide by the answer's length, so each of its tokens gets an equal share. Dr. GRPO keeps the first step and replaces both divisions with one constant.

With numbers

Two wrong answers with A = −0.775: 100 tokens gives w = −0.0078 per token; 1,000 tokens gives −0.00078, ten times weaker. Each answer's total push is the same, −0.775. Divide by a constant 1,000 instead, and the long answer's total push is ten times the short one's.

Length bias. The update pushes a long wrong answer down less per token than a short one, and pushes a short right answer up more. Length comes from many small choices to keep going or stop, so the update listens mostly to short answers.

Train the stop knob with each rule

Left: accuracy against average length, best at the yellow mark. Right: length over training. Press Train.

Illustrative toy, seeded. One parameter sets the chance to stop after each token; a made-up accuracy curve rises, then falls with rambling. Both rules divide by σ; only the length division differs. 32 groups of 8 per step.

Worked number, from the device: both rules start at 200 tokens and 39.4%. GRPO passes the best length, about 470 tokens, near step 110. By step 1,500 its answers average 1,370 tokens and accuracy is 28.8%. Dr. GRPO settles at 449 tokens and 45.9%, the best this toy allows.

Difficulty bias. For 0/1 rewards, a group's total push, Σ|Ai|, is 2G√(p(1 − p)) with σ and 2Gp(1 − p) without. With σ, 1 right of 8 weighs 5.29 against 8 for 4 of 8; without, 1.75 against 4. So σ lifts the prompts the model almost always or almost never solves: the lecture's "upweights too easy or hard questions".

Dr. GRPO uses A = r − μ and divides each answer's token sum by a constant, such as the generation budget. That is Chapter 1's leave-one-out advantage times (G − 1)/G. The authors' 7B recipe reached 43.3% on AIME 2024 in about 27 hours on 8 A100 GPUs.

Symptom: answers keep growing after the reward flattens; wrong ones are longest.

Measure: the mean length of right answers and of wrong answers, logged separately.

Fix: Dr. GRPO's constant divisor and no σ, or a length reward (Chapter 8).

Under GRPO, why is a long wrong answer pushed down less than a short wrong one?

Chapter 7

DeepSeek-R1: Zero, Then the Full Recipe

Follow R1-Zero from a base model with two rule rewards, then the stages that made R1 readable

DeepSeek-R1 (January 2025) matched OpenAI's o1 on reasoning tests with an open recipe. The lecture lists what stood out: scores at o1's level and a simple RL recipe. It also ended speculation that such models need tree search or process reward models.

R1-Zero is the controlled experiment. Start from DeepSeek-V3-Base with no supervised fine-tuning. A template asks for reasoning in think tags and the answer in answer tags. GRPO trains on the accuracy and format rewards only. AIME 2024 pass@1 rose from 15.6% to 71.0%, and to 86.7% with a majority vote over 64 samples. (The 2026 revision reports 77.9% after longer training.)

Answers grew from hundreds to thousands of tokens. An intermediate checkpoint wrote "Wait, wait. Wait. That's an aha moment I can flag here." The lecture flags this as maybe overstated. Dr. GRPO found that DeepSeek-V3-Base already shows such self-reflection before RL, and part of the length growth may come from the length bias.

Step through the R1 recipe

Choose a stage. The flow lights what it adds; the bars show the paper's AIME 2024 pass@1 scores.

Scores from DeepSeek-R1 (arXiv 2501.12948, v1): Tables 2, 4 and 6. The 15.6% is R1-Zero at step 0 of RL, Figure 2.

Worked number: distillation beat RL at 32B. Distill-Qwen-32B, fine-tuned on R1's 800k samples, scored 72.6% on AIME 2024. The same Qwen-32B base, trained with large-scale RL for over 10,000 steps, scored 47.0%: 25.6 points lower. Small supervised sets go far too. The lecture's example, s1, fine-tuned a 32B model on 1,000 questions with long reasoning traces in 26 minutes on 16 H100 GPUs.

Symptom: R1-Zero's reasoning mixes English and Chinese and is hard to read.

Measure: the language consistency reward: words in the target language divided by all words in the reasoning.

Fix: add it to the reward. R1 did, at a small cost in accuracy.

What does R1-Zero show most directly?

Chapter 8

Kimi k1.5 and Qwen 3: Other Recipes

Compare a length reward and curricula in Kimi with 3,995 chosen problems in Qwen 3

Kimi k1.5 (Moonshot AI) came out with R1 and also matched o1, with its own loss. It uses the previous policy as the reference and solves the KL-regularised problem in closed form, as DPO does. Then it fits that solution with a squared loss. The lecture's summary: a baselined policy gradient (the mean of the sampled rewards) with regularization. Kimi uses no value network either.

Kimi's data work: drop multiple-choice, true/false and proof questions. Drop any prompt that a model answers right within 8 guesses without reasoning, since it is easy to hack. Train from easy to hard, and sample each problem with weight 1 − si, where si is its success rate. To check math answers, Kimi trained a reward model that reasons first: 98.5% accurate in spot checks, against 84.4% for a classic one.

Kimi also controls length. In each group, call the shortest and longest lengths min and max, and answer i's length leni:

Say it aloud

lambda-i equals one half, minus len-i minus min, over max minus min.

λi
lambda-i answer i's place in the group's length range, from +0.5 (shortest) to −0.5 (longest). A right answer's length reward is λi; a wrong one's is min(0, λi).
0.5
one half centres the range on zero: the middle length earns nothing.
leni
len-i the number of tokens in answer i.
min
min the shortest answer's length in this group.
max
max the longest answer's length. If max equals min, every length reward is 0.
In plain words

Find where len-i sits between min and max, as a fraction. Subtract it from one half to get lambda-i. Right answers get lambda-i; wrong answers get it only when it is negative.

With numbers

With made-up lengths from 200 to 800 tokens: a right answer of 200 gets λ = +0.5; one of 500 gets 0. A wrong answer of 800 gets −0.5; a wrong answer of 200 gets min(0, 0.5) = 0.

Give eight answers Kimi's length reward

Blue bars are lengths. Tap an answer to flip it right or wrong, and drag the longest answer's length.

800

Illustrative lengths; the formula is Kimi k1.5's (Section 2.3.3). Kimi adds this reward to the main reward with a weight, and only after a warm-up.

Qwen 3 (May 2025) ran its reasoning RL with GRPO on just 3,995 query-verifier pairs. Each had to be unused in the cold-start stage, learnable for the cold-start model, as hard as possible, and from a broad range of sub-domains. Qwen3-235B-A22B's AIME'24 score rose from 70.1 to 85.1 in 170 RL steps. A later stage fuses thinking and non-thinking modes with /think and /no_think flags, and a thinking budget ends long reasoning with a fixed sentence. The report notes that thinking-mode AIME'24 and LiveCodeBench scores drop a little after the general stages.

RecipeAlgorithmReferenceDataLength
DeepSeek-R1GRPOfrozen, reset every 400 steps (2026 revision)rule-checkable math, code, logicgrows freely
Kimi k1.5mirror-descent policy gradient, mean-reward baselinethe previous policyno multiple-choice; easy-to-hack removed; curriculumlength reward after warm-up
Qwen 3GRPO, large batches, many rolloutsnot stated; entropy held steady or rising3,995 query-verifier pairsthinking budget at inference

Symptom: answers grow long and the cost per problem climbs.

Measure: the mean length of right answers, per step.

Fix: a length reward like Kimi's, switched on after warm-up, or a thinking budget at inference like Qwen 3's.

Qwen 3's reasoning RL used only 3,995 problems. Which criterion makes each one useful to GRPO?

Chapter 9

Showcase: Run the RLVR Loop

Train the toy policy with every knob from this lesson, and break it on purpose

This is the hero's toy with all its controls. Each step: draw G answers for each problem, check them, compute advantages, take one step, and pay the KL leash. Pink lines are measured: checked accuracy (solid) and the judge's score (dashed). Blue is the share of groups that taught nothing.

Run the loop

Change one control, then press Train. Compare the curves and the final policy.

Reward
Advantage
G = 8
0.0

Illustrative toy, the hero's simulation: 16 made-up problems (3 trivial, 4 easy, 4 medium, 3 hard, 2 impossible), five strategies, 150 steps, seed fixed. The KL is exact here, against the starting policy.

Things to try. With the judge and β = 0, checked accuracy peaks at 54.3% and ends at 33.0%. Raise β to 0.3: it ends at 49.3%, because the leash holds the policy near its start. Switch to the checker and turn on the filter: groups with no signal drop from 45% to 21%. The no-baseline rule then climbs from 61.2% to 65.0%, since trivial problems no longer feed it noise. At G = 2, three in four groups teach nothing.

Check yourself. Which control helps against a hackable reward, and what does it cost with an honest one? (With the checker, β = 0.3 ends at 56.4% instead of 66.0%.)

Chapter 10

Field Guide

Keep the table, the code, and the questions to ask of any RLVR run

RLVR replaces a learned reward with a checker. GRPO turns 0/1 checks into a gradient with no critic: sample a group, centre on the group mean, clip, and leash with a KL estimate. Its two divisions bias length and difficulty, and Dr. GRPO removes them. R1, Kimi k1.5 and Qwen 3 add data filters, extra rewards and stages around that core.

PieceFormula or numberMain caveat
Baselineweight r − b; bonus 1: spread 0.268 → 0.074must not depend on the scored answer
Group advantage(r − μ)/σ; 3 of 8 right: +1.29, −0.775all equal: no signal
No critic16 Ntrain + 2 Nfrozen; 7B: 252 vs 126 GBpays in rollouts instead
Clipmin(ρA, clip(ρ)A); ρ 1.3, A 1.29: 1.55, flatidle with one update per batch
KL estimatek3 = x − log x − 1; 0.8 gives 0.023unbiased only on-policy
Biasesw = (r − μ)/(σ|o|); toy length 200 → 1,370Dr. GRPO: r − μ, constant divisor
Kimi length reward0.5 − (len − min)/(max − min)wrong answers never gain

The core, as Python we ran (PyTorch for the loss):

python
import re
import torch
from fractions import Fraction

def verify(response, key):                       # 1.0 if the one final answer equals the key
    m = re.search(r"<answer>(.*?)</answer>", response, re.S)
    if not m:
        return 0.0
    ans = re.sub(r"^\s*x\s*=\s*", "", m.group(1)).strip()
    try:
        return float(Fraction(ans) == Fraction(key))
    except ValueError:                           # "5 or 7" does not parse: no reward
        return 0.0

def group_advantage(r, mode="grpo", eps=1e-4):   # r: (G,) rewards for one prompt
    centred = r - r.mean()
    if mode == "grpo":
        return centred / (r.std(unbiased=False) + eps)
    return centred                               # Dr. GRPO

def k3(logp, logp_ref):                          # per token, never negative
    log_x = logp_ref - logp                      # log of pi_ref / pi_theta
    return torch.exp(log_x) - log_x - 1

def grpo_loss(logp, logp_old, logp_ref, mask, A, eps=0.2, beta=0.04, dr=False):
    # logp*: (G, T) log probs of the sampled tokens; mask: (G, T), 1 on answer tokens
    ratio = torch.exp(logp - logp_old)
    surr = torch.min(ratio * A[:, None], ratio.clamp(1 - eps, 1 + eps) * A[:, None])
    per_tok = surr - beta * k3(logp, logp_ref)
    if dr:                                       # Dr. GRPO: sum, divide by a constant
        per_ans = (per_tok * mask).sum(1) / mask.shape[1]
    else:                                        # GRPO: average over each answer's tokens
        per_ans = (per_tok * mask).sum(1) / mask.sum(1)
    return -per_ans.mean()                       # minimise the negative objective

r = torch.tensor([1., 0, 1, 0, 0, 1, 0, 0])
group_advantage(r)                                # +1.291 for right, -0.774 for wrong
verify("<think>...</think><answer>15/3</answer>", "5")  # 1.0
verify("<think>...</think><answer>5 or 7</answer>", "5")  # 0.0

The lecture's recap: overoptimization is a problem, and RL in narrow, checkable domains is one answer. GRPO is simple, with some flaws, and it enables RLVR. Many recipes now work in the open: R1, Kimi k1.5 and Qwen 3.

Keep going

Read next

The habit. For any RLVR run, ask four things: what exactly does the checker accept, how many groups carry no signal, how does length move for right and for wrong answers, and how far has the policy drifted from its reference.
Your GRPO run's reward is flat, and 70% of groups have all-equal rewards. What do you change first?

Now teach it: press Present or Teach. Explain how eight right-or-wrong answers become a gradient with no critic, and what a loose checker and the length division do to it. Then go back to the tiny reasoner and predict what the judge does to checked accuracy before you press Train.

Alignment II: RLVR & GRPO · Stanford CS336, Lecture 16
Previous: Alignment I · Next: Alignment III · Course site · Back to Gleams