对齐 第 16 讲 / 共 17 讲

第 16 讲:Alignment: RLVR

本讲介绍 RLVR (Reinforcement Learning from Verifiable Rewards) — 一种利用可自动验证的 reward signal 进行强化学习的方法。与 RLHF 依赖人类标注不同,RLVR 的核心优势在于 reward 可以通过程序自动计算,从而实现大规模、低成本的 RL 训练。

为什么 RLVR 很重要

RLHF 的瓶颈在于人类标注:成本高、速度慢、一致性差。而在数学、编程等领域,答案的正确性可以被自动验证。RLVR 利用这一特性,将 RL 的 reward signal 从"人类偏好"变为"可验证的正确性",从根本上解决了 reward 的可扩展性问题。DeepSeek-R1 的成功充分证明了这一方法的潜力。

1. RLVR 概念

1.1 什么是 Verifiable Rewards

Verifiable Rewards 指的是可以通过程序自动判断正确性的 reward signal。与 RLHF 中需要人类或 reward model 主观判断不同,verifiable rewards 具有客观标准:

1.2 RLVR vs RLHF

方面 RLHF RLVR
Reward 来源 人类偏好 → Reward Model 自动验证器
标注成本 高(需要人类标注者) 低(自动化)
Reward 准确性 受 RM 质量限制,可能有偏差 准确、无偏(正确答案是客观的)
Reward Hacking 风险 高(RM 容易被欺骗) 低(难以欺骗自动验证器)
适用范围 广泛(任何文本生成任务) 受限(需要可验证的任务)
扩展性 受限于标注速度 几乎无限扩展

2. 数学推理场景下的 RL

数学推理是 RLVR 最成功的应用场景。数学题具有天然的可验证性:答案要么对,要么错。

2.1 问题设定

在数学推理场景中,RL 的设定如下:

2.2 答案验证方法

数学答案的验证看似简单,实际上有一些技术细节:

import re
from sympy import simplify, parse_expr

def verify_math_answer(model_output, ground_truth):
    """Verify if the model's answer matches the ground truth."""
    # Step 1: Extract the final answer from model output
    # Common format: "The answer is \\boxed{42}"
    match = re.search(r'\\boxed\{(.+?)\}', model_output)
    if match is None:
        return 0.0  # No answer found

    model_answer = match.group(1)

    # Step 2: Try exact string match first
    if model_answer.strip() == str(ground_truth).strip():
        return 1.0

    # Step 3: Try symbolic equivalence (e.g., "2/4" == "1/2")
    try:
        expr1 = parse_expr(model_answer)
        expr2 = parse_expr(str(ground_truth))
        if simplify(expr1 - expr2) == 0:
            return 1.0
    except:
        pass

    return 0.0

2.3 常用数学训练数据集

3. GRPO 算法

GRPO (Group Relative Policy Optimization) 是 DeepSeek 提出的一种 RL 算法,专门设计用于 LLM 的 alignment。它是 PPO 的一个重要改进,避免了训练 value model(critic)的需求。

3.1 PPO 的问题

在 LLM 场景中,PPO 存在几个实际问题:

3.2 GRPO 的核心思想

GRPO 的关键创新是用组内相对比较来替代 value model 进行 advantage 估计。对于每个 prompt,生成一组(group of)回答,然后用组内的 reward 统计量来估计 advantage:

A_i = (r_i - mean(r_1, ..., r_G)) / std(r_1, ..., r_G)

其中 G 是 group size(每个 prompt 生成的回答数量),r_i 是第 i 个回答的 reward。

3.3 GRPO 算法流程

def grpo_step(policy, ref_model, prompts, reward_fn, group_size=16):
    """One step of GRPO training."""
    all_advantages = []
    all_responses = []
    all_old_logprobs = []

    for prompt in prompts:
        # 1. Sample a group of responses
        responses = [policy.generate(prompt) for _ in range(group_size)]

        # 2. Compute rewards for each response
        rewards = [reward_fn(prompt, resp) for resp in responses]
        rewards = torch.tensor(rewards)

        # 3. Compute group-relative advantages (no value model needed!)
        mean_r = rewards.mean()
        std_r = rewards.std() + 1e-8
        advantages = (rewards - mean_r) / std_r

        # 4. Compute log probabilities under current policy
        for resp, adv in zip(responses, advantages):
            logprob = policy.log_prob(prompt, resp)
            all_responses.append((prompt, resp))
            all_advantages.append(adv)
            all_old_logprobs.append(logprob.detach())

    # 5. PPO-style clipped update with KL penalty
    for epoch in range(num_epochs):
        for (prompt, resp), adv, old_lp in zip(
            all_responses, all_advantages, all_old_logprobs
        ):
            new_lp = policy.log_prob(prompt, resp)
            ref_lp = ref_model.log_prob(prompt, resp)

            # Importance ratio
            ratio = torch.exp(new_lp - old_lp)
            clipped_ratio = torch.clamp(ratio, 1 - eps, 1 + eps)

            # Clipped objective
            policy_loss = -torch.min(ratio * adv, clipped_ratio * adv)

            # KL penalty
            kl_loss = beta * (new_lp - ref_lp)

            loss = policy_loss + kl_loss
            loss.backward()
            optimizer.step()

