跳转至

math_verify.py — 这个文件使用第三方库 math-verify(HuggingFace 开发)来进行更精确的数...

模块路径: verl.utils.reward_score.math_verify

文件概述

这个文件使用第三方库 math-verify(HuggingFace 开发)来进行更精确的数学答案验证。相比 math_reward.py 中基于字符串的比较,math-verify 能够进行符号计算级别的等价判断。

需要手动安装:pip install math-verify。

关键代码讲解

1. 依赖导入(带容错)

try:
    from math_verify.errors import TimeoutException
    from math_verify.metric import math_metric
    from math_verify.parser import ExprExtractionConfig, LatexExtractionConfig
except ImportError:
    print("To use Math-Verify, please install it first by running `pip install math-verify`.")

使用 try-except 处理库未安装的情况,给出友好提示。

2. 评分函数

def compute_score(model_output: str, ground_truth: str, timeout_score: float = 0) -> bool:
    verify_func = math_metric(
        gold_extraction_target=(LatexExtractionConfig(),),       # 标准答案用 LaTeX 解析
        pred_extraction_target=(ExprExtractionConfig(), LatexExtractionConfig()),  # 模型输出先尝试表达式解析,再尝试 LaTeX
    )
    ground_truth_boxed = "\\boxed{" + ground_truth + "}"  # 包装成 \boxed{} 格式
    try:
        ret_score, _ = verify_func([ground_truth_boxed], [model_output])
    except Exception:
        pass
    except TimeoutException:
        ret_score = timeout_score  # 超时返回指定分数
    return ret_score

核心流程: 1. 创建一个验证函数,配置如何从标准答案和模型输出中提取数学表达式 2. 将标准答案包装成 \boxed{...} 格式 3. 调用验证函数判断等价性

核心类/函数列表

函数名 作用
compute_score 使用 math-verify 库进行精确数学等价验证

与其他模块的关系

  • 是 math_reward.py 的可选替代,精度更高
  • 在 __init__.py 中有注释说明如何替换使用
  • 需要额外安装 math-verify 库

小结

math-verify 是一个更强大但需要额外安装的验证工具。它能处理更多数学等价情况(如 1/2 = 0.5),适合需要高精度评分的场景。在 __init__.py 的注释中可以看到替换方法。