GRPO: Group Relative Policy Optimization

GRPO is a variant of Proximal Policy Optimization (PPO) introduced in the DeepSeekMath paper, and TRL supports a GRPO Trainer for training language models.

Verified

On this page

Definition

TRL supports the GRPO Trainer for training language models, as described in the DeepSeekMath paper. The abstract of that paper introduces Group Relative Policy Optimization (GRPO) as a variant of Proximal Policy Optimization (PPO) and says it enhances mathematical reasoning abilities while concurrently optimizing the memory usage of PPO. GRPO is an online learning algorithm, meaning it improves iteratively by using the data generated by the trained model itself during training.

The intuition behind the GRPO objective is to maximize the advantage of the generated completions while ensuring that the model remains close to the reference policy. GRPO also supports agent training: the model calls tools during generation and learns from the outcome.

At a glance

The documentation breaks GRPO down into four main steps: generating completions, computing the advantage, estimating the KL divergence, and computing the loss.

Diagram: Generating completions: at each training step, a batch of prompts is sampled and a set of G completions is generated for each prompt. > Computing the advantage: for the G completions of each prompt, a reward model or reward function calculates rewards, then the advantage reflects relative comparisons between outputs for the same question. > Estimating the KL divergence: KL divergence is estimated using the approximator introduced by Schulman et al. (2020). > Computing the loss: the first term represents the scaled advantage and the second term penalizes deviations from the reference policy through KL divergence. TRL uses a beta of 0.0 by default, though, meaning the KL divergence term is not used.1Generating completions: at each training step,a batch of prompts is sampled and a set of Gcompletions is generated for each prompt.2Computing the advantage: for the G completionsof each prompt, a reward model or rewardfunction calculates rewards, then theadvantage reflects relative comparisonsbetween outputs for the same question.3Estimating the KL divergence: KL divergence isestimated using the approximator introduced bySchulman et al. (2020).4Computing the loss: the first term representsthe scaled advantage and the second termpenalizes deviations from the reference policythrough KL divergence. TRL uses a beta of 0.0 bydefault, though, meaning the KL divergence term is not used.

How it works

Reward models are typically trained on datasets of comparisons between outputs for the same question, so the advantage is calculated to reflect those relative comparisons. In the documented advantage normalization, the group mean reward is subtracted from each reward and the result is divided by the reward standard deviation; this group-relative calculation gives GRPO its name. TRL uses a beta of 0.0 by default, meaning the KL divergence term is not used.

To include the KL divergence term, set beta in GRPOConfig to a non-zero value. In the original paper, the formulation is generalized to account for multiple updates after each generation, denoted μ and set with num_iterations in GRPOConfig, by leveraging the clipped surrogate objective. When μ equals 1, the default in TRL, the clipped surrogate objective simplifies to the original objective.

Scaling the advantage by the standard deviation can be disabled by setting scale_rewards to False in GRPOConfig. Turning off std-based scaling also removes variance normalization, so update magnitudes depend directly on the raw reward scale and batch composition. The DAPO paper highlights the limitations of the GRPO sample-level loss in long-CoT scenarios, where longer responses are under-penalized, leading to poorer quality outputs.

To use the DAPO formulation, set loss_type to dapo in GRPOConfig. The paper Understanding R1-Zero-Like Training demonstrated that the initial GRPO formulation introduces a response length bias. That paper also shows that the DAPO formulation reduces this bias but does not eliminate it completely.

To fully remove the bias, the paper proposes dividing by a constant instead of the sequence length. That constant is recommended to be the maximum completion length. To use this Dr. GRPO formulation, set loss_type to dr_grpo in GRPOConfig.

In the SAPO paper, the Qwen team proposes replacing the hard clipping mechanism of GRPO with a smooth, temperature-controlled soft gating mechanism. GRPO zeroes out gradients when the policy deviates too far from the reference, while SAPO uses a soft trust region that smoothly decays the gradient weight. In GRPOConfig, the dapo loss type is the default and aggregates token-level losses by normalizing with the number of active tokens in the global accumulated batch.

The documentation states that generation is often the main bottleneck when training with online methods.

Example

The quick start demonstrates how to train a model with GRPO. That example trains a Qwen2.5 0.5B Instruct model with the prompts from the DeepMath-103K dataset. In the quick start, accuracy_reward needs math-verify.

Distributed across 8 GPUs, the quick start takes approximately 1 day, according to the documentation. The GRPOTrainer supports custom reward functions instead of dense reward models. A custom reward function returns a reward list: applicable completions receive floats, while a sample without a relevant reward function can return None and the trainer continues with valid functions and tasks.

Each float in the list is the reward for a single completion. For standard format, prompts and completions will be lists of strings. Example 3 in the documentation is a reward function that checks if the completion is correct.

This example is designed for standard format, where the dataset contains a column named ground_truth. When several reward functions are passed, the reward is computed as the sum of the rewards from each function, or the weighted sum if reward_weights is provided in the config.

From the official source
python
# train_grpo.py
from datasets import load_dataset
from trl import GRPOTrainer
from trl.rewards import accuracy_reward

dataset = load_dataset("trl-lib/DeepMath-103K", split="train")

trainer = GRPOTrainer(
    model="Qwen/Qwen2.5-0.5B-Instruct",
    reward_funcs=accuracy_reward,
    train_dataset=dataset,
)
trainer.train()
From the official source
Shell
accelerate launch train_grpo.py
From the official source
python
import re

def reward_func(completions, ground_truth, **kwargs):
    # Regular expression to capture content inside \boxed{}
    matches = [re.search(r"\\boxed\{(.*?)\}", completion) for completion in completions]
    contents = [match.group(1) if match else "" for match in matches]
    # Reward 1 if the content is the same as the ground truth, 0 otherwise
    return [1.0 if c == gt else 0.0 for c, gt in zip(contents, ground_truth)]
From the official source
python
>>> prompts = ["Problem: Solve the equation $2x + 3 = 7$. Solution:", "Problem: Solve the equation $3x - 5 = 10$."]
>>> completions = [r" The solution is \boxed{2}.", r" The solution is \boxed{6}."]
>>> ground_truth = ["2", "5"]
>>> reward_func(prompts=prompts, completions=completions, ground_truth=ground_truth)
[1.0, 0.0]

Sources

This page is written from the official sources below. Open them to check the original text.

Verified ·

This page is written by AI from the official sources above and checked automatically. This site has not tested it. Found a mistake? Tell us.