3.4 GRPO 的优势

4. DeepSeek-R1 中的 RL 应用

DeepSeek-R1 是 RLVR 最成功的案例之一,展示了纯 RL 训练如何让模型"自发"发展出强大的推理能力。

4.1 DeepSeek-R1-Zero

DeepSeek-R1-Zero 是一个里程碑式的实验:完全不使用 SFT 数据,直接在 base model 上进行 RL 训练(使用 GRPO),模型自发发展出了 chain-of-thought 推理能力。

关键发现:

4.2 DeepSeek-R1 的完整流程

完整的 DeepSeek-R1 在 R1-Zero 基础上增加了更多阶段:

  1. 冷启动数据收集:先用少量 long-CoT SFT 数据进行微调,为 RL 提供更好的起点
  2. 推理 RL 训练:使用 GRPO 在数学和代码任务上进行 RL 训练,reward 来自自动验证器
  3. 拒绝采样 + SFT:用 RL 模型生成大量推理数据,筛选高质量的进行 SFT
  4. 全场景 RL:在更广泛的任务上进行第二轮 RL,包括有用性和安全性

4.3 从 DeepSeek-R1 中学到的教训

Distillation 的力量

DeepSeek-R1 还展示了 distillation 的强大效果:将 R1 的推理能力蒸馏到更小的模型(如 Qwen-1.5B, Llama-7B)中,这些小模型在数学推理上的表现甚至超过了同规模的直接 RL 训练模型。这说明大模型探索到的推理模式可以有效地转移给小模型。

5. Process Reward Models vs Outcome Reward Models

在数学推理场景中,reward 的粒度有两种选择:

5.1 Outcome Reward Model (ORM)

ORM 只根据最终答案给出 reward:

5.2 Process Reward Model (PRM)

PRM 对推理过程的每一步都给出 reward:

5.3 PRM800K 与 Math-Shepherd

OpenAI 的 PRM800K 数据集包含 800K 个 step-level 的标注,用于训练 process reward model。但这种规模的人工标注成本极其高昂。

Math-Shepherd 提出了一种自动生成 process reward 标注的方法:对于每一步推理,通过 Monte Carlo sampling 估计从该步出发最终到达正确答案的概率,作为该步的 process reward。这大幅降低了标注成本。

PRM(step_i) ≈ P(correct final answer | step_1, ..., step_i)

6. 自动化 Reward 的其他应用

6.1 代码执行验证

代码任务提供了另一种天然的 verifiable reward:

import subprocess
import tempfile

def verify_code(generated_code, test_cases):
    """Verify generated code by running test cases."""
    rewards = []
    for test_input, expected_output in test_cases:
        try:
            # Write code to temp file
            with tempfile.NamedTemporaryFile(suffix='.py', mode='w') as f:
                f.write(generated_code)
                f.write(f"\nprint(solution({test_input}))")
                f.flush()

                # Execute with timeout
                result = subprocess.run(
                    ['python', f.name],
                    capture_output=True, text=True, timeout=10
                )
                actual_output = result.stdout.strip()
                rewards.append(1.0 if actual_output == expected_output else 0.0)
        except (subprocess.TimeoutExpired, Exception):
            rewards.append(0.0)

    return sum(rewards) / len(rewards)  # Fraction of tests passed

代码验证的优势在于测试用例可以涵盖各种边界情况,提供非常可靠的 reward signal。

6.2 事实性验证

事实性验证是另一个重要方向,虽然难度更大:

FActScore 是一个专门用于评估长文本事实性的 metric,将文本分解为 atomic facts 后逐一验证。

6.3 格式和约束验证

许多实际应用中,模型需要按照特定格式或约束生成输出:

本讲小结

本讲介绍了 RLVR 的概念和实践:

  1. RLVR 概念:利用可自动验证的 reward 进行 RL,无需人类标注,可大规模扩展
  2. 数学推理 RL:数学答案的可验证性使其成为 RLVR 的最佳场景
  3. GRPO 算法:通过 group-relative advantage 估计避免训练 value model,节省内存和计算
  4. DeepSeek-R1:证明了纯 RL 可以让模型自发发展出长链推理能力
  5. PRM vs ORM:过程奖励提供更细粒度的信号,但标注成本更高
  6. 其他 Verifiable Rewards:代码执行、事实性验证、格式约束等

下一讲将讨论 DPO、Expert Iteration 等更多 alignment 方法,以及前沿的 reasoning 和 test-time compute scaling 方向。