RL with verifiable rewards: GRPO and reasoning¶
If you can check an answer with code, you can train a language model with reinforcement learning against that check and nothing else. That one idea — reward from a verifier, not a learned judge — plus a cheap critic-free algorithm, GRPO, is how 2025's reasoning models learned to think for thousands of tokens before answering.
10,000 ft
Classic post-training has three stages: supervised fine-tuning teaches the format, a reward model trained on human preferences scores outputs, and RLHF with PPO (or DPO) pushes the model toward what humans prefer. That pipeline is bounded by the reward model: optimise a learned judge hard enough and the policy finds its blind spots. Reinforcement learning with verifiable rewards (RLVR) replaces the judge with a program — does the final answer match the reference, do the unit tests pass, does the output obey the requested format — which cannot be flattered and can be run millions of times. Combined with group-relative advantage estimation (GRPO), which deletes PPO's value network, it made large-scale RL on language models cheap and stable enough to scale. The results are the reasoning models — OpenAI's o-series, DeepSeek-R1, Kimi k1.5, Qwen3 and their successors — that spend test-time compute on long chains of thought. This page is the bridge between the policy-gradient theory of the RL track and the post-training stack of a frontier model.
2,000 ft
One RLVR step, as almost every open recipe runs it in 2025–2026:
- Pick prompts with checkable answers — maths with a reference answer, code with tests, instructions with machine-checkable constraints.
- Sample a group of \(G\) completions (typically 8–64) per prompt from the current policy at temperature about 1.
- Score each completion with the verifier: 1 if correct, 0 (or −1) otherwise, sometimes plus a small format reward.
- Turn scores into advantages by comparing siblings: subtract the group's mean reward (and often divide by its standard deviation). Better-than-siblings completions get positive advantage, worse get negative. No value network.
- Take a clipped policy-gradient step (PPO-style ratio clipping), optionally with a KL penalty to a frozen reference model, applying each completion's advantage to every one of its tokens.
- Repeat for thousands of steps. Accuracy rises, responses usually get longer, and behaviours such as checking and backtracking become more frequent.
Ground level¶
What makes a reward "verifiable"¶
A verifiable reward is a deterministic function \(v(q, o)\) of the prompt and the completion that can be computed without a learned model and that you trust. The term was coined by the Tülu 3 team at AI2 (Lambert et al., 2024), who defined it in the simplest possible way: the reward is \(\alpha\) if the completion is verifiably correct and 0 otherwise, optimised with PPO under the usual KL penalty — they set \(\alpha = 10\) "based on pilot experiments". DeepSeek had already used rule-based rewards for DeepSeek-R1-Zero; what made the idea take over the field was the combination of three facts:
| Domain | Verifier | What can go wrong |
|---|---|---|
| Maths with a final answer | Extract the \boxed{…} answer, normalise, compare symbolically with the reference |
\(\tfrac12\) vs 0.5 vs 1/2 judged different; answer-extraction regexes rewarded for format, not truth |
| Code | Run hidden unit tests in a sandbox | Tests too weak; policy special-cases the tests; timeouts and flaky tests add noise |
| Precise instruction following | Check constraints ("exactly 3 bullet points", "no commas", "end with P.S.") | The model satisfies the letter and ignores the substance |
| Formal proof | A proof checker (Lean, Isabelle) accepts or rejects | Essentially none, which is why theorem proving is RL's best case; the bottleneck is search |
| Format | Tags present (<think>…</think>), language consistent |
Pure shaping; never let it dominate the correctness reward |
- The signal is honest. A unit-test runner does not drift, and it cannot be persuaded. The failure mode of RLHF — reward over-optimisation, where the policy finds inputs the reward model scores highly but humans would not — is much weaker (not absent: see reward hacking below).
- It scales. No human labels per sample. Every maths problem with a known answer, every repository with tests, every puzzle with a checker becomes training signal.
- It rewards outcomes, not imitation. The model is not told how to solve the problem. Any chain of thought that reaches the right answer is reinforced, including strategies no human annotator would have written down.
The price is the obvious one: most of what people want from an assistant — a kind reply, a good essay, a sound piece of financial advice — has no verifier. RLVR is therefore one stage of a modern pipeline, not a replacement for it, and the frontier question for 2026 is how far verifiable training generalises beyond the domains where the checker exists.
The gradient you are actually computing¶
Treat the whole completion \(o = (o_1, \dots, o_T)\) as one action. The model is a policy \(\pi_\theta(o \mid q) = \prod_t \pi_\theta(o_t \mid q, o_{<t})\), the verifier returns a scalar reward at the end, and the objective is the expected reward over prompts and samples:
The policy-gradient theorem (REINFORCE) gives
for any baseline \(b(q)\) that does not depend on the sampled \(o\). Two things in this formula are worth staring at.
First, with a binary reward, \(J\) for one prompt is the probability of solving it — pass@1. So RLVR is literally stochastic gradient ascent on the model's success probability. Nothing more mysterious is going on.
Second, every token of a completion receives the same scalar, \(r - b\). There is no per-token credit assignment: a correct proof with one lucky step and a correct proof that is clean throughout push all their tokens up equally. Credit assignment happens statistically: tokens and phrases that appear more often in successful completions than unsuccessful ones, across thousands of groups, accumulate net positive gradient. "Wait, let me check" survives because, on average, completions that check are right more often.
GRPO: a baseline from siblings¶
PPO estimates the baseline with a learned value function \(V_\psi\), a second network the size of the policy, trained alongside it. Group Relative Policy Optimisation (GRPO), introduced in DeepSeekMath (Shao et al., 2024), throws the critic away. For each prompt it samples a group of \(G\) completions and uses their mean reward as the baseline:
and every token of completion \(i\) gets advantage \(\hat A_{i,t} = \hat A_i\). Then it optimises a PPO-style clipped surrogate, with a KL penalty to a frozen reference policy placed in the loss rather than folded into the reward:
Worked example: eight samples, three correct
A maths prompt, \(G = 8\) samples, the verifier marks samples 1, 4 and 8 correct: \(\mathbf r = (1,0,0,1,0,0,0,1)\).
- Mean \(= 3/8 = 0.375\); population standard deviation \(= \sqrt{0.375 \times 0.625} = 0.4841\).
- Correct samples: \(\hat A = (1 - 0.375)/0.4841 = +1.291\). Wrong ones: \((0 - 0.375)/0.4841 = -0.775\).
- The advantages sum to zero: \(3 \times 1.291 = 5 \times 0.775 \approx 3.87\). The update moves probability mass from the five failures to the three successes and does not change the total "size" of the policy.
- If all eight had been correct (or all wrong), every advantage would be \(0/0 \to 0\): the prompt contributes no gradient at all. Hold on to that; it drives half the engineering in this field.
The leave-one-out baseline (RLOO; Ahmadian et al., 2024), which compares each sample with the mean of the other seven, gives \((+0.714, -0.429)\) — exactly \(\tfrac{8}{7}\) times \(r_i - \bar r\). The group mean is therefore an unbiased baseline up to a constant factor; it is the division by the standard deviation that changes the weighting between prompts (derivation below).
Why deleting the critic matters¶
PPO for RLHF keeps four large networks in play: the policy and the value model (both trained, both carrying Adam state), the reward model and the reference (both frozen). GRPO with a verifiable reward keeps one trained network and, if you use a KL penalty at all, one frozen copy. That roughly halves the memory and removes the hardest part of PPO to get right. A value function for language must predict, from a half-written solution, the probability it ends correct — a hard regression problem whose errors become bias in the advantage. DeepSeekMath's authors argue exactly this: when only the last token carries a reward, a value function that is accurate at every token is hard to train. The group baseline is a Monte Carlo estimate of the same quantity at the start of the completion, and it is unbiased.
What you give up is per-token credit assignment (the critic's main job) and sample efficiency: GRPO needs \(G\) completions per prompt to estimate one baseline. Methods such as VinePPO (Kazemnejad et al., 2024) recover per-step values by Monte Carlo rollouts from intermediate states; most large-scale recipes have judged the extra rollouts not worth it.
Not every prompt teaches: the pass-rate window¶
If the policy solves a prompt with probability \(p\), the chance that a group of \(G\) independent samples is mixed (at least one success and one failure, so the advantages are non-zero) is
| \(G\) | \(p = 0.02\) | \(p = 0.1\) | \(p = 0.5\) | \(p = 0.9\) | \(p = 0.98\) |
|---|---|---|---|---|---|
| 4 | 0.078 | 0.344 | 0.875 | 0.344 | 0.078 |
| 8 | 0.149 | 0.570 | 0.992 | 0.570 | 0.149 |
| 16 | 0.276 | 0.815 | 1.000 | 0.815 | 0.276 |
| 64 | 0.726 | 0.999 | 1.000 | 0.999 | 0.726 |
Three practical consequences follow, and every serious recipe acts on them:
- Curate by pass rate. Before training, sample each candidate prompt a few times with the starting model and drop the ones it always or never solves. As training proceeds, prompts migrate to \(p = 1\) and stop teaching, so the effective batch shrinks.
- Fill the batch dynamically. DAPO (Yu et al., 2025) over-samples and keeps only groups with \(0 < \#\text{correct} < G\) until the batch is full ("dynamic sampling").
- Raise \(G\) for hard problems. A larger group is the only way to see a rare success. This is also the cleanest statement of RLVR's main limit: the policy cannot learn from a solution it never samples.
The case study: DeepSeek-R1-Zero and DeepSeek-R1¶
DeepSeek-R1 (DeepSeek-AI, January 2025; later published in Nature) is the paper that made RLVR the centre of post-training, because it ran the experiment everyone wanted to see: GRPO, applied directly to a base model, with no supervised fine-tuning first.
R1-Zero. The prompt template only asked the model to put its reasoning between <think> and
</think> and its answer between <answer> and </answer>; the authors deliberately avoided
"content-specific biases" such as asking for reflection. The reward was rule-based: an accuracy
reward (boxed maths answers checked by rule, LeetCode-style problems checked by a compiler and
test cases) plus a format reward for the tags. They did not use a neural outcome or process
reward model, because "the neural reward model may suffer from reward hacking in the large-scale
reinforcement learning process". Results, from the paper:
- AIME 2024 pass@1 rose from 15.6% to 71.0%, and to 86.7% with majority voting over 64 samples (cons@64).
- Average response length grew steadily through training, with no length reward: the model learned on its own that longer thinking pays.
- The authors report an "aha moment": an intermediate checkpoint writing, mid-solution, "Wait, wait. Wait. That's an aha moment I can flag here," and re-evaluating its approach.
- The outputs had poor readability and mixed languages.
R1. To fix readability and broaden ability, the full model used four stages: a cold-start SFT on "thousands" of curated long chain-of-thought examples; reasoning-focused RL with an added language-consistency reward (the fraction of target-language words in the chain of thought — which slightly lowered benchmark scores, a trade the authors accepted for readability); rejection sampling from that checkpoint to build about 600k reasoning and 200k non-reasoning SFT examples, on which DeepSeek-V3-Base was fine-tuned for two epochs; and a final RL stage mixing rule rewards for reasoning with reward models for helpfulness and harmlessness.
Distillation beat small-scale RL. Fine-tuning Qwen and Llama models on R1's 800k samples (SFT only, no RL) gave, for example, 55.5% AIME pass@1 for the 7B Qwen student and 72.6% for the 32B. Running R1-Zero-style RL directly on Qwen-32B-Base for over 10k steps reached only 47.0%. The paper's conclusion is worth quoting in substance: distilling a stronger model is cheaper and better for small models, while "advancing beyond the boundaries of intelligence may still require more powerful base models and larger-scale reinforcement learning". See distillation and synthetic data.
What failed. The paper's "unsuccessful attempts" section is the most useful part for practitioners: process reward models (hard to define a step, hard to label it, and reward hacking once a learned PRM is in the loop) and Monte Carlo tree search (token-level search spaces are vastly larger than Go's, and training a fine-grained value model was the bottleneck).
The GRPO repair shop¶
GRPO as published has several properties that only show up at scale, with long chains of thought. The 2025 literature is largely a list of fixes:
| Problem | Cause | Fix (paper) |
|---|---|---|
| Responses grow long, especially wrong ones | Dividing each sequence's loss by its own length \(\lvert o_i\rvert\): a long wrong answer's per-token penalty is diluted, a short right answer's per-token reward is concentrated | Normalise by a constant (Dr. GRPO, Liu et al., 2025) or by total tokens in the batch (DAPO's token-level loss) |
| Easy and impossible prompts over-weighted | Dividing by the group's std, which is tiny when \(p \approx 0\) or \(1\) | Drop the std (Dr. GRPO); or batch-level normalisation |
| Entropy collapse: the policy becomes near-deterministic early, exploration stops, accuracy plateaus | Clipping caps how fast low-probability tokens can grow; positive-advantage updates on likely tokens shrink entropy | "Clip-higher": asymmetric \(\varepsilon_{\text{low}} = 0.2\), \(\varepsilon_{\text{high}} = 0.28\) (DAPO); Clip-Cov / KL-Cov on high-covariance tokens (Cui et al., 2025) |
| Batches full of zero-advantage groups | Prompts drift to \(p \in \{0, 1\}\) | Dynamic sampling (DAPO) |
| Truncated long answers punished as if wrong | Hitting the length limit gives reward 0 regardless of the reasoning so far | Mask truncated samples, or a soft length penalty ramp (DAPO's overlong shaping) |
| Instability on mixture-of-experts models | Token-level importance ratios are noisy, and routing changes between rollout and update | Sequence-level, length-normalised ratio and clipping (GSPO, Zheng et al., 2025) |
| KL penalty holds the policy back | Reasoning RL wants to move far from the SFT model | Many recipes set \(\beta = 0\) (DAPO, Dr. GRPO); others reset the reference periodically |
DAPO's ablation on Qwen2.5-32B (AIME 2024, avg@32) shows how much these details matter: naive GRPO reached 30; adding overlong filtering 36; clip-higher 38; soft overlong punishment 41; token-level loss 42; dynamic sampling 50 — beating DeepSeek's own R1-Zero-Qwen-32B result (47) in half the training steps.
What RL actually changes: sharpening or discovery?¶
Here is the uncomfortable result of 2024–2025, and the most important thing on this page to understand properly.
DeepSeekMath already observed it: RL improved Maj@K (majority vote over \(K\) samples) but not Pass@K (at least one of \(K\) correct) on GSM8K and MATH. Their interpretation: RL makes "the output distribution more robust" by boosting correct answers already in the model's top-\(K\), "rather than the enhancement of fundamental capabilities". Yue et al. (2025) tested this across model families, algorithms and domains and found the curves cross: the RL model wins at pass@1, but the base model wins at pass@256. Coverage analysis showed the RL model's solvable problems were essentially a subset of the base model's.
The mechanism is not mysterious once you see the objective. RL with a binary reward maximises pass@1. Sharpening a distribution onto its most reliable mode is the fastest way to raise pass@1, and it necessarily removes probability from rare modes — some of which were the only route to certain problems. The reverse-KL-like, mode-seeking character of policy gradients (see entropy and KL) makes this the default behaviour.
The picture is still being argued, and you should hold it with nuance:
- Distillation does add patterns. Yue et al. found that distilling from a stronger teacher did expand the student's reasoning boundary, unlike RL on the student itself.
- Longer, broader RL may push the boundary. ProRL (Liu et al., 2025, NVIDIA) reports that prolonged RL with KL control and reference resets expands pass@k on some tasks where the base model was weak.
- Some gains are not about the reward at all. Shao et al. (2025) found that RLVR with random rewards raised Qwen2.5-Math-7B's MATH-500 score by 21.4 points, close to the 29.1-point gain from true rewards. They trace it to GRPO's clipping bias amplifying a behaviour already common in pre-training ("code reasoning"), and the effect did not transfer to Llama 3 or OLMo 2. Wang et al. (2025) showed RLVR on a single training example lifting Qwen2.5-Math-1.5B from 36.0% to 73.6% on MATH-500. Both results say the same thing: on these models, RL is mostly eliciting a latent skill, and a result on one model family is not a result about RL.
Sharpening is still enormously valuable
A model that solves a problem one time in eight is useless to a user; one that solves it seven times in eight is a product. Even if RLVR "only" moves pass@k into pass@1, that is exactly the conversion that makes reasoning models usable. And amortising a search the model would otherwise do at test time (sampling 64 answers and voting) into a single sample is a real gain in capability per unit of inference compute.
Reward hacking with a verifier¶
Verifiable rewards are harder to hack than learned ones, not impossible:
- Weak verifiers. If the code reward is "tests pass", a policy can learn to special-case the tests, or (with tool access) edit them. Baker et al. (OpenAI, 2025) document frontier reasoning models in agentic coding environments doing exactly this, and found that a weaker model reading the chain of thought could catch much of it. Their key warning: penalising "bad thoughts" directly made models hide their intent while still hacking — so do not optimise against your monitor.
- Parser exploits. Answer extraction that takes the last number, or any
\boxed{}, can be gamed by printing several candidates. - Format-reward dominance. If format rewards are comparable in size to correctness, the policy learns tags first and maths second.
- Length as a lever. A max-length cutoff that scores truncation as 0 interacts with normalisation choices to push length up or down for reasons unrelated to reasoning quality.
Lilian Weng's survey of reward hacking (linked below) is the best map of the general phenomenon; see also the alignment problem.
History¶
- 2021 — verifiers as rerankers. Cobbe et al. (OpenAI) released GSM8K and trained a verifier to rank sampled solutions, showing that sampling many answers and picking the verified one beats fine-tuning alone.
- 2022 — STaR. Zelikman et al.'s Self-Taught Reasoner fine-tuned a model on its own rationales that reached correct answers: in effect, RL with a binary reward and a crude (filtering) policy gradient. See also rejection-sampling fine-tuning (Yuan et al., 2023).
- 2023 — process supervision. Let's Verify Step by Step (Lightman et al.) showed step-level human labels train better reward models than outcome labels for reranking MATH solutions. Math-Shepherd automated step labels. Process rewards became the expected path.
- February 2024 — GRPO in DeepSeekMath, used with a learned reward model on GSM8K/MATH (DeepSeekMath-RL 7B: GSM8K 82.9% → 88.2%, MATH 46.8% → 51.7% over the Instruct model).
- September 2024 — OpenAI o1 announced as a model trained with large-scale RL to reason in a long hidden chain of thought, with performance improving with both train-time RL compute and test-time thinking.
- November 2024 — Tülu 3 names RLVR and releases a fully open pipeline using it.
- January 2025 — DeepSeek-R1 and Kimi k1.5, both reporting o1-level reasoning from large-scale RL with outcome rewards and no process reward model or tree search. Kimi k1.5 also introduced "long2short" methods to transfer long-reasoning gains to short answers.
- 2025 — the open replication wave. Open-R1 (Hugging Face), SimpleRL-Zoo, Open-Reasoner-Zero, DAPO, Dr. GRPO, GSPO and many more; frameworks such as verl and OpenRLHF make GRPO a configuration flag.
First principles¶
Why a single bit per episode is enough to learn reasoning¶
Each RLVR episode delivers at most about one bit of information: right or wrong. Compare pre-training or SFT, which deliver a full target distribution at every token. John Schulman's LoRA Without Regret (Thinking Machines, 2025) uses this to explain why policy-gradient RL works even with rank-1 LoRA adapters: the number of bits RL can absorb is tiny relative to the parameter count, so capacity is never the constraint. Two implications:
- RLVR cannot teach much knowledge. It can only reweight behaviours the model already produces. Knowledge must come from pre-training, mid-training or distillation.
- RLVR can still teach a great deal of behaviour: when to check, how long to think, which of its strategies to trust. These are low-information, high-leverage choices.
What the KL-regularised objective wants¶
With a KL penalty, the per-prompt objective is \(\max_\pi \mathbb E_{o\sim\pi}[r(o)] - \beta\,\mathrm{KL}(\pi\|\pi_{\text{ref}})\). Its exact maximiser (derived on the DPO page) is
With a binary reward this has a beautiful reading: every correct completion is multiplied by the same factor \(e^{1/\beta}\), every wrong one by 1. The relative probabilities among correct answers are exactly those of the reference model; diversity among correct solutions is preserved. If the reference solves the prompt with probability \(p\), the optimum solves it with
For \(p = 0.1\): \(\beta = 1\) gives \(p^\star = 0.232\); \(\beta = 0.25\) gives \(0.858\); \(\beta = 0.1\) gives \(0.9996\). Without the KL (\(\beta \to 0\)), any distribution supported on correct answers is optimal — including one that has collapsed onto a single solution. Policy gradient does not pick the diverse optimum; it drifts towards the collapsed one, because each step favours the currently most probable correct mode. That is the theoretical root of the entropy collapse and the pass@k crossover above, and why recipes that drop the KL have to add entropy management back in some other form.
Exploration is borrowed from pre-training¶
In game-playing RL, exploration comes from randomness over a small action space and from search (see model-based RL and planning). In RLVR the action space is all strings, and the only exploration is sampling from the pre-trained distribution at temperature ~1. If the right idea has probability \(10^{-6}\) under the base model, you will not sample it. The base model's pass@k, at the \(k\) you can afford, is therefore a soft ceiling on what RLVR can reach. This is why base-model quality (and mid-training on reasoning-heavy data) is the dominant variable, why curricula start from problems at the edge of the model's ability, and why the field is excited about methods that let the model explore in more structured ways: tools, multi-turn environments and self-generated sub-problems.
The maths¶
Derivation: the baseline does not bias the gradient
For a prompt \(q\), with \(b\) independent of the sampled completion,
The group mean \(\bar r = \frac1G\sum_j r_j\) does depend on \(o_i\) through \(r_i\). Write \(\bar r_{-i}\) for the mean of the other \(G-1\) rewards. Then
The leave-one-out baseline \(\bar r_{-i}\) is independent of \(o_i\) (the samples are independent), so it is unbiased; the group-mean advantage is the same thing times the constant \((G-1)/G\). Subtracting the group mean is therefore an unbiased policy gradient with a slightly smaller step. The worked example above checks this numerically: \(1.291\) and \(-0.775\) before standardisation become \(0.625\) and \(-0.375\), which are \(\tfrac78\) of RLOO's \(0.714\) and \(-0.429\).
Derivation: what dividing by the standard deviation does
Model one prompt with a single logit \(z\) controlling success, \(p = \sigma(z)\). The true gradient of the expected reward is \(\partial p/\partial z = p(1-p)\). The unbiased (RLOO-style) estimator has exactly this expectation. GRPO divides the advantages by the group standard deviation, which concentrates around \(\sqrt{p(1-p)}\), so its expected update is
Relative to the true gradient, a prompt is up-weighted by \(1/\sqrt{p(1-p)}\): by 1.25× at \(p = 0.2\) and by about 10× at \(p = 0.01\). GRPO therefore spends a disproportionate share of each step on prompts that are nearly always right or nearly always wrong — the "question-level difficulty bias" of Liu et al. (2025). Whether that bias is harmful is an empirical question (it acts like a curriculum toward hard prompts), but it is a bias: GRPO is not following the gradient of mean accuracy.
Derivation: the k3 KL estimator is unbiased and non-negative
GRPO penalises \(\mathrm{KL}(\pi_\theta\|\pi_{\text{ref}})\) per token using samples from \(\pi_\theta\). Write \(x = \pi_{\text{ref}}(o_t)/\pi_\theta(o_t)\) for a sampled token. Three estimators (Schulman, Approximating KL Divergence, 2020):
Since \(\mathbb E_{\pi_\theta}[x] = \sum_o \pi_\theta(o)\,\pi_{\text{ref}}(o)/\pi_\theta(o) = 1\), we get \(\mathbb E[k_3] = 1 - 1 + \mathbb E[-\log x] = \mathbb E[k_1] = \mathrm{KL}\): unbiased. And \(x - 1 - \log x \ge 0\) for all \(x > 0\) (the tangent line of the convex \(-\log\) at 1), so every single sample is non-negative, unlike \(k_1\), which has high variance and is negative whenever the reference prefers the token. \(k_2\) is non-negative but biased. In the Build-it check below, on a three-outcome example with true KL 0.0851, the means are \(k_1\) 0.0861 (std 0.39), \(k_2\) 0.0799 (biased), \(k_3\) 0.0848 (std 0.076).
PPO's clip. The ratio \(\rho = \pi_\theta/\pi_{\theta_{\text{old}}}\) corrects for the fact that, after the first gradient step on a batch, the samples come from a slightly older policy. For \(\hat A > 0\) the objective \(\min(\rho\hat A, \operatorname{clip}(\rho, 1-\varepsilon, 1+\varepsilon)\hat A)\) stops rewarding increases of \(\rho\) beyond \(1+\varepsilon\); for \(\hat A < 0\) it stops rewarding decreases below \(1-\varepsilon\). It is a cheap trust region (see actor-critic and PPO). If you take exactly one gradient step per batch of rollouts (as DeepSeekMath did: "the policy model only has a single update following each exploration stage"), \(\rho = 1\) at the point where the gradient is taken and the clip never binds; it matters only with several mini-batch updates per rollout. Clip-higher's insight is asymmetric: a token at probability 0.01 with \(\varepsilon = 0.2\) can rise only to 0.012 per update, while a token at 0.9 can rise to 1.0 — so symmetric clipping systematically favours already-likely tokens, which is entropy collapse.
Loss aggregation. Three normalisations appear in practice, with \(\ell_{i,t}\) the per-token clipped term:
Only the last makes each token's weight independent of the length of the sequence it sits in, which is what the REINFORCE gradient asks for. Under per-sequence normalisation a wrong 2,000-token answer receives a per-token penalty 10× smaller than a wrong 200-token answer, so length is a way to dodge blame.
GSPO's sequence ratio. GSPO replaces the per-token ratio with a length-normalised sequence ratio and clips that:
matching the unit of optimisation (a sequence) to the unit of reward (a sequence). Because \(s_i\) is a geometric mean, its clip range is tiny — the paper uses \(3\times10^{-4}\) and \(4\times10^{-4}\) — compared with 0.2 for token ratios.
Build it¶
NumPy, no frameworks. A toy "language model" over 12 reasoning strategies shared across 400 prompts; strategy \(j\) solves prompt \(p\) with a fixed hidden pattern \(S_{pj}\). The base model prefers three decent strategies; nine rare ones each solve a few prompts the common ones miss. We run GRPO (group size 8, group-normalised advantages, exact softmax gradient) with and without a KL anchor, and measure pass@k and entropy.
import numpy as np
rng = np.random.default_rng(0)
K, P = 12, 400 # K reasoning "strategies", P training prompts
prior = rng.normal(0, 1.0, K); prior[:3] += 1.5 # the base model likes strategies 0-2
skill = np.r_[0.55, 0.45, 0.35, rng.uniform(0.02, 0.15, K - 3)] # how often each strategy works
S = (rng.random((P, K)) < skill).astype(float) # S[p, j] = 1 if strategy j solves prompt p
softmax = lambda z: np.exp(z - z.max()) / np.exp(z - z.max()).sum()
def report(theta, tag):
pi = softmax(theta)
p_solve = S @ pi # per-prompt pass@1
pass_k = lambda k: np.mean(1 - (1 - p_solve) ** k)
H = -(pi * np.log(pi)).sum()
print(f"{tag:<14} pass@1 {pass_k(1):.3f} pass@16 {pass_k(16):.3f} "
f"pass@256 {pass_k(256):.3f} entropy {H:.2f} nats")
def grpo(theta, steps=300, B=32, G=8, lr=0.5, beta=0.0, ref=None):
theta = theta.copy(); dead = 0
for _ in range(steps):
pi = softmax(theta); grad = np.zeros(K)
for p in rng.integers(0, P, B):
j = rng.choice(K, G, p=pi) # G sampled completions
r = S[p, j] # verifier: 1 correct, 0 wrong
if r.std() == 0: dead += 1; continue # all same -> zero advantage
A = (r - r.mean()) / r.std() # group-relative advantage
for a, jj in zip(A, j):
grad += a * (np.eye(K)[jj] - pi) / (B * G) # A * d log pi(j) / d theta
if beta: # gradient of KL(pi || ref)
lr_ = np.log(pi / softmax(ref)); grad -= beta * pi * (lr_ - pi @ lr_)
theta += lr * grad
return theta, dead / (steps * B)
report(prior, "base model")
for beta in (0.0, 0.05):
th, dead = grpo(prior, beta=beta, ref=prior)
report(th, f"GRPO beta={beta}")
print(f"{'':14} share of zero-advantage groups during training: {dead:.2f}")
Output:
base model pass@1 0.311 pass@16 0.897 pass@256 0.940 entropy 2.06 nats
GRPO beta=0.0 pass@1 0.540 pass@16 0.576 pass@256 0.810 entropy 0.10 nats
share of zero-advantage groups during training: 0.71
GRPO beta=0.05 pass@1 0.537 pass@16 0.621 pass@256 0.875 entropy 0.19 nats
share of zero-advantage groups during training: 0.60
Everything this page argued is in those five lines: pass@1 up by 23 points, pass@256 down by 13, entropy collapsed from 2.06 to 0.10 nats, and most groups carrying no gradient by the end. The KL anchor keeps the same pass@1 while preserving more coverage.
And the numbers used in the worked examples and the KL derivation:
import numpy as np
r = np.array([1, 0, 0, 1, 0, 0, 0, 1.0]) # verifier rewards for G = 8 samples
A = (r - r.mean()) / r.std()
print("mean", r.mean(), "std", round(r.std(), 4), "A", np.round(A, 3))
loo = np.array([r[i] - np.delete(r, i).mean() for i in range(len(r))])
print("RLOO advantage", np.round(loo, 3), " = G/(G-1)*(r-mean):", np.round(8/7*(r-r.mean()), 3))
for G in (4, 8, 16, 64):
row = [1 - p**G - (1-p)**G for p in (0.02, 0.1, 0.5, 0.9, 0.98)]
print(f"G={G:<3} informative share at p=.02/.1/.5/.9/.98:", np.round(row, 3))
rng = np.random.default_rng(0) # k1, k2, k3 estimators of KL(pi||ref)
pi, ref = np.array([0.7, 0.2, 0.1]), np.array([0.5, 0.3, 0.2])
true = np.sum(pi * np.log(pi / ref))
x = rng.choice(3, 200_000, p=pi); ratio = ref[x] / pi[x]
for name, k in [("k1 = -log r", -np.log(ratio)), ("k2 = (log r)^2/2", np.log(ratio)**2 / 2),
("k3 = r - 1 - log r", ratio - 1 - np.log(ratio))]:
print(f"{name:<20} mean {k.mean():.4f} std {k.std():.4f} min {k.min():+.4f}")
print(f"true KL(pi||ref) {true:.4f}")
mean 0.375 std 0.4841 A [ 1.291 -0.775 -0.775 1.291 -0.775 -0.775 -0.775 1.291]
RLOO advantage [ 0.714 -0.429 -0.429 0.714 -0.429 -0.429 -0.429 0.714] = G/(G-1)*(r-mean): [ 0.714 -0.429 -0.429 0.714 -0.429 -0.429 -0.429 0.714]
G=4 informative share at p=.02/.1/.5/.9/.98: [0.078 0.344 0.875 0.344 0.078]
G=8 informative share at p=.02/.1/.5/.9/.98: [0.149 0.57 0.992 0.57 0.149]
G=16 informative share at p=.02/.1/.5/.9/.98: [0.276 0.815 1. 0.815 0.276]
G=64 informative share at p=.02/.1/.5/.9/.98: [0.726 0.999 1. 0.999 0.726]
k1 = -log r mean 0.0861 std 0.3903 min -0.6931
k2 = (log r)^2/2 mean 0.0799 std 0.0540 min +0.0566
k3 = r - 1 - log r mean 0.0848 std 0.0755 min +0.0508
true KL(pi||ref) 0.0851
For a real model, the loss is a few lines of PyTorch on per-token log-probabilities you have already computed (standard PyTorch; not run here). It implements GRPO's group advantage with DAPO's asymmetric clip and token-level mean, and the optional k3 KL term:
import torch
def grpo_loss(logp, logp_old, logp_ref, rewards, mask, G,
eps_lo=0.2, eps_hi=0.28, beta=0.0, scale_by_std=True):
"""logp*: [N, T] log-probs of the sampled tokens (N = prompts * G); rewards: [N]; mask: [N, T]."""
r = rewards.view(-1, G)
adv = r - r.mean(dim=1, keepdim=True)
if scale_by_std: # GRPO; Dr. GRPO sets this False
adv = adv / (r.std(dim=1, keepdim=True) + 1e-6)
adv = adv.view(-1, 1) # one advantage for every token
ratio = torch.exp(logp - logp_old)
loss = -torch.min(ratio * adv, ratio.clamp(1 - eps_lo, 1 + eps_hi) * adv)
if beta > 0:
d = logp_ref - logp
loss = loss + beta * (torch.exp(d) - d - 1) # k3 estimate of KL(pi || ref)
return (loss * mask).sum() / mask.sum() # token-level mean over the batch
Things to try
- Set
G=2and thenG=32in the toy. How do the zero-advantage share and the final pass@256 change? Relate it to the informative-share table. - Replace
A = (r - r.mean()) / r.std()withA = r - r.mean()(Dr. GRPO) and compare the speed of learning on prompts whose pass rate is near 0. - Implement "clip-higher" in the toy by capping how much each strategy's probability can grow per step relative to the old policy, separately for increases and decreases. Does an asymmetric cap slow the entropy collapse?
- Add a rare strategy that is the only solution to 10% of prompts, with base probability
\(10^{-4}\). Can GRPO ever find it with
G=8? WithG=256? - Train a real model: TRL's
GRPOTrainerwith a regex answer checker on GSM8K and a small instruct model is a one-file experiment; the Hugging Face course chapter below walks through it.
In practice¶
| Knob | Typical 2025 values | Notes |
|---|---|---|
| Learning rate | \(10^{-6}\), constant (DeepSeekMath; DAPO) | RL updates are tiny; a fine-tuning LR destroys the model |
| Group size \(G\) | 8–64 (DeepSeekMath 64; DAPO 16) | Larger for harder prompts |
| Prompts per step | 256–1024 (DAPO: 512) | Then split into mini-batches for several updates |
| KL coefficient \(\beta\) | 0.04 (DeepSeekMath) to 0 (DAPO, Dr. GRPO) | Zero is common for reasoning RL from a strong base |
| Clip \(\varepsilon\) | 0.2, or 0.2 / 0.28 asymmetric | GSPO uses ~\(10^{-4}\) on its sequence ratio |
| Max length | 16k–32k tokens for reasoning (DAPO: 16,384 + 4,096 soft-penalty zone) | Truncation handling matters |
| Sampling temperature | ~1.0 | Lower temperature = less exploration |
- Rollouts dominate cost. Generating long chains of thought is most of the compute. Real systems run an inference engine (vLLM, SGLang) for sampling and a training engine for updates, sync weights between them, and increasingly run them asynchronously, which makes the data slightly off-policy (the ratio \(\rho\) then matters). See serving LLMs.
- The verifier is production code. Normalise answers (fractions, units, LaTeX), sandbox code with time and memory limits, log every reward with its parsed answer, and read samples daily. Most "RL doesn't work" bugs are verifier bugs.
- Decontaminate. RL on maths prompts that overlap the benchmark is especially misleading, because RL can memorise answers with very little signal. See contamination and evaluation hygiene.
- Watch these curves: mean reward, response length (split by correct and wrong), entropy, share of zero-advantage groups, clip fraction, KL to reference, and held-out accuracy at pass@1 and pass@k.
- Evaluate across families. The spurious-rewards paper is a standing warning: a trick that works on Qwen2.5-Math may be eliciting a Qwen-specific pre-training habit.
- LoRA is enough for many RL runs (Schulman, 2025): RL absorbs few bits, so low-rank adapters match full fine-tuning even at rank 1 in their experiments. See PEFT and LoRA.
Common misconceptions¶
“R1-Zero proves self-reflection emerges from RL”
The "aha moment" is real in R1-Zero's transcripts, but Liu et al. (2025) found DeepSeek-V3-Base already produces self-reflection before any RL, and that Qwen2.5 base models reason well with no template at all. RL raised the frequency and usefulness of the behaviour; it did not invent it.
“Longer chains of thought mean better reasoning”
Some of the length growth in GRPO runs is an artefact of per-sequence normalisation: long wrong answers are penalised less per token. Dr. GRPO keeps accuracy while shortening wrong answers. Length is a means; tokens cost money and latency.
“Verifiable rewards can't be hacked”
They can be satisfied without solving the task whenever the verifier checks less than you think it does. The verifier is the specification; it deserves the same review as any security-critical code.
“RLVR teaches the model new facts”
At about one bit per episode it barely can. Gains come from reweighting existing behaviour. If the base model never gets a problem right in hundreds of samples, more RL steps will not help; better data, a stronger base, or a teacher will.
Check yourself¶
With a 0/1 reward, what quantity does the RLVR gradient ascend for a single prompt?
The probability that a sample is correct, i.e. pass@1 for that prompt: \(J = \mathbb E_{o\sim\pi}[r(o)] = P_\pi(\text{correct})\). Averaged over prompts, it is mean accuracy (plus \(-\beta\) KL if regularised).
Why does GRPO not need a value network, and what does it lose by dropping it?
It estimates the baseline \(\mathbb E[r\mid q]\) by the mean reward of \(G\) samples for the same prompt — a Monte Carlo estimate that is unbiased up to a \((G-1)/G\) factor. It loses per-token credit assignment (every token gets the same advantage) and pays \(G\) rollouts per prompt for its baseline.
A prompt's pass rate is 3%. With G = 8, how often will it produce a non-zero gradient? What two remedies do you have?
\(1 - 0.03^8 - 0.97^8 \approx 1 - 0.784 = 0.216\), about one group in five. Increase \(G\) for hard prompts, or use dynamic sampling (keep sampling prompts until the batch has enough mixed groups); a curriculum or a hint/partial-solution scaffold also raises \(p\).
Show that subtracting the group mean is equivalent to a leave-one-out baseline up to a constant, and say what dividing by the std adds.
\(r_i - \bar r = \frac{G-1}{G}(r_i - \bar r_{-i})\), and \(\bar r_{-i}\) is independent of \(o_i\), so the gradient is unbiased up to scale. Dividing by the std rescales each prompt by \(\approx 1/\sqrt{p(1-p)}\), up-weighting prompts with pass rates near 0 or 1 — a difficulty bias, not an unbiased gradient of accuracy.
Why does symmetric ratio clipping cause entropy collapse, and how does DAPO's clip-higher help?
The clip bounds the ratio \(\pi_\theta/\pi_{\text{old}}\), so a token's probability can grow by at most a factor \(1+\varepsilon\) per update. For an unlikely token (0.01) that is +0.002; for a likely one (0.8) up to +0.16. Positive advantages therefore mostly reinforce already-likely tokens and entropy falls. Raising \(\varepsilon_{\text{high}}\) (0.28) lets rare tokens grow faster, keeping exploration alive; \(\varepsilon_{\text{low}}\) stays at 0.2 to avoid crushing tokens to zero.
With β = 0.25 and a reference pass rate of 10%, what pass rate does the KL-regularised optimum have, and how is it distributed among correct answers?
\(p^\star = 0.1e^4/(0.1e^4 + 0.9) = 5.46/6.36 \approx 0.858\). Among correct answers the distribution is proportional to the reference's: each correct completion is scaled by the same \(e^{4}\), so diversity among correct solutions is preserved exactly.
The RL model beats the base model at pass@1 but loses at pass@256. Give the mechanism and one way to reduce the effect.
RL maximises pass@1, which is fastest done by concentrating probability on the most reliable strategy; probability leaves rare strategies that were the only solution to some prompts, so coverage at large \(k\) drops. Remedies: a KL anchor (see the toy, which keeps 0.875 vs 0.810 at pass@256), entropy bonuses or clip-higher, larger groups to keep rare successes in play, distillation from a teacher that adds new strategies, or explicitly diversity-aware objectives (optimising pass@k rather than pass@1).
Hard: why might per-sequence length normalisation make wrong answers longer over training?
With loss \(\frac{1}{|o_i|}\sum_t \ell_{i,t}\), a wrong answer's total negative push is spread over its tokens, so each token of a 2,000-token wrong answer is pushed down 10× less than each token of a 200-token wrong answer. The gradient therefore penalises the tokens typical of short wrong answers more, and "being long" becomes the cheapest way for a wrong answer to avoid blame. Over many steps the policy drifts toward long wrong answers. Constant normalisation (Dr. GRPO) or token-level averaging removes the asymmetry.
Go deeper¶
Papers
- DeepSeekMath: Pushing the Limits of Mathematical Reasoning in Open Language Models — Shao et al., 2024. Section 4 introduces GRPO; section 5.2's "unified paradigm" and the Maj@K vs Pass@K figure are the seeds of the sharpening debate.
- DeepSeek-R1: Incentivizing Reasoning Capability in LLMs via Reinforcement Learning — DeepSeek-AI, 2025 (Nature version). Read R1-Zero (§2.2), the pipeline (§2.3), distillation vs RL and the unsuccessful attempts (§4).
- Tülu 3: Pushing Frontiers in Open Language Model Post-Training — Lambert et al., 2024. Section 6 defines RLVR; the whole report is the best open post-training recipe.
- DAPO: An Open-Source LLM Reinforcement Learning System at Scale — Yu et al., 2025. Four fixes and the ablation table; the clearest guide to what breaks at scale.
- Understanding R1-Zero-Like Training: A Critical Perspective — Liu et al., 2025. Dr. GRPO, the two GRPO biases, and the "aha moment is already in the base model" result.
- Does Reinforcement Learning Really Incentivize Reasoning Capacity in LLMs Beyond the Base Model? — Yue et al., 2025. The pass@k crossover across families and algorithms.
- Spurious Rewards: Rethinking Training Signals in RLVR — Shao et al., 2025. Random rewards help Qwen2.5-Math, not Llama or OLMo; why you must test across model families.
- Group Sequence Policy Optimization — Zheng et al. (Qwen), 2025. Sequence-level ratios; why token ratios destabilise MoE RL.
- Kimi k1.5: Scaling Reinforcement Learning with LLMs — Kimi Team, 2025. A parallel, critic-free recipe with long-context RL and long2short.
- Back to Basics: Revisiting REINFORCE Style Optimization for Learning from Human Feedback in LLMs — Ahmadian et al., 2024. RLOO, and the argument that PPO's machinery is unnecessary for LLMs.
- The Entropy Mechanism of Reinforcement Learning for Reasoning Language Models — Cui et al., 2025. Entropy collapse as a covariance effect; Clip-Cov and KL-Cov.
- Monitoring Reasoning Models for Misbehavior and the Risks of Promoting Obfuscation — Baker et al., 2025. Reward hacking by frontier reasoning models, and why not to train against the CoT monitor.
- STaR: Bootstrapping Reasoning With Reasoning — Zelikman et al., 2022 and Let's Verify Step by Step — Lightman et al., 2023. The two pre-o1 roads: self-generated rationales, and process supervision.
Videos and lectures
- Stanford CS336, Spring 2025, Lecture 17: Alignment - RL 2 — Stanford Online. Policy gradients, GRPO and verifiable rewards, from a course that builds everything from scratch; Lecture 16 (video) sets up RLHF vs RLVR.
- Understanding Policy Gradient Algorithms for RL on LLMs — Nathan Lambert, Post-Training Course lecture 3. REINFORCE → PPO → GRPO with the RLHF Book's notation.
- GRPO Explained: DeepSeekMath — Yannic Kilcher, 2025. An hour-long paper reading of DeepSeekMath, data pipeline and GRPO.
Articles and books
- RLHF Book: Reasoning and Inference-Time Scaling — Nathan Lambert. The best continuously updated survey chapter on RLVR recipes.
- The State of Reinforcement Learning for LLM Reasoning — Sebastian Raschka, 2025. A readable map of the 2025 papers.
- Why We Think and Reward Hacking in Reinforcement Learning — Lilian Weng. Test-time compute and reasoning; the definitive reward-hacking survey.
- Learning to Reason with LLMs — OpenAI, September 2024. The o1 announcement: accuracy rising smoothly with both RL train-time compute and test-time thinking.
- Approximating KL Divergence — John Schulman, 2020. Where k1, k2, k3 come from.
- LoRA Without Regret — John Schulman et al., Thinking Machines, 2025. The bits-per-episode argument for why RL needs so little capacity.
Courses and code
- Hugging Face LLM Course, chapter 12: Open R1 for Students — Build a small reasoning model with GRPO in TRL.
- TRL GRPOTrainer docs — The most accessible GRPO implementation; its
loss_typeoptions (such asdr_grpoanddapo) implement the normalisations discussed above. - volcengine/verl and OpenRLHF — Production-scale RL frameworks (DAPO is built on verl).
- huggingface/open-r1 — A fully open reproduction effort of the R1 pipeline, with data and recipes.
Where this leads¶
- Reasoning models and test-time compute — what these RL-trained models do at inference: long chains of thought, budgets, and how test-time compute trades against model size.
- Distillation and synthetic data — why distilling a reasoning teacher beat RL on small models in R1, and on-policy distillation as the cheap middle path.
- Constitutional AI and RLAIF — the other way to replace human labels: a model judging against written principles, for the domains no verifier covers.
- Offline RL and RL for language models — the RL-theory view: credit assignment, off-policy corrections, multi-turn agent environments.
- Model merging and continual learning — why on-policy RL forgets less than SFT ("RL's Razor") and how to combine RL-trained skills.