Group-Based Policy Optimization

Michael BrenndoerferNovember 29, 202644 min read

Learn how GRPO trains language models without a learned critic, using group-relative rewards, clipped surrogates, and tied-reward handling.

Language AI HandbookAll chapters
Part 40 of 67Reasoning Post-Training and Verifiable Rewards
Chapter 301Group-Based Policy Optimization
Reading the full chapter · 10 sections · 44 min10 sections · 44 min

All 10 sections · 44 min read

Reading settings

Definitions

Choose how many terms have tooltips.

Article links

Make inline references clickable

Notes & comments

Group-Based Policy Optimization

Eight completions answer the same question. Seven are correct and one is wrong. If the verifier awards 1 for a correct answer and 0 otherwise, what signal does each completion send to its tokens? Group Relative Policy Optimization (GRPO) answers with the scores from that same prompt, avoiding a learned critic. Its reward can come from a verifier or a learned reward model. The choice of reward and the choice of optimizer are separate.

Proximal Policy Optimization (PPO) supplies the clipped surrogate that GRPO adapts. In actor-critic implementations of PPO, a learned value function helps estimate how much better or worse a sampled action was than expected. Estimating that expectation can reduce variance, but it adds another component to train.

A separate trainable critic adds parameters and forward and backward computation. Extra optimizer state depends on the optimizer. A shared-backbone value head changes those costs. GRPO avoids fitting a critic by estimating a baseline from several completions of each prompt.

For each prompt, GRPO samples responses under a behavior policy and compares their rewards. The outcome-supervised version centers and scales each response’s reward within its group and supplies the resulting advantage to that response’s tokens. A group mean that includes the response being scored depends on that very response, so the usual action-independent baseline proof does not directly apply.

DeepSeekMath, by Shao et al., introduced GRPO in 2024 and described both outcome and process supervision. Later work revisits the objective, including how it weights tokens and how it handles groups with tied rewards.

We will derive the clipped objective, work through tied rewards, and run the update on a small CPU policy. The toy makes the arithmetic visible. The original DeepSeekMath setting and later variants are described separately.

Why a Critic-Free Baseline?

One ingredient of a PPO advantage estimator is the one-step temporal-difference residual:

δt=rt+γVϕ(st+1)−Vϕ(st),\delta_t = r_t + \gamma V_\phi(s_{t+1}) - V_\phi(s_t),

Here rtr_t is the reward after the current decision, γ\gamma discounts the next state’s value, and VϕV_\phi estimates discounted return. Set the next-state value to zero at a true terminal transition. In the language-model setting, sts_t is the prompt and generated prefix. A PPO implementation can fit a separate critic or add a value head to a shared backbone.

A critic adds resource costs and changes how PPO estimates the advantage.

  1. Memory and compute. A separately trained critic adds parameter storage and forward and backward computation. Optimizers that keep per-parameter state add memory for that state. The overhead depends on the critic’s size and what it shares with the policy.
  2. Hyperparameter sensitivity. If PPO uses generalized advantage estimation (GAE), the choice of its coefficient λ\lambda changes how strongly the estimate relies on bootstrapped values. The way the critic is fit also affects the advantage estimates.
  3. Bootstrapping error. A wrong estimate at the next state can bias a bootstrapped advantage estimate. Subtracting an action-independent baseline from a complete sampled return does not introduce that bias.

With outcome supervision, GRPO scores each complete response and uses its group to estimate relative quality. The response still consists of successive token decisions, and DeepSeekMath also describes a process-supervised variant with intermediate rewards. The critic-free baseline is the design choice in both variants.

Baselines in policy gradient methods

In an on-policy score-function estimator, draw aa from πθ(⋅∣s)\pi_\theta(\cdot\mid s). Here ss is what the policy conditions on before sampling, such as the prompt and generated prefix. A baseline b(s)b(s) can depend on that history and must be independent of the action drawn at that decision, conditional on ss. When subtracting it from a sampled return, hold the baseline fixed in backpropagation, even if it was computed from a model that shares policy parameters. For a differentiable policy with locally fixed action support, this baseline contributes zero in expectation because

Ea∼πθ[∇θlog⁡πθ(a∣s) b(s)]=b(s)∑a∇θπθ(a∣s)=b(s) ∇θ1=0.\mathbb{E}_{a \sim \pi_\theta}\left[\nabla_\theta \log \pi_\theta(a \mid s) \, b(s)\right] = b(s) \sum_a \nabla_\theta \pi_\theta(a \mid s) = b(s) \, \nabla_\theta 1 = 0.

An action-independent baseline can reduce variance. The within-group mean includes the current sample. Suppose the group contains independent completions from the same policy for a fixed prompt. In an unclipped on-policy update without standard-deviation scaling, use the full completion score, the sum of its token log-probability gradients. A completion’s own reward enters the mean at weight 1/G1/G. The full score has mean zero, so the other completions’ rewards have zero expected product with it. The expected centered update is (G−1)/G(G-1)/G times the uncentered gradient. A common multiplier fixed before sampling preserves this result. When G>1G>1, a leave-one-out mean is independent of the held-out completion and cancels in expectation under the same score condition. Standard-deviation scaling, clipping, and division by realized response length when lengths vary can change the calculation.

The group mean provides a prompt-specific comparison without a value network. Its uncertainty depends on the sample count and reward distribution, and it uses rollouts that still have to be generated and scored.

The variance argument is not only theoretical. The next cells compare three gradient estimators on a one-state bandit with a known reward vector: no baseline at all, the exact value as an oracle baseline, and the group mean of eight sampled actions. All three estimators reuse the same groups drawn from the same stochastic softmax policy. The seed makes the experiment repeatable. It does not make the policy deterministic or off-policy. The fixed value baseline is action-independent. The inclusive group mean uses the sampled action’s reward; that dependence, rather than a different sampling policy, accounts for the shift in expectation.

PythonIn [3]
CollapseExpand
import numpy as np

# One-state bandit with four actions, known rewards, and a fixed policy.
rng = np.random.default_rng(
    0
)  # seed fixed so the reported spreads are reproducible
theta = np.array([0.0, 0.4, -0.3, 0.2])
policy_probs = np.exp(theta - theta.max())
policy_probs = policy_probs / policy_probs.sum()
action_rewards = np.array([0.0, 0.25, 0.75, 1.0])

group_size = 8  # same group size as the toy training loop below
n_replicates = 4000  # Monte Carlo replicates per estimator

actions = rng.choice(4, size=(n_replicates, group_size), p=policy_probs)
# Verify that this is a shared, non-degenerate behavior sample.
assert np.all((policy_probs > 0) & (policy_probs < 1))
counts = np.bincount(actions.ravel(), minlength=4)
assert np.all(counts > 0)
print("Behavior probabilities:", np.round(policy_probs, 4))
print("Sampled action counts:", counts)
sampled_rewards = action_rewards[actions]  # shape (replicates, group)
score = np.eye(4)[actions] - policy_probs  # grad log pi(a) per sample

value_baseline = float(policy_probs @ action_rewards)


def gradient_estimate(baseline):
    """Average of (reward - baseline) * grad log pi over the sampled group."""
    centered = sampled_rewards - baseline
    return (centered[..., None] * score).mean(axis=1)


