AI Knowledge Tree

Group relative policy optimization (GRPO)

Replace the value baseline in PPO with a group-relative reward; show how this simplifies the training loop and scales to DeepSeek-R1-style reasoning.

⏱ 28 minPrerequisites:RLHF with PPO

PPO requires a trained value model (the critic) to compute advantages. Training two models simultaneously -- the policy and the value network -- is expensive and adds complexity. Group Relative Policy Optimization (GRPO, Shao et al., 2024) eliminates the value model by estimating baselines from a group of responses sampled from the current policy[1].

The core idea

Instead of training a neural value model Vψ(st)V_\psi(s_t) to estimate expected return, GRPO samples GG responses {y1,…,yG}\{y_1, \dots, y_G\} from the policy for the same prompt xx and uses the group mean reward as the baseline:

Ai=ri−1G∑j=1Grj,A_i = r_i - \frac{1}{G} \sum_{j=1}^{G} r_j,

where ri=rϕ(x,yi)r_i = r_\phi(x, y_i) is the reward for response ii. The advantage AiA_i measures how much better response ii is compared to the average response from the current policy -- a form of self-normalized reward.

This is essentially REINFORCE with leave-one-out baseline, adapted to the LLM setting.

What "group-relative" buys you. The same reward yields a different advantage depending on the company it keeps, because the baseline is the group mean. Take a verifiable reward r∈{0,1}r \in \{0, 1\} and G=8G = 8 responses, and look at a single correct response (ri=1r_i = 1):

  • Easy prompt, 7 of 8 responses correct. Group mean =0.875= 0.875, so the correct response gets advantage Ai=1−0.875=0.125A_i = 1 - 0.875 = 0.125. Getting it right was expected; the gradient barely pushes.
  • Hard prompt, 1 of 8 responses correct. Group mean =0.125= 0.125, so the same correct response gets Ai=1−0.125=0.875A_i = 1 - 0.125 = 0.875. Solving what the policy usually fails is the signal worth chasing, and the advantage is 7×7\times larger.

So the curriculum is automatic: per-prompt, the baseline subtracts off whatever the policy can already do, leaving the gradient to concentrate on the prompts at the edge of its ability. The degenerate case makes the same point from the other side: if all 8 responses agree (all correct or all wrong), the mean equals every reward and every Ai=0A_i = 0, so a group that gives no information gives no update.

The GRPO objective

For each group of GG responses, the objective mirrors PPO's clipped surrogate[2]:

LGRPO=−1G∑i=1Gmin⁡ ⁣(ρiA^i, clip(ρi,1−ϵ,1+ϵ)A^i)+β KL(πθ∥πref),\mathcal{L}_{\text{GRPO}} = -\frac{1}{G} \sum_{i=1}^{G} \min\!\left(\rho_i \hat{A}_i,\ \text{clip}(\rho_i, 1-\epsilon, 1+\epsilon) \hat{A}_i\right) + \beta\, \mathrm{KL}(\pi_\theta \| \pi_{\text{ref}}),

where ρi=πθ(yi∣x)/πθold(yi∣x)\rho_i = \pi_\theta(y_i|x) / \pi_{\theta_{\text{old}}}(y_i|x) and A^i=(Ai−μA)/σA\hat{A}_i = (A_i - \mu_A) / \sigma_A is the normalized advantage.

The KL penalty (against the SFT reference model) prevents reward hacking.

Normalizing advantages

GRPO normalizes advantages within the group:

A^i=Ai−mean({Aj}j=1G)std({Aj}j=1G)+ϵ.\hat{A}_i = \frac{A_i - \text{mean}(\{A_j\}_{j=1}^G)}{\text{std}(\{A_j\}_{j=1}^G) + \epsilon}.

This normalization:

  • Makes the objective invariant to the reward scale (no need to carefully tune reward magnitude).
  • Stabilizes gradient magnitudes throughout training.

Verifiable reward functions

GRPO is particularly powerful when the reward function is verifiable -- when you can check the correctness of an answer without human annotation:

  • Mathematics: did the model reach the correct numerical answer?
  • Code: does the generated function pass unit tests?
  • Formal verification: does the proof check?

With a verifiable reward r∈{0,1}r \in \{0, 1\}, there is no need for a reward model at all. The policy is trained directly with binary correctness signals.

GRPO implementation sketch

import torch

def grpo_step(policy, ref_model, reward_fn, prompts, G=8, beta=0.04, eps=0.2):
    """
    prompts: (B,) list of prompt strings
    G: group size (samples per prompt)
    """
    all_responses, all_rewards, all_log_pi_old = [], [], []

    with torch.no_grad():
        for prompt in prompts:
            responses   = [policy.generate(prompt, do_sample=True) for _ in range(G)]
            rewards     = [reward_fn(prompt, r) for r in responses]
            log_pi_olds = [policy.log_probs(prompt, r) for r in responses]
            all_responses.append(responses)
            all_rewards.append(rewards)
            all_log_pi_old.append(log_pi_olds)

    total_loss = 0.0
    for i, (prompt, responses, rewards, log_pi_olds) in enumerate(
            zip(prompts, all_responses, all_rewards, all_log_pi_old)):
        r_tensor = torch.tensor(rewards, dtype=torch.float)
        # Group-relative advantage
        A = (r_tensor - r_tensor.mean()) / (r_tensor.std() + 1e-8)

        for j, (response, adv, log_pi_old) in enumerate(zip(responses, A, log_pi_olds)):
            log_pi  = policy.log_probs(prompt, response)
            log_ref = ref_model.log_probs(prompt, response)

            ratio = torch.exp(log_pi - log_pi_old)
            clip  = ratio.clamp(1 - eps, 1 + eps)
            ppo_loss = -torch.min(ratio * adv, clip * adv).mean()
            kl_loss  = beta * (log_pi - log_ref).mean()
            total_loss += ppo_loss + kl_loss

    return total_loss / (len(prompts) * G)

