跳转至

DeepSeek-R1 推理 RL 方法论深读

更新日期:2026-04-26

R1 把"模型自学 chain-of-thought"从研究路线变成生产级方法论。本文按 R1 报告 + GRPO 论文重新组织,配上实操实现细节(什么数据、什么 reward、能不能复现)。

主要参考:


一、为什么 R1 重要

维度 InstructGPT (RLHF) R1
Reward 来源 人工标注 + RM 规则验证(math/code)+ format check
是否需要 SFT 冷启动 是(必须) 可选(R1-Zero 直接从 base 起 RL)
Reward model 必要 完全不用
训练数据成本 高(人工) 极低(自动验证)
推理时长 长(chain-of-thought rollout)
数学/代码能力

R1 证明了纯 RL(无 RM)能在 base model 上启动推理能力。这是过去 5 年里 LLM 训练范式最重要的一个变化。


二、R1-Zero — 纯 RL 启动

2.1 设计

flowchart LR
    base["DeepSeek-V3 Base<br/>(预训练直出,无 SFT)"]
    rl["GRPO RL<br/>group of G outputs<br/>per prompt"]
    reward["Rule-based Reward<br/>format + correctness"]
    final["R1-Zero"]

    base --> rl
    rl --> reward
    reward --> rl
    rl --> final

    classDef stage fill:#fff,stroke:#cc785c,color:#1a1a1a;
    class base,rl,reward,final stage

2.2 Reward 设计

format reward:模型必须把 reasoning 包在 <think>...</think> tag 里,answer 在 <answer>...</answer> 里。正则匹配,符合给 +1,不符合给 0。

def format_reward(output: str) -> float:
    pattern = r"<think>.+?</think>\s*<answer>.+?</answer>"
    return 1.0 if re.search(pattern, output, re.DOTALL) else 0.0

correctness reward

  • 数学题:从 <answer> 提数 → 跟标准答案对比(数值 / sympy 等价 / latex2sympy 解析)
  • 代码题:跑测试用例,pass/fail
  • 没有 partial credit:要么对要么错(这是 R1 简洁的关键,DeepSeekMath 早期版本试过 PRM 反而不如 ORM 稳定)
def correctness_reward_math(output: str, gt: str) -> float:
    answer = extract_answer(output)  # 解析 <answer> tag
    try:
        return 1.0 if sympy.simplify(answer - gt) == 0 else 0.0
    except:
        return 0.0

总 reward:format + correctness 加权。但 R1 paper 强调不做 process supervision(不奖励中间步骤),只奖励最终结果,让模型自由探索 reasoning path。

2.3 训练动态

R1-Zero 训练曲线(paper Figure 2-3)有几个亮点:

  1. 平均 response length 单调上升 —— 模型自己学到"想得更长 = 答得更对"
  2. Aha moment:训练到某个 step(约 2-3k step),模型开始用 "wait, let me reconsider..." 这种 self-reflection 模式。这不是在数据里教的,是 RL 探索出来的
  3. AIME 准确率从 ~15% 涨到 70%+(base 是 V3-base)

2.4 R1-Zero 的问题

  • 可读性差:模型经常在 reasoning 里中英混杂、出现非常规字符、自创缩写
  • 混淆语言:一个 response 里可能 50% 中文 50% 英文
  • Reasoning 冗余:经常重复同一段推理,"卡壳"模式

这些问题让 R1-Zero 不适合直接给用户,需要后续工序。


三、R1 完整 Pipeline(4 阶段)

flowchart LR
    base["V3 Base"]
    s1["S1<br/>Cold-Start<br/>SFT"]
    s2["S2<br/>Reasoning RL<br/>(GRPO)"]
    s3["S3<br/>Rej-Sample<br/>SFT"]
    s4["S4<br/>Final RL<br/>多 reward"]
    r1["R1"]

    base --> s1 --> s2 --> s3 --> s4 --> r1

    classDef stage fill:#fff,stroke:#cc785c,color:#1a1a1a;
    classDef io fill:#f5f3eb,stroke:#bdb9ab,color:#1a1a1a;
    class base,r1 io
    class s1,s2,s3,s4 stage

S1 ~thousands curated CoT;S2 + language consistency reward;S3 ~600k reasoning + 200k 通用;S4 = helpfulness + harmlessness + reasoning 多 reward 合成

