Group-Based Policy Optimization › The GRPO Objective

Michael BrenndoerferNovember 29, 202614 min read
Language AI HandbookAll chapters
Part 40 of 67Reasoning Post-Training and Verifiable Rewards
Chapter 301Group-Based Policy Optimization › The GRPO Objective
Reading section 3 of 10 · The GRPO Objective · 14 minSection 3 of 10 · 14 min

Section 3 of 10 · 14 min read

Reading settings

Definitions

Choose how many terms have tooltips.

Article links

Make inline references clickable

Notes & comments

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.

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!

Newsletter

Stay up to date

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

Unsubscribe at any time. Privacy policy