GRPO and DeepSeek-R1

GRPO is the training algorithm behind DeepSeek-R1 (DeepSeek, 2025), which uses pure RL (no SFT warm-up) with GRPO and a verifiable math reward to train a model that generates long reasoning chains before answering.

Key findings from DeepSeek-R1:

  • With only binary correctness rewards (no process reward), the model spontaneously develops self-reflection, backtracking, and extended chain-of-thought.
  • The emergent reasoning behavior appears without explicit supervision of the reasoning steps.
  • A "cold start" with a small amount of SFT on curated reasoning chains before GRPO prevents reward hacking and improves final performance.

Comparison: PPO vs DPO vs GRPO

PropertyPPODPOGRPO
Requires reward modelYesNoSometimes
Requires value modelYesNoNo
Requires reference modelYesYesYes
Online (policy rollouts)YesNoYes
Works with verifiable rewardsYesNoYes
Computational costHighestLowestMedium

Exercises

Exercise 1. A group of G=4G = 4 responses to one prompt earns verifiable rewards r=(1,0,1,0)r = (1, 0, 1, 0). Compute the group-mean baseline, the raw advantages Ai=ri−rˉA_i = r_i - \bar r, and the normalized advantages A^i=(Ai−mean(A))/std(A)\hat A_i = (A_i - \text{mean}(A)) / \text{std}(A) (population std). State which responses get a positive gradient.

Solution

Step 1. The group mean is rˉ=(1+0+1+0)/4=0.5\bar r = (1 + 0 + 1 + 0)/4 = 0.5.

Step 2. Raw advantages Ai=ri−0.5A_i = r_i - 0.5: A=(0.5,−0.5,0.5,−0.5)A = (0.5, -0.5, 0.5, -0.5).

Step 3. mean(A)=0\text{mean}(A) = 0 (subtracting the mean already centers the advantages). The population variance is 14(0.52+0.52+0.52+0.52)=0.25\frac{1}{4}(0.5^2 + 0.5^2 + 0.5^2 + 0.5^2) = 0.25, so std(A)=0.5\text{std}(A) = 0.5.

Step 4. Normalized: A^i=Ai/0.5=(1,−1,1,−1)\hat A_i = A_i / 0.5 = (1, -1, 1, -1). The two correct responses get A^=+1\hat A = +1 (positive gradient, made more likely); the two wrong ones get A^=−1\hat A = -1 (made less likely).

Exercise 2. Take a verifiable reward r∈{0,1}r \in \{0, 1\} and a group of GG responses of which kk are correct. Show that a single correct response gets raw advantage A=1−k/GA = 1 - k/G and a single wrong response gets A=−k/GA = -k/G. Use this to explain why a group where all responses agree (k=0k = 0 or k=Gk = G) produces no update.

Solution

Step 1. The group mean reward is rˉ=k/G\bar r = k/G (the fraction correct).

Step 2. A correct response has ri=1r_i = 1, so A=1−k/GA = 1 - k/G. A wrong response has ri=0r_i = 0, so A=0−k/G=−k/GA = 0 - k/G = -k/G.

Step 3. If k=Gk = G (all correct), rˉ=1\bar r = 1, every ri=1r_i = 1, so every A=0A = 0. If k=0k = 0 (all wrong), rˉ=0\bar r = 0, every A=0A = 0. In both cases all advantages vanish, the normalization is undefined or zero, and the policy gets no gradient: a group whose responses all agree carries no relative signal.

Exercise 3 (code). Implement the group-relative advantage (raw and normalized) in numpy. Verify the Exercise 1 numbers, and confirm that a unanimous group (rr all equal) yields all-zero raw advantages.

Solution
python · numpy
import numpy as np

def group_advantages(rewards):
    r = np.asarray(rewards, float)
    raw = r - r.mean()                          # leave-one-out style baseline
    std = raw.std()                             # population std
    norm = (raw - raw.mean()) / (std + 1e-8)
    return raw, norm

# Exercise 1: rewards (1, 0, 1, 0).
raw, norm = group_advantages([1, 0, 1, 0])
assert np.allclose(raw, [0.5, -0.5, 0.5, -0.5])
assert np.allclose(norm, [1.0, -1.0, 1.0, -1.0])

# Unanimous group -> all-zero raw advantages, no update.
raw_all_correct, _ = group_advantages([1, 1, 1, 1])
assert np.allclose(raw_all_correct, 0.0)
raw_all_wrong, _ = group_advantages([0, 0, 0, 0])
assert np.allclose(raw_all_wrong, 0.0)
print("raw:", raw, "norm:", norm)

The raw advantages are ±0.5\pm 0.5 and normalize to ±1\pm 1, while a unanimous group gives all-zero advantages, matching the automatic-curriculum argument: only groups with mixed outcomes move the policy.

GRPO occupies a useful middle ground: simpler than PPO (no value model), but online (generates new rollouts) and compatible with verifiable rewards -- making it the method of choice for reasoning-oriented RL.


References

  1. [1]Shao, Z., et al. (2024). "DeepSeekMath: pushing the limits of mathematical reasoning in open language models (GRPO)". arXiv:2402.03300. Introduces the group-relative baseline that replaces the value model.↩
  2. [2]Schulman, J., Wolski, F., Dhariwal, P., Radford, A., & Klimov, O. (2017). "Proximal policy optimization algorithms (PPO)". arXiv:1707.06347. The clipped surrogate objective GRPO reuses with a group-mean baseline.↩