est_none = gradient_estimate(0.0)
est_value = gradient_estimate(value_baseline)
est_group = gradient_estimate(sampled_rewards.mean(axis=1, keepdims=True))

score_actions = np.eye(4) - policy_probs
true_grad = ((policy_probs * action_rewards)[:, None] * score_actions).sum(
    axis=0
)


def total_std(est):
    """Square root of the summed per-component variance of the estimator."""
    return float(np.sqrt(np.sum(est.var(axis=0))))


estimator_names = ["No baseline", "Oracle value", "Group mean (G=8)"]
estimators = [est_none, est_value, est_group]
summary_std = np.array([total_std(est) for est in estimators])
summary_error = np.array(
    [float(np.abs(est.mean(axis=0) - true_grad).max()) for est in estimators]
)
bar_positions = np.arange(len(estimators))

for name, spread, error in zip(estimator_names, summary_std, summary_error):
    print(f"{name:18s} std={spread:.4f}  max|error|={error:.5f}")
ConsoleOut [3]
CollapseExpand
Behavior probabilities: [0.2245 0.3349 0.1663 0.2742]
Sampled action counts: [ 7101 10810  5323  8766]
No baseline        std=0.1773  max|error|=0.00057
Oracle value       std=0.0972  max|error|=0.00116
Group mean (G=8)   std=0.0971  max|error|=0.01745
VisualizationOut [4]
CollapseExpand
Bar chart of gradient estimator spread for no baseline, oracle value, and group mean.
Spread of three policy-gradient estimators on a one-state bandit, measured as the square root of the summed per-component variance over 4000 replicates of eight sampled actions, with seed 0. The two baseline estimators have similar spread in this experiment. Spread measures precision around each estimator’s own mean. The inclusive group-mean estimator’s expected gradient is 7/8 of the true gradient.

Because this bandit’s probabilities and rewards are known, the code computes the exact gradient. The largest absolute coordinate error of the Monte Carlo mean is about 0.0170.017 for the inclusive mean and about 0.0010.001 for the other two estimators. These finite-run errors include sampling noise. Spread measures how much repeated estimates vary around their own expectation. The oracle estimator is centered on the true gradient, while the inclusive mean shrinks the expected gradient by (G−1)/G(G-1)/G. Similar spread can therefore accompany different bias.

The GRPO Objective

Let qq be a prompt drawn from a distribution P(Q)P(Q), and let {o1,…,oG}\{o_1, \dots, o_G\} be GG responses sampled from the current behavior policy πθold(⋅∣q)\pi_{\theta_\text{old}}(\cdot \mid q). Let ri=R(q,oi)r_i = R(q, o_i) be the scalar reward for response ii. The GRPO objective from Shao et al. is

JGRPO(θ)=Eq,{oi}[1G∑i=1G1∣oi∣∑t=1∣oi∣(min⁡ ⁣(ρi,t(θ) A^i,  clip(ρi,t(θ), 1−ε, 1+ε) A^i)−β D^i,t)],\mathcal{J}_{\text{GRPO}}(\theta) = \mathbb{E}_{q, \{o_i\}}\left[ \frac{1}{G} \sum_{i=1}^{G} \frac{1}{|o_i|} \sum_{t=1}^{|o_i|} \left( \min\!\left( \rho_{i,t}(\theta)\,\hat{A}_i,\; \text{clip}\bigl(\rho_{i,t}(\theta),\, 1-\varepsilon,\, 1+\varepsilon\bigr)\,\hat{A}_i \right) - \beta \, \hat{D}_{i,t} \right) \right],

GG is the number of responses to the prompt. In response ii, ∣oi∣|o_i| is the token count, oi,to_{i,t} is token tt, and oi,<to_{i,<t} is its preceding prefix. The clip range is set by ε\varepsilon, and β\beta weights the reference KL penalty. The importance ratio and per-token KL contribution are

ρi,t(θ)=πθ(oi,t∣q,oi,<t)πθold(oi,t∣q,oi,<t),D^i,t=πref(oi,t∣q,oi,<t)πθ(oi,t∣q,oi,<t)−log⁡πref(oi,t∣q,oi,<t)πθ(oi,t∣q,oi,<t)−1,\rho_{i,t}(\theta) = \frac{\pi_\theta(o_{i,t} \mid q, o_{i,<t})}{\pi_{\theta_\text{old}}(o_{i,t} \mid q, o_{i,<t})}, \qquad \hat{D}_{i,t} = \frac{\pi_\text{ref}(o_{i,t} \mid q, o_{i,<t})}{\pi_\theta(o_{i,t} \mid q, o_{i,<t})} - \log \frac{\pi_\text{ref}(o_{i,t} \mid q, o_{i,<t})}{\pi_\theta(o_{i,t} \mid q, o_{i,<t})} - 1,

and the group-relative advantage uses only the rewards in this group:

A^i=ri−mean(r1,…,rG)std(r1,…,rG).\hat{A}_i = \frac{r_i - \text{mean}(r_1, \dots, r_G)}{\text{std}(r_1, \dots, r_G)}.

The formula reads from the inside out:

  • The per-token importance ratio ρi,t\rho_{i,t} measures how much more (or less) likely the current policy is to produce token tt of response ii than the behavior policy that generated it.
  • The clipped surrogate term turns that ratio and the response-level advantage into a per-token objective, exactly as in PPO.
  • The objective subtracts the weighted reference KL contribution from each token’s clipped surrogate. It averages those regularized terms over tokens within each response and then over responses in the group.

Each layer addresses a specific concern, and untangling them makes it easier to see what each later variant is changing.

In the outcome-supervised case, each token in response ii receives the same A^i\hat A_i. For each token the inner term compares the raw ratio times that advantage with the clipped ratio times that advantage. The two averages, 1/∣oi∣1/|o_i| and 1/G1/G, reduce tokens within each response and then responses within each group. Process supervision can assign different advantages to different tokens.

The Clipped Surrogate with Group Advantages

The clipped surrogate comes from PPO. Its minimum selects the smaller of the raw and clipped products. For a positive advantage, raising ρ\rho above 1+ε1+\varepsilon no longer increases this token’s surrogate contribution. For a negative advantage, lowering ρ\rho below 1−ε1-\varepsilon no longer improves it. The opposite branch in each case still varies. Shared parameters and other tokens can move a ratio outside the clip interval.

The next two cells evaluate the clipped surrogate on a grid of importance ratios, once for a positive advantage and once for a negative one, holding the clip range fixed.

PythonIn [5]
CollapseExpand
import numpy as np

clip_eps = 0.2
ratio_grid = np.linspace(0.0, 2.0, 401)


def clipped_surrogate(ratio, advantage, eps=clip_eps):
    """Pessimistic PPO/GRPO surrogate: min of the clipped and unclipped terms."""
    unclipped = ratio * advantage
    clipped = np.clip(ratio, 1.0 - eps, 1.0 + eps) * advantage
    return np.minimum(unclipped, clipped)


