GRPO 深度解析:DeepSeek 的高效对齐算法与数学推理革命

4764 字
24 分钟
GRPO 深度解析:DeepSeek 的高效对齐算法与数学推理革命

1. 引言:DeepSeek-R1 如何颠覆 LLM 对齐范式#

1.1 一个令学术界震惊的结果#

2025 年 1 月,DeepSeek 团队发布了 DeepSeek-R1-Zero 和 DeepSeek-R1,在数学推理、代码生成和常识推理任务上与 OpenAI o1 持平——没有任何人类标注的思维链数据

这背后的核心算法创新是 GRPO(Group Relative Policy Optimization)

传统 RLHF 路线(InstructGPT → GPT-4):
偏好数据 ──→ 训练 Reward Model ──→ PPO ──→ 对齐模型
需要单独的 Value Network
(与 Policy 同尺寸,显存翻倍)
DeepSeek 路线(GRPO):
偏好数据 ──→ RM ──→ GRPO ──→ 推理能力突破
不需要 Value Network
用组内相对排名替代

1.2 GRPO 的核心思想#

GRPO 的设计哲学:用尽可能少的结构实现尽可能强的对齐效果

三条核心原则:

  1. 去掉 Critic:用组内相对排名替代 Value 网络
  2. 保留 KL 约束:与参考策略的 KL 散度作为正则
  3. 在线探索:每个 prompt 采样多个回答,用组内比较驱动学习
Tip

GRPO 不是 PPO 的简化版,而是一种不同的优势估计范式。PPO 需要 Value 网络来估计 baseline,GRPO 用”同组回答的平均水平”作为隐式 baseline。


2. 从 PPO 到 GRPO:Critic 的必要性分析#

2.1 PPO 的 Critic 做什么?#

在 PPO 中,Value 网络(Critic)的核心作用是估计 baseline,以降低策略梯度的方差:

At=GtVϕ(st)A_t = G_t - V_\phi(s_t)

Vϕ(st)V_\phi(s_t) 是从状态 sts_t 开始的期望累计奖励的估计。

问题:对于 LLM 对齐,这个 Critic 真的必要吗?

2.2 为什么 LLM 不需要传统 Critic?#

三个关键观察

观察 1:序列决策特性

LLM 的”决策”是一次性生成整个回答,而非逐步决策:

πθ(yx)=t=1yπθ(ytx,y<t)\pi_\theta(y|x) = \prod_{t=1}^{|y|}\pi_\theta(y_t|x, y_{<t})

回答的 reward 是序列级别的(RM 给出单个分数),不存在中间状态的 value 估计需求。

观察 2:终态奖励

在 LLM 对齐中,RM 只在序列末尾给出一个分数:

