过程奖励与验证器快速开始:1 小时训出第一个 PRM
七 天实战
本页对应 7天学会 过程奖励与验证器 的 Day 1–3,子站提供标注好的数据集与训练脚本。
一、环境
pip install torch transformers datasets accelerate peft
# 单卡 24 GB 足够:用 1.5B~3B 的 base 模型当 PRM 基座
| 组件 | 建议 | 说明 |
|---|---|---|
| 基座 | Qwen2.5-1.5B-Instruct 或同规模 | PRM 只需「判断」,不需要生成能力 |
| 数据 | GSM8K(7.5k 题,带标准答案) | 有可靠的结果验证器(数值匹配) |
| 标注 | 结果回测, | 每题每步 8 次补全 |
| 显存 | 24 GB(训练) | LoRA 可降到 12 GB |
二、第一步:把解答切成「步」
import re
STEP_PAT = re.compile(r"(?<=[.。\n])\s*(?=(?:Step|\d+[\.\)]|第\s*\d+\s*步))", re.I)
def split_steps(solution: str) -> list[str]:
"""按显式步标记切分;若无标记,按句子切并合并过短句"""
parts = [p.strip() for p in STEP_PAT.split(solution) if p.strip()]
if len(parts) <= 1:
parts = [s.strip() + "." for s in re.split(r"(?<=[.。])\s+", solution) if s.strip()]
# 合并过短的片段(< 15 字符)
out, buf = [], ""
for p in parts:
buf = (buf + " " + p).strip() if buf else p
if len(buf) >= 15:
out.append(buf); buf = ""
if buf: out.append(buf)
return out
切分粒度是 PRM 的隐性超参
切太细(每个算式一步)→ 标签噪声大、序列长、训练慢;切太粗(整段推理一步)→ 退化成 ORM。
经验:每步 1–3 个句子、含 1 个明确结论。GSM8K 上平均 4–8 步/题是合理区间。如果你的切分让平均步数 > 15,多半是切太细了。
三、第二步:结果回测自动标注
import torch
from collections import Counter
@torch.no_grad()
def label_prefix_value(model, tok, problem, prefix, n=8, max_new=256, temp=0.8):
"""对前缀做 n 次补全,用最终答案正确率当该步的软标签"""
prompt = f"问题:{problem}\n解答:{prefix}"
inputs = tok(prompt, return_tensors="pt").to(model.device)
outs = model.generate(
**inputs, max_new_tokens=max_new, do_sample=True, temperature=temp,
num_return_sequences=n, pad_token_id=tok.eos_token_id)
succ = 0
for o in outs:
text = tok.decode(o[inputs.input_ids.shape[1]:], skip_special_tokens=True)
if answer_matches(problem, text): # 数值/表达式精确匹配
succ += 1
return succ / n
def answer_matches(problem, completion):
gold = GSM8K_ANSWERS[problem]
pred = extract_last_number(completion) # 取最后一个数字
return pred is not None and abs(pred - gold) < 1e-6
成本估算(务必先算):200 题 × 6 步 × 8 次 × 256 token ≈ 250 万 token 生成。在单张 A100 上约 40–60 分钟。用 1.5B 模型可以快 3 倍,但标签质量下降——建议用比被评测模型强一档的模型做 rollout。
四、第三步:构造训练样本
PRM 的训练格式:(问题, 前缀[0..t], 标签)。正负样本都要有。
def build_prm_dataset(items, neg_ratio=1.0):
"""items: [(problem, steps, step_labels)] ;负样本 = 首个错误步的前缀"""
rows = []
for problem, steps, labels in items:
prefix = ""
for t, (st, lb) in enumerate(zip(steps, labels)):
prefix = (prefix + "\n" + st).strip()
rows.append({"prompt": f"问题:{problem}\n解答:{prefix}",
"label": float(lb)}) # 软标签 0~1
if lb < 0.5 and neg_ratio > 0: # 首个错误步之后不再累积
break
return rows
| 设计选择 | 推荐 | 理由 |
|---|---|---|
| 标签类型 | 软标签(回归/MSE 或 BCE with soft target) | 保留「部分可行」信息 |
| 负样本比例 | 30%–50% | 太少学不到「识别错误」 |
| 截断位置 | 首个错误步之后截断 | 避免「已知错的链」污染 |
| 序列长度 | 1024–2048 | 覆盖 95% 样本 |
五、第四步:训练 PRM
from transformers import AutoModelForSequenceClassification, Trainer, TrainingArguments
model = AutoModelForSequenceClassification.from_pretrained(
"Qwen/Qwen2.5-1.5B-Instruct", num_labels=1, torch_dtype=torch.bfloat16)
def collate(batch):
texts = [b["prompt"] for b in batch]
labels = torch.tensor([b["label"] for b in batch], dtype=torch.float32)
enc = tok(texts, padding=True, truncation=True, max_length=2048,
return_tensors="pt")
enc["labels"] = labels
return enc
args = TrainingArguments(
output_dir="prm-out", num_train_epochs=2, learning_rate=2e-5,
per_device_train_batch_size=4, gradient_accumulation_steps=8,
bf16=True, logging_steps=20, save_strategy="epoch",
warmup_ratio=0.05, lr_scheduler_type="cosine")
损失选择:用 MSE(对软标签)或 BCEWithLogitsLoss 配合软目标。不要用交叉熵二分类 + 硬标签——会丢掉软标签的核心价值。