surr_positive = clipped_surrogate(ratio_grid, 1.0)
surr_negative = clipped_surrogate(ratio_grid, -1.0)
VisualizationOut [6]
CollapseExpand
The positive-advantage curve flattens above the upper boundary and the negative-advantage curve flattens below the lower boundary.
The clipped surrogate term as a function of the importance ratio for an advantage of +1 and an advantage of -1, with clip range 0.2. For a positive advantage the term is flat for ratios above the upper boundary. For a negative advantage it is flat for ratios below the lower boundary. Outside each flat region, the corresponding curve still varies with the ratio.

The shaded band is where both signs use the unclipped ratio. Beyond the upper boundary only the positive-advantage curve is flat. Below the lower boundary only the negative-advantage curve is flat. Clip-higher moves the upper boundary.

Both formulations use a clipped policy surrogate. In the outcome GRPO objective above, each response gets a group-standardized advantage instead of a token-level estimate from a learned critic. DeepSeekMath also subtracts the reference-policy KL penalty in this objective. The original PPO clipped surrogate does not prescribe that penalty.

Within-Prompt Relative Advantages

Outcome-supervised GRPO centers and scales rewards within each prompt group. Centered rewards sum to zero in exact arithmetic. Dividing by a shared positive denominator preserves that identity. With tied rewards the raw standard deviation is zero, so the unguarded standardized advantages are undefined. The toy adds a positive denominator guard and returns zero advantages for ties.

The same reward can earn different advantages depending on its companions. For example, a correct answer to either of two prompts receives reward one, but it earns more relative credit in a group where fewer other answers were correct. Grouping keeps scores from different prompts out of the same mean. Prompt difficulty can still affect the mix of outcomes, the reward dispersion, and the chance of drawing a group with no reward variation.

The next cells take an easy prompt and a hard prompt, four responses each, and compute advantages both within each group and across the pooled batch.

PythonIn [7]
CollapseExpand
import numpy as np

eps = 1e-4  # guards the division when a group has zero reward variance

easy_rewards = np.array([1.0, 1.0, 1.0, 0.0])  # prompt A: usually solved
hard_rewards = np.array([0.0, 0.0, 0.0, 1.0])  # prompt B: rarely solved


def within_prompt(r):
    return (r - r.mean()) / (r.std() + eps)


batch_rewards = np.concatenate([easy_rewards, hard_rewards])

adv_within = np.concatenate(
    [within_prompt(easy_rewards), within_prompt(hard_rewards)]
)
adv_batch = within_prompt(batch_rewards)

response_positions = np.arange(batch_rewards.size)
response_labels = [
    "easy 1",
    "easy 2",
    "easy 3",
    "easy 4",
    "hard 1",
    "hard 2",
    "hard 3",
    "hard 4",
]
bar_width = 0.38
VisualizationOut [8]
CollapseExpand
Grouped bars comparing within-prompt and batch-level advantages for eight responses.
Within-prompt versus batch-level normalization on the same eight responses, four from an easy prompt and four from a hard prompt. Within-prompt normalization gives the single correct hard response +1.73 and each correct easy response +0.58, so the rare success receives about three times the advantage of a correct answer in the easier group. Pooled normalization gives equal advantages to equal raw rewards, even when the groups have different outcomes.

The pooled standardization gives the same advantage to responses with the same raw reward, regardless of prompt. Within-prompt standardization gives the correct responses different advantages because their companions differ. The groups still contain different mixes of correct and incorrect responses.

For binary rewards, write qq for the fraction of successes in a sampled group. For 0<q<10<q<1, the population standard deviation is q(1−q)\sqrt{q(1-q)}. With the unguarded equation, a success receives (1−q)/q\sqrt{(1-q)/q} and a failure receives −q/(1−q)-\sqrt{q/(1-q)}. If all scores agree, the raw formula gives 0/00/0. The guarded implementation below gives zero reward advantages instead. With independent draws of success probability pp, ties occur with probability pG+(1−p)Gp^G+(1-p)^G. Such groups can still contribute to a separate KL term.

The KL Penalty

The reference policy πref\pi_\text{ref} provides a distribution to compare against. DeepSeekMath’s iterative GRPO algorithm sets the reference to the current policy at the start of each outer iteration. Inside that iteration, it snapshots the behavior policy before each new rollout batch. A positive KL coefficient penalizes distributional divergence. It does not assess reward quality or rule out a high-reward shortcut.

The per-token penalty uses the nonnegative k3k_3 form below. Its expectation is the forward KL divergence when the token is sampled from the current policy and the two distributions have the same support. In an update on stored rollouts from a different behavior policy, that equality need not hold unless the sampling difference is accounted for. The equality concerns the expected penalty value. In the toy, backpropagation holds the sampled tokens fixed and differentiates their k3k_3 terms. Even when the behavior policy matches the learner on the first pass, this derivative can differ from the gradient of exact forward KL.

D^i,t=r−log⁡r−1,r=πref(oi,t∣q,oi,<t)πθ(oi,t∣q,oi,<t).\hat{D}_{i,t} = r - \log r - 1, \qquad r = \frac{\pi_\text{ref}(o_{i,t} \mid q, o_{i,<t})}{\pi_\theta(o_{i,t} \mid q, o_{i,<t})}.

The inequality log⁡r≤r−1\log r \le r-1 gives D^i,t≥0\hat D_{i,t}\ge0, with equality when the two probabilities for the sampled token agree. Under current-policy sampling, the expectation of the reference-to-current ratio is one, so both k3k_3 and the log-ratio −log⁡r-\log r estimate the same forward KL. Their variances need not coincide.

The next cells plot both estimators as a function of the probability ratio.

PythonIn [9]
CollapseExpand
import numpy as np

kl_ratio = np.exp(np.linspace(-1.5, 1.5, 401))  # r = pi_ref / pi_theta
kl_k3 = kl_ratio - np.log(kl_ratio) - 1.0  # k3 estimator
kl_log_ratio = -np.log(kl_ratio)  # naive log(pi_theta / pi_ref)

# Enumerate a two-token example under the current policy.
current = np.array([0.8, 0.2])
reference = np.array([0.5, 0.5])
ref_to_current = reference / current
exact_kl = np.sum(current * np.log(current / reference))
k1_mean = np.sum(current * -np.log(ref_to_current))
k3_mean = np.sum(current * (ref_to_current - np.log(ref_to_current) - 1))
assert np.allclose([k1_mean, k3_mean], exact_kl)
print(f"Expected k1 = {k1_mean:.6f}; expected k3 = {k3_mean:.6f}")
ConsoleOut [9]
CollapseExpand
Expected k1 = 0.192745; expected k3 = 0.192745
VisualizationOut [10]
CollapseExpand
The k3 curve is nonnegative and reaches zero at ratio one. The log-ratio curve is negative above one.
Two per-token KL estimators as functions of the reference-to-policy probability ratio r. The k3 estimator r - log r - 1 is non-negative everywhere and touches zero only at r = 1. The naive log-ratio estimator crosses zero at r = 1 and is negative for r > 1, although its expectation under the current policy remains the nonnegative forward KL.

The curves depict individual contributions, not their sampling distribution. A negative log-ratio contribution for a token with r>1r>1 does not imply a negative expected KL.

DeepSeek-R1 specifies a KL term in its GRPO objective. DAPO removes the term in its recipe. Omitting this term removes the need for reference scores in the loss and removes that penalty on policy drift.

Per-Token and Per-Sequence Normalization

