跳转至

RLVR 深入:数学推理方向

更新日期:2026-04-14


一、数学推理为什么是 RLVR 的最佳赛道

数学是 RLVR 最成功的领域,因为它完美满足了"可验证奖励"的条件:答案是唯一确定的,可以自动判对错。


二、数学 RLVR 训练流程

flowchart LR
    prompt["数学题<br/>(GSM8K / AIME)"]
    rollout["模型 rollout<br/>k 条 CoT"]
    extract["答案提取<br/>\\boxed{} / regex"]
    verify["验证器<br/>SymPy / 数值"]
    reward["0/1 reward"]
    rl["GRPO / PPO 更新"]

    prompt --> rollout --> extract --> verify --> reward --> rl
    rl -.-> rollout

    classDef stage fill:#fff,stroke:#cc785c,color:#1a1a1a;
    class prompt,rollout,extract,verify,reward,rl stage

数学之所以是 RLVR 最佳赛道:reward 函数零歧义——没有 reward hacking 的空间,模型只能通过真正学会推理来提分。

2.1 验证器实现

class MathVerifier:
    def verify(self, model_output, ground_truth):
        # Step 1: 从 CoT 中提取最终答案
        # 常用格式: "The answer is \\boxed{42}" 或 "Answer: 42"
        extracted = self.extract_answer(model_output)

        # Step 2: 规范化比较
        # 处理: 分数("1/2" vs "0.5"), 科学记数法, LaTeX 格式
        if self.symbolic_equal(extracted, ground_truth):
            return 1.0  # 正确

        # Step 3: SymPy 符号比较 (处理等价表达式)
        try:
            expr1 = sympy.sympify(extracted)
            expr2 = sympy.sympify(ground_truth)
            if sympy.simplify(expr1 - expr2) == 0:
                return 1.0
        except:
            pass

        return 0.0  # 错误

    def extract_answer(self, text):
        # 尝试多种格式
        patterns = [
            r'\\boxed\{(.+?)\}',           # LaTeX boxed
            r'[Tt]he answer is[:\s]*(.+)',  # "The answer is ..."
            r'[Aa]nswer[:\s]*(.+)',         # "Answer: ..."
            r'=\s*(.+)$',                  # 最后一行的等号
        ]
        for pattern in patterns:
            match = re.search(pattern, text)
            if match:
                return match.group(1).strip()
        return text.strip().split('\n')[-1]  # fallback: 最后一行

2.2 GRPO 用于数学的具体配置

grpo_config = {
    'group_size': 64,        # 每个题目采样 64 个回答
    'max_new_tokens': 2048,  # CoT 最长 2048 tokens
    'temperature': 0.7,      # 采样温度
    'top_p': 0.95,
    'kl_coeff': 0.01,        # KL 惩罚系数 (防偏离太远)
    'clip_eps': 0.2,         # PPO clip 范围
    'reward': 'binary',      # 0/1 奖励 (对/错)
}

# 训练循环
for batch in math_dataset:
    for question, answer in batch:
        # 采样 group_size 个回答
        responses = model.generate(question, n=64, temperature=0.7)

        # 验证
        rewards = [verifier.verify(r, answer) for r in responses]
        # rewards: [0, 1, 0, 0, 1, 1, 0, ...] 大部分是 0

        # 组内归一化
        rewards = tensor(rewards)
        advantages = (rewards - rewards.mean()) / (rewards.std() + 1e-8)

        # GRPO 更新
        grpo_update(model, responses, advantages, kl_coeff=0.01)

三、数据源

3.1 训练题库

3.2 题目生成

RLVR 的核心优势:只需要题目+答案,不需要 CoT 标注。题目可以自动大量生成。

# 方法 1: 程序化生成
def generate_math_problem():
    # 随机生成多项式方程
    degree = random.choice([2, 3, 4])
    coefficients = [random.randint(-10, 10) for _ in range(degree + 1)]
    # 计算答案 (用 SymPy)
    x = sympy.Symbol('x')
    poly = sum(c  x*i for i, c in enumerate(coefficients))
    solutions = sympy.solve(poly, x)
    return {
        'question': f'Solve {poly} = 0',
        'answer': str(solutions)
    }

# 方法 2: 用 LLM 改写现有题目
# 给定 GSM8K 的一道题, 让 LLM 改变数字/情境
# "小明有 5 个苹果" → "小红有 8 个橘子"

