推理时计算:大模型能力提升的新维度

传统提升模型能力的方式是"训练时计算扩展"——更多参数、更多数据、更多训练算力。OpenAI o1开创了"推理时计算扩展"——在推理阶段投入更多计算来获得更好的输出。这就像人类的System 2思维:花更多时间思考,得到更准确的答案。

核心技术原理

隐式思维链

o1的标志性特征是"隐式思维链"——模型在生成最终回答前,先在内部进行长链推理:

传统模型:
用户问题 → 模型直接回答(快速但可能出错)

o1模型:
用户问题 → 内部推理(可能数百步)→ 最终回答(慢但准确)

关键区别:o1的推理过程不是通过prompt引导的(如"让我们一步步思考"),而是通过训练内化的。模型学会了在生成答案前先"思考"。

过程奖励模型(PRM)

o1的核心技术之一是过程奖励模型,它评估推理过程中每一步的质量:

class ProcessRewardModel:
    def __init__(self, base_model):
        self.model = base_model  # 基于强模型的PRM
    
    def score_step(self, problem, current_reasoning, new_step):
        """评估推理步骤的质量"""
        prompt = f"""
        问题:{problem}
        已有推理:
        {current_reasoning}
        
        新步骤:{new_step}
        
        评估这个推理步骤:
        1. 正确性(1-10):这一步的推理是否正确
        2. 相关性(1-10):这一步是否与解决问题相关
        3. 进展性(1-10):这一步是否推进了解题
        
        输出JSON。
        """
        result = self.model.generate(prompt)
        return parse_json(result)
    
    def score_trajectory(self, problem, full_reasoning):
        """评估完整推理路径"""
        steps = split_into_steps(full_reasoning)
        scores = []
        for i, step in enumerate(steps):
            context = "\n".join(steps[:i])
            score = self.score_step(problem, context, step)
            scores.append(score)
        return scores

PRM与结果奖励模型(ORM)的区别:

  • ORM只评估最终答案对不对
  • PRM评估每一步对不对,可以在错误发生时及时发现
  • PRM允许在推理过程中做搜索

推理时搜索

class InferenceTimeSearch:
    def __init__(self, model, prm, search_config):
        self.model = model
        self.prm = prm
        self.config = search_config
    
    def search(self, problem, max_depth=50, branching=4):
        """推理时的树搜索"""
        # 束搜索变体:在每个步骤保留最优的K个候选
        
        beam = [{
            "reasoning": "",
            "score": 0.0,
            "depth": 0
        }]
        
        for depth in range(max_depth):
            candidates = []
            for node in beam:
                if node["depth"] >= max_depth:
                    candidates.append(node)
                    continue
                
                # 生成多个候选步骤
                steps = self.model.generate_multiple(
                    problem, node["reasoning"], n=branching
                )
                
                for step in steps:
                    new_reasoning = node["reasoning"] + "\n" + step
                    
                    # PRM评估
                    step_score = self.prm.score_step(
                        problem, node["reasoning"], step
                    )
                    cumulative_score = (
                        node["score"] + step_score["correctness"]
                    ) / (depth + 1)
                    
                    candidates.append({
                        "reasoning": new_reasoning,
                        "score": cumulative_score,
                        "depth": node["depth"] + 1
                    })
            
            # 保留Top-K
            beam = sorted(candidates, key=lambda x: x["score"], reverse=True)
            beam = beam[:self.config["beam_width"]]
            
            # 检查是否找到答案
            best = beam[0]
            if self._has_answer(best["reasoning"]):
                return self._extract_answer(best["reasoning"])
        
        return self._extract_answer(beam[0]["reasoning"])

训练方法推测

推理数据生成

o1需要大量高质量的推理数据来训练。这些数据可能来自:

class ReasoningDataGenerator:
    def __init__(self, strong_model, verifier):
        self.model = strong_model
        self.verifier = verifier
    
    def generate_reasoning_traces(self, problem, answer, n_traces=8):
        """为有标准答案的问题生成推理路径"""
        traces = []
        for _ in range(n_traces):
            # 强模型生成推理过程
            trace = self.model.generate(f"""
            问题:{problem}
            标准答案:{answer}
            
            请生成详细的推理过程,最终得到答案{answer}            """, temperature=0.8)
            
            # 验证推理正确性
            if self.verifier.verify(problem, trace, answer):
                traces.append(trace)
        
        return traces
    
    def self_play_reasoning(self, problem):
        """通过自我博弈生成推理数据"""
        # 两个模型交替生成推理步骤
        reasoning = ""
        while not is_complete(reasoning):
            # Generator生成下一步
            step = self.model.generate(f"问题:{problem}\n推理:{reasoning}\n下一步:")
            reasoning += step
            
            # Verifier评估
            eval_result = self.verifier.evaluate(problem, reasoning)
            if eval_result["error"]:
                # 生成修正步骤
                correction = self.model.generate(
                    f"推理有误:{eval_result['error']}\n请修正。"
                )
                reasoning += correction
        
        return reasoning

