Group-Based Policy Optimization › The GRPO Objective
Language AI HandbookAll chapters 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.
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!