# 方法 3: 从 AIME/AMC 真题出发, 生成变体


四、关键工程细节

4.1 奖励信号设计

DeepSeek-R1 使用最简单的 binary reward + 少量格式奖励就达到了 SOTA。过于复杂的奖励反而可能引入噪声。

4.2 CoT 涌现

DeepSeek R1-Zero 最重要的发现:不需要任何 CoT 标注数据,仅通过 RLVR 训练,模型自发产生了以下行为: - 分步推理 ("First, let me consider...")

  • 自我验证 ("Let me check: if x=3, then...")

  • 回溯 ("Wait, this doesn't seem right. Let me try again...")

  • 多方法尝试 ("Alternatively, I can approach this by...")

# R1-Zero 的惊人输出示例 (训练中自然涌现):
"""
<think>
I need to solve x^2 - 5x + 6 = 0.
Let me try factoring: I'm looking for two numbers that multiply to 6 and add to -5.
-2 × -3 = 6 ✓
-2 + (-3) = -5 ✓
So (x-2)(x-3) = 0

Wait, let me verify: (x-2)(x-3) = x^2 - 3x - 2x + 6 = x^2 - 5x + 6 ✓

Therefore x = 2 or x = 3.
</think>
The answer is \boxed{x = 2, 3}
"""
# 没有人教它 "verify" 或 "wait" — 这是 RL 压力下自发涌现的!

4.3 训练稳定性


五、数学推理的前沿

方向 描述 为什么重要 当前局限 代表工作
Process Reward Model (PRM) 对推理的每一步打分而非只看最终结果 ORM 只有最终信号,50 步推理中某步出错但最终碰巧答对会得到正奖励(false positive);PRM 逐步纠错,理论上能提升推理可靠性 标注成本极高(每步需要人工判断对错);自动 PRM 训练仍是开放问题;Math-Shepherd 尝试用 MC 采样自动标注但精度有限 Let's Verify Step by Step (Lightman et al., 2023)
Tree Search + RL MCTS 搜索推理树 + RL 选择最优路径,类似 AlphaGo 的思路 线性 CoT 一旦走错无法回头;树搜索允许在多个推理分支中选最优,显著提升难题求解率 推理成本指数级增长:深度 d 宽度 b 的搜索树需要 b^d 次前向推理;实时服务几乎不可行,主要用于离线求解 AlphaProof (DeepMind, 2024)
形式化验证 将自然语言推理转为 Lean4/Isabelle 形式化证明,由定理证明器验证 自然语言推理有"看似正确实则错误"的步骤;形式化证明由机器验证,100% 可靠 自然语言到形式语言的转换(autoformalization)仍不成熟;训练数据极少(Mathlib 约 10 万定理);覆盖的数学领域有限 AlphaProof
数学预训练 在大规模数学文本(教科书、论文、网页数学内容)上继续预训练 通用预训练中数学文本占比 <5%,模型数学"基础知识"不足;数学预训练能补齐符号运算、定理记忆等基础能力 数学文本质量参差不齐(网页公式渲染错误、OCR 噪声);预训练可能遗忘通用能力(需要仔细调 mixing ratio) Llemma (Azerbayev et al., 2023)
工具增强推理 在 CoT 中调用外部工具(计算器、SymPy、Python 解释器)辅助计算 LLM 的算术能力弱(多位数乘法错误率高);调用计算器可将计算准确率提升到 100%,让模型专注于推理逻辑 工具调用增加延迟(每次调用约 100-500ms);需要训练模型学会"何时调用"和"如何格式化调用" TORA (Gou et al., 2023)

参考文献

  • [1] Shao et al. DeepSeekMath: Pushing the Limits of Mathematical Reasoning (GRPO). 2024. 论文

  • [2] DeepSeek-AI. DeepSeek-R1 Technical Report. 2025. 论文

  • [3] Lightman et al. Let's Verify Step by Step (PRM). 2023. 论文

  • [4] Cobbe et al. Training Verifiers to Solve Math Word Problems (GSM8K). 2021. 论文

  • [5] Hendrycks et al. Measuring Mathematical Problem Solving (MATH). 2021. 论文

  • [6] Gou et al. TORA: A Tool-Integrated Reasoning Agent. 2023. 论文

  • [7] Azerbayev et al. Llemma: An Open Language Model for Mathematics. 2023. 论文


上级 · E. 后训练与对齐