Chapter 7 · Book pages 164–179

GRPO — Group Relative Policy Optimization

Main read ≈ 22 minutes · dotted words have hover/tap definitions · ▸ boxes go deeper · finish with the test (100% to complete)

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.

Introduced in DeepSeekMath and scaled to DeepSeek-R1, GRPO is now the default RL algorithm in TRL, OpenRLHF, and veRL — dominant for reasoning tasks with verifiable rewards, for 70B+ models where the memory savings are critical, and for multi-turn/agentic settings where value estimation across tool calls is intractable. This is chapter 3's actor-critic with the critic deleted, chapter 4's RLVR paradigm in its production form, and the method behind the most influential reasoning model to date.

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)

Why group normalization works: the group mean is a Monte Carlo estimate of V(s) — sample enough responses to one prompt and their average reward is the value function. Above the mean → reinforce; below → suppress. Dividing by σG makes advantages scale-invariant across prompts with different reward ranges. The DeepSeek-R1 breakthrough: pure GRPO with binary correctness rewards (1 if correct, 0 otherwise) on math/code spontaneously produced chain-of-thought reasoning, self-verification, and error correction — never instructed to.
y₁ ✓ r=1Â ≈ +0.8 y₂ ✓ r=1Â ≈ +0.8 y₃ ✗ r=0Â ≈ −1.2 y₄ ✓ r=1Â ≈ +0.8 y₅ ✗ r=0Â ≈ −1.2 baseline µG = 0.6 (the group mean — no critic needed) · above → reinforce, below → suppress
Book fig. 7.1: G = 5 responses to one math prompt, 3 correct — the group mean µG = 0.6 is the baseline (advantage values are our arithmetic from eq. 7.1) (p. 165).

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!
    ...)
Read the config against the chapter so far: 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

GSignal qualityComputeWhen to use
2Very noisy (coin flip)LowNever recommended — too noisy for stable learning
4ModerateModerateQuick experiments, easy tasks (pass rate > 50%)
8Good (standard)HighDefault — good balance for most tasks
16ExcellentVery highHard tasks (pass rate < 20%), need many attempts to get positives
32Near-perfectExtremeOnly with massive compute and a very hard task
The critical constraint: a group must contain both successes and failures. All-correct or all-wrong → every advantage is 0 → no learning signal at all. The Goldilocks rule: filter prompts to a 20–80% pass rate for the current model, and re-filter every 500 steps as the model improves.
Hold this against 2-GRPO (stop 6): the table says G = 2 is "never recommended," yet the "It Takes Two" paper matches G = 16 with G = 2 — because GRPO's power is the contrastive signal, not advantage precision. Both claims are in the book; the reconciliation is that signal quality per group and learning signal per unit compute are different metrics.
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.

The monitoring trio: response entropy, unique n-gram ratio, and reward distribution width. If all three drop together, you have a collapse problem. (The book's table 7.1 also lists entropy bonuses, rejection sampling, best-of-N, DPO with approach-diverse pairs, and multi-reward training as diversity levers.)
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.

DAPO — five components: (1) clip-higher: asymmetric band, ε = 0.2 down but εhigh = 0.28 up for positive advantages (raising a good token is safe; over-suppressing a neutral token in a bad completion is not); (2) token-level loss aggregation (divide by total tokens, not sequences, so long completions don't dominate); (3) overlong filtering (mask truncated completions entirely — their signal is misleading); (4) soft overlong punishment (a smooth length penalty past a safe threshold Lcache); (5) dynamic sampling (re-sample zero-variance groups, keeping effective batch size stable). TRL: 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.

GSPO — the sequence-level fix. Per-token ratios can each sit inside [1−ε, 1+ε] while their product over 500 tokens explodes (the book's example: a product ratio of 10⁵⁰). GSPO clips one scalar per sequence: the geometric mean of per-token ratios, si(θ) = (πθ(oi|q)/πold(oi|q))1/|oi|. Theoretically correct for off-policy IS — and off-policy training (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

Dr. GRPO — the pretraining-bias fix. Tokens common in pretraining receive large gradients even when task-irrelevant; Dr. GRPO down-weights them: wi,t = Âi · (1 − πref(oi,t|q, oi,<t)), concentrating gradient on tokens where the policy genuinely needs to change (TRL: 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.
TIS / MIS — the vLLM probability-mismatch fix. vLLM's log-probs differ from the training forward pass (different CUDA kernels, precision, attention implementations — FlashAttention vs PagedAttention), silently breaking the on-policy assumption. TIS multiplies the gradient by a correction truncated at C = 5.0 (preferred for small mismatch); MIS zeroes the gradient entirely when the ratio exceeds C = 3.0 (preferred for large or unpredictable mismatch). Both exist in sequence- (theoretically correct, higher variance) and token-level (practical compromise) forms. VESPO — a variational-inference kernel g(τ) = W(τ)k · exp(λ(1 − W(τ))): smooth everywhere, asymmetric, and naturally down-weights stale trajectories in off-policy training (TRL: vespo_k_pos=2.0, vespo_lambda_pos=3.0, steps_per_generation=2).
CISPO / ScaleRL — the at-scale recipe. ScaleRL's five findings: batch-level reward scaling alone → modest; token-level loss alone → modest; both together → synergistic, significantly better; larger batches benefit more from batch-level scaling; and CISPO (batch-normalized advantages Âi = (ri − µbatch)/(σbatch + ϵ) + DAPO-style token loss) is the recommended default for large-scale RL training. TRL: 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.

The final guidance: use GRPO when rewards are verifiable and exact (math correctness, code tests, binary signals — magnitudes carry meaning); use GOPO when rewards come from a learned reward model on subjective tasks (helpfulness, style, safety — the ordering is trustworthy, the absolute scores arbitrary).
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.

Stop 8 — When to use which

The consolidated selection guide: DAPO — drop-in default improvement, especially long-form reasoning or reward-variance collapse · GSPO — whenever steps_per_generation > 1 (off-policy reuse) · SAPO — when the hard clip's cliff edge destabilizes training · DPPO — research-stage, for skewed token distributions where ratio clipping fails · Dr. GRPO — large pretraining/RL vocabulary mismatch, filler tokens dominating gradients · 2-GRPO — compute-constrained binary-reward tasks (mind the {+1,−1} caveat) · TIS — small vLLM mismatch (truncate at 5.0); MIS — large or unpredictable mismatch (mask at 3.0) · VESPO — asynchronous/off-policy with staleness · CISPO — the recommended default at scale · GDPO — multi-objective rewards with mismatched scales · GOPO — subjective, reward-model-scored tasks.
The arc of Part II so far: PPO gave you the full machine, DPO deleted the RL, GRPO deleted the critic — and its eleven variants are a decade of RL engineering compressed into one chapter's worth of dials. Next: chapter 8 surveys the preference-optimization variants (Online DPO, KTO, Best-of-N) and how to choose among them.

Chapter test