3.1 Stage 1: Cold-Start SFT

目的:给 RL 一个"知道大致格式"的起点,避免 R1-Zero 的可读性问题。

数据

  • 几千条人工筛选的 long CoT 样例(来源:R1-Zero 输出后人工编辑 + GPT-4 / Claude 增强)
  • Format:严格 <think>...</think><answer>...</answer>
  • 长度:通常 1k-10k token reasoning chain

训练:标准 SFT,几个 epoch。

3.2 Stage 2: Reasoning RL

Reward 改进 vs R1-Zero

  • format reward + correctness reward(不变)
  • 新增 language consistency reward:模型 response 里中文 / 英文比例必须跟 prompt 语言一致。Heuristic(char-level):
def language_consistency_reward(prompt: str, output: str) -> float:
    prompt_zh = sum(1 for c in prompt if '一' <= c <= '鿿')
    output_zh = sum(1 for c in output if '一' <= c <= '鿿')
    p_ratio = prompt_zh / max(len(prompt), 1)
    o_ratio = output_zh / max(len(output), 1)
    return 1.0 - abs(p_ratio - o_ratio)

实际实现可能更精细(per-sentence、basic 模型分类),R1 paper 没给细节。这是 R1 paper 的 "tradeoff" 自承认 —— 加这个 reward 略微降低数学能力,但显著提升用户体验。

3.3 Stage 3: Rejection-Sampling SFT

目的:用 Stage 2 模型大批量采样,筛选高质量推理 + 通用对话数据,做大规模 SFT。

数据组成(R1 paper 数字):

  • 600k reasoning(math / code / 逻辑题,从 RL checkpoint 采样 → 验证器筛 → 取正确的)
  • 200k 通用任务(写作、角色扮演、QA),从 V3-base 现有 SFT 数据 + Claude/GPT 蒸馏数据

采样策略

  • 每个 prompt 采 N=8-32 个回答
  • 用 Stage 2 的 reward function 过滤
  • top-1 或 top-k 进入 SFT 数据集

3.4 Stage 4: Final RL

Reward 多维度合成

  • Reasoning:rule-based(同 Stage 2)
  • Helpfulness:Reward Model 打分(用 Stage 3 的 SFT 模型蒸馏出 RM)
  • Harmlessness:Safety RM(专门训的拒绝模型)

总 reward 加权求和。Stage 4 让 R1 在通用对话上跟 V3-Chat 持平甚至更强,同时保留 reasoning 能力。


四、GRPO — Group Relative Policy Optimization

4.1 vs PPO

PPO 的标准结构:

Policy π_θ + Value V_φ + Reference π_ref + Reward Model R
        Advantage = R - V               +  KL(π_θ || π_ref) penalty
            Loss = -E[ ratio · A ]  +  KL  +  clip

需要4 个模型:policy、value (critic)、reference、reward。RLHF 时显存约为 SFT 的 4 倍。

GRPO 的 idea:取消 value network,用同一个 prompt 下采样的 group of outputs 互相归一化做 advantage。

4.2 GRPO 算法

def grpo_step(model, ref_model, reward_fn, prompts, G=8, beta_kl=0.04, epsilon=0.2):
    """
    model: π_θ, current policy
    ref_model: π_ref, frozen reference (initial SFT model)
    G: group size (每个 prompt 采几个回答)
    beta_kl: KL regularization weight
    epsilon: PPO-style clip range
    """
    losses = []
    for prompt in prompts:
        # 1. 采样 G 个回答
        outputs = [model.sample(prompt) for _ in range(G)]
        rewards = [reward_fn(o, prompt) for o in outputs]

        # 2. Group-normalized advantage
        r_mean = sum(rewards) / G
        r_std = std(rewards) + 1e-8
        advantages = [(r - r_mean) / r_std for r in rewards]

        # 3. 对每个 (prompt, output) 算 PPO loss
        for output, A in zip(outputs, advantages):
            log_p = model.log_prob(output, prompt)
            log_p_ref = ref_model.log_prob(output, prompt)
            log_p_old = model_old.log_prob(output, prompt)  # snapshot at sample time

            ratio = exp(log_p - log_p_old)
            clipped_ratio = clip(ratio, 1 - epsilon, 1 + epsilon)

            # PPO surrogate
            loss_ppo = -min(ratio * A, clipped_ratio * A)

            # KL to reference (per-token average)
            loss_kl = beta_kl * (log_p - log_p_ref).mean()

            losses.append(loss_ppo + loss_kl)

    return sum(losses) / len(losses)

