GRPO Training
Group Relative Policy Optimization — derived from the policy gradient theorem, situated against PPO, DPO and RLOO, with its known biases stated and its memory footprint accounted for. Then a memory-efficient implementation on GSM8K with LoRA and DeepSpeed ZeRO-2.
Model: Qwen-1.5B (distilled) · Dataset: GSM8K · Target: 8 GB GPU
GRPO is frequently described — including in earlier versions of this page — as "eliminating the reference model, so no KL term is needed." This is wrong. The objective published in DeepSeekMath (Shao et al., 2024, Eq. 3) contains an explicit term and requires a frozen reference model.
What GRPO eliminates is the critic (value network) — a trainable model the same size as the policy. That is where the memory saving comes from, and it is a much stronger claim than dropping a frozen reference. The distinction is developed in §5.
1. Why Reinforcement Learning At All
An LLM is trained in stages, and each stage optimizes a different objective:
The reason RL is not redundant with SFT is a distribution mismatch. SFT is maximum likelihood on a fixed corpus of demonstrations — behaviour cloning. It trains the model on the demonstrator's state distribution, but at inference the model must act on states induced by its own previous tokens. Errors compound: this is the classic covariate-shift argument of DAgger (Ross et al., 2011), and in the sequence setting it is exposure bias.
More fundamentally, SFT can only imitate. If a correct answer is reachable by a reasoning chain no human wrote down, likelihood training on human chains cannot find it. RL optimizes — the quantity you actually care about — over the model's own output distribution, and can therefore discover behaviours absent from the demonstration set.
For mathematical reasoning this is especially compelling, because need not be learned at all: the answer is checkable. That is the regime GRPO was designed for.
2. From Policy Gradients to PPO
2.1 The policy gradient theorem
Treat generation as a finite-horizon MDP: state is the prompt plus tokens so far, action is the next token, and the policy is the LM itself, . We maximize
The score-function identity gives the REINFORCE estimator (Williams, 1992):
This is unbiased and essentially unusable on its own: its variance scales with the magnitude of and with sequence length. With tokens, a single scalar reward must be credited across 512 factors.
2.2 Baselines and why they are free
For any function that does not depend on the action,
So replacing with the advantage leaves the gradient unbiased while changing its variance. Choosing well is the entire game. This identity is the hinge of the whole page: PPO, GRPO and RLOO differ almost exclusively in how they construct .
| Method | Baseline | Cost |
|---|---|---|
| REINFORCE | None; variance is enormous | |
| Actor–critic / PPO | , a learned value network | A second trainable model of policy size |
| RLOO | Mean reward of the other samples | samples per prompt, no extra model |
| GRPO | Mean reward of the group, then divided by group std | samples per prompt, no extra model |
2.3 PPO
PPO (Schulman et al., 2017) fixes a second problem: a large policy step can collapse the policy, and the sampled data is only valid near . Define the importance ratio
and optimize the clipped surrogate — the objective the DeepSeekMath paper states as its Eq. 1:
The with a clipped copy creates a pessimistic bound: once the ratio moves beyond in the direction that would improve the surrogate, the gradient is cut off. Typically .
In RLHF, comes from GAE (Schulman et al., 2016) over a learned critic . That critic is the problem. It is initialized from the policy, is the same size, and is trained concurrently — so it carries a full of model states. It is also genuinely hard to fit: it must predict the expected future reward of a partial generation, from a sparse terminal signal, on a non-stationary distribution.
3. Direct Preference Optimization — the other escape route
DPO (Rafailov et al., 2023) takes a different exit. Under the KL-regularized RL objective the optimal policy has a closed form,
which can be inverted for the implied reward,
Substituting into a Bradley–Terry preference model, the intractable cancels between the two responses, leaving a supervised objective:
No rollouts, no reward model, no critic — DPO is a classification loss on a fixed preference dataset.
Its limitation is exactly what makes GRPO attractive for math. DPO is off-policy and offline: it can only learn from preference pairs already collected, cannot query a verifier during training, and cannot exploit a scalar reward that is cheap to evaluate on new samples. When you have a ground-truth checker, throwing it away to collect pairwise human preferences is a strange trade.
4. GRPO
4.1 The idea
Ask what the critic is for. It supplies a baseline: an estimate of the expected reward from state . But if you are willing to sample responses to the same prompt, you can estimate that expectation by Monte Carlo — directly, with no learned model:
Replace a learned function approximator with an empirical mean over a group of rollouts. That is GRPO in one sentence. It exploits a property special to LLM alignment: unlike a robotics episode, generating samples from the same prompt is cheap and embarrassingly parallel.
4.2 The objective
For prompt , sample a group and score each with . Under outcome supervision, every token of receives the same normalized advantage:
Writing , the GRPO objective (Shao et al., 2024, Eq. 3) is
Compare term by term with : the clipped surrogate is identical. Exactly two things changed.
- from a learned critic from group statistics.
- The KL penalty moved out of the reward and into the loss, as an explicit term with its own estimator.
Everything else — the ratio, the clip, — is PPO.
4.3 The KL estimator — why it is not what you would write
Naively, is estimated by the sample mean of . GRPO instead uses (Eq. 4):
This is Schulman's k3 estimator. Writing , the three candidates are
| Estimator | Form | Unbiased? | Variance | Sign |
|---|---|---|---|---|
| k1 | Yes | High | Can be negative | |
| k2 | No | Low | Always | |
| k3 | Yes | Low | Always |
k3 is unbiased and guaranteed non-negative, because for all real with equality only at . That non-negativity matters: k1 fluctuates in sign sample-to-sample, and a "penalty" that is sometimes a bonus is a poor regularizer.
A KL penalty written as kl = (old_log_probs - log_probs).mean() is k1 — high variance and sign-unstable. Prefer:
log_ratio = ref_logprobs - policy_logprobs # u
kl = torch.exp(log_ratio) - log_ratio - 1.0 # k3: unbiased, non-negative
4.4 Relation to RLOO
RLOO (Ahmadian et al., 2024) uses the leave-one-out baseline
Since excludes , it is independent of the action being scored and the baseline identity of §2.2 applies exactly — RLOO's advantage is strictly unbiased. GRPO's includes , so is weakly correlated with and carries an bias. Note the two differ only by the constant factor , which is absorbed into the learning rate — so before std-normalization, GRPO's advantage is RLOO's up to a scalar. The real divergence is the factor, and that turns out to be the contentious part.
5. What GRPO Actually Removes: A Memory Accounting
Use the mixed-precision Adam accounting from ZeRO Stages: a trainable model costs bytes of model states; a frozen model in BF16 costs .
| Component | PPO / RLHF | GRPO | DPO |
|---|---|---|---|
| Policy (trainable) | |||
| Critic (trainable) | — | — | |
| Reward model (frozen) | — a verifier | — | |
| Reference (frozen) | |||
| Total model states |
For : PPO 54 GB, GRPO 27 GB. GRPO halves model-state memory, and the entire saving is the critic. Dropping a frozen reference model would have saved — about 6% — which is why the "no reference model" framing both misstates the algorithm and undersells it.
Two caveats that keep this honest:
- GRPO's activation memory is worse than PPO's per optimizer step, because it holds rollouts per prompt rather than one. Model states fall; rollout buffers rise. Budget for both.
- With LoRA, only adapter parameters are trainable, so the terms collapse to . The critic's removal still matters, but proportionally less — and the reference model can often be obtained for free by disabling the adapters, since the frozen base weights are . See §8.
6. A Worked Numerical Example
Take GSM8K with binary verifier reward and group size .
Prompt. Janet's ducks lay 16 eggs per day. She eats 3 for breakfast and bakes muffins with 4. She sells the rest at $2 per egg. How much does she make daily? Ground truth: 18.
Rollouts and rewards.
| Final answer | ||
|---|---|---|
| 1 | 18 ✓ | 1 |
| 2 | 15 ✗ | 0 |
| 3 | 18 ✓ | 1 |
| 4 | 20 ✗ | 0 |
. The population standard deviation is
giving advantages
Every token of responses 1 and 3 is reinforced with weight ; every token of 2 and 4 is suppressed with weight . No critic was consulted, and the absolute scale of never entered.
torch.std uses Bessel's correction — this is a real bug sourcePyTorch's Tensor.std() defaults to unbiased=True, dividing by , not . On the same data:
A 13% smaller effective advantage than the paper's formula, i.e. a silently reduced learning rate — and the discrepancy grows as shrinks. Write rewards.std(dim=1, unbiased=False) (or correction=0) to match the published objective, and be aware that library implementations differ on this point.
6.1 The degenerate-group problem
Now suppose all four rollouts are correct: . Then , , and
The gradient is exactly zero. The prompt contributes nothing. The same holds if all four are wrong. This is not a numerical edge case — it is structural, and it governs how much of your compute does useful work.
Model each rollout as i.i.d. within a group, where is the model's per-sample success rate on that prompt. A group is degenerate iff all samples agree:
| 0.1 | 65.6% | 43.0% | 18.5% |
| 0.3 | 24.8% | 5.8% | 0.33% |
| 0.5 | 12.5% | 0.78% | 0.003% |
| 0.7 | 24.8% | 5.8% | 0.33% |
| 0.9 | 65.6% | 43.0% | 18.5% |
Three consequences worth internalizing:
- Signal is maximized at . GRPO learns most from problems the model solves about half the time — a formal statement of "train at the edge of competence."
- Success is self-defeating. As training drives , roughly two-thirds of groups at become degenerate. Throughput of useful gradient collapses precisely because the model improved. Reward curves flattening late in training often reflect this, not a converged policy.
- Group size is variance-reduction with sharply diminishing returns. Going at takes waste from 65.6% to 43.0%; takes it to 18.5%. Each doubling doubles rollout cost, and rollout dominates GRPO wall-clock.
The practical remedies follow directly: filter degenerate groups before the optimizer step (DAPO's dynamic sampling, Yu et al., 2025), curriculum toward problems near , and raise only once filtering is in place.
For a full simulation of this effect with runnable code, see the worked example page.
7. Known Biases: The Dr. GRPO Critique
Liu et al. (2025) show that two normalizers in the objective are not innocuous.
Length normalization . For a response with negative advantage, dividing the summed per-token loss by means a longer wrong answer receives a smaller per-token penalty. Gradient descent therefore finds it cheaper to be wrong at length, and incorrect responses grow monotonically during training — the widely-observed "length inflation" of R1-Zero-style runs, which is easy to misread as emergent deliberation.
Standard-deviation normalization . Under binary rewards