Chapter 7 · Book pages 164–179
GRPO — Group Relative Policy Optimization
The big picture
Chapter 5's PPO needs a critic — a value network predicting expected reward — and for language that critic has three problems: memory (the value head shares the policy backbone — 140GB for 70B — and doubles memory if separate), accuracy (predicting reward for a partial sequence is extremely hard; a wrong value means a wrong advantage means a wrong gradient direction), and training (early in RL the critic's noisy predictions destabilize policy learning). GRPO's insight: don't learn V(s) at all — estimate it empirically from a group of samples.
Stop 1 — The algorithm
Four steps. (1) For each prompt x, sample G completions {y₁,…,yG} from the current policy. (2) Score each: ri = R(x, yi). (3) Normalize within the group: Âi = (ri − µG)/σG, where µG and σG are the group's mean and standard deviation. (4) Apply a PPO-style clipped update with these advantages, plus a KL term:
Âi = (ri − µG) / σG, L = E[ min(rt(θ)Âi, clip(rt(θ), 1±ε)Âi) ] − β DKL[πθ ‖ πref] (7.1)
Interactive · Group normalization simulator
Pick G and a prompt's pass rate, sample groups, and watch µG, σG, and the advantages — including the all-correct/all-wrong zero-signal failure. (Simulated rewards — illustrative.)
Go deeper: the recap's exact forms
The variants recap (§7.5.1) writes the normalization with a stabilizer, Âi = (ri − µr)/(σr + ϵ), and the per-token clipped surrogate as an average over both sequences and tokens: L = −(1/G) Σi (1/|oi|) Σt min(ρi,tÂi, clip(ρi,t, 1−ε, 1+ε)Âi), where ρi,t is the per-token probability ratio against the old policy. Note §7.2's boxed form has no +ϵ — both are the book's, each in its context. Book §7.2, p. 165; §7.5.1, p. 169.
Stop 2 — TRL implementation
Minimal GRPO with HuggingFace TRL (values verbatim from the book):
grpo_config = GRPOConfig(
num_generations=8, # G = group size
temperature=1.0, # high temp for diversity within group
max_completion_length=2048,
beta=0.04, # KL penalty coefficient
learning_rate=1e-6,
per_device_train_batch_size=2, # prompts per device (×8 gens = 16 responses)
gradient_accumulation_steps=8,
num_train_epochs=2,
max_grad_norm=0.5,
use_vllm=True, # critical for GRPO due to 8× generation
vllm_gpu_memory_utilization=0.7,
)
def reward_fn(completions, prompts, **kwargs):
"""1.0 if correct, 0.0 if wrong."""
...
def format_reward_fn(completions, **kwargs):
"""Bonus for proper LaTeX formatting."""
return [0.5 if "\\boxed{" in c else 0.0 for c in completions]
trainer = GRPOTrainer(model=model, args=grpo_config,
reward_funcs=[reward_fn, format_reward_fn], # multi-objective!
...)
num_generations=8 is the stop-3 default group size; temperature=1.0 buys the within-group diversity of stop 4; beta=0.04 is the KL leash (an order below DPO's 0.1); use_vllm is chapter 2's serving stack paying for 8× generation; and reward_funcs taking a list is the multi-objective door that stop 7's GDPO walks through.Go deeper: the reward functions
reward_fn returns 1.0/0.0 by extracting the answer and comparing to ground truth — the R1-style binary signal. format_reward_fn adds 0.5 for proper LaTeX (\boxed{}). Passing both as a list makes training multi-objective; how those rewards get combined is exactly the advantage-collapse problem GDPO solves in stop 7. Book §7.3, p. 165–166.
Stop 3 — Group size: the signal-vs-compute dial
| G | Signal quality | Compute | When to use |
|---|---|---|---|
| 2 | Very noisy (coin flip) | Low | Never recommended — too noisy for stable learning |
| 4 | Moderate | Moderate | Quick experiments, easy tasks (pass rate > 50%) |
| 8 | Good (standard) | High | Default — good balance for most tasks |
| 16 | Excellent | Very high | Hard tasks (pass rate < 20%), need many attempts to get positives |
| 32 | Near-perfect | Extreme | Only with massive compute and a very hard task |
Go deeper: the arithmetic of a dead group
If every ri = 1: µG = 1, so every Âi = 0/σG = 0 — a full group of correct answers teaches nothing, because the baseline is empirical: there is no "better than average" without variation. Same for all-wrong. This is why DAPO's dynamic sampling (stop 5) re-rolls zero-variance groups instead of wasting the batch slot. Book §7.4, p. 166.
Stop 4 — Diversity: keeping the group alive
Without diversity pressure, RL-trained LLMs mode-collapse: one "template" answer per question type, entropy dropping fast, reward hacking made easier (narrow outputs are easier to exploit), and memorized reward patterns instead of reasoning. The KL penalty is the primary defense but not sufficient alone. Within-group diversity is the GRPO-specific lever: high temperature (τ = 0.8–1.0) for varied responses, large N (8–16) so both good and bad approaches appear, and DAPO's "no repeat" penalty rejecting duplicate responses inside a group. All-identical responses → zero advantage; too-random responses → noisy reward, slow learning. The sweet spot: distinct approaches that stay on-topic.
Go deeper: verbalized sampling — training-free diversity for group generation
Alignment itself causes typicality bias: annotators prefer familiar text, so aligned models collapse to "safe" modes. Verbalized Sampling (VS) sidesteps it with a prompt: "Generate 5 jokes about coffee and their corresponding probabilities" — the model articulates the whole distribution (temperature 0.7 in the book's code), you sample from it, and low-probability creative responses become reachable. Semantic diversity rather than temperature's lexical noise; more capable models benefit more (1.6–2.1× diversity gain in creative writing); training-free. For GRPO: use VS to generate the G candidates so the group contains genuinely different approaches. Book §7.5.1, p. 167–168.
Stop 5 — The clipping and aggregation variants
The variants each fix one observed failure mode: pretraining bias diluting gradients (Dr. GRPO, stop 6), symmetric clipping limiting exploration (DAPO), wasteful large groups (2-GRPO, stop 6), reward-scale imbalance (GDPO, stop 7). First, the four that re-engineer the clip and the loss aggregation.
epsilon=0.2, epsilon_high=0.28, loss_type="dapo", mask_truncated_completions=True. Recommended as a drop-in improvement over base GRPO for most tasks.Interactive · Clip-higher visualizer
Slide the ratio ρ and flip the advantage sign — see the symmetric band versus DAPO's asymmetric one, and how much movement each allows.
steps_per_generation=4 in TRL) slashes generation cost, the most expensive step. For purely on-policy training the difference from GRPO is negligible.Interactive · Per-token ratios compound; geometric means don't
Slide sequence length and per-token drift to watch the product ratio escape to astronomical values while GSPO's geometric mean stays clipped. (Illustrative arithmetic.)
Go deeper: SAPO and DPPO — softening and replacing the clip
SAPO replaces the hard clip's zero-gradient cliff with a smooth temperature-controlled gate: −A·σ((ρ−1)/τ⁺)·ρ for A > 0, −A·σ((1−ρ)/τ⁻)·ρ for A ≤ 0. Higher temperature = softer gate (more exploration); τ → 0 recovers hard PPO clipping; τ → ∞ recovers unclipped policy gradient. Book's settings: τ⁺ = 1.0, τ⁻ = 1.05 (TRL: sapo_temperature_pos=1.0, sapo_temperature_neg=1.05). DPPO replaces ratio clipping — an imperfect KL proxy that over-penalizes low-probability tokens — with direct divergence masks: binary/top-k over TV or KL contributions. Research-stage: not yet in mainstream libraries; relevant when ratio clipping visibly fails on skewed token distributions. Book §7.5.2–7.5.3, 7.5.6, 7.5.9, p. 169–171, 173–174, 176.
Stop 6 — The data and bias variants
loss_type="dr_grpo", reference model required). 2-GRPO — the "It Takes Two" result: G = 2 matches or exceeds G = 16 on most reasoning benchmarks, because GRPO's power is an implicit contrastive objective structurally similar to DPO (compare o⁺ vs o⁻), not advantage precision. 8× less generation compute, ~4–6× end-to-end speedup, no accuracy loss on GSM8K, MATH, and code. Caveat: with G = 2 the normalized advantages are always {+1, −1} (or {0, 0} when the pair ties — the zero-signal case from stop 3) — fixed gradient magnitude regardless of the reward gap, so partial-credit tasks may still want larger G.vespo_k_pos=2.0, vespo_lambda_pos=3.0, steps_per_generation=2).loss_type="cispo", scale_rewards="batch", epsilon_high=5.0.Go deeper: where each of these lives in the pipeline
Dr. GRPO touches the per-token gradient weight; 2-GRPO touches G; TIS/MIS sit at the generation/training boundary (enable whenever vLLM generates); VESPO replaces the clip with a principled kernel for asynchronous work; CISPO re-bases the normalization from group to batch. They compose: a production stack might run DAPO's clip-higher + token loss, TIS correction on vLLM output, and CISPO's batch scaling simultaneously. Book §7.5.4–7.5.8, 7.5.10, p. 172–177.
Stop 7 — Multi-reward and ranking variants
GDPO fixes advantage collapse: with multiple rewards (correctness + format), standard GRPO normalizes the combined reward — and if one reward has much higher variance, it dominates, drowning the other to near-zero gradient. GDPO normalizes each reward independently within the group, then combines with user weights: Â⁽ⁱ⁾n = (r⁽ⁱ⁾n − µn)/(σn + ϵ), then Â⁽ⁱ⁾ = Σn wnÂ⁽ⁱ⁾n. TRL: multi_objective_aggregation="normalize_then_sum", reward_weights=[1.0, 0.5].
Interactive · Advantage collapse, before and after GDPO
Two rewards with different scales across four completions — watch standard combined normalization drown the format signal, then flip to GDPO. (Canned numbers — illustrative.)
GOPO starts from an epistemics point: reward models are trained on pairwise comparisons, so only the rank order of their scores is trustworthy — a 0.6-point gap might mean genuine quality in one region and nothing in another. GOPO discards magnitudes entirely: rank the group (1 = worst, N = best) and set Âi = f(rank(oi)/N) with f monotonic (e.g. linear to [−1, 1]) (eq. 7.2). Invariant to any monotonic reward transformation; empirically (book's report): reward curves above GRPO throughout, better LLM-judged win-rates at most checkpoints, markedly faster convergence, and the advantage grows as the reward model gets noisier.
Go deeper: the GRPO-vs-GOPO comparison
Advantage signal: (ri − µ)/σ (magnitudes) vs f(ranki/N) (ordinal only). Sensitivity to reward scale: high (miscalibrated RM scores distort advantages) vs none (monotonic invariance). Best for: verifiable, well-calibrated rewards vs non-verifiable, RM-based noisy magnitudes. GOPO is the bridge back toward chapter 6's world — preferences are ordinal all the way down. Book §7.5.11–7.5.12, p. 178–179.