Group-Based Policy Optimization
Learn how GRPO trains language models without a learned critic, using group-relative rewards, clipped surrogates, and tied-reward handling.
Language AI HandbookAll chapters 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:
Here is the reward after the current decision, discounts the next state’s value, and estimates discounted return. Set the next-state value to zero at a true terminal transition. In the language-model setting, 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.
- 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.
- Hyperparameter sensitivity. If PPO uses generalized advantage estimation (GAE), the choice of its coefficient changes how strongly the estimate relies on bootstrapped values. The way the critic is fit also affects the advantage estimates.
- 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.
In an on-policy score-function estimator, draw from . Here is what the policy conditions on before sampling, such as the prompt and generated prefix. A baseline can depend on that history and must be independent of the action drawn at that decision, conditional on . 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
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 . The full score has mean zero, so the other completions’ rewards have zero expected product with it. The expected centered update is times the uncentered gradient. A common multiplier fixed before sampling preserves this result. When , 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]Expand
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]Expand
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]Expand

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 for the inclusive mean and about 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 . Similar spread can therefore accompany different bias.
The GRPO Objective
Let be a prompt drawn from a distribution , and let be responses sampled from the current behavior policy . Let be the scalar reward for response . The GRPO objective from Shao et al. is
is the number of responses to the prompt. In response , is the token count, is token , and is its preceding prefix. The clip range is set by , and weights the reference KL penalty. The importance ratio and per-token KL contribution are
and the group-relative advantage uses only the rewards in this group:
The formula reads from the inside out:
- The per-token importance ratio measures how much more (or less) likely the current policy is to produce token of response 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 receives the same . For each token the inner term compares the raw ratio times that advantage with the clipped ratio times that advantage. The two averages, and , 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 above no longer increases this token’s surrogate contribution. For a negative advantage, lowering below 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]Expand
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]Expand

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]Expand
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.38VisualizationOut [8]Expand

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 for the fraction of successes in a sampled group. For , the population standard deviation is . With the unguarded equation, a success receives and a failure receives . If all scores agree, the raw formula gives . The guarded implementation below gives zero reward advantages instead. With independent draws of success probability , ties occur with probability . Such groups can still contribute to a separate KL term.
The KL Penalty
The reference policy 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 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 terms. Even when the behavior policy matches the learner on the first pass, this derivative can differ from the gradient of exact forward KL.
The inequality gives , 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 and the log-ratio 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]Expand
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]Expand
Expected k1 = 0.192745; expected k3 = 0.192745
VisualizationOut [10]Expand

The curves depict individual contributions, not their sampling distribution. A negative log-ratio contribution for a token with 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 . It then takes a mean over the 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]Expand
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.36VisualizationOut [12]Expand

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:
- Add a small epsilon to the denominator, . 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.
- Explicitly set below a chosen dispersion threshold. A positive threshold may discard low-dispersion groups that still contain distinct rewards.
- 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.
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 . The group mean is and the population standard deviation is . The normalization gives:
The unrounded advantages sum to zero. The displayed values sum to 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 and its population standard deviation is . Each correct completion gives its tokens advantage . The incorrect completion gives its tokens advantage . 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.
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]Expand
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]Expand
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]Expand

Two properties are worth noting. First, the correct responses are visually shorter than the incorrect ones: versus . That asymmetry follows directly from the mean being , 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, .
- Fixed prompt (implicit in the parameterization).
- Target response of length four.
- Reward is the fraction of positions that match the target.
- Group size .
- 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 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]Expand
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 so that index 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 , 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]Expand
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_probsThe two routines mirror each other token by token. Sampling uses torch.multinomial to draw a token and records ; scoring uses the same forward pass but looks up 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]Expand
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 centeredThe 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 , the sample standard deviation exceeds the population standard deviation by the factor .
The GRPO Loss
The code minimizes the negative clipped reward surrogate plus the coefficient-weighted penalty. This is the negative of the maximization objective above, where the penalty is subtracted.
PythonIn [18]Expand
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 . 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 with clipping inactive, the negative reward term contributes a derivative proportional to , 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]Expand
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]Expand
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]Expand

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]Expand

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]Expand
# 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]Expand

The first group gives advantages ranging from about to . 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 prompts with completions per prompt requires 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 groups of responses, each of length at most , requires 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 . It averages one objective term per response with the group factor . 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 and , the lower boundary stays at and the upper boundary moves from to . 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, 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 into a single ratio for response :
The exponent makes the geometric mean of the learner-to-behavior ratios for the tokens. GSPO applies the clipped surrogate once per response, using and the group-standardized advantage. The objective averages those response-level terms with . The length term acts inside the ratio before clipping. Differentiating gives the mean of the token log-probability gradients. The authors report greater stability in their experiments with this sequence-based formulation.
Comparison
| Published objective | Advantage | Ratio | Reduction within a prompt group | Ties or sampling eligibility |
|---|---|---|---|---|
| DeepSeekMath GRPO (2024) | Token-level | Token mean per response, then mean over responses | Equation leaves zero variance undefined | |
| DeepSeek-R1 (2025), Eq. (1) | Group-standardized outcome | Whole-output likelihood ratio | Mean of response-level terms | Eq. (3) leaves zero variance undefined |
| DAPO (2025) | Group-standardized outcome | Token-level with clip-higher | Mean over all completion-token terms in the group | Filter by mixed binary correctness |
| Dr. GRPO (2025) | Token-level | Token sum divided by the fixed budget per response, then mean over responses | Mean centering yields zero | |
| GSPO (2025) | Within-group standardized reward | Sequence geometric-mean ratio | Mean of response-level terms | Eq. (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 . A fixed budget divisor instead scales those same averages by . That scale is shared across responses. It equals one only if . 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, for a prompt group with positive reward dispersion. Each token of response 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
Join the discussionAsk a question or share what you learned.
Keep exploring
Reference
Citation details
Cite or share this article.


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!