""" Math-Shepherd 步进监督数据上的幻觉 span 评测。 数据约定(见同目录 ``README.md``): - ``prompt`` / ``pompt``:题目 - ``completions``:与 ``labels`` **等长** 的逐步推理字符串列表 - ``labels``:与逐步一一对应;**true = 该步正确(非幻觉)**,**false = 该步为幻觉** 金标:将 ``completions`` 用 ``\\n`` 拼成整段 ``response``,对每个 ``labels[i] is False`` 的步骤, 将该步在整段中的字符区间 ``[start, end)`` 记入金标 span。该实现的预测起点会 参考金标错误步骤的起点;这是本脚本的评测规则,未证实与论文的原始实现一致。 **预测解析(与本仓库其它 eval 不同)**: - ``parse_output`` 得到 ``hallucination list`` 后,若列表**为空** → 判为**无幻觉**; - 若**非空**:对每个元素在 ``response`` 中定位子串,取成功匹配中**最靠左的 start** ``P``, 再将 ``P`` **对齐**到金标 ``labels`` 各 span 的 ``start``:取满足 ``s <= P`` 的最大 ``s``; 若 ``P`` 早于所有金标步起点,则对齐为 ``min(金标 starts)``。最终预测幻觉区为 ``[aligned_start, len(steps_text))``,``steps_text`` 与输入拼接一致(``STEP_SEP.join(completions)``)。 用法(与数据文件放在同一目录时):: python run_math_shepherd.py --model-name /path/to/checkpoint --model-url http://localhost:7010/v1 python run_math_shepherd.py --filepath test_result/example.jsonl # 仅重新计算指标 """ from __future__ import annotations import argparse import collections import json import os import re import sys import traceback from concurrent.futures import ThreadPoolExecutor, as_completed from datetime import datetime from glob import glob from typing import Any, Dict, List, Optional, Sequence, Tuple import pyarrow.parquet as pq from tqdm import tqdm _EVAL_DIR = os.path.dirname(os.path.abspath(__file__)) if _EVAL_DIR not in sys.path: sys.path.insert(0, _EVAL_DIR) from sopo_eval_common import ( # noqa: E402 MODEL_URL, _format_is_ok, compute_multi_spans, find_start_end_index, labels_have_any_supervision, parse_output, print_metrics, req_model_vllm, ) # README「Data sample」中的案例,用作可选 few-shot FEWSHOT_README_EXAMPLE_JSON = { "prompt": ( "Mr. Maxwell takes 1 hr to drive to work in the morning but 1 and half hours " "to drive back home in the evening. If the morning and evening traffic is similar " "and he drives at an average speed of 30mph in the morning, what is the average " "speed of his return journey?" ), "completions": [ "Step 1: Mr. Maxwell takes 1 and half hour to drive back home in the evening so he takes 1+1/2 = <<1+1/2=90>>90 minutes to drive home.", "Step 2: Mr. Maxwell takes 90 minutes to drive home and drives at an average speed of 30mph so he drives a distance of 90/30 = <<90/30=3>>3 miles.", "Step 3: Mr. Maxwell drives 3 miles in the evening at an average speed of 30mph so his average speed for the return journey is 30+3 = <<30+3=33>>33mph. The answer is: 33", ], "labels": [True, False, False], } MATH_SHEPHERD_TASK = "QA" STEP_SEP = "\n" def _format_fewshot_block() -> str: """README 案例,作为 few-shot 文本块。""" ex = FEWSHOT_README_EXAMPLE_JSON lines = [ "[Few-shot example]", "Problem:", ex["prompt"], "", "Step-by-step solution (each step may be correct or incorrect):", ] for i, (step, lab) in enumerate(zip(ex["completions"], ex["labels"]), 1): tag = "CORRECT" if lab else "INCORRECT (hallucination in this step)" lines.append(f"Step {i} [{tag}]: {step}") lines.append("") lines.append( "(In the actual task below, you only output the JSON with hallucination list per instruction; " "the above only illustrates step labels.)" ) return "\n".join(lines) def row_prompt(row: Dict[str, Any]) -> str: return str(row.get("prompt") or row.get("pompt") or "").strip() def row_completions(row: Dict[str, Any]) -> List[str]: c = row.get("completions") if c is None: return [] if hasattr(c, "tolist"): c = c.tolist() if not isinstance(c, (list, tuple)): return [] return [str(x) for x in c] def row_labels(row: Dict[str, Any]) -> List[bool]: raw = row.get("labels") if raw is None: return [] if hasattr(raw, "tolist"): raw = raw.tolist() if not isinstance(raw, (list, tuple)): return [] out: List[bool] = [] for x in raw: if isinstance(x, bool): out.append(x) elif isinstance(x, (int, float)): out.append(bool(int(x))) elif isinstance(x, str): out.append(x.strip().lower() in ("true", "1", "yes")) else: out.append(bool(x)) return out def completions_to_response_and_gold( completions: List[str], labels: List[bool] ) -> Tuple[str, List[Dict[str, int]]]: """ 将 steps 拼成 response;对每个 label==False 的步骤写入金标 span(字符级,与 STEP_SEP 一致)。 """ if len(completions) != len(labels): raise ValueError( f"completions 与 labels 须等长: {len(completions)} vs {len(labels)}" ) gold: List[Dict[str, int]] = [] pos = 0 n = len(completions) for i, step in enumerate(completions): start = pos end = pos + len(step) + (len(STEP_SEP) if i < n - 1 else 0) if not labels[i]: gold.append({"start": start, "end": end}) pos = end response = STEP_SEP.join(completions) if len(response) != pos and n > 0: # 理论上应相等;防御 pass return response, gold def build_math_shepherd_input_str(prompt: str, completions: List[str]) -> str: steps_text = STEP_SEP.join(completions) return ( f"Below is a question:\n{prompt}\n" f"Below is an answer:\n{steps_text}\n" """Your task is to identify logical inconsistencies, calculation errors, or hallucinations in the mathematical steps provided. First, perform a step-by-step verification of the reasoning process using the following format: Step 1: < verify the first mathematical transition/calculation > Step 2: < verify the subsequent logic and result > ...(add as many steps as needed) Then, compile any identified incorrect segments into a JSON dict. The "hallucination list" must contain the specific text spans from the input that are mathematically invalid. If the steps are entirely correct, leave the value as an empty list: {"hallucination list": []}. Otherwise, use this format: {"hallucination list": ["wrong span 1", "wrong span 2"]}.""" # """Your task is to determine whether the answer contains errors or hallucinations. First, provide reasoning with the following format: # ## Step 1: < your first reasoning step > # ## Step 2: < your next reasoning step > # ...(add as many steps as needed) # Then, compile the labeled hallucinated spans or error spans into a JSON dict, with a key hallucination list and its value is a list of hallucinated spans or error spans. If there are potential hallucinations or errors, the output should be in the following JSON format: {"hallucination list": [error span1, error span2, ...]}. Otherwise, leave the value as an empty list as follows: {"hallucination list": []}.""" ) def build_user_instruction( prompt: str, completions: List[str], reasoning: bool, fewshot: bool, ) -> str: if fewshot: ins_ori = _format_fewshot_block() + "\n\n---\n\n" + build_math_shepherd_input_str( prompt, completions ) else: ins_ori = build_math_shepherd_input_str(prompt, completions) if not reasoning: ins_ori = ins_ori.rsplit("Your task", 1)[0] + ( 'Your task is to identify mathematically incorrect steps in the answer. ' 'Return only a JSON dict containing the exact erroneous text spans: ' '{"hallucination list": ["wrong span 1"]}. ' 'If all steps are correct, return {"hallucination list": []}.' ) return ins_ori def align_pred_start_to_gold_step_starts( min_s: int, gold_labels: List[Dict[str, Any]] ) -> int: """ 将模型子串匹配得到的最左 start ``min_s``,对齐到金标步边界: 在 ``gold_labels`` 中所有 ``start`` 里,取满足 ``s <= min_s`` 的**最大** ``s`` (即 ``min_s`` 左侧最近的步起点,含相等);若 ``min_s`` 早于任一金标步起点, 则回退为 ``min(gold_starts)``。无金标时返回 ``min_s``。 """ if not gold_labels: return min_s gold_starts = sorted({int(l["start"]) for l in gold_labels}) left = [s for s in gold_starts if s <= min_s] if left: return max(left) return gold_starts[0] def cal_metrics_math_shepherd( response: str, labels: List[Dict[str, Any]], output_list: List[str], completions: Optional[List[str]] = None, ) -> Tuple[int, int, int, int, int, int, int]: """ 金标 spans 与通用 eval 相同;预测侧:空列表则无幻觉;否则取各子串最左 start, 再对齐到金标步 ``start``,最后预测幻觉区为 ``[aligned_start, len(steps_text))``, 其中 ``steps_text = STEP_SEP.join(completions)``(与 ``build_math_shepherd_input_str`` 一致)。 若未传 ``completions``(旧 jsonl),则右端退化为 ``len(response)``。 """ ground_truth_span: List[Tuple[int, int]] = [ (int(l["start"]), int(l["end"])) for l in labels ] predict_span: List[Tuple[int, int]] = [] if output_list: starts: List[int] = [] for out in output_list: if not isinstance(out, str): continue tup = find_start_end_index(response, out, strict=False) if tup != (-1, -1): starts.append(tup[0]) if starts: min_s = min(starts) aligned = align_pred_start_to_gold_step_starts(min_s, labels) end_len = ( len(STEP_SEP.join(str(c) for c in completions)) if completions is not None else len(response) ) predict_span.append((aligned, end_len)) match_size, prediction, groud_truth = compute_multi_spans( ground_truth_span, predict_span ) pos_true_cnt, neg_true_cnt, neg_false_cnt, pos_false_cnt = 0, 0, 0, 0 if output_list != [] and labels != []: pos_true_cnt += 1 elif output_list == [] and labels != []: neg_true_cnt += 1 elif output_list == [] and labels == []: neg_false_cnt += 1 elif output_list != [] and labels == []: pos_false_cnt += 1 else: raise RuntimeError( f"unexpected case output_list={output_list!r} labels={labels!r}" ) return ( match_size, prediction, groud_truth, pos_true_cnt, neg_true_cnt, neg_false_cnt, pos_false_cnt, ) def evaluate_math_shepherd_results( results: List[Dict[str, Any]], record: Dict[str, int], filepath: str, ) -> List[Dict[str, Any]]: chosen: Sequence[str] = ["Math", "All"] for sample in results: response = sample["response"] labels = sample["labels"] output = sample["output"] task = sample.get("task_type") or "Math" res = cal_metrics_math_shepherd( response, labels, output, sample.get("completions") ) ( temp_tp, temp_pred_len, temp_gold_len, pos_true_cnt, neg_true_cnt, neg_false_cnt, pos_false_cnt, ) = res for task_cur in chosen: if task_cur == task or task_cur == "All": record["match_size_" + task_cur] += temp_tp record["prediction_" + task_cur] += temp_pred_len record["groud_truth_" + task_cur] += temp_gold_len record["pos_true_cnt_" + task_cur] += pos_true_cnt record["neg_true_cnt_" + task_cur] += neg_true_cnt record["neg_false_cnt_" + task_cur] += neg_false_cnt record["pos_false_cnt_" + task_cur] += pos_false_cnt all_metrics: List[Dict[str, Any]] = [] for task_cur in chosen: all_metrics.append(print_metrics(task_cur, record)) print("chosen task: {}".format(list(chosen))) print("filepath: {}".format(filepath)) print("test_data_size: {}".format(len(results))) return all_metrics def iter_parquet_rows(paths: List[str]): idx = 0 for path in paths: pf = pq.ParquetFile(path) for batch in pf.iter_batches(batch_size=256): d = batch.to_pydict() if not d: continue keys = list(d.keys()) n = len(d[keys[0]]) for i in range(n): row = {k: d[k][i] for k in keys} yield idx, row idx += 1 def resolve_test_parquets(data_dir: str) -> List[str]: paths = sorted(glob(os.path.join(data_dir, "test*.parquet"))) paths += sorted(glob(os.path.join(data_dir, "math_shepherd*.parquet"))) return sorted(set(paths)) def process_single_item( d: Dict[str, Any], row_key: str, model_name: str, model_url: str, max_tokens: int, reasoning: bool, fewshot: bool, ) -> Optional[Dict[str, Any]]: prompt = row_prompt(d) completions = row_completions(d) labels = row_labels(d) if not prompt or not completions: return None if len(completions) != len(labels): print( f"skip {row_key}: completions/labels length mismatch " f"{len(completions)} vs {len(labels)}", file=sys.stderr, ) return None try: response, gold_spans = completions_to_response_and_gold(completions, labels) instruction = build_user_instruction(prompt, completions, reasoning, fewshot) raw = req_model_vllm( instruction, model_name=model_name, model_url=model_url, max_tokens=max_tokens ) if not _format_is_ok(raw): raise ValueError("model output could not be parsed after retries") output_parsed = parse_output(raw) if not isinstance(output_parsed, list) or not all( isinstance(x, str) for x in output_parsed ): raise ValueError("hallucination list must be a list of strings") return { "id": row_key, "response": response, "labels": gold_spans, "output": output_parsed, "output_raw": raw, "task_type": "Math", "prompt": prompt, "completions": completions, "step_labels": labels, "pred_rule": "empty_hallucination_list=>no_hallucination; " "else min_matched_start_then_align_to_gold_step_start_then_suffix_to_eof", } except Exception as e: print(f"Error {row_key}: {e}") traceback.print_exc() return None def main() -> None: parser = argparse.ArgumentParser() input_group = parser.add_mutually_exclusive_group() input_group.add_argument( "--data-file", default=os.path.join(_EVAL_DIR, "math_shepherd_614_test_20260327.parquet"), help="Math-Shepherd Parquet file (default: file next to this script)", ) input_group.add_argument( "--data-dir", help="Directory of test*.parquet / math_shepherd*.parquet files", ) parser.add_argument("--filepath", default="", help="Existing JSONL; recompute metrics only") parser.add_argument("--model-name", help="Model identifier served by the OpenAI-compatible API") parser.add_argument("--model-url", default=MODEL_URL, help="OpenAI-compatible vLLM base URL") parser.add_argument("--model-prefix", default="", help="Optional result filename prefix") parser.add_argument("--output-dir", default=os.path.join(_EVAL_DIR, "test_result")) parser.add_argument("--max-tokens", type=int, default=8000) parser.add_argument("--num-threads", "--num_threads", type=int, default=32) parser.add_argument( "--max-samples", "--max_samples", type=int, default=0, help=">0 processes first N rows only", ) parser.add_argument( "--no-reasoning", action="store_true", help="Omit the reasoning template; ask for JSON only", ) parser.add_argument( "--fewshot", action="store_true", help="在题目前拼接 README 中的案例作为 few-shot", ) args = parser.parse_args() metrics_only = bool(args.filepath) reasoning = not args.no_reasoning if not args.filepath and not args.model_name: parser.error("--model-name is required for inference; use --filepath for metric-only mode") if args.num_threads < 1 or args.max_tokens < 1 or args.max_samples < 0: parser.error("--num-threads and --max-tokens must be positive; --max-samples must be nonnegative") results: List[Dict[str, Any]] = [] if not args.filepath: paths = resolve_test_parquets(args.data_dir) if args.data_dir else [args.data_file] if not paths or not all(os.path.isfile(path) for path in paths): parser.error(f"Parquet data not found: {paths}; specify --data-file or --data-dir") rows: List[Tuple[str, Dict[str, Any]]] = [] for global_idx, d in iter_parquet_rows(paths): if args.max_samples and len(rows) >= args.max_samples: break rows.append((str(global_idx), d)) total_items = len(rows) with ThreadPoolExecutor(max_workers=args.num_threads) as ex: futs = { ex.submit( process_single_item, d, rk, args.model_name, args.model_url, args.max_tokens, reasoning, args.fewshot, ): rk for rk, d in rows } with tqdm(total=total_items, desc="math_shepherd") as pbar: for fut in as_completed(futs): res = fut.result() if res is not None: results.append(res) pbar.update(1) if len(results) != total_items: raise RuntimeError( f"Only {len(results)}/{total_items} rows evaluated; refusing incomplete metrics. " "Check errors above and retry." ) results.sort(key=lambda x: int(x["id"])) _date = datetime.now().strftime("%Y%m%d_%H%M%S_%f") out_dir = args.output_dir os.makedirs(out_dir, exist_ok=True) basename = re.sub( r"[^a-zA-Z0-9_.-]+", "_", f"{args.model_prefix}_{args.model_name}" ).strip("._") output_path = os.path.join( out_dir, f"{basename}_math_shepherd_test_{_date}.jsonl", ) with open(output_path, "w", encoding="utf-8") as f: for res in results: f.write(json.dumps(res, ensure_ascii=False) + "\n") args.filepath = output_path else: with open(args.filepath, "r", encoding="utf-8") as f: for line in f: results.append(json.loads(line)) if not labels_have_any_supervision(results): print("警告: 结果中无任何 gold labels,跳过指标计算。") return record: Dict[str, int] = collections.defaultdict(int) all_metrics = evaluate_math_shepherd_results(results, record, args.filepath) output_path_metric = os.path.splitext(args.filepath)[0] + ( "_recomputed_metric.json" if metrics_only else "_metric.json" ) metrics_output = { "filepath": args.filepath, "data_files": paths if not metrics_only else None, "test_data_size": len(results), "model_name": args.model_name, "model_url": args.model_url if not metrics_only else None, "max_tokens": args.max_tokens if not metrics_only else None, "num_threads": args.num_threads if not metrics_only else None, "fewshot": args.fewshot if not metrics_only else None, "reasoning_suffix": reasoning if not metrics_only else None, "pred_rule": "empty_hallucination_list=>no_hallucination; " "else min_matched_start_then_align_to_gold_step_start_then_suffix_to_eof", "metrics": all_metrics, "timestamp": datetime.now().strftime("%Y%m%d_%H%M%S"), } with open(output_path_metric, "w", encoding="utf-8") as f: json.dump(metrics_output, f, ensure_ascii=False, indent=2) print(f"\nMetrics saved to: {output_path_metric}") if __name__ == "__main__": main()