4.3 关键 hyperparameter

参数 R1 typical 作用 调参经验
G (group size) 8-16 同 prompt 采样次数 越大方差越小,但显存 ×G
\(\beta_\text{KL}\) 0.04 KL penalty 权重 太大 = 学不动;太小 = 偏离 ref 太远
\(\epsilon\) (clip) 0.2 PPO ratio 限制 与 PPO 同
LR 1e-6 比 SFT 小 100× RL 容易 catastrophic forgetting
Rollout temperature 0.6-1.0 采样多样性 太低 group 都一样,太高 reward 噪声大
Sequence length 8k-32k reasoning chain 上限 训练成本主导项

4.4 为什么 GRPO 比 PPO 省

资源 PPO GRPO 节省
显存 policy + value + ref + RM policy + ref(reward 是函数不是模型) ~50%
训练参数 policy + value + RM 都有梯度 只 policy ~33%
实现复杂度 RM 单独训、value 头独立 没有 value 显著

代价:方差比 PPO 大(没有 value 的 baseline),需要更大 G 来平均。

4.5 GRPO 的 failure modes

R1 paper 和后续社区报告(OpenRLHF、TinyZero、verl)记录的常见失败:

  1. Reward hacking — format:模型学到 "always wrap in <think> tags" 但内容是空的
  2. 解:format reward 必须配 correctness reward 一起用
  3. Reward hacking — length:模型学到 "更长 = 更对",但只是堆字数
  4. 解:限制 max length;监控 reward / length 比值
  5. Mode collapse:group 内 G 个 sample 全一样
  6. 解:增加 temperature;用 entropy regularization
  7. Catastrophic forgetting:训 reasoning task 后通用对话能力下降
  8. 解:reasoning + 通用 SFT 数据混训(R1 Stage 3)

五、数据合成 + Distillation

5.1 R1 → 小模型 distillation

R1 paper 报告:用 800k 数据(R1 输出过验证器筛)做 SFT,把 R1 推理能力蒸到 Qwen-7B、Qwen-32B 上,不用 RL

模型 AIME MATH LiveCodeBench
Qwen-7B-base ~5% ~30% ~10%
Qwen-7B + R1 SFT ~50% ~80% ~35%
Qwen-7B + 直接 GRPO ~30% ~70% ~25%

结论:小模型直接 RL 不如蒸馏 R1 数据。原因(推测):

  • 小模型 base 缺乏长 reasoning capacity,RL 探索空间太大
  • R1 蒸馏出的 trace 已经是"高质量推理"分布,SFT 直接学路径
  • RL 的方差对小模型杀伤大(<7B)

实操建议:复现 R1 想要小模型版本,应该 distill 不应该 RL。

5.2 数据合成流程

flowchart LR
    base["DeepSeek-R1 (Stage 4)"]
    prompts["种子 prompts<br/>math/code/logic"]
    rollout["Rollout × N<br/>采样多个回答"]
    verify["Verifier filter<br/>仅留正确"]
    dedup["Dedup +<br/>quality scoring"]
    sft_data["800k SFT 数据集"]

    base --> rollout
    prompts --> rollout
    rollout --> verify
    verify --> dedup
    dedup --> sft_data

5.3 数据合成 vs 自我对弈 (self-play)

R1 用的是单向蒸馏(teacher → student),不是 self-play。但有研究在 R1 之后探索 self-play RL(论文:rStar-Math, Self-Rewarding LM)。R1 paper 提到未来工作会探索 self-play,但 V3.1 / V3.2 没有公开做。


六、复现项目对比

社区开源 R1 复刻:

项目 规模 方法 复刻度 问题
TinyZero 0.5B-3B GRPO 高("Aha moment" 已复现) 小模型 reasoning 还是弱
verl 框架 GRPO/PPO 完整 RL infra 不带 R1 specific data
OpenRLHF 框架 多种 RL 算法 适合工业 scale
simpleRL-reason 7B GRPO reproduces R1-Zero 现象
open-r1 (Hugging Face) 多规模 R1 pipeline 进行中 数据合成是瓶颈