强化学习训练

class ReasoningRLTrainer:
    def __init__(self, model, prm):
        self.model = model
        self.prm = prm
    
    def train_step(self, problem):
        # 1. 模型生成推理路径
        reasoning = self.model.generate(problem)
        
        # 2. PRM评估每一步
        step_scores = self.prm.score_trajectory(problem, reasoning)
        
        # 3. 计算奖励
        # 每一步的奖励 = 该步PRM分数 + 最终答案正确性
        final_correct = check_answer(problem, reasoning)
        rewards = []
        for i, score in enumerate(step_scores):
            reward = score["correctness"] * 0.1  # 过程奖励
            if i == len(step_scores) - 1:
                reward += 1.0 if final_correct else -0.5  # 结果奖励
            rewards.append(reward)
        
        # 4. PPO优化
        loss = self._ppo_loss(problem, reasoning, rewards)
        loss.backward()

推理时计算的最优分配

自适应计算分配

不同难度的问题应该分配不同的推理时间:

class AdaptiveCompute:
    def __init__(self, model, difficulty_classifier):
        self.model = model
        self.classifier = difficulty_classifier
    
    def answer(self, question):
        # 1. 评估问题难度
        difficulty = self.classifier.classify(question)
        
        # 2. 分配推理预算
        if difficulty == "easy":
            budget = 100  # tokens
        elif difficulty == "medium":
            budget = 1000
        elif difficulty == "hard":
            budget = 10000
        else:  # extreme
            budget = 50000
        
        # 3. 生成答案
        return self.model.generate(
            question,
            max_thinking_tokens=budget
        )

计算效率分析

def compute_accuracy_vs_cost(model, problems, budgets):
    """评估不同推理预算下的准确率"""
    results = {}
    for budget in budgets:
        correct = 0
        total_cost = 0
        
        for problem in problems:
            response = model.generate(
                problem["question"],
                max_thinking_tokens=budget
            )
            if check_answer(response, problem["answer"]):
                correct += 1
            total_cost += count_tokens(response)
        
        results[budget] = {
            "accuracy": correct / len(problems),
            "avg_cost": total_cost / len(problems),
            "cost_per_correct": total_cost / correct if correct > 0 else float('inf')
        }
    
    return results

典型结果:

思考预算准确率平均tokens每正确答案成本
0 (直接回答)45%200444
50062%600968
200078%21002692
1000085%80009412
5000087%3000034483

收益递减效应明显:从500到2000提升16%,从10000到50000仅提升2%。

开源复现方案

Open-R1项目

社区正在积极复现o1的推理能力:

# 使用开源模型复现推理时计算扩展
class OpenR1:
    def __init__(self):
        self.model = AutoModelForCausalLM.from_pretrained(
            "deepseek-ai/DeepSeek-R1-Distill-Qwen-32B"
        )
        self.prm = AutoModelForSequenceClassification.from_pretrained(
            "OpenAssistant/reward-model-deberta-v3-large-v2"
        )
    
    def reason_and_answer(self, question):
        # 1. 生成多条推理路径
        traces = self._generate_traces(question, n=8)
        
        # 2. PRM评估
        scored = [(t, self.prm.score(question, t)) for t in traces]
        scored.sort(key=lambda x: x[1], reverse=True)
        
        # 3. 返回最优路径的答案
        return self._extract_answer(scored[0][0])

适用场景分析

适合推理时计算扩展的场景

  1. 数学竞赛题:需要多步严密推理
  2. 编程难题:需要设计算法并验证
  3. 逻辑推理:需要严格的演绎推理
  4. 科学问题:需要综合多个知识点

不适合的场景

  1. 简单问答:推理开销大于收益
  2. 创意写作:推理不会提升创意
  3. 日常对话:不需要复杂推理
  4. 实时交互:延迟不可接受

结语

推理时计算扩展代表了AI能力提升的新范式——从"更大模型"到"更长时间思考"。这种范式的意义在于:它更接近人类的认知模式——遇到难题时停下来想,而不是凭直觉回答。随着推理搜索算法的优化和过程奖励模型的改进,推理时计算扩展的效率将持续提升,成为AI系统的标准能力。