rt={R(x,y)t=T0t<Tr_t = \begin{cases} R(x, y) & t = T \\ 0 & t < T \end{cases}

这意味着每个 token 的”未来奖励”都相同——不需要复杂的 TD 估计。

观察 3:组内天然有 baseline

如果我们采样 GG 个回答 {y1,,yG}\{y_1, \ldots, y_G\},这 GG 个回答的平均 RM 分数就是一个天然的 baseline!

A^i=R(x,yi)1Gj=1GR(x,yj)\hat{A}_i = R(x, y_i) - \frac{1}{G}\sum_{j=1}^{G}R(x, y_j)

这就是 GRPO 的核心洞察。

2.3 为什么之前没人这样做?#

在传统 RL 中,同一条轨迹无法同时充当数据和基线——因为你需要 baseline 来区分”这个动作好”还是”这个状态好”。

但 LLM 对齐的特殊性在于:RM 分数是即时给出的,不需要”估计”未来奖励——我们可以直接比较同一 prompt 的多个回答。


3. GRPO 数学原理#

3.1 问题设定#

给定一个 prompt xx 和一个参考策略 πref\pi_{\text{ref}}(通常是 SFT 后的模型),GRPO 从 πθ\pi_\theta 采样 GG 个回答:

{y1,y2,,yG}πθ(x)\{y_1, y_2, \ldots, y_G\} \sim \pi_\theta(\cdot|x)

用 Reward Model 评分:

{r1,r2,,rG}={R(x,y1),R(x,y2),,R(x,yG)}\{r_1, r_2, \ldots, r_G\} = \{R(x, y_1), R(x, y_2), \ldots, R(x, y_G)\}

3.2 组内归一化优势估计#

GRPO 的优势函数:

Ai=riμσA_i = \frac{r_i - \mu}{\sigma}

其中:

  • μ=1Gj=1Grj\mu = \frac{1}{G}\sum_{j=1}^{G}r_j 是组内平均分数(隐式 baseline)
  • σ=1Gj=1G(rjμ)2\sigma = \sqrt{\frac{1}{G}\sum_{j=1}^{G}(r_j - \mu)^2} 是组内标准差(归一化因子)
def compute_grpo_advantages(rewards: torch.Tensor, G: int) -> torch.Tensor:
"""
GRPO 组内归一化优势。
rewards: (num_prompts * G,) 展平的所有回答的 RM 分数
返回: (num_prompts * G,) 每个回答的相对优势
"""
num_prompts = rewards.size(0) // G
rewards = rewards.view(num_prompts, G) # (P, G)
# 组内均值
mean_r = rewards.mean(dim=-1, keepdim=True) # (P, 1)
# 组内标准差
std_r = rewards.std(dim=-1, keepdim=True) + 1e-8 # (P, 1)
# 归一化优势
advantages = (rewards - mean_r) / std_r # (P, G)
return advantages.flatten()

3.3 为什么用标准差归一化?#

直觉:标准差衡量了”组内回答之间的差异程度”。

  • 如果 GG 个回答的 RM 分数都差不多(std 很小),说明 prompt 很简单,任何回答都差不多好 → 优势都很小(避免无意义的更新)
  • 如果 GG 个回答的 RM 分数差异很大(std 很大),说明 prompt 很难,最好的和最差的差距明显 → 优势被放大(信号更强)

3.4 GRPO 目标函数#

LGRPO(θ)=Ex[1Gi=1G[min(ri(θ)Ai, clip(ri(θ),1ϵ,1+ϵ)Ai)]βKL(πθπref)]\mathcal{L}_{\text{GRPO}}(\theta) = -\mathbb{E}_x\Big[\frac{1}{G}\sum_{i=1}^{G}\Big[\min\big(r_i(\theta)\,A_i,\ \text{clip}(r_i(\theta), 1-\epsilon, 1+\epsilon)\,A_i\big)\Big] - \beta\,\text{KL}\big(\pi_\theta\,\|\,\pi_{\text{ref}}\big)\Big]

其中:

  • ri(θ)=πθ(yix)πθold(yix)r_i(\theta) = \frac{\pi_\theta(y_i|x)}{\pi_{\theta_{\text{old}}}(y_i|x)} 是重要性比率
  • AiA_i 是组内归一化优势
  • β\beta 是 KL 系数
  • ϵ\epsilon 是 clip 范围(通常 0.2)

3.5 与 PPO 的对比#

维度PPOGRPO
优势估计At=GtVϕ(st)A_t = G_t - V_\phi(s_t)Ai=(riμ)/σA_i = (r_i - \mu)/\sigma
Baseline 来源Value 网络预测同组回答的平均值
需要 Critic
需要 GAE✅(可选)
方差控制通过 Value 网络通过组内归一化
对 reward 方差敏感通过 std 归一化自动适应

3.6 理论分析:GRPO 的方差#

假设对于某个 prompt xxGG 个回答的 RM 分数为 r1,,rGr_1, \ldots, r_G

策略梯度的方差与优势函数的方差成正比:

Var(1Gi=1Gri(θ)Ai)\text{Var}\Big(\frac{1}{G}\sum_{i=1}^{G} r_i(\theta)\,A_i\Big)

在 PPO 中,At=GtVϕ(st)A_t = G_t - V_\phi(s_t) 的方差由 Value 网络的估计误差决定。

在 GRPO 中,Ai=(riμ)/σA_i = (r_i - \mu)/\sigma 的方差有界:

Var(Ai)1(因为是 z-score)\text{Var}(A_i) \leq 1 \quad \text{(因为是 z-score)}

这意味着 GRPO 的梯度方差被自然地控制在 [0,1][0, 1] 范围内,不需要额外的方差控制机制。


4. GRPO 完整实现#

4.1 整体训练流程#

def grpo_train_step(
policy_model, # π_θ,待优化
ref_model, # π_ref,冻结
reward_model, # R(x, y),冻结
prompts: list[str], # prompt 列表
tokenizer,
G: int = 8, # 每个 prompt 采样的回答数
beta: float = 0.04, # KL 系数
clip_ratio: float = 0.2,
lr: float = 1e-6,
):
"""
GRPO 单步训练。
"""
# === 1. 采样 G 个回答 ===
all_responses, all_policy_logps, all_ref_logps, all_rewards = \
grpo_rollout(policy_model, ref_model, reward_model, prompts, tokenizer, G)
# === 2. 计算组内归一化优势 ===
advantages = compute_grpo_advantages(all_rewards, G) # (P*G,)
# === 3. 计算 GRPO 损失 ===
policy_logps_flat = all_policy_logps.flatten()
ref_logps_flat = all_ref_logps.flatten()
# PPO-style clipped surrogate(per-sequence level)
# 展平后,每个 sequence 一个 loss
grpo_loss = compute_grpo_loss(
policy_logps_flat,
ref_logps_flat,
advantages,
clip_ratio=clip_ratio,
)
# KL 散度作为额外正则
kl_penalty = (policy_logps_flat - ref_logps_flat).mean()
total_loss = grpo_loss + beta * kl_penalty
# === 4. 反向传播 ===
optimizer.zero_grad()
total_loss.backward()
torch.nn.utils.clip_grad_norm_(policy_model.parameters(), 1.0)
optimizer.step()
return {
"grpo_loss": grpo_loss.item(),
"kl_penalty": kl_penalty.item(),
"adv_mean": advantages.mean().item(),
"reward_mean": all_rewards.mean().item(),
}

4.2 GRPO Rollout:组内采样#

def grpo_rollout(
policy_model,
ref_model,
reward_model,
prompts: list[str],
tokenizer,
G: int = 8,
max_new_tokens: int = 512,
temperature: float = 0.9,
):
"""
GRPO Rollout:每个 prompt 采样 G 个回答。
返回:
- all_responses: 展平的所有回答 tokenized
- all_policy_logps: 展平的所有回答的 policy log prob
- all_ref_logps: 展平的所有回答的 ref log prob
- all_rewards: 展平的所有回答的 RM 分数
"""
all_responses = []
all_policy_logps = []
all_ref_logps = []
all_rewards = []
for prompt in prompts:
prompt_batch = [prompt] * G
# === 1. Policy 采样 ===
with torch.no_grad():
prompt_inputs = tokenizer(prompt_batch, return_tensors="pt",
padding=True, truncation=True)
prompt_inputs = {k: v.to(policy_model.device) for k, v in prompt_inputs.items()}
outputs = policy_model.generate(
**prompt_inputs,
max_new_tokens=max_new_tokens,
do_sample=True,
temperature=temperature,
top_p=0.95,
pad_token_id=tokenizer.pad_token_id or tokenizer.eos_token_id,
)
# === 2. 提取 response(去掉 prompt 部分)===
responses = extract_responses(prompt_batch, outputs, tokenizer)
# === 3. 计算 log probs ===
# Policy: 需要梯度
policy_logps = compute_response_log_probs(policy_model, responses) # (G,)
# Ref: 不需要梯度
with torch.no_grad():
ref_logps = compute_response_log_probs(ref_model, responses) # (G,)
# === 4. RM 评分 ===
with torch.no_grad():
rewards = reward_model(responses["input_ids"],
responses["attention_mask"]) # (G,)
all_responses.append(responses)
all_policy_logps.append(policy_logps)
all_ref_logps.append(ref_logps)
all_rewards.append(rewards)
# 展平
all_policy_logps = torch.cat(all_policy_logps, dim=0)
all_ref_logps = torch.cat(all_ref_logps, dim=0)
all_rewards = torch.cat(all_rewards, dim=0)
return all_responses, all_policy_logps, all_ref_logps, all_rewards

4.3 GRPO Clipped Loss#

def compute_grpo_loss(
policy_logps_new: torch.Tensor, # (N,) π_θ(y_i)
policy_logps_old: torch.Tensor, # (N,) π_{θ_old}(y_i)
ref_logps: torch.Tensor, # (N,) π_ref(y_i)
advantages: torch.Tensor, # (N,) 组内归一化优势
beta: float = 0.04,
clip_ratio: float = 0.2,
):
"""
GRPO 损失函数。
每个回答的损失 = PPO-style clip loss + KL penalty
"""
# 重要性比率
ratio = torch.exp(policy_logps_new - policy_logps_old) # (N,)
# PPO-style clip
surr1 = ratio * advantages
surr2 = torch.clamp(ratio, 1 - clip_ratio, 1 + clip_ratio) * advantages
# 取较小的(防止过度优化)
policy_loss = -torch.min(surr1, surr2).mean()
# KL 正则(per-sequence 级别)
kl = (policy_logps_new - ref_logps).mean()
total_loss = policy_loss + beta * kl
return total_loss

4.4 自熵正则(GRPO+)#

DeepSeek-R1 训练中加入自熵正则以防止策略坍缩:

def entropy_loss(logits: torch.Tensor) -> torch.Tensor:
"""
熵正则:鼓励策略保持随机性(探索)。
熵 = -Σ p(a)·log p(a)
"""
probs = torch.softmax(logits, dim=-1)
log_probs = torch.log_softmax(logits, dim=-1)
entropy = -(probs * log_probs).sum(dim=-1)
return -entropy.mean() # 最大化熵 = 最小化负熵
# 在 GRPO 损失中加入
entropy_coef = 0.01 # 典型值
total_loss = grpo_loss + beta * kl + entropy_coef * entropy_loss(logits)

物理含义

  • 当策略变得”自信”(某个 token 的概率接近 1),熵降低
  • 熵正则会惩罚这种确定性,鼓励模型保持一定的探索
  • 这在推理任务中尤其重要——早期需要探索多种推理路径

5. DeepSeek-R1:GRPO 的工业级应用#

5.1 DeepSeek-R1 训练流水线#

┌──────────────────────────────────────────────────────────────┐
│ DeepSeek-R1 训练流水线 │
├──────────────────────────────────────────────────────────────┤
│ │
│ 阶段 0: DeepSeek-V3 Base │
│ ↓ 预训练得到的基模型 │
│ │
│ 阶段 1: GRPO (用于推理能力涌现) │
│ → 使用 GRPO + 规则奖励(数学/代码/逻辑) │
│ → 无 SFT 中间阶段 │
│ → AIME 2024: 15 pass@1 → 71.0 pass@1 │
│ → 涌现出"反思"和"长思维链"行为 │
│ │
│ 阶段 2: Reinforced Fine-Tuning (RFT) │
│ → 用 GRPO 生成的高质量思维链数据 │
│ → 做 SFT 微调 │
│ → 目的:将 GRPO 的探索知识压缩为快速推理能力 │
│ │
│ 阶段 3: 拒绝采样 + 下一阶段 SFT │
│ → 扩大数据规模和多样性 │
│ │
│ 阶段 4: 所有场景的 GRPO │
│ → 包括写作、角色扮演、实用任务等 │
│ → 混合奖励(规则奖励 + 人类偏好) │
│ │
└──────────────────────────────────────────────────────────────┘

5.2 规则奖励(Rule-Based Rewards)#

DeepSeek-R1-Zero 的关键:只用规则奖励,不需要 RM

def rule_based_reward(prompt: str, response: str) -> float:
"""
规则奖励函数。无需训练的 RM。
"""
reward = 0.0
# 1. 准确性奖励
if is_math_problem(prompt):
# 提取最终答案
ground_truth = extract_answer(prompt)
model_answer = extract_final_answer(response)
if model_answer == ground_truth:
reward += 1.0
else:
reward -= 0.5 # 惩罚错误答案
elif is_code_problem(prompt):
# 执行测试用例
test_result = execute_code(response, prompt["testcases"])
if test_result.all_passed:
reward += 1.0
# 2. 格式奖励
if "</answer>" in response or "答案是" in response:
reward += 0.1
# 3. 长度奖励(鼓励长思维链)
num_thinking_tokens = count_think_tags(response)
reward += 0.001 * num_thinking_tokens # 微弱鼓励
return reward
为什么规则奖励足够?

数学和代码问题有可验证的ground truth——答案对不对是客观的,不需要人类判断。这使得规则奖励比偏好数据更可靠、更便宜、更可扩展。

5.3 思维链的涌现#

DeepSeek-R1-Zero 最惊人的发现:没有经过任何思维链 SFT,就涌现出了长思维链(Long CoT)能力

训练过程中的行为演化:
Step 0 (Base):
输入: 计算 1+1
输出: 2
Step 500:
输入: 证明 √2 是无理数
输出: [短推理,直接给出证明]
Step 2000:
输入: 证明 √2 是无理数
输出: [开始出现换行,但很快]
Step 5000 (涌现点):
输入: 证明 √2 是无理数
输出:
"让我们一步步分析...
假设 √2 = a/b 是有理数
那么 a² = 2b²
由于 2 整除 a²,所以 2 整除 a
...(长链反思)
所以假设不成立,√2 是无理数。
等等,我需要重新检查第一步的逻辑..."
Step 10000:
模型学会了主动"反思"、验证中间步骤、尝试多种方法

这是 RL 直接涌现的证据——不需要模仿人类写的思维链数据。

5.4 Reinforced Fine-Tuning (RFT)#

GRPO 学到了”如何推理”,但推理速度慢(需要大量思考 token)。

RFT 的目的:将 GRPO 探索出的推理能力,压缩到快速推理的 SFT 模型中。

def rft_pipeline(
base_model, # DeepSeek-V3 Base
grpo_model, # GRPO 训练后的模型(会生成思维链)
sft_model, # 待微调的模型
):
"""
RFT 两阶段:
1. GRPO 模型生成高质量思维链数据
2. 用这些数据 SFT 其他模型
"""
# === Stage 1: 生成思维链数据 ===
prompts = generate_reasoning_prompts()
# 用 GRPO 模型生成(可以加入 temperature 等探索)
thinking_chain_data = []
for prompt in prompts:
response = grpo_model.generate(prompt, max_tokens=8192)
# 保留思维链过程
thinking_chain_data.append({
"prompt": prompt,
"response": response,
"reward": rule_based_reward(prompt, response)
})
# 过滤高质量数据
high_quality = [d for d in thinking_chain_data if d["reward"] > 0.5]
# === Stage 2: SFT 微调 ===
for sample in high_quality:
# SFT loss 只在 response 上计算
sft_loss = compute_sft_loss(sft_model, sample["prompt"], sample["response"])
return sft_model # 学会了快速推理

5.5 GRPO 的 Scaling 特性#

DeepSeek 展示了 GRPO 的 scaling 特性

模型规模 vs GRPO 效果(AIME 2024 pass@1):
7B:
Base: ~5%
+ GRPO: ~45%
提升: ~9×
20B:
Base: ~15%
+ GRPO: ~60%
提升: ~4×
70B:
Base: ~30%
+ GRPO: ~70%
提升: ~2.3×
671B (DeepSeek-R1):
Base: ~40%
+ GRPO: ~79%
提升: ~2×

关键洞见:小模型 + GRPO 可以显著缩小与大模型的差距,但大模型 + GRPO 才能达到最强效果。


6. GRPO 的工程实践#

6.1 超参数指南#

超参数推荐范围说明
G(采样数)4 ~ 16越大优势估计越稳定,但显存和延迟增加
β\beta(KL 系数)0.01 ~ 0.1通常比 PPO 小(GRPO 不用 Value 网络)
clip ϵ\epsilon0.1 ~ 0.3默认 0.2
温度 temperature0.6 ~ 1.0采样多样性
top_p0.9 ~ 0.95配合 temperature 控制采样
熵系数0 ~ 0.02推荐 0.01 防止坍缩
学习率5e-7 ~ 2e-6比 SFT 小
max_tokens任务相关数学:2048+,代码:1024+

6.2 G 的大小选择#

def choose_G(task_type: str) -> int:
"""根据任务类型选择采样数 G"""
if "math" in task_type:
return 16 # 数学问题差异大,需要更多样本
elif "code" in task_type:
return 8 # 代码测试用例明确,8 个够用
elif "chat" in task_type:
return 4 # 聊天风格差异主观,4 个足够
else:
return 8 # 默认

G 越大越好的原因

  • 更多样本 → 更准确的优势估计
  • 更宽的 reward 分布 → 更清晰的偏好信号

G 越大的代价

  • 显存线性增长(GG 个回答需要存储 GG 份 KV Cache)
  • Rollout 时间线性增长
  • 训练延迟增加

6.3 GRPO + LoRA#

对于 7B+ 模型,GRPO 通常需要 LoRA 来节省显存:

from peft import get_peft_model, LoraConfig
def apply_lora_to_grpo(model, rank=64, lora_alpha=16):
"""
GRPO + LoRA 配置。
只对 Attention 的 Q, K, V, O 应用 LoRA。
"""
lora_config = LoraConfig(
r=rank,
lora_alpha=lora_alpha,
target_modules=["q_proj", "k_proj", "v_proj", "o_proj"],
lora_dropout=0.05,
bias="none",
task_type="CAUSAL_LM",
)
return get_peft_model(model, lora_config)
# 显存估算(7B 模型,bfloat16):
# 全参数 GRPO: ~56 GB
# LoRA (rank=64): ~28 GB
# LoRA (rank=128): ~32 GB

6.4 训练监控指标#

def log_grpo_metrics(step: int, metrics: dict):
"""GRPO 关键监控指标"""
print(f"[Step {step}] "
f"Reward={metrics['reward']:.4f} | "
f"KL={metrics['kl']:.4f} | "
f"Adv_Mean={metrics['adv_mean']:.4f} | "
f"Entropy={metrics['entropy']:.3f} | "
f"ClipFrac={metrics['clip_frac']:.2%} | "
f"G_Rewards=[{', '.join(f'{r:.2f}' for r in metrics['group_rewards'][:3])}...]")

关键指标解读

指标正常范围危险信号
Reward mean逐步上升突然跌到 0
**KL(ππ_ref)**< 0.1/token
Adv mean~0(对称分布)偏向一侧
Entropy逐步下降但 > 2.0快速下降到 < 1.0(坍缩)
Clip fraction5~20%> 50%

6.5 常见问题与对策#

┌────────────────────────────────┬────────────────────────────────────────┐
│ 现象 │ 对策 │
├────────────────────────────────┼────────────────────────────────────────┤
│ Reward 不上升 │ G 太小 → 增大 G;RM 质量差 → 检查 RM │
│ KL 爆炸(策略偏离太远) │ 增大 β,减小学习率 │
│ Entropy 快速下降(坍缩) │ 加入熵正则,减小学习率 │
│ Clip fraction > 50% │ 增大 clip ε,减小学习率 │
│ 组内 reward 全相同(无信号) │ prompt 太简单 → 换更难的任务 │
│ G=1 时(退化为 SFT) │ 确保 batch 中每个 prompt 都有 G>1 │
└────────────────────────────────┴────────────────────────────────────────┘

7. GRPO vs PPO vs DPO:完整对比#

7.1 三种对齐范式对比#

维度PPOGRPODPO
需要 Critic
需要 RM✅(可用规则奖励)
需要参考模型
训练阶段3(RM→Critic→Policy)2(RM→Policy)1(Policy)
显存占用~4× 模型~3× 模型~2× 模型
在线探索
梯度方差依赖 Critic≤1(归一化)取决于 β
数学推理⚠️ 需要调优✅ 天然适合⚠️ 弱
工程复杂度
超参数敏感性

7.2 何时用哪个#

任务类型决策树:
你的任务是什么?
├── 数学/代码/有 ground truth
│ └── ✅ GRPO + 规则奖励(DeepSeek-R1 路线)
├── 开放式生成(聊天/写作)
│ │
│ ├── 资源充足 + 追 SOTA
│ │ └── ✅ PPO + RM
│ │
│ ├── 资源有限 + 快速迭代
│ │ └── ✅ GRPO + RM
│ │
│ └── 资源极度有限
│ └── ✅ DPO
├── 已有大量偏好数据
│ └── ✅ DPO(最简单)
└── 想研究自我改进
└── ✅ GRPO + Self-Reward(下一节)

7.3 GRPO 的理论优势#

为什么 GRPO 在数学推理上比 DPO 强?

DPO 的局限:
- 离线优化:只用训练数据中的偏好对
- 没有探索:不会生成新的回答来探索空间
- 偏好对的质量上限:受限于标注数据的分布
GRPO 的优势:
- 在线探索:每个 batch 都会采样新的回答
- 主动发现:模型可能生成比训练数据更好的推理路径
- 自适应课程:hard prompt 自然获得更大的优势信号

8. 进阶:GRPO 的扩展#

8.1 Self-Reward 与 GRPO 的结合#

DeepSeek-Foundational (2024) 提出了 Constitutional AI + GRPO 的结合:

def grpo_self_reward(prompt: str, response: str, reward_model, constitution: list[str]) -> float:
"""
GRPO + AI 反馈:自己当自己的裁判。
"""
# 规则奖励
rule_reward = rule_based_reward(prompt, response)
# Constitutional AI 奖励
constitution_score = 0.0
for principle in constitution:
verdict = llm_judge(f"{principle}\n\nResponse: {response}")
if "good" in verdict.lower():
constitution_score += 0.1
return rule_reward + constitution_score

8.2 混合奖励(GRPO+)#

def mixed_reward(prompt: str, response: str) -> float:
"""
多目标混合奖励。
"""
reward = 0.0
# 1. 准确性(规则奖励)
reward += 0.6 * accuracy_reward(prompt, response)
# 2. 有帮助性(RM)
reward += 0.3 * helpfulness_rm(response)
# 3. 安全性(分类器)
reward += 0.1 * safety_score(response)
return reward

8.3 GRPO 的迭代版本#

DeepSeekMath 的训练采用多轮 GRPO

def iterative_grpo(
model,
rounds: int = 3,
prompts_per_round: list = None,
):
"""
迭代 GRPO:每轮用更新的模型重新生成数据。
"""
current_model = model
for round_idx in range(rounds):
print(f"=== GRPO Round {round_idx + 1}/{rounds} ===")
# 生成新的偏好数据
new_prompts = sample_prompts(prompts_per_round[round_idx])
rollout_data = grpo_rollout(current_model, ...)
# GRPO 更新
current_model = grpo_update(current_model, rollout_data)
# 评估
eval_score = evaluate(current_model)
print(f"Round {round_idx + 1} score: {eval_score}")
return current_model

9. 核心公式汇总#

9.1 GRPO 组内归一化优势#

Ai=riμσ,μ=1Gj=1Grj,σ=1Gj=1G(rjμ)2A_i = \frac{r_i - \mu}{\sigma}, \quad \mu = \frac{1}{G}\sum_{j=1}^{G}r_j,\quad \sigma = \sqrt{\frac{1}{G}\sum_{j=1}^{G}(r_j - \mu)^2}

9.2 重要性比率#

ri(θ)=πθ(yix)πθold(yix)r_i(\theta) = \frac{\pi_\theta(y_i|x)}{\pi_{\theta_{\text{old}}}(y_i|x)}

9.3 GRPO Clipped Surrogate#

LGRPO=E[1Gi=1Gmin(ri(θ)Ai, clip(ri(θ),1ϵ,1+ϵ)Ai)]\mathcal{L}^{\text{GRPO}} = -\mathbb{E}\Big[\frac{1}{G}\sum_{i=1}^{G}\min\big(r_i(\theta)\,A_i,\ \text{clip}(r_i(\theta), 1-\epsilon, 1+\epsilon)\,A_i\big)\Big]

9.4 KL 正则#

LKL=βKL(πθ(x)πref(x))\mathcal{L}_{\text{KL}} = \beta\,\text{KL}\big(\pi_\theta(\cdot|x)\,\|\,\pi_{\text{ref}}(\cdot|x)\big)

9.5 总损失#

LGRPO Total=LGRPO+LKL+λentLentropy\mathcal{L}_{\text{GRPO Total}} = \mathcal{L}^{\text{GRPO}} + \mathcal{L}_{\text{KL}} + \lambda_{\text{ent}}\,\mathcal{L}_{\text{entropy}}

9.6 GRPO 梯度方差上界#

Var(Ai)=Var(riμσ)1\text{Var}(A_i) = \text{Var}\left(\frac{r_i - \mu}{\sigma}\right) \leq 1

10. 总结#

10.1 GRPO 的核心贡献#

┌─────────────────────────────────────────────────────────────┐
│ GRPO 的三点核心贡献 │
├─────────────────────────────────────────────────────────────┤
│ │
│ 1. 去掉 Critic:用组内排名替代 Value 网络 │
│ → 减少 33% 显存,简化工程复杂度 │
│ → 方差有自然上界(≤1) │
│ │
│ 2. 在线探索 + 组内比较: │
│ → 每个 batch 都能探索新回答 │
│ → 自适应 baseline(组内均值) │
│ │
│ 3. 数学推理的天然适配: │
│ → 规则奖励替代 RM,不需要偏好数据 │
│ → 在线探索 → 思维链自动涌现 │
│ │
└─────────────────────────────────────────────────────────────┘

10.2 算法定位图#

对齐算法空间:
需要在线探索?
┌────┴────┐
│ │
是 否
│ │
┌─────┴─────┐ │
│ │ │
需要 Critic? │ │
│ │ │
是 否 │
│ │ │
PPO GRPO DPO
(经典) (DeepSeek)

10.3 未来方向#

  • GRPO + Model-based RL:结合世界模型减少采样成本
  • GRPO + 主动学习:优先选择高不确定性的 prompt 做 GRPO
  • GRPO + 多智能体:多模型协作推理,用 GRPO 对齐协作策略
  • GRPO + 持续学习:不遗忘旧能力的 GRPO 扩展
推荐阅读
  1. DeepSeekMath(Shao et al., 2024)—— GRPO 首次亮相
  2. DeepSeek-R1-Zero(DeepSeek, 2025)—— GRPO + 规则奖励 + 思维链涌现
  3. DeepSeek-R1(DeepSeek, 2025)—— RFT + 多阶段 GRPO
  4. PPO 原论文(Schulman et al., 2017)—— GRPO 的对比基准

参考资料#

  1. Shao, Z., et al. (2024). “DeepSeekMath: Pushing the Limits of Mathematical Reasoning in Open Language Models.” arXiv (GRPO).
  2. DeepSeek-AI. (2025). “DeepSeek-R1: Incentivizing Reasoning Capability in LLMs via Reinforcement Learning.” arXiv.
  3. DeepSeek-AI. (2025). “DeepSeek-R1-Zero: Scaling Reinforcement Learning with Zero Supervised Data.” arXiv.
  4. DeepSeek-AI. (2025). “DeepSeek-V3 Technical Report.” arXiv.
  5. Schulman, J., et al. (2017). “Proximal Policy Optimization Algorithms.” arXiv.
  6. Bai, Y., et al. (2022). “Constitutional AI: Harmlessness from AI Feedback.” arXiv.
  7. Ouyang, L., et al. (2022). “Training language models to follow instructions with human feedback.” NeurIPS.
  8. Rafailov, R., et al. (2023). “Direct Preference Optimization: Your Language Model is Secretly a Reward Model.” NeurIPS.
  9. Snell, C., et al. (2024). “Scaling LLM Training with compute-optimal RL.” arXiv.
  10. Lambert, N., et al. (2024). “RewardBench: Evaluating Reward Models for Language Modeling.” arXiv.

文章分享

如果这篇文章对你有帮助,欢迎分享给更多人!

GRPO 深度解析:DeepSeek 的高效对齐算法与数学推理革命
https://aiattnstudio.link/posts/grpo/
作者
Federico
发布于
2026-07-16
许可协议
CC BY-NC-SA 4.0
Profile Image of the Author

Federico

AI Research Lab

Hello, I'm Federico.

关于实验室 / About
公告

欢迎来到Federico的个人博客

分类
标签
站点统计
57文章
7分类
404标签