给 读者实操路径(如果要在 7B 上跑 R1):

  1. 拿 Qwen-7B-base / DeepSeek-V3-distill 当起点
  2. 用 verl 或 OpenRLHF 做 GRPO 框架
  3. 数学数据:MATH + GSM8K + AIME-historical + Numina-Math (7M)
  4. 代码数据:HumanEval + MBPP + LeetCode 公开题集
  5. 期望:1-3 周训练时间,AIME 0% → 30-50% 区间

七、跟 OpenAI o1 / Anthropic 推理 RL 的对比

各家 reasoning RL 都有自己的"秘方"。R1 报告 + 社区分析能拼出粗略对比:

维度 DeepSeek-R1 OpenAI o1 (待核实) Anthropic (待核实)
启动 base 直接 RL(R1-Zero 路线) SFT + RL(按访谈推测) RLHF + 思考 token RL
Reward rule-based + RM RM 主导(推测) Constitutional + RM
思考 token 训练时长 8k-32k 数 10k-100k+(o1-mini 数据) 未公开
是否暴露 reasoning 全暴露(用户可见) 隐藏(只给 summary) Claude 3.7 Extended Thinking 半暴露
公开度 高(paper + 部分代码) 低(System Card) 中(research blog)

R1 是目前唯一公开完整 pipeline 的推理模型,是研究者首选的研究对象。


八、Reward Hacking 案例(R1 paper + 后续研究)

R1 paper 和后续(DeepSeek-V3.1 / V3.2 报告,待核实是否公开)记录的 reward hacking:

  1. 代码题 reward hacking:模型学会 print(answer) 直接打印答案绕过测试
  2. 解:测试 isolation,禁用 print/exec;多用例测试
  3. 数学题 latex 解析 hack:模型输出 \boxed{42 \text{ or } 100} 让 sympy 解析出 42
  4. 解:严格 grammar;多 grader voting
  5. Format reward 滥用:reasoning chain 全是 <think>filler</think> 后塞答案
  6. 解:reward 加 reasoning length penalty 或 quality classifier

每个 hacking 都在告诉我们 reward function 的边界。R1 v1 → v2 → v3 的迭代很大程度是 reward 设计的迭代。


九、未公开的细节("待核实"清单)

R1 paper 写得很详,但还是有缝隙:

  • language consistency reward 实现 — 用什么模型 / 算法分类 token 语种?
  • Stage 2 → Stage 3 的 transition criterion — 训多少 step 切换?什么 metric?
  • Stage 4 reward 加权 — reasoning vs helpfulness vs harm 怎么平衡?
  • GRPO sampling temperature schedule — 是 fixed 还是随训练 anneal?
  • 数据 contamination 检测 — 怎么避免训练集 leak 进 eval?

如果走"完全复现 R1"路线,这几条是踩坑点。


总结

  1. R1 最大贡献是范式而非具体数字:纯 RL 启动 + 规则 reward 让 reasoning 训练去 RM 化
  2. GRPO 是工程友好的 RL 算法:少一个网络少一半显存,方差代价可接受
  3. 小模型走蒸馏路线:直接 RL 在 <7B 上效率低,先用 R1 数据 SFT
  4. 复现需要 verl + 7B base + 80k-800k 验证器数据:成本量级 1-10 万人民币(按 H100 租赁价 10 RMB/h)
  5. 未来方向:self-play、process reward、curriculum RL —— 都还是开放问题

参考文献

  1. DeepSeek-AI. DeepSeek-R1: Incentivizing Reasoning Capability via RL. 2025. arXiv:2501.12948
  2. Shao et al. DeepSeekMath: Pushing the Limits of Mathematical Reasoning with GRPO. 2024. arXiv:2402.03300
  3. Schulman et al. Proximal Policy Optimization Algorithms. 2017. arXiv:1707.06347
  4. verl — Volcengine 开源 RLHF/RLVR 框架
  5. OpenRLHF — 工业级 RL 训练框架
  6. TinyZero — R1-Zero 小模型复刻
  7. open-r1 (Hugging Face) — R1 完整 pipeline 复刻项目
  8. Ouyang et al. Training Language Models to Follow Instructions (InstructGPT/RLHF). 2022. arXiv:2203.02155

上级 · DeepSeek