The original objective first takes a token mean inside each response with 1/∣oi∣1/|o_i|. It then takes a mean over the GG response means. Each response has the same total averaging weight within that prompt group, while tokens from different-length responses have different coefficients. The outer expectation averages across prompts and sampled groups.

Liu et al. identify response-length weighting as one source of optimization bias. At a fixed advantage and likelihood ratio, dividing by a longer response length shrinks each token’s coefficient. Their alternative uses a fixed generation-budget divisor. Equalizing that coefficient does not guarantee equal gradients or determine the total effect on a response.

The bias is about the magnitude of the weight each token receives, not the total weight of a response. The next cells compute that per-token weight for a short and a long response that carry the same advantage magnitude.

PythonIn [11]
CollapseExpand
import numpy as np

advantage_magnitude = 1.0  # same |A| for both responses, so only length differs
short_len, long_len = 4, 16
generation_limit = (
    16  # fixed for this illustration, independent of observed lengths
)

per_sequence = np.array(
    [advantage_magnitude / short_len, advantage_magnitude / long_len]
)
fixed_divisor = np.array(
    [
        advantage_magnitude / generation_limit,
        advantage_magnitude / generation_limit,
    ]
)

response_names = ["Short (4 tokens)", "Long (16 tokens)"]
weight_positions = np.arange(2)
bar_width = 0.36
VisualizationOut [12]
CollapseExpand
Grouped bars of per-token weight for short and long responses under two normalizations.
Magnitude of the weight applied to each token for two responses with the same advantage magnitude and lengths 4 and 16. Under per-sequence normalization the token weight is A divided by the response length, so a token in the short response receives four times the weight of a token in the long response. Under a constant divisor every token receives the same weight, regardless of which response it belongs to.

The unequal amber bars show the length-dependent coefficient at the same reference advantage magnitude. The blue bars match because both token sums use the same divisor. This arithmetic illustration does not predict the gradients of the individual token probabilities.

Standard-deviation scaling changes the relative multiplier between groups. Holding a centered reward fixed, dividing by a smaller positive standard deviation increases the magnitude of its coefficient. With binary rewards, groups near one extreme have lower dispersion than groups split evenly. An exact tie is a separate case because its centered rewards are all zero. Actual gradients also depend on sampled tokens and clipping. Liu et al. remove the standard-deviation scaling and retain mean centering.

Zero-Variance Groups

The unguarded formula is undefined when every reward in a group is the same. In a binary example this means all responses are correct or all are incorrect. There are several ways to handle the group:

  1. Add a small epsilon to the denominator, A^i=(ri−rˉ)/(σr+ϵ)\hat{A}_i = (r_i - \bar{r})/(\sigma_r + \epsilon). In exact arithmetic, the numerator is zero at a tie, so the advantage and its contribution to the reward-surrogate gradient are both zero. The epsilon keeps the denominator positive. In floating point, even the mean of identical stored rewards can round away from their common value, so the toy checks for exact ties before reducing the group.
  2. Explicitly set A^i=0\hat{A}_i=0 below a chosen dispersion threshold. A positive threshold may discard low-dispersion groups that still contain distinct rewards.
  3. DAPO’s eligibility rule uses binary correctness. All-correct and all-incorrect groups are tied under the unshaped binary reward. DAPO excludes those groups even when length shaping makes their rewards differ.

Guarding the normalization avoids an undefined value but does not recover a reward-surrogate signal from tied rewards. Filtering also incurs sampling work, including for the excluded groups. The amount of additional work to fill a batch depends on the mix of eligible groups.

Tied rewards give no within-group signal

When a group receives identical rewards, the guarded reward advantages are zero. DAPO draws additional groups to fill the batch with groups of mixed correctness. Refilling requires a positive chance of sampling an eligible group, and rejected groups still cost sampling work. A reference KL term can still contribute a gradient in recipes that keep it. Even if the total current gradient is zero, a stateful optimizer can move parameters using previously accumulated momentum.

A Worked Example by Hand

Before writing code, work through a small group by hand. Suppose a prompt receives five sampled responses with rewards [1,0,1,1,0][1, 0, 1, 1, 0]. The group mean is 0.60.6 and the population standard deviation is 0.24≈0.49\sqrt{0.24} \approx 0.49. The normalization gives:

A^1=(1−0.6)/0.49≈+0.82,A^2=(0−0.6)/0.49≈−1.22,A^3=+0.82,A^4=+0.82,A^5=−1.22.\begin{aligned} \hat{A}_1 &= (1 - 0.6)/0.49 \approx +0.82, \\ \hat{A}_2 &= (0 - 0.6)/0.49 \approx -1.22, \\ \hat{A}_3 &= +0.82, \\ \hat{A}_4 &= +0.82, \\ \hat{A}_5 &= -1.22. \end{aligned}

The unrounded advantages sum to zero. The displayed values sum to 3(0.82)+2(−1.22)=0.023(0.82)+2(-1.22)=0.02 because of rounding. There are fewer incorrect answers in this group, so each has a larger absolute advantage than each correct one. A zero sum of advantage coefficients does not imply a zero update.

Return to the opening group with seven rewards of 1 and one reward of 0. Its mean is 7/87/8 and its population standard deviation is 7/8\sqrt{7}/8. Each correct completion gives its tokens advantage 1/7≈0.381/\sqrt{7}\approx 0.38. The incorrect completion gives its tokens advantage −7≈−2.65-\sqrt{7}\approx -2.65. At the start of an update with the learner equal to the behavior policy, every ratio is one. The clipped surrogate for each token then equals that token’s advantage before the KL term and the two averaging steps apply.

A useful mental model

The group mean plays a role similar to the reference point in grading on a curve. In the five-response group, the correct answers sit 0.4 above it and the incorrect answers sit 0.6 below it before scaling. If all answers receive the same score, every score equals the group mean and the guarded advantages are zero.

PythonIn [13]
CollapseExpand
import torch

rewards_example = torch.tensor([1.0, 0.0, 1.0, 1.0, 0.0])
mean_r = rewards_example.mean()
std_r = rewards_example.std(unbiased=False)
adv_example = (rewards_example - mean_r) / (std_r + 1e-4)

print(f"rewards:     {rewards_example.tolist()}")
print(f"group mean:  {mean_r.item():.4f}")
print(f"group std:   {std_r.item():.4f}")
print(f"advantages:  {[round(x, 4) for x in adv_example.tolist()]}")
print(f"adv mean:    {adv_example.mean().item():.6f}")
ConsoleOut [13]
CollapseExpand
rewards:     [1.0, 0.0, 1.0, 1.0, 0.0]
group mean:  0.6000
group std:   0.4899
advantages:  [0.8163, -1.2245, 0.8163, 0.8163, -1.2245]
adv mean:    -0.000000

The computed advantages match the hand calculation. The mean of the advantages is approximately zero, which is what the within-prompt normalization is designed to enforce. Note that the epsilon in the denominator has essentially no effect here, because the standard deviation is well above it; the epsilon exists for the case where the standard deviation collapses to zero.

The figure below visualizes the mapping from rewards to advantages for this group.

VisualizationOut [14]
CollapseExpand
Bar chart of GRPO group advantages for five responses; three positive bars and two negative bars, all summing to zero.
Within-group GRPO advantages for a group of five responses with rewards [1, 0, 1, 1, 0]. The three correct responses receive equal positive advantage of about +0.82, the two incorrect responses receive larger-magnitude negative advantage of about -1.22, and the advantages sum to zero within the group. The asymmetry arises because the group mean of 0.6 sits closer to 1 than to 0.

Two properties are worth noting. First, the correct responses are visually shorter than the incorrect ones: +0.82+0.82 versus −1.22-1.22. That asymmetry follows directly from the mean being 0.60.6, closer to 1 than to 0. Second, subtracting one shared mean makes the advantages sum to zero in exact arithmetic. Dividing by one shared positive number, including the standard deviation plus epsilon, preserves that arithmetic identity. The inclusive group mean still depends on each action, and the weighted token gradient can be nonzero.

If all five rewards were one, the group mean would be one and the standard deviation would be zero. The unguarded equation would be undefined. With the positive epsilon used in the example, every advantage is zero and this group contributes no reward-surrogate gradient.

Implementing GRPO on a Toy Policy

The objective is small enough to implement directly, but it requires an autoregressive policy, a sampling routine, a scoring routine, and a training loop. We build each piece in turn, using a deliberately tiny model so that everything runs on CPU. The implementation makes the mechanics inspectable: you can print every intermediate tensor, rerun with different seeds, and watch the effect of each design choice on the same toy problem.

The Toy Task

The toy task is chosen to expose the mechanisms that matter for understanding GRPO, without pretending to replicate real LLM training. The setup is:

  • Vocabulary of five tokens, {0,1,2,3,4}\{0, 1, 2, 3, 4\}.
  • Fixed prompt (implicit in the parameterization).
  • Target response [1,2,3,4][1, 2, 3, 4] of length four.
  • Reward is the fraction of positions that match the target.
  • Group size G=8G = 8.
  • Reference policy is a frozen copy of the initial policy.

The reward takes one of five values from 0 through 1 because it grades each position separately. The graded reward can distinguish two completions that would both fail exact-match scoring. Under uniform independent token draws, exact match occurs with probability 1/6251/625 per response, so a group of eight has about a 1.27% chance of containing at least one exact match. That calculation is an illustration, not a measurement of the randomly initialized network.

The toy illustrates the original outcome-supervised GRPO objective with a tiny policy and fixed-length responses. It samples groups, standardizes their rewards, and uses the tokenwise clipped surrogate and a reference penalty. Tied reward groups become common during training in this run.

The Tiny Policy

The policy conditions on the position in the sequence and the previously generated token, and outputs a categorical distribution over the next token. This is enough to produce autoregressive behavior without needing a transformer. Position embeddings rather than a recurrent hidden state keep the focus on the learning signal rather than the architecture.

PythonIn [15]
CollapseExpand
import torch
import torch.nn as nn
import torch.nn.functional as F


class TinyPolicy(nn.Module):
    """Autoregressive policy over a tiny vocabulary.

    Given the position index and the previous token, outputs logits over the
    next token. The model is deliberately minimal so the GRPO mechanics
    dominate the training signal.
    """

    def __init__(self, vocab_size=5, max_len=4, hidden=32):
        super().__init__()
        self.vocab_size = vocab_size
        self.pos_emb = nn.Embedding(max_len, hidden)
        self.tok_emb = nn.Embedding(vocab_size + 1, hidden)  # +1 for BOS
        self.net = nn.Sequential(
            nn.Linear(2 * hidden, hidden),
            nn.Tanh(),
            nn.Linear(hidden, vocab_size),
        )

    def forward(self, prev_tokens, positions):
        h = torch.cat(
            [self.pos_emb(positions), self.tok_emb(prev_tokens)], dim=-1
        )
        return self.net(h)  # (B, vocab_size)

The embedding table for previous tokens has size vocab_size+1\text{vocab\_size} + 1 so that index 55 can be used as a begin-of-sequence token. Concatenating a position embedding and a token embedding is enough to distinguish, for example, "the first token is 3" from "the third token is 3," which matters because the model should be allowed to make different predictions at different positions. The hidden dimension of 32 is arbitrary; any small value works.

Sampling and Scoring

Sampling records the detached log-probability under the behavior policy for each sampled token. Scoring reuses those tokens and prefixes with gradients enabled under the learner policy. Subtract the behavior log-probability from the learner log-probability and exponentiate to obtain ρi,t\rho_{i,t}, the ratio of probabilities. The learner and behavior policies initially have the same weights and temperature. Rescoring after an update can change the ratio even though the original records are fixed.

PythonIn [16]
CollapseExpand
sampling_temperature = 1.15


@torch.no_grad()
def sample_group(policy, group_size, seq_len, bos_id):
    """Sample `group_size` fixed-length responses and record their log-probs."""
    B = group_size
    prev = torch.full((B,), bos_id, dtype=torch.long)
    tokens = torch.zeros(B, seq_len, dtype=torch.long)
    log_probs = torch.zeros(B, seq_len)
    for t in range(seq_len):
        positions = torch.full((B,), t, dtype=torch.long)
        logits = policy(prev, positions)
        probs = F.softmax(logits / sampling_temperature, dim=-1)
        sampled = torch.multinomial(probs, 1).squeeze(-1)
        log_probs[:, t] = torch.log(
            probs.gather(1, sampled.unsqueeze(-1))
        ).squeeze(-1)
        tokens[:, t] = sampled
        prev = sampled
    return tokens, log_probs


def score_sequence(policy, tokens, bos_id):
    """Recompute per-token log-probs for a fixed token sequence (with grad)."""
    B, T = tokens.shape
    prev = torch.full((B,), bos_id, dtype=torch.long)
    log_probs = torch.zeros(B, T)
    for t in range(T):
        positions = torch.full((B,), t, dtype=torch.long)
        logits = policy(prev, positions)
        log_probs[:, t] = (
            torch.log_softmax(logits / sampling_temperature, dim=-1)
            .gather(1, tokens[:, t : t + 1])
            .squeeze(-1)
        )
        prev = tokens[:, t]
    return log_probs

The two routines mirror each other token by token. Sampling uses torch.multinomial to draw a token and records log⁡πθold(ot∣⋅)\log \pi_{\theta_\text{old}}(o_t \mid \cdot); scoring uses the same forward pass but looks up log⁡πθ(ot∣⋅)\log \pi_\theta(o_t \mid \cdot) for a given token, building an autograd graph along the way. The @torch.no_grad() decorator on sample_group prevents backpropagation through the trajectory that generated the data; gradients flow only through the likelihood reassessment under the current policy.

The Reward and the Advantage

The reward function computes the fraction of matching tokens. The advantage function implements within-prompt normalization. Keeping the functions separate lets us change the advantage calculation in this toy while holding its reward fixed. Other recipes can change both. For example, DAPO also adjusts rewards for some long responses.

PythonIn [17]
CollapseExpand
def compute_rewards(tokens, target):
    """Fraction of positions matching the target token sequence."""
    matches = (tokens == target).float()
    return matches.mean(dim=-1)


def group_advantages(rewards, eps=1e-4, use_std=True):
    """Center a nonempty group of finite rewards, with optional scaling."""
    if (rewards == rewards[0]).all():
        return torch.zeros_like(rewards)
    centered = rewards - rewards.mean()
    if use_std:
        std = rewards.std(unbiased=False)
        return centered / (std + eps)
    return centered

The use_std=True branch follows DeepSeekMath’s group standardization with two explicit implementation choices. It uses the population standard deviation and adds positive eps to the denominator. The published equation does not include the epsilon. Both branches return zeros if all stored rewards are equal, including a group of one response. Distinct rewards still use the usual centering and, when enabled, scaling. Setting use_std=False gives mean-only advantages. Dr. GRPO separately changes response-length weighting. For a nonconstant group of size G>1G>1, the sample standard deviation exceeds the population standard deviation by the factor G/(G−1)\sqrt{G/(G-1)}.

The GRPO Loss

The code minimizes the negative clipped reward surrogate plus the coefficient-weighted k3k_3 penalty. This is the negative of the maximization objective above, where the penalty is subtracted.

PythonIn [18]
CollapseExpand
def grpo_loss(
    log_probs,
    old_log_probs,
    advantages,
    ref_log_probs=None,
    mask=None,
    clip_eps=0.2,
    kl_beta=0.01,
):
    """Compute the minimized loss for a nonempty group of responses."""
    if log_probs.numel() == 0:
        raise ValueError(
            "The response group and its token dimension must be nonempty."
        )
    lengths = log_probs.size(1)
    if mask is not None:
        # Replace padded values before subtraction: -inf - -inf would be NaN.
        mask = mask.to(dtype=torch.bool)
        lengths = mask.sum(dim=-1)
        if (lengths == 0).any():
            raise ValueError(
                "Each response must have at least one valid token."
            )
        log_probs = log_probs.masked_fill(~mask, 0.0)
        old_log_probs = old_log_probs.masked_fill(~mask, 0.0)
    log_ratio = log_probs - old_log_probs
    ratio = torch.exp(log_ratio)
    adv = advantages.unsqueeze(-1)

    surr1 = ratio * adv
    surr2 = torch.clamp(ratio, 1.0 - clip_eps, 1.0 + clip_eps) * adv
    per_token = -torch.min(surr1, surr2)

    if kl_beta != 0:
        if ref_log_probs is None:
            raise ValueError(
                "A nonzero KL coefficient requires reference log-probabilities."
            )
        if mask is not None:
            ref_log_probs = ref_log_probs.masked_fill(~mask, 0.0)
        log_ratio_ref = ref_log_probs - log_probs
        kl = torch.exp(log_ratio_ref) - log_ratio_ref - 1.0
        per_token = per_token + kl_beta * kl
    if mask is not None:
        per_token = per_token.masked_fill(~mask, 0.0)
    per_seq = per_token.sum(dim=-1) / lengths
    return per_seq.mean()

log_ratio is the current-minus-behavior log-probability, while ratio is ρi,t\rho_{i,t}. The vector adv broadcasts each response’s advantage to its token positions. surr1 is the unclipped operand and surr2 is the clipped operand. With a nonzero KL coefficient, log_ratio_ref is the reference-minus-current log-probability used in kl. At zero coefficient the helper skips reference arithmetic and accepts missing reference log-probabilities. If a mask is supplied, padding is replaced before ratio arithmetic and excluded from the numerator and token count. Every row represents a real response with at least one valid token. The helper rejects an all-padding row so it cannot dilute the average over responses. The toy uses four valid tokens in every row.

At ρi,t=1\rho_{i,t}=1 with clipping inactive, the negative reward term contributes a derivative proportional to −A^i∇θlog⁡πθ(oi,t∣q,oi,<t)-\hat A_i\nabla_\theta\log\pi_\theta(o_{i,t}\mid q,o_{i,<t}), with the same averaging as the loss. Its value can average to zero even when this derivative does not, because the token score gradients differ. The reference penalty contributes its own derivative when enabled; it vanishes if reference and current token probabilities coincide on the sampled prefixes.

Running the Training Loop

Each outer-loop iteration samples a new group from the learner’s current weights and records that group’s behavior log-probabilities. It immediately rescores the group with the same weights and temperature, so the likelihood ratios start at one, up to floating-point rounding, in every iteration. After the first optimizer step on that group, the second rescoring still uses the original behavior log-probabilities in the denominator. Those ratios can move away from one. The next outer iteration starts over with freshly recorded behavior probabilities. The evaluation also draws fresh responses from the updated policy on the same prompt.

PythonIn [19]
CollapseExpand
torch.manual_seed(0)

policy = TinyPolicy()
ref_policy = TinyPolicy()
ref_policy.load_state_dict(policy.state_dict())
for p in ref_policy.parameters():
    p.requires_grad = False

optimizer = torch.optim.Adam(policy.parameters(), lr=1e-2)

target = torch.tensor([1, 2, 3, 4])
group_size = 8
seq_len = 4
bos_id = 5
n_steps = 800
inner_epochs = 2

history = {
    k: [] for k in ["step", "mean_reward", "group_std", "zero_var_frac", "loss"]
}
reward_snapshots = {}
reward_groups = []

eval_steps, eval_mean_rewards, eval_success = [], [], []

for step in range(n_steps):
    tokens, old_log_probs = sample_group(policy, group_size, seq_len, bos_id)
    rewards = compute_rewards(tokens, target)
    adv = group_advantages(rewards, use_std=True)

    with torch.no_grad():
        ref_log_probs = score_sequence(ref_policy, tokens, bos_id)

    group_std = rewards.std(unbiased=False).item()
    zero_var = group_std < 1e-6

    loss_val = 0.0
    for _ in range(inner_epochs):
        log_probs = score_sequence(policy, tokens, bos_id)
        loss = grpo_loss(
            log_probs,
            old_log_probs,
            adv,
            ref_log_probs,
            clip_eps=0.2,
            kl_beta=0.01,
        )
        optimizer.zero_grad()
        loss.backward()
        optimizer.step()
        loss_val = loss.item()

    reward_groups.append(rewards.detach().clone())
    history["step"].append(step)
    history["mean_reward"].append(rewards.mean().item())
    history["group_std"].append(group_std)
    history["zero_var_frac"].append(float(zero_var))
    history["loss"].append(loss_val)

    if step in {0, n_steps // 2, n_steps - 1}:
        reward_snapshots[step] = rewards.detach().clone()

    if step % 50 == 0 or step == n_steps - 1:
        eval_tokens, _ = sample_group(policy, 100, seq_len, bos_id)
        eval_r = compute_rewards(eval_tokens, target)
        eval_steps.append(step)
        eval_mean_rewards.append(eval_r.mean().item())
        eval_success.append((eval_r == 1.0).float().mean().item())
ConsoleOut [20]
CollapseExpand
Mean reward, first 50 steps:   0.926
Mean reward, final 50 steps:   0.998
Mean group std, final 50 steps: 0.005
Fraction of zero-variance groups: 0.900
Final exact-match rate on fresh draws:   1.000

The printed averages compare the first and last 50 rollout groups, and the exact-match rate comes from a fresh sample under the final policy. All draws use the same prompt, so this run checks training behavior without measuring generalization to new tasks.

What the Curves Show

The first figure plots the mean reward on the training batch against the fresh-sample evaluation.

VisualizationOut [21]
CollapseExpand
Line chart comparing rollout and fresh-sample mean reward during training.
GRPO on the toy task. The line labeled Training batch shows the mean reward in each group of eight training responses. The line labeled Fresh draws (n=100) shows the mean reward for 100 responses sampled after updates. The first evaluation follows both optimizer steps on the first group.

Under a fixed policy and independent draws, averaging 100 rewards gives a more precise estimate than averaging eight. The two curves also use different policies. The evaluation at step zero follows both optimizer steps on the first group. It does not measure the untrained policy. A distribution drawing all five tokens uniformly would earn mean reward 0.2.

The second figure shows what happens to the group standard deviation over time.

VisualizationOut [22]
CollapseExpand
Line chart of group reward standard deviation over training, declining toward zero.
Within-group reward standard deviation during training. Group reward spread is often nonzero early in training and usually zero late in this seeded run.

Most late groups in this run have zero reward dispersion. They supply no reward-surrogate gradient, but the reference KL term or the optimizer’s prior state can still affect the parameter update. The line shows the actual groups, including occasional nonzero values late in training.

The histograms display advantages computed from the rewards actually recorded during training. At each checkpoint the code pools up to 40 preceding groups, including the checkpoint’s group. The first checkpoint has only one group.

PythonIn [23]
CollapseExpand
# Pool recorded groups from each window ending at the selected checkpoint.
steps_sorted = sorted(reward_snapshots)
advantage_snapshot_by_step = {}
for step_key in steps_sorted:
    start_step = max(0, step_key - 39)
    groups = reward_groups[start_step : step_key + 1]
    advantage_snapshot_by_step[step_key] = np.concatenate(
        [group_advantages(group).numpy() for group in groups]
    )
VisualizationOut [24]
CollapseExpand
Histograms of recorded group advantages in three training windows.
Advantages from measured reward groups in windows ending at the indicated steps. The first window has one group. The later windows each have 40 groups. The center bin spans roughly -0.23 to +0.23. It includes exact zeros and small nonzero advantages. All first-window values in that bin are nonzero.

The first group gives advantages ranging from about −1.12-1.12 to +1.44+1.44. In this toy run the quarter-step rewards and groups of eight give a computed standard deviation of zero at exact ties. A single response can have zero advantage in a mixed group when its reward equals the group mean. Most groups in the final window receive tied rewards and contribute only zero advantages. A few still differ and provide a reward-surrogate signal. The histogram measures behavior on a specific toy prompt and seed. It cannot establish optimizer convergence or generalization.

Sampling and Rollout Costs

There are three costs to track separately: response generation, reward scoring, and learner updates. Which one dominates depends on response length, batching, verifier latency, and how often a rollout is reused.

A batch of BB prompts with GG completions per prompt requires BGB G sequences. In ordinary autoregressive decoding, each next-token distribution depends on the generated prefix. Batching can execute multiple completions together. During teacher-forced scoring the model already has the complete sequence, so token positions can be processed together under causal masking.

Storing a constant number of per-token rollout fields for BB groups of GG responses, each of length at most TT, requires O(BGT)\mathcal{O}(BGT) storage. That is a bound for the rollout fields, separate from parameters, optimizer states, activations, and generation caches.

DeepSeekMath §4.2 reports sampling 64 outputs per question in its DeepSeekMath-RL training configuration. Group size determines the number of responses to generate and compare. With independent binary scores and a success probability strictly between zero and one, a larger group is less likely to tie. If success is certain or impossible, every group ties regardless of size.

The number of optimizer steps per rollout controls reuse. Reuse amortizes sampling but means the learner can differ from the behavior policy. DeepSeekMath reports one update per exploration stage in its main experiments. The toy uses two updates per group to illustrate the distinction.

Later Variants and What Changed

Variants change different parts of the objective. When comparing their results, track which estimator, reduction, and sampling rule each reported experiment actually used.

DeepSeek-R1

DeepSeek-R1-Zero uses rule-based accuracy and format rewards and starts RL from a base model without a preliminary supervised fine-tuning step. The later DeepSeek-R1 recipe includes additional stages. Equation (1) in the published paper keeps the reference KL penalty and uses the whole-output likelihood ratio πθ(oi∣q)/πθold(oi∣q)\pi_\theta(o_i\mid q)/\pi_{\theta_\text{old}}(o_i\mid q). It averages one objective term per response with the group factor 1/G1/G. The ratio uses the raw likelihood of the complete response. GSPO takes a geometric mean before clipping.

DAPO

DAPO combines four techniques. Two alter the policy objective, and the others change which groups enter training and how lengths are rewarded:

  • Clip-higher. DAPO widens the upper side of the clipping interval. With εlow=0.2\varepsilon_{\mathrm{low}}=0.2 and εhigh=0.28\varepsilon_{\mathrm{high}}=0.28, the lower boundary stays at 0.80.8 and the upper boundary moves from 1.21.2 to 1.281.28. A positive-advantage token can keep increasing the clipped objective over that additional range. The authors introduce this change to address entropy collapse in their setup.
  • Dynamic sampling. Keep groups with both correct and incorrect answers. Draw more groups until the batch fills, provided eligible groups can be sampled. The method can draw groups from other prompts. Eligibility uses correctness even if length shaping changes the rewards.
  • Token-level policy gradient loss. In the published formula, divide the summed completion-token terms by the number of completion tokens across the responses to that prompt. Each token in that pool has the same averaging coefficient. A single token mean across a whole update would generally weight prompts differently. Dr. GRPO uses a fixed generation-budget divisor instead.
  • Overlong reward shaping. The paper applies a length-dependent penalty over a buffer near the generation limit.

Dr. GRPO

Dr. GRPO is the name Liu et al. (2025) give their modified objective. Their analysis identifies two sources of weighting in the original objective.

  • Length weighting. At equal advantage and likelihood ratio, 1/∣oi∣1/|o_i| gives each token of a longer response a smaller coefficient. Liu et al. analyze this weighting and measure length effects in their experiments.
  • Difficulty weighting. At a fixed centered reward, a smaller positive group standard deviation gives a larger multiplier. For binary rewards, groups split evenly have larger dispersion than groups with almost all successes or failures. An exact tie needs a separate guard.

The authors replace group standard-deviation scaling with mean-only centering. They use a fixed generation-length divisor in place of the length of the individual response.

GSPO

GSPO (Qwen, 2025) combines the per-token likelihood ratios ρi,t\rho_{i,t} into a single ratio for response oio_i:

si(θ)=(πθ(oi∣q)πθold(oi∣q))1/∣oi∣=exp⁡ ⁣(1∣oi∣∑t=1∣oi∣log⁡ρi,t(θ)).s_i(\theta) = \left(\frac{\pi_\theta(o_i \mid q)}{\pi_{\theta_\text{old}}(o_i \mid q)}\right)^{1/|o_i|} = \exp\!\left(\frac{1}{|o_i|}\sum_{t=1}^{|o_i|}\log\rho_{i,t}(\theta)\right).

The exponent makes sis_i the geometric mean of the learner-to-behavior ratios for the ∣oi∣|o_i| tokens. GSPO applies the clipped surrogate once per response, using sis_i and the group-standardized advantage. The objective averages those response-level terms with 1/G1/G. The length term acts inside the ratio before clipping. Differentiating log⁡si\log s_i gives the mean of the token log-probability gradients. The authors report greater stability in their experiments with this sequence-based formulation.

Comparison

Advantage, likelihood ratio, objective averaging, and the rules for tied rewards or sampling eligibility in published GRPO recipes.
Published objectiveAdvantageRatioReduction within a prompt groupTies or sampling eligibility
DeepSeekMath GRPO (2024)(ri−rˉ)/σr(r_i - \bar{r})/\sigma_rToken-level ρi,t\rho_{i,t}Token mean per response, then mean over responsesEquation leaves zero variance undefined
DeepSeek-R1 (2025), Eq. (1)Group-standardized outcomeWhole-output likelihood ratioMean of response-level termsEq. (3) leaves zero variance undefined
DAPO (2025)Group-standardized outcomeToken-level with clip-higherMean over all completion-token terms in the groupFilter by mixed binary correctness
Dr. GRPO (2025)ri−rˉr_i - \bar{r}Token-levelToken sum divided by the fixed budget per response, then mean over responsesMean centering yields zero
GSPO (2025)Within-group standardized rewardSequence geometric-mean ratioMean of response-level termsEq. (6) leaves zero variance undefined

The table compares the displayed objectives. The surrounding training recipe can also change which prompts enter a batch or how rewards are computed. For example, DAPO combines mixed-correctness sampling with a penalty for responses near the length limit.

Limitations & Impact

The toy starts from a randomly initialized 2,565-parameter policy with a vocabulary of five tokens. It generates fixed-length responses and scores each by the fraction of tokens matching the target. The reference is a frozen copy of the initial policy. DeepSeekMath-RL starts from the instruction-tuned DeepSeekMath-Instruct checkpoint, and the iterative algorithm refreshes its reference at the start of each outer iteration.

Holding the token terms fixed, per-response averaging and a token mean give identical results when every response has the same length LL. A fixed budget divisor Lmax⁡L_{\max} instead scales those same averages by L/Lmax⁡L/L_{\max}. That scale is shared across responses. It equals one only if L=Lmax⁡L=L_{\max}. The toy’s fixed lengths hide the relative reweighting that a response-length divisor can introduce when lengths differ. This comparison isolates the length divisor. Dr. GRPO also changes the advantage scaling.

The toy lets you inspect within-prompt normalization, clipping, and the increasing frequency of tied reward groups in this run. Results on its single artificial prompt tell us little about reasoning behavior on real tasks.

GRPO removes the need to train a critic in these formulations. Actor training, rollouts, and reward scoring still have costs, and a reference model can add scoring work if the objective uses it. The overall resource comparison depends on how those components are implemented.

Grouped rewards, response lengths, and sampling affect the update. A verifier can still reward a shortcut, and a group in which every response earns the same reward reveals nothing about their relative quality. Inspect the actual completions when the reward is meant to stand in for a broader objective.

Summary

  • GRPO uses rewards from completions of the same prompt to replace the learned critic used in common actor-critic PPO implementations.
  • In the original outcome-supervised objective, A^i=(ri−rˉ)/σr\hat{A}_i = (r_i - \bar{r})/\sigma_r for a prompt group with positive reward dispersion. Each token of response ii receives that same advantage.
  • GRPO borrows the clipped surrogate from PPO, uses relative rewards in place of a learned critic, and can penalize divergence from a reference policy.
  • The toy sets the advantages to zero when all rewards tie. The reward-surrogate gradient is then zero, although a reference penalty or existing optimizer state can still affect the update. DAPO fills batches with groups of mixed correctness when eligible groups can be sampled.
  • Dr. GRPO drops reward standard-deviation scaling and divides each response’s token sum by a fixed budget. DAPO pools the token terms across the responses to one prompt before taking their mean.
  • Related recipes can change advantage scaling, clipping, token weighting, sampling, or the granularity of the likelihood ratio. The DeepSeek-R1 paper shows a whole-output ratio, while GSPO clips a length-normalized sequence ratio.
  • The toy implementation in this chapter reproduces the mechanics (sampling, within-group advantages, clipped loss, KL to a reference, saturation into zero-variance groups) at a scale where you can inspect every piece. It does not reproduce the scale, the tokenizer, the variable-length responses, or the emergent reasoning behavior of real models, and it cannot show the length bias that Dr. GRPO identifies because its responses have fixed length.
  • When comparing variants, keep track of the reward source, grouping, weighting, clipping, and rollout budget.

Quiz

Ready to test your understanding? Take this quick quiz to reinforce what you've learned about Group Relative Policy Optimization.

Group Relative Policy Optimization

Question 1 of 80 of 8 completed
In the original outcome-supervised GRPO objective, how is each response's advantage computed?
Join the discussionAsk a question or share what you learned.

Comments

Add to the conversation

A question, a correction, or an example from your own work.

No comments yet. Be the first to share your thoughts!

A different angle
All writing
Language AI Handbook · Vol. 13

Search, Reflection, and Test-Time Compute

Learn how sampling, verifiers, and adaptive stopping convert inference compute into accuracy, and why selection limits what more draws can deliver.

36 min read
Language AI Handbook · Vol. 13

Outcome and Process Reward Models

Compare outcome and process reward models: labeling schemes, verifiers versus learned graders, step-score aggregation, reranking, and reward hacking.

38 min read
Language AI Handbook · Vol. 13

Faithful, Hidden, and Latent Reasoning

Separate visible explanations from the computation that produces answers. Learn how perturbation tests and causal examples measure faithfulness.

38 min read

About the author

Reference

Citation details

Cite or share this article.

BIBTEXAcademic
@misc{brenndoerfer2026groupbased, author = {Michael Brenndoerfer}, title = {Group-Based Policy Optimization}, year = {2026}, url = {https://mbrenndoerfer.com/writing/group-based-policy-optimization-grpo-critic-free}, organization = {mbrenndoerfer.com}, note = {Accessed: 2026-12-03} }
APAAcademic
Michael Brenndoerfer (2026). Group-Based Policy Optimization. Retrieved from https://mbrenndoerfer.com/writing/group-based-policy-optimization-grpo-critic-free
MLAAcademic
Michael Brenndoerfer. "Group-Based Policy Optimization." 2026. Web. December 3, 2026. <https://mbrenndoerfer.com/writing/group-based-policy-optimization-grpo-critic-free>.
CHICAGOAcademic
Michael Brenndoerfer. "Group-Based Policy Optimization." Accessed December 3, 2026. https://mbrenndoerfer.com/writing/group-based-policy-optimization-grpo-critic-free.
HARVARDAcademic
Michael Brenndoerfer (2026) 'Group-Based Policy Optimization'. Available at: https://mbrenndoerfer.com/writing/group-based-policy-optimization-grpo-critic-free (Accessed: December 3, 2026).
SimpleBasic
Michael Brenndoerfer (2026). Group-Based Policy Optimization. https://mbrenndoerfer.com/writing/group-based-policy-optimization-grpo-critic-free
Newsletter

Stay up to date

Get new articles, book updates, and notes on AI and technology.

Unsubscribe at any time. Privacy policy