Datasets:
Add Math-Shepherd-614 test data and evaluation scripts
Browse files- README.md +74 -0
- math_shepherd_614_test_20260327.parquet +3 -0
- requirements.txt +4 -0
- run_math_shepherd.py +531 -0
- sopo_eval_common.py +476 -0
- test_run_math_shepherd.py +107 -0
README.md
ADDED
|
@@ -0,0 +1,74 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
pretty_name: Math-Shepherd-614 (SOPO evaluation subset)
|
| 3 |
+
task_categories:
|
| 4 |
+
- text-classification
|
| 5 |
+
tags:
|
| 6 |
+
- math-shepherd
|
| 7 |
+
- stepwise-verification
|
| 8 |
+
- hallucination-detection
|
| 9 |
+
data_files:
|
| 10 |
+
- split: test
|
| 11 |
+
path: math_shepherd_614_test_20260327.parquet
|
| 12 |
+
---
|
| 13 |
+
|
| 14 |
+
# Math-Shepherd-614 evaluation subset
|
| 15 |
+
|
| 16 |
+
This repository packages a **614-example** Math-Shepherd step-verification test subset and a runnable evaluation script. It is intended to document the evaluation data relevant to the [SOPO paper](https://arxiv.org/html/2610.32212) (Appendix F.4); the exact selection procedure and the authors' original Math-Shepherd scoring implementation have **not** been independently confirmed. The data file alone and the accompanying script should **not** be represented as independently reproducing the paper's 89.02 mean span-F1.
|
| 17 |
+
|
| 18 |
+
## Dataset
|
| 19 |
+
|
| 20 |
+
The Parquet file `math_shepherd_614_test_20260327.parquet` contains 614 rows with three columns:
|
| 21 |
+
|
| 22 |
+
- `prompt`: the math problem.
|
| 23 |
+
- `completions`: an ordered list of solution steps.
|
| 24 |
+
- `labels`: one Boolean per step; `true` means correct and `false` means incorrect.
|
| 25 |
+
|
| 26 |
+
The file has 1,794 correctly labeled and 1,395 incorrectly labeled steps. There are 334 examples with at least one incorrect step and 280 with no incorrect steps. Every row (including its step text and labels) was found as an exact match in the publicly available [`trl-lib/math_shepherd` test split](https://huggingface.co/datasets/trl-lib/math_shepherd). This demonstrates provenance at the *record* level; it does not prove how the original paper selected its subset. The Parquet file's SHA-256 is `e01fabbc80b99f01307aa9095b9e186f13cae392ed0bff983dcbdd61ee0d1087`.
|
| 27 |
+
|
| 28 |
+
Load the dataset with `datasets` (install it separately with `python -m pip install datasets`), or read the Parquet file with `pyarrow`:
|
| 29 |
+
|
| 30 |
+
```python
|
| 31 |
+
from datasets import load_dataset
|
| 32 |
+
|
| 33 |
+
test = load_dataset("OverwhelmingFit/SOPO-Math-Shepherd-614", split="test")
|
| 34 |
+
print(len(test)) # 614
|
| 35 |
+
```
|
| 36 |
+
|
| 37 |
+
The repository is **private pending confirmation of the upstream data's redistribution terms**. Access requires authorization and a Hugging Face login (`hf auth login`); the code above works for authorized users. This release includes **test data only**; it is not a training split.
|
| 38 |
+
|
| 39 |
+
## Evaluate using a local OpenAI-compatible vLLM endpoint
|
| 40 |
+
|
| 41 |
+
Place `run_math_shepherd.py`, `sopo_eval_common.py`, the Parquet file, and `requirements.txt` in the **same directory**. Python 3.9+ is recommended.
|
| 42 |
+
|
| 43 |
+
```bash
|
| 44 |
+
python -m pip install -r requirements.txt
|
| 45 |
+
python -m unittest discover -s . -p test_run_math_shepherd.py # offline validation, no model server
|
| 46 |
+
python run_math_shepherd.py \
|
| 47 |
+
--data-file math_shepherd_614_test_20260327.parquet \
|
| 48 |
+
--model-name YOUR_SERVED_MODEL_NAME \
|
| 49 |
+
--model-url http://localhost:7010/v1 \
|
| 50 |
+
--num-threads 32 \
|
| 51 |
+
--output-dir ./test_result
|
| 52 |
+
```
|
| 53 |
+
|
| 54 |
+
`--model-name` must match the model name exposed by your vLLM OpenAI-compatible server. The default endpoint is `http://localhost:7010/v1`, the default generation limit is 8,000 tokens, and a complete run should write 614 JSON Lines records plus a `_metric.json` file. The API client sends `api_key="EMPTY"` for local vLLM. Use `--max-samples N` only for a quick smoke test; it is **not** the full 614-example evaluation. You can recompute metrics from a saved run without contacting the model:
|
| 55 |
+
|
| 56 |
+
```bash
|
| 57 |
+
python run_math_shepherd.py --filepath ./test_result/YOUR_RUN.jsonl
|
| 58 |
+
```
|
| 59 |
+
|
| 60 |
+
The metric-only command writes a separate `_recomputed_metric.json` file and leaves the original `_metric.json` intact.
|
| 61 |
+
|
| 62 |
+
The paper reports a mean over **10 inference runs**. To obtain comparable *run counts* with this script, invoke the full command 10 separate times, check each output's `test_data_size` is 614, and average the `metrics` entry for `All` → `span_level` → `f1` from the ten `_metric.json` files. This alone does **not** establish equivalence to the paper's unpublished prompt, decoding and scoring settings.
|
| 63 |
+
|
| 64 |
+
### Exact scoring behavior of this implementation
|
| 65 |
+
|
| 66 |
+
1. Concatenate `completions` with a **single newline** to form the evaluated response. Each step labeled `false` becomes a gold character span, including the separator newline following that step (except the last).
|
| 67 |
+
2. Ask the model for a JSON `"hallucination list"` containing copied erroneous text spans; retry malformed responses up to three times (first attempt with temperature 0, retries at 0.4). Invalid model outputs abort the complete run rather than being silently scored as no hallucination.
|
| 68 |
+
3. An empty list yields no predicted span. For a nonempty list, find the earliest successfully located text substring in the response. **Align this position using the starts of gold incorrect steps**, then predict the entire suffix from that aligned point to the response end. The overlap of predicted and gold character positions determines micro-aggregated span precision, recall, and F1. The script also reports case-level metrics.
|
| 69 |
+
|
| 70 |
+
**Important limitation:** step 3 uses the gold annotations when constructing the predicted span. This is a *label-dependent scoring rule*, which can affect the resulting F1 and is not a standard gold-independent conversion of predictions to spans. We have not verified that this rule matches the SOPO authors' original Math-Shepherd protocol. Share results with the rule disclosed; do not label this implementation an exact reproduction of 89.02 without confirming the original protocol and running the original model.
|
| 71 |
+
|
| 72 |
+
## Source and redistribution
|
| 73 |
+
|
| 74 |
+
This subset's records match the `trl-lib/math_shepherd` test split, which attributes its processed format to the [Math-Shepherd project](https://huggingface.co/datasets/peiyi9979/Math-Shepherd). See the original dataset and paper for citations. The upstream TRL dataset card does not state a license; **confirm the applicable data terms before making a new public repository**. This dataset card does not assign a new license to third-party data.
|
math_shepherd_614_test_20260327.parquet
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:e01fabbc80b99f01307aa9095b9e186f13cae392ed0bff983dcbdd61ee0d1087
|
| 3 |
+
size 240015
|
requirements.txt
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
pyarrow>=14
|
| 2 |
+
openai>=1.40,<1.60
|
| 3 |
+
json-repair>=0.30
|
| 4 |
+
tqdm>=4.66
|
run_math_shepherd.py
ADDED
|
@@ -0,0 +1,531 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Math-Shepherd 步进监督数据上的幻觉 span 评测。
|
| 3 |
+
|
| 4 |
+
数据约定(见同目录 ``README.md``):
|
| 5 |
+
- ``prompt`` / ``pompt``:题目
|
| 6 |
+
- ``completions``:与 ``labels`` **等长** 的逐步推理字符串列表
|
| 7 |
+
- ``labels``:与逐步一一对应;**true = 该步正确(非幻觉)**,**false = 该步为幻觉**
|
| 8 |
+
|
| 9 |
+
金标:将 ``completions`` 用 ``\\n`` 拼成整段 ``response``,对每个 ``labels[i] is False`` 的步骤,
|
| 10 |
+
将该步在整段中的字符区间 ``[start, end)`` 记入金标 span。该实现的预测起点会
|
| 11 |
+
参考金标错误步骤的起点;这是本脚本的评测规则,未证实与论文的原始实现一致。
|
| 12 |
+
|
| 13 |
+
**预测解析(与本仓库其它 eval 不同)**:
|
| 14 |
+
- ``parse_output`` 得到 ``hallucination list`` 后,若列表**为空** → 判为**无幻觉**;
|
| 15 |
+
- 若**非空**:对每个元素在 ``response`` 中定位子串,取成功匹配中**最靠左的 start** ``P``,
|
| 16 |
+
再将 ``P`` **对齐**到金标 ``labels`` 各 span 的 ``start``:取满足 ``s <= P`` 的最大 ``s``;
|
| 17 |
+
若 ``P`` 早于所有金标步起点,则对齐为 ``min(金标 starts)``。最终预测幻觉区为
|
| 18 |
+
``[aligned_start, len(steps_text))``,``steps_text`` 与输入拼接一致(``STEP_SEP.join(completions)``)。
|
| 19 |
+
|
| 20 |
+
用法(与数据文件放在同一目录时)::
|
| 21 |
+
|
| 22 |
+
python run_math_shepherd.py --model-name /path/to/checkpoint --model-url http://localhost:7010/v1
|
| 23 |
+
python run_math_shepherd.py --filepath test_result/example.jsonl # 仅重新计算指标
|
| 24 |
+
"""
|
| 25 |
+
|
| 26 |
+
from __future__ import annotations
|
| 27 |
+
|
| 28 |
+
import argparse
|
| 29 |
+
import collections
|
| 30 |
+
import json
|
| 31 |
+
import os
|
| 32 |
+
import re
|
| 33 |
+
import sys
|
| 34 |
+
import traceback
|
| 35 |
+
from concurrent.futures import ThreadPoolExecutor, as_completed
|
| 36 |
+
from datetime import datetime
|
| 37 |
+
from glob import glob
|
| 38 |
+
from typing import Any, Dict, List, Optional, Sequence, Tuple
|
| 39 |
+
|
| 40 |
+
import pyarrow.parquet as pq
|
| 41 |
+
from tqdm import tqdm
|
| 42 |
+
|
| 43 |
+
_EVAL_DIR = os.path.dirname(os.path.abspath(__file__))
|
| 44 |
+
if _EVAL_DIR not in sys.path:
|
| 45 |
+
sys.path.insert(0, _EVAL_DIR)
|
| 46 |
+
|
| 47 |
+
from sopo_eval_common import ( # noqa: E402
|
| 48 |
+
MODEL_URL,
|
| 49 |
+
_format_is_ok,
|
| 50 |
+
compute_multi_spans,
|
| 51 |
+
find_start_end_index,
|
| 52 |
+
labels_have_any_supervision,
|
| 53 |
+
parse_output,
|
| 54 |
+
print_metrics,
|
| 55 |
+
req_model_vllm,
|
| 56 |
+
)
|
| 57 |
+
# README「Data sample」中的案例,用作可选 few-shot
|
| 58 |
+
FEWSHOT_README_EXAMPLE_JSON = {
|
| 59 |
+
"prompt": (
|
| 60 |
+
"Mr. Maxwell takes 1 hr to drive to work in the morning but 1 and half hours "
|
| 61 |
+
"to drive back home in the evening. If the morning and evening traffic is similar "
|
| 62 |
+
"and he drives at an average speed of 30mph in the morning, what is the average "
|
| 63 |
+
"speed of his return journey?"
|
| 64 |
+
),
|
| 65 |
+
"completions": [
|
| 66 |
+
"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.",
|
| 67 |
+
"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.",
|
| 68 |
+
"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",
|
| 69 |
+
],
|
| 70 |
+
"labels": [True, False, False],
|
| 71 |
+
}
|
| 72 |
+
|
| 73 |
+
MATH_SHEPHERD_TASK = "QA"
|
| 74 |
+
STEP_SEP = "\n"
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
def _format_fewshot_block() -> str:
|
| 78 |
+
"""README 案例,作为 few-shot 文本块。"""
|
| 79 |
+
ex = FEWSHOT_README_EXAMPLE_JSON
|
| 80 |
+
lines = [
|
| 81 |
+
"[Few-shot example]",
|
| 82 |
+
"Problem:",
|
| 83 |
+
ex["prompt"],
|
| 84 |
+
"",
|
| 85 |
+
"Step-by-step solution (each step may be correct or incorrect):",
|
| 86 |
+
]
|
| 87 |
+
for i, (step, lab) in enumerate(zip(ex["completions"], ex["labels"]), 1):
|
| 88 |
+
tag = "CORRECT" if lab else "INCORRECT (hallucination in this step)"
|
| 89 |
+
lines.append(f"Step {i} [{tag}]: {step}")
|
| 90 |
+
lines.append("")
|
| 91 |
+
lines.append(
|
| 92 |
+
"(In the actual task below, you only output the JSON with hallucination list per instruction; "
|
| 93 |
+
"the above only illustrates step labels.)"
|
| 94 |
+
)
|
| 95 |
+
return "\n".join(lines)
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
def row_prompt(row: Dict[str, Any]) -> str:
|
| 99 |
+
return str(row.get("prompt") or row.get("pompt") or "").strip()
|
| 100 |
+
|
| 101 |
+
|
| 102 |
+
def row_completions(row: Dict[str, Any]) -> List[str]:
|
| 103 |
+
c = row.get("completions")
|
| 104 |
+
if c is None:
|
| 105 |
+
return []
|
| 106 |
+
if hasattr(c, "tolist"):
|
| 107 |
+
c = c.tolist()
|
| 108 |
+
if not isinstance(c, (list, tuple)):
|
| 109 |
+
return []
|
| 110 |
+
return [str(x) for x in c]
|
| 111 |
+
|
| 112 |
+
|
| 113 |
+
def row_labels(row: Dict[str, Any]) -> List[bool]:
|
| 114 |
+
raw = row.get("labels")
|
| 115 |
+
if raw is None:
|
| 116 |
+
return []
|
| 117 |
+
if hasattr(raw, "tolist"):
|
| 118 |
+
raw = raw.tolist()
|
| 119 |
+
if not isinstance(raw, (list, tuple)):
|
| 120 |
+
return []
|
| 121 |
+
out: List[bool] = []
|
| 122 |
+
for x in raw:
|
| 123 |
+
if isinstance(x, bool):
|
| 124 |
+
out.append(x)
|
| 125 |
+
elif isinstance(x, (int, float)):
|
| 126 |
+
out.append(bool(int(x)))
|
| 127 |
+
elif isinstance(x, str):
|
| 128 |
+
out.append(x.strip().lower() in ("true", "1", "yes"))
|
| 129 |
+
else:
|
| 130 |
+
out.append(bool(x))
|
| 131 |
+
return out
|
| 132 |
+
|
| 133 |
+
|
| 134 |
+
def completions_to_response_and_gold(
|
| 135 |
+
completions: List[str], labels: List[bool]
|
| 136 |
+
) -> Tuple[str, List[Dict[str, int]]]:
|
| 137 |
+
"""
|
| 138 |
+
将 steps 拼成 response;对每个 label==False 的步骤写入金标 span(字符级,与 STEP_SEP 一致)。
|
| 139 |
+
"""
|
| 140 |
+
if len(completions) != len(labels):
|
| 141 |
+
raise ValueError(
|
| 142 |
+
f"completions 与 labels 须等长: {len(completions)} vs {len(labels)}"
|
| 143 |
+
)
|
| 144 |
+
gold: List[Dict[str, int]] = []
|
| 145 |
+
pos = 0
|
| 146 |
+
n = len(completions)
|
| 147 |
+
for i, step in enumerate(completions):
|
| 148 |
+
start = pos
|
| 149 |
+
end = pos + len(step) + (len(STEP_SEP) if i < n - 1 else 0)
|
| 150 |
+
if not labels[i]:
|
| 151 |
+
gold.append({"start": start, "end": end})
|
| 152 |
+
pos = end
|
| 153 |
+
response = STEP_SEP.join(completions)
|
| 154 |
+
if len(response) != pos and n > 0:
|
| 155 |
+
# 理论上应相等;防御
|
| 156 |
+
pass
|
| 157 |
+
return response, gold
|
| 158 |
+
|
| 159 |
+
|
| 160 |
+
def build_math_shepherd_input_str(prompt: str, completions: List[str]) -> str:
|
| 161 |
+
steps_text = STEP_SEP.join(completions)
|
| 162 |
+
return (
|
| 163 |
+
f"Below is a question:\n{prompt}\n"
|
| 164 |
+
f"Below is an answer:\n{steps_text}\n"
|
| 165 |
+
"""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:
|
| 166 |
+
|
| 167 |
+
Step 1: < verify the first mathematical transition/calculation >
|
| 168 |
+
Step 2: < verify the subsequent logic and result >
|
| 169 |
+
...(add as many steps as needed)
|
| 170 |
+
|
| 171 |
+
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"]}."""
|
| 172 |
+
# """Your task is to determine whether the answer contains errors or hallucinations. First, provide reasoning with the following format:
|
| 173 |
+
# ## Step 1: < your first reasoning step >
|
| 174 |
+
# ## Step 2: < your next reasoning step >
|
| 175 |
+
# ...(add as many steps as needed)
|
| 176 |
+
# 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": []}."""
|
| 177 |
+
)
|
| 178 |
+
|
| 179 |
+
|
| 180 |
+
def build_user_instruction(
|
| 181 |
+
prompt: str,
|
| 182 |
+
completions: List[str],
|
| 183 |
+
reasoning: bool,
|
| 184 |
+
fewshot: bool,
|
| 185 |
+
) -> str:
|
| 186 |
+
if fewshot:
|
| 187 |
+
ins_ori = _format_fewshot_block() + "\n\n---\n\n" + build_math_shepherd_input_str(
|
| 188 |
+
prompt, completions
|
| 189 |
+
)
|
| 190 |
+
else:
|
| 191 |
+
ins_ori = build_math_shepherd_input_str(prompt, completions)
|
| 192 |
+
if not reasoning:
|
| 193 |
+
ins_ori = ins_ori.rsplit("Your task", 1)[0] + (
|
| 194 |
+
'Your task is to identify mathematically incorrect steps in the answer. '
|
| 195 |
+
'Return only a JSON dict containing the exact erroneous text spans: '
|
| 196 |
+
'{"hallucination list": ["wrong span 1"]}. '
|
| 197 |
+
'If all steps are correct, return {"hallucination list": []}.'
|
| 198 |
+
)
|
| 199 |
+
return ins_ori
|
| 200 |
+
|
| 201 |
+
|
| 202 |
+
def align_pred_start_to_gold_step_starts(
|
| 203 |
+
min_s: int, gold_labels: List[Dict[str, Any]]
|
| 204 |
+
) -> int:
|
| 205 |
+
"""
|
| 206 |
+
将模型子串匹配得到的最左 start ``min_s``,对齐到金标步边界:
|
| 207 |
+
在 ``gold_labels`` 中所有 ``start`` 里,取满足 ``s <= min_s`` 的**最大** ``s``
|
| 208 |
+
(即 ``min_s`` 左侧最近的步起点,含相等);若 ``min_s`` 早于任一金标步起点,
|
| 209 |
+
则回退为 ``min(gold_starts)``。无金标时返回 ``min_s``。
|
| 210 |
+
"""
|
| 211 |
+
if not gold_labels:
|
| 212 |
+
return min_s
|
| 213 |
+
gold_starts = sorted({int(l["start"]) for l in gold_labels})
|
| 214 |
+
left = [s for s in gold_starts if s <= min_s]
|
| 215 |
+
if left:
|
| 216 |
+
return max(left)
|
| 217 |
+
return gold_starts[0]
|
| 218 |
+
|
| 219 |
+
|
| 220 |
+
def cal_metrics_math_shepherd(
|
| 221 |
+
response: str,
|
| 222 |
+
labels: List[Dict[str, Any]],
|
| 223 |
+
output_list: List[str],
|
| 224 |
+
completions: Optional[List[str]] = None,
|
| 225 |
+
) -> Tuple[int, int, int, int, int, int, int]:
|
| 226 |
+
"""
|
| 227 |
+
金标 spans 与通用 eval 相同;预测侧:空列表则无幻觉;否则取各子串最左 start,
|
| 228 |
+
再对齐到金标步 ``start``,最后预测幻觉区为 ``[aligned_start, len(steps_text))``,
|
| 229 |
+
其中 ``steps_text = STEP_SEP.join(completions)``(与 ``build_math_shepherd_input_str`` 一致)。
|
| 230 |
+
若未传 ``completions``(旧 jsonl),则右端退化为 ``len(response)``。
|
| 231 |
+
"""
|
| 232 |
+
ground_truth_span: List[Tuple[int, int]] = [
|
| 233 |
+
(int(l["start"]), int(l["end"])) for l in labels
|
| 234 |
+
]
|
| 235 |
+
|
| 236 |
+
predict_span: List[Tuple[int, int]] = []
|
| 237 |
+
if output_list:
|
| 238 |
+
starts: List[int] = []
|
| 239 |
+
for out in output_list:
|
| 240 |
+
if not isinstance(out, str):
|
| 241 |
+
continue
|
| 242 |
+
tup = find_start_end_index(response, out, strict=False)
|
| 243 |
+
if tup != (-1, -1):
|
| 244 |
+
starts.append(tup[0])
|
| 245 |
+
if starts:
|
| 246 |
+
min_s = min(starts)
|
| 247 |
+
aligned = align_pred_start_to_gold_step_starts(min_s, labels)
|
| 248 |
+
|
| 249 |
+
end_len = (
|
| 250 |
+
len(STEP_SEP.join(str(c) for c in completions))
|
| 251 |
+
if completions is not None
|
| 252 |
+
else len(response)
|
| 253 |
+
)
|
| 254 |
+
predict_span.append((aligned, end_len))
|
| 255 |
+
match_size, prediction, groud_truth = compute_multi_spans(
|
| 256 |
+
ground_truth_span, predict_span
|
| 257 |
+
)
|
| 258 |
+
|
| 259 |
+
pos_true_cnt, neg_true_cnt, neg_false_cnt, pos_false_cnt = 0, 0, 0, 0
|
| 260 |
+
if output_list != [] and labels != []:
|
| 261 |
+
pos_true_cnt += 1
|
| 262 |
+
elif output_list == [] and labels != []:
|
| 263 |
+
neg_true_cnt += 1
|
| 264 |
+
elif output_list == [] and labels == []:
|
| 265 |
+
neg_false_cnt += 1
|
| 266 |
+
elif output_list != [] and labels == []:
|
| 267 |
+
pos_false_cnt += 1
|
| 268 |
+
else:
|
| 269 |
+
raise RuntimeError(
|
| 270 |
+
f"unexpected case output_list={output_list!r} labels={labels!r}"
|
| 271 |
+
)
|
| 272 |
+
|
| 273 |
+
return (
|
| 274 |
+
match_size,
|
| 275 |
+
prediction,
|
| 276 |
+
groud_truth,
|
| 277 |
+
pos_true_cnt,
|
| 278 |
+
neg_true_cnt,
|
| 279 |
+
neg_false_cnt,
|
| 280 |
+
pos_false_cnt,
|
| 281 |
+
)
|
| 282 |
+
|
| 283 |
+
|
| 284 |
+
def evaluate_math_shepherd_results(
|
| 285 |
+
results: List[Dict[str, Any]],
|
| 286 |
+
record: Dict[str, int],
|
| 287 |
+
filepath: str,
|
| 288 |
+
) -> List[Dict[str, Any]]:
|
| 289 |
+
chosen: Sequence[str] = ["Math", "All"]
|
| 290 |
+
for sample in results:
|
| 291 |
+
response = sample["response"]
|
| 292 |
+
labels = sample["labels"]
|
| 293 |
+
output = sample["output"]
|
| 294 |
+
task = sample.get("task_type") or "Math"
|
| 295 |
+
res = cal_metrics_math_shepherd(
|
| 296 |
+
response, labels, output, sample.get("completions")
|
| 297 |
+
)
|
| 298 |
+
(
|
| 299 |
+
temp_tp,
|
| 300 |
+
temp_pred_len,
|
| 301 |
+
temp_gold_len,
|
| 302 |
+
pos_true_cnt,
|
| 303 |
+
neg_true_cnt,
|
| 304 |
+
neg_false_cnt,
|
| 305 |
+
pos_false_cnt,
|
| 306 |
+
) = res
|
| 307 |
+
for task_cur in chosen:
|
| 308 |
+
if task_cur == task or task_cur == "All":
|
| 309 |
+
record["match_size_" + task_cur] += temp_tp
|
| 310 |
+
record["prediction_" + task_cur] += temp_pred_len
|
| 311 |
+
record["groud_truth_" + task_cur] += temp_gold_len
|
| 312 |
+
record["pos_true_cnt_" + task_cur] += pos_true_cnt
|
| 313 |
+
record["neg_true_cnt_" + task_cur] += neg_true_cnt
|
| 314 |
+
record["neg_false_cnt_" + task_cur] += neg_false_cnt
|
| 315 |
+
record["pos_false_cnt_" + task_cur] += pos_false_cnt
|
| 316 |
+
all_metrics: List[Dict[str, Any]] = []
|
| 317 |
+
for task_cur in chosen:
|
| 318 |
+
all_metrics.append(print_metrics(task_cur, record))
|
| 319 |
+
print("chosen task: {}".format(list(chosen)))
|
| 320 |
+
print("filepath: {}".format(filepath))
|
| 321 |
+
print("test_data_size: {}".format(len(results)))
|
| 322 |
+
return all_metrics
|
| 323 |
+
|
| 324 |
+
|
| 325 |
+
def iter_parquet_rows(paths: List[str]):
|
| 326 |
+
idx = 0
|
| 327 |
+
for path in paths:
|
| 328 |
+
pf = pq.ParquetFile(path)
|
| 329 |
+
for batch in pf.iter_batches(batch_size=256):
|
| 330 |
+
d = batch.to_pydict()
|
| 331 |
+
if not d:
|
| 332 |
+
continue
|
| 333 |
+
keys = list(d.keys())
|
| 334 |
+
n = len(d[keys[0]])
|
| 335 |
+
for i in range(n):
|
| 336 |
+
row = {k: d[k][i] for k in keys}
|
| 337 |
+
yield idx, row
|
| 338 |
+
idx += 1
|
| 339 |
+
|
| 340 |
+
|
| 341 |
+
def resolve_test_parquets(data_dir: str) -> List[str]:
|
| 342 |
+
paths = sorted(glob(os.path.join(data_dir, "test*.parquet")))
|
| 343 |
+
paths += sorted(glob(os.path.join(data_dir, "math_shepherd*.parquet")))
|
| 344 |
+
return sorted(set(paths))
|
| 345 |
+
|
| 346 |
+
|
| 347 |
+
def process_single_item(
|
| 348 |
+
d: Dict[str, Any],
|
| 349 |
+
row_key: str,
|
| 350 |
+
model_name: str,
|
| 351 |
+
model_url: str,
|
| 352 |
+
max_tokens: int,
|
| 353 |
+
reasoning: bool,
|
| 354 |
+
fewshot: bool,
|
| 355 |
+
) -> Optional[Dict[str, Any]]:
|
| 356 |
+
prompt = row_prompt(d)
|
| 357 |
+
completions = row_completions(d)
|
| 358 |
+
labels = row_labels(d)
|
| 359 |
+
if not prompt or not completions:
|
| 360 |
+
return None
|
| 361 |
+
if len(completions) != len(labels):
|
| 362 |
+
print(
|
| 363 |
+
f"skip {row_key}: completions/labels length mismatch "
|
| 364 |
+
f"{len(completions)} vs {len(labels)}",
|
| 365 |
+
file=sys.stderr,
|
| 366 |
+
)
|
| 367 |
+
return None
|
| 368 |
+
try:
|
| 369 |
+
response, gold_spans = completions_to_response_and_gold(completions, labels)
|
| 370 |
+
instruction = build_user_instruction(prompt, completions, reasoning, fewshot)
|
| 371 |
+
raw = req_model_vllm(
|
| 372 |
+
instruction, model_name=model_name, model_url=model_url, max_tokens=max_tokens
|
| 373 |
+
)
|
| 374 |
+
if not _format_is_ok(raw):
|
| 375 |
+
raise ValueError("model output could not be parsed after retries")
|
| 376 |
+
output_parsed = parse_output(raw)
|
| 377 |
+
if not isinstance(output_parsed, list) or not all(
|
| 378 |
+
isinstance(x, str) for x in output_parsed
|
| 379 |
+
):
|
| 380 |
+
raise ValueError("hallucination list must be a list of strings")
|
| 381 |
+
return {
|
| 382 |
+
"id": row_key,
|
| 383 |
+
"response": response,
|
| 384 |
+
"labels": gold_spans,
|
| 385 |
+
"output": output_parsed,
|
| 386 |
+
"output_raw": raw,
|
| 387 |
+
"task_type": "Math",
|
| 388 |
+
"prompt": prompt,
|
| 389 |
+
"completions": completions,
|
| 390 |
+
"step_labels": labels,
|
| 391 |
+
"pred_rule": "empty_hallucination_list=>no_hallucination; "
|
| 392 |
+
"else min_matched_start_then_align_to_gold_step_start_then_suffix_to_eof",
|
| 393 |
+
}
|
| 394 |
+
except Exception as e:
|
| 395 |
+
print(f"Error {row_key}: {e}")
|
| 396 |
+
traceback.print_exc()
|
| 397 |
+
return None
|
| 398 |
+
|
| 399 |
+
|
| 400 |
+
def main() -> None:
|
| 401 |
+
parser = argparse.ArgumentParser()
|
| 402 |
+
input_group = parser.add_mutually_exclusive_group()
|
| 403 |
+
input_group.add_argument(
|
| 404 |
+
"--data-file",
|
| 405 |
+
default=os.path.join(_EVAL_DIR, "math_shepherd_614_test_20260327.parquet"),
|
| 406 |
+
help="Math-Shepherd Parquet file (default: file next to this script)",
|
| 407 |
+
)
|
| 408 |
+
input_group.add_argument(
|
| 409 |
+
"--data-dir",
|
| 410 |
+
help="Directory of test*.parquet / math_shepherd*.parquet files",
|
| 411 |
+
)
|
| 412 |
+
parser.add_argument("--filepath", default="", help="Existing JSONL; recompute metrics only")
|
| 413 |
+
parser.add_argument("--model-name", help="Model identifier served by the OpenAI-compatible API")
|
| 414 |
+
parser.add_argument("--model-url", default=MODEL_URL, help="OpenAI-compatible vLLM base URL")
|
| 415 |
+
parser.add_argument("--model-prefix", default="", help="Optional result filename prefix")
|
| 416 |
+
parser.add_argument("--output-dir", default=os.path.join(_EVAL_DIR, "test_result"))
|
| 417 |
+
parser.add_argument("--max-tokens", type=int, default=8000)
|
| 418 |
+
parser.add_argument("--num-threads", "--num_threads", type=int, default=32)
|
| 419 |
+
parser.add_argument(
|
| 420 |
+
"--max-samples", "--max_samples", type=int, default=0,
|
| 421 |
+
help=">0 processes first N rows only",
|
| 422 |
+
)
|
| 423 |
+
parser.add_argument(
|
| 424 |
+
"--no-reasoning",
|
| 425 |
+
action="store_true",
|
| 426 |
+
help="Omit the reasoning template; ask for JSON only",
|
| 427 |
+
)
|
| 428 |
+
parser.add_argument(
|
| 429 |
+
"--fewshot",
|
| 430 |
+
action="store_true",
|
| 431 |
+
help="在题目前拼接 README 中的案例作为 few-shot",
|
| 432 |
+
)
|
| 433 |
+
args = parser.parse_args()
|
| 434 |
+
metrics_only = bool(args.filepath)
|
| 435 |
+
reasoning = not args.no_reasoning
|
| 436 |
+
if not args.filepath and not args.model_name:
|
| 437 |
+
parser.error("--model-name is required for inference; use --filepath for metric-only mode")
|
| 438 |
+
if args.num_threads < 1 or args.max_tokens < 1 or args.max_samples < 0:
|
| 439 |
+
parser.error("--num-threads and --max-tokens must be positive; --max-samples must be nonnegative")
|
| 440 |
+
|
| 441 |
+
results: List[Dict[str, Any]] = []
|
| 442 |
+
|
| 443 |
+
if not args.filepath:
|
| 444 |
+
paths = resolve_test_parquets(args.data_dir) if args.data_dir else [args.data_file]
|
| 445 |
+
if not paths or not all(os.path.isfile(path) for path in paths):
|
| 446 |
+
parser.error(f"Parquet data not found: {paths}; specify --data-file or --data-dir")
|
| 447 |
+
|
| 448 |
+
rows: List[Tuple[str, Dict[str, Any]]] = []
|
| 449 |
+
for global_idx, d in iter_parquet_rows(paths):
|
| 450 |
+
if args.max_samples and len(rows) >= args.max_samples:
|
| 451 |
+
break
|
| 452 |
+
rows.append((str(global_idx), d))
|
| 453 |
+
|
| 454 |
+
total_items = len(rows)
|
| 455 |
+
with ThreadPoolExecutor(max_workers=args.num_threads) as ex:
|
| 456 |
+
futs = {
|
| 457 |
+
ex.submit(
|
| 458 |
+
process_single_item,
|
| 459 |
+
d,
|
| 460 |
+
rk,
|
| 461 |
+
args.model_name,
|
| 462 |
+
args.model_url,
|
| 463 |
+
args.max_tokens,
|
| 464 |
+
reasoning,
|
| 465 |
+
args.fewshot,
|
| 466 |
+
): rk
|
| 467 |
+
for rk, d in rows
|
| 468 |
+
}
|
| 469 |
+
with tqdm(total=total_items, desc="math_shepherd") as pbar:
|
| 470 |
+
for fut in as_completed(futs):
|
| 471 |
+
res = fut.result()
|
| 472 |
+
if res is not None:
|
| 473 |
+
results.append(res)
|
| 474 |
+
pbar.update(1)
|
| 475 |
+
if len(results) != total_items:
|
| 476 |
+
raise RuntimeError(
|
| 477 |
+
f"Only {len(results)}/{total_items} rows evaluated; refusing incomplete metrics. "
|
| 478 |
+
"Check errors above and retry."
|
| 479 |
+
)
|
| 480 |
+
results.sort(key=lambda x: int(x["id"]))
|
| 481 |
+
_date = datetime.now().strftime("%Y%m%d_%H%M%S_%f")
|
| 482 |
+
out_dir = args.output_dir
|
| 483 |
+
os.makedirs(out_dir, exist_ok=True)
|
| 484 |
+
basename = re.sub(
|
| 485 |
+
r"[^a-zA-Z0-9_.-]+", "_", f"{args.model_prefix}_{args.model_name}"
|
| 486 |
+
).strip("._")
|
| 487 |
+
output_path = os.path.join(
|
| 488 |
+
out_dir,
|
| 489 |
+
f"{basename}_math_shepherd_test_{_date}.jsonl",
|
| 490 |
+
)
|
| 491 |
+
with open(output_path, "w", encoding="utf-8") as f:
|
| 492 |
+
for res in results:
|
| 493 |
+
f.write(json.dumps(res, ensure_ascii=False) + "\n")
|
| 494 |
+
args.filepath = output_path
|
| 495 |
+
else:
|
| 496 |
+
with open(args.filepath, "r", encoding="utf-8") as f:
|
| 497 |
+
for line in f:
|
| 498 |
+
results.append(json.loads(line))
|
| 499 |
+
|
| 500 |
+
if not labels_have_any_supervision(results):
|
| 501 |
+
print("警告: 结果中无任何 gold labels,跳过指标计算。")
|
| 502 |
+
return
|
| 503 |
+
|
| 504 |
+
record: Dict[str, int] = collections.defaultdict(int)
|
| 505 |
+
all_metrics = evaluate_math_shepherd_results(results, record, args.filepath)
|
| 506 |
+
|
| 507 |
+
output_path_metric = os.path.splitext(args.filepath)[0] + (
|
| 508 |
+
"_recomputed_metric.json" if metrics_only else "_metric.json"
|
| 509 |
+
)
|
| 510 |
+
metrics_output = {
|
| 511 |
+
"filepath": args.filepath,
|
| 512 |
+
"data_files": paths if not metrics_only else None,
|
| 513 |
+
"test_data_size": len(results),
|
| 514 |
+
"model_name": args.model_name,
|
| 515 |
+
"model_url": args.model_url if not metrics_only else None,
|
| 516 |
+
"max_tokens": args.max_tokens if not metrics_only else None,
|
| 517 |
+
"num_threads": args.num_threads if not metrics_only else None,
|
| 518 |
+
"fewshot": args.fewshot if not metrics_only else None,
|
| 519 |
+
"reasoning_suffix": reasoning if not metrics_only else None,
|
| 520 |
+
"pred_rule": "empty_hallucination_list=>no_hallucination; "
|
| 521 |
+
"else min_matched_start_then_align_to_gold_step_start_then_suffix_to_eof",
|
| 522 |
+
"metrics": all_metrics,
|
| 523 |
+
"timestamp": datetime.now().strftime("%Y%m%d_%H%M%S"),
|
| 524 |
+
}
|
| 525 |
+
with open(output_path_metric, "w", encoding="utf-8") as f:
|
| 526 |
+
json.dump(metrics_output, f, ensure_ascii=False, indent=2)
|
| 527 |
+
print(f"\nMetrics saved to: {output_path_metric}")
|
| 528 |
+
|
| 529 |
+
|
| 530 |
+
if __name__ == "__main__":
|
| 531 |
+
main()
|
sopo_eval_common.py
ADDED
|
@@ -0,0 +1,476 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""与 run_ragtruth.py 对齐的幻觉 span 评估与解析逻辑(供 eval 脚本复用)。"""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import collections
|
| 6 |
+
import json
|
| 7 |
+
import re
|
| 8 |
+
import traceback
|
| 9 |
+
from typing import Any, Dict, List, Optional, Sequence, Tuple
|
| 10 |
+
|
| 11 |
+
import json_repair
|
| 12 |
+
from openai import OpenAI
|
| 13 |
+
import threading
|
| 14 |
+
|
| 15 |
+
_thread_local = threading.local()
|
| 16 |
+
_client_lock = threading.Lock()
|
| 17 |
+
_shared_clients = {}
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
def _get_openai_client(model_url: str) -> OpenAI:
|
| 21 |
+
"""Reuse OpenAI/httpx clients to avoid FD exhaustion under thread pools."""
|
| 22 |
+
with _client_lock:
|
| 23 |
+
client = _shared_clients.get(model_url)
|
| 24 |
+
if client is None:
|
| 25 |
+
client = OpenAI(api_key="EMPTY", base_url=model_url, timeout=None)
|
| 26 |
+
_shared_clients[model_url] = client
|
| 27 |
+
return client
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
MODEL_URL = "http://localhost:7010/v1"
|
| 31 |
+
|
| 32 |
+
TASK_TYPE_TO_INSTRUCTION = {
|
| 33 |
+
"QA": "answer",
|
| 34 |
+
"Data2txt": "article",
|
| 35 |
+
"Summary": "summary",
|
| 36 |
+
}
|
| 37 |
+
|
| 38 |
+
SAVE_DIR = "test_result_0506"
|
| 39 |
+
|
| 40 |
+
extra_sft_prompt_reasoning = """Your task is to determine whether the <|task_word|> contains hallucinations. First, provide reasoning with the following format:
|
| 41 |
+
## Step 1: < your first reasoning step >
|
| 42 |
+
## Step 2: < your next reasoning step >
|
| 43 |
+
...(add as many steps as needed)
|
| 44 |
+
Then, compile the labeled hallucinated spans into a JSON dict, with a key hallucination list and its value is a list of hallucinated spans. If there are potential hallucinations, the output should be in the following JSON format: {"hallucination list": [hallucination span1, hallucination span2, ...]}. Otherwise, leave the value as an empty list as follows: {"hallucination list": []}."""
|
| 45 |
+
|
| 46 |
+
extra_sft_prompt = """Your task is to determine whether the <|task_word|> contains hallucinations. Then, compile the labeled hallucinated spans into a JSON dict, with a key hallucination list and its value is a list of hallucinated spans. If there are potential hallucinations, the output should be in the following JSON format: {"hallucination list": [hallucination span1, hallucination span2, ...]}. Otherwise, leave the value as an empty list as follows: {"hallucination list": []}."""
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
# 格式错误重试相关常量:首次 attempt 用 temperature=0(贪心、可复现),
|
| 50 |
+
# 第 2/3 次重试切到 RETRY_TEMPERATURE 引入随机性以摆脱反复输出错误格式。
|
| 51 |
+
MAX_GEN_ATTEMPTS = 3
|
| 52 |
+
RETRY_TEMPERATURE = 0.4
|
| 53 |
+
_HALLU_LIST_REGEX = re.compile(r"""{"hallucination list": \[.*?\]}""")
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
def _format_is_ok(output_str: str) -> bool:
|
| 57 |
+
"""
|
| 58 |
+
与 ``parse_output`` 等价的"格式校验"快速通道:
|
| 59 |
+
1) 至少要能匹配到一个 ``{"hallucination list": [...]}`` 片段;
|
| 60 |
+
2) 取最后一个片段经 ``json_repair`` 解析后,必须是含 ``hallucination list`` 键的 dict 或本身是 list。
|
| 61 |
+
任一条不满足则视为格式错误,调用方据此决定是否重试。
|
| 62 |
+
"""
|
| 63 |
+
if not isinstance(output_str, str) or not output_str:
|
| 64 |
+
return False
|
| 65 |
+
matches = _HALLU_LIST_REGEX.findall(output_str)
|
| 66 |
+
if not matches:
|
| 67 |
+
return False
|
| 68 |
+
try:
|
| 69 |
+
parsed = json_repair.loads(matches[-1])
|
| 70 |
+
except Exception:
|
| 71 |
+
return False
|
| 72 |
+
if isinstance(parsed, dict) and "hallucination list" in parsed:
|
| 73 |
+
return True
|
| 74 |
+
if isinstance(parsed, list):
|
| 75 |
+
return True
|
| 76 |
+
return False
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
def req_model_vllm_with_finish_reason(
|
| 80 |
+
query: str,
|
| 81 |
+
model_name: str,
|
| 82 |
+
model_url: str = MODEL_URL,
|
| 83 |
+
max_tokens: int = 4000,
|
| 84 |
+
temperature: float = 0.0,
|
| 85 |
+
) -> Tuple[str, Optional[str]]:
|
| 86 |
+
"""
|
| 87 |
+
与 ``req_model_vllm`` 相同请求,额外返回 vLLM/OpenAI 兼容的 ``finish_reason``(如 ``stop``、``length``)。
|
| 88 |
+
请求失败时返回 ``(错误信息字符串, None)``。``temperature`` 用于重试时切换采样温度。
|
| 89 |
+
"""
|
| 90 |
+
try:
|
| 91 |
+
client = _get_openai_client(model_url)
|
| 92 |
+
chat_response = client.chat.completions.create(
|
| 93 |
+
model=model_name,
|
| 94 |
+
messages=[{"role": "user", "content": query}],
|
| 95 |
+
max_tokens=max_tokens,
|
| 96 |
+
temperature=temperature,
|
| 97 |
+
top_p=0.95,
|
| 98 |
+
extra_body={
|
| 99 |
+
"stop": ["<|im_end|>"],
|
| 100 |
+
"top_k": -1,
|
| 101 |
+
"repetition_penalty": 1.0,
|
| 102 |
+
},
|
| 103 |
+
)
|
| 104 |
+
except Exception as e:
|
| 105 |
+
traceback.print_exc()
|
| 106 |
+
return str(e), None
|
| 107 |
+
choice = chat_response.choices[0]
|
| 108 |
+
content = choice.message.content
|
| 109 |
+
if content is None:
|
| 110 |
+
content = ""
|
| 111 |
+
fr = getattr(choice, "finish_reason", None)
|
| 112 |
+
return content, fr
|
| 113 |
+
|
| 114 |
+
|
| 115 |
+
def req_model_vllm(
|
| 116 |
+
query: str,
|
| 117 |
+
model_name: str,
|
| 118 |
+
model_url: str = MODEL_URL,
|
| 119 |
+
max_tokens: int = 4000,
|
| 120 |
+
max_attempts: int = MAX_GEN_ATTEMPTS,
|
| 121 |
+
retry_temperature: float = RETRY_TEMPERATURE,
|
| 122 |
+
) -> str:
|
| 123 |
+
"""
|
| 124 |
+
请求模型并在格式错误时重试:
|
| 125 |
+
- 第 1 次 attempt 使用 temperature=0;后续重试使用 ``retry_temperature``(默认 0.4)。
|
| 126 |
+
- 通过 ``_format_is_ok`` 检查是否包含可解析的 ``{"hallucination list": [...]}`` 片段。
|
| 127 |
+
- 至多尝��� ``max_attempts`` 次(含首次),仍失败则返回最后一次的原始内容(交由下游 ``parse_output`` 兜底为 ``[]``)。
|
| 128 |
+
"""
|
| 129 |
+
last_content = ""
|
| 130 |
+
attempts = max(1, int(max_attempts))
|
| 131 |
+
for attempt in range(1, attempts + 1):
|
| 132 |
+
temperature = 0.0 if attempt == 1 else float(retry_temperature)
|
| 133 |
+
content, _ = req_model_vllm_with_finish_reason(
|
| 134 |
+
query,
|
| 135 |
+
model_name,
|
| 136 |
+
model_url,
|
| 137 |
+
max_tokens=max_tokens,
|
| 138 |
+
temperature=temperature,
|
| 139 |
+
)
|
| 140 |
+
last_content = content
|
| 141 |
+
if _format_is_ok(content):
|
| 142 |
+
return content
|
| 143 |
+
if attempt < attempts:
|
| 144 |
+
print(
|
| 145 |
+
f"[req_model_vllm] format invalid on attempt {attempt}/{attempts}, "
|
| 146 |
+
f"retrying with temperature={retry_temperature}."
|
| 147 |
+
)
|
| 148 |
+
return last_content
|
| 149 |
+
|
| 150 |
+
|
| 151 |
+
def compute_multi_spans(
|
| 152 |
+
gold_spans: Sequence[Tuple[int, int]], pred_spans: Sequence[Tuple[int, int]]
|
| 153 |
+
) -> Tuple[int, int, int]:
|
| 154 |
+
gold_sets = [set(range(int(start), int(end))) for start, end in gold_spans]
|
| 155 |
+
pred_sets = [set(range(int(start), int(end))) for start, end in pred_spans]
|
| 156 |
+
gold_union = set.union(*gold_sets) if gold_sets else set()
|
| 157 |
+
pred_union = set.union(*pred_sets) if pred_sets else set()
|
| 158 |
+
tp = len(gold_union.intersection(pred_union))
|
| 159 |
+
pred_len = len(pred_union)
|
| 160 |
+
gold_len = len(gold_union)
|
| 161 |
+
return tp, pred_len, gold_len
|
| 162 |
+
|
| 163 |
+
|
| 164 |
+
def find_start_end_index(response: str, output: str, strict: bool = False) -> Tuple[int, int]:
|
| 165 |
+
response = response.lower()
|
| 166 |
+
sub_str = output.lower().strip()
|
| 167 |
+
start = response.find(sub_str)
|
| 168 |
+
if start == -1:
|
| 169 |
+
if len(sub_str) >= 10 and not strict:
|
| 170 |
+
match_length = 10
|
| 171 |
+
prefix_match = response.find(sub_str[:match_length])
|
| 172 |
+
suffix_match = response.find(sub_str[-match_length:])
|
| 173 |
+
new_start, new_end = prefix_match, suffix_match + match_length
|
| 174 |
+
if (
|
| 175 |
+
prefix_match != -1
|
| 176 |
+
and suffix_match != -1
|
| 177 |
+
and 0.7 < (new_end - new_start) / len(sub_str) < 1.3
|
| 178 |
+
):
|
| 179 |
+
return new_start, new_end
|
| 180 |
+
sub_str = " ".join(sub_str.split())
|
| 181 |
+
start = response.find(sub_str)
|
| 182 |
+
if start == -1:
|
| 183 |
+
return -1, -1
|
| 184 |
+
end = start + len(sub_str)
|
| 185 |
+
return (start, end)
|
| 186 |
+
|
| 187 |
+
|
| 188 |
+
def cal_metrics(
|
| 189 |
+
response: str,
|
| 190 |
+
labels: List[Dict[str, Any]],
|
| 191 |
+
output_list: List[str],
|
| 192 |
+
) -> Tuple[int, int, int, int, int, int, int]:
|
| 193 |
+
predict_span = []
|
| 194 |
+
for output in output_list:
|
| 195 |
+
if not isinstance(output, str):
|
| 196 |
+
continue
|
| 197 |
+
tup = find_start_end_index(response, output, strict=False)
|
| 198 |
+
if tup != (-1, -1):
|
| 199 |
+
predict_span.append(tup)
|
| 200 |
+
ground_truth_span = []
|
| 201 |
+
for label in labels:
|
| 202 |
+
tup = (label["start"], label["end"])
|
| 203 |
+
ground_truth_span.append(tup)
|
| 204 |
+
if len(predict_span) == 0:
|
| 205 |
+
predict_span.append((0, 0))
|
| 206 |
+
if len(ground_truth_span) == 0:
|
| 207 |
+
ground_truth_span.append((0, 0))
|
| 208 |
+
match_size, prediction, groud_truth = compute_multi_spans(
|
| 209 |
+
ground_truth_span, predict_span
|
| 210 |
+
)
|
| 211 |
+
pos_true_cnt, neg_true_cnt, neg_false_cnt, pos_false_cnt = 0, 0, 0, 0
|
| 212 |
+
if output_list != [] and labels != []:
|
| 213 |
+
pos_true_cnt += 1
|
| 214 |
+
elif output_list == [] and labels != []:
|
| 215 |
+
neg_true_cnt += 1
|
| 216 |
+
elif output_list == [] and labels == []:
|
| 217 |
+
neg_false_cnt += 1
|
| 218 |
+
elif output_list != [] and labels == []:
|
| 219 |
+
pos_false_cnt += 1
|
| 220 |
+
else:
|
| 221 |
+
raise Exception("Error! output: {} labels: {}".format(output_list, labels))
|
| 222 |
+
return (
|
| 223 |
+
match_size,
|
| 224 |
+
prediction,
|
| 225 |
+
groud_truth,
|
| 226 |
+
pos_true_cnt,
|
| 227 |
+
neg_true_cnt,
|
| 228 |
+
neg_false_cnt,
|
| 229 |
+
pos_false_cnt,
|
| 230 |
+
)
|
| 231 |
+
|
| 232 |
+
|
| 233 |
+
def print_metrics(task_cur: str, record: Dict[str, Any]) -> Dict[str, Any]:
|
| 234 |
+
record["recall" + task_cur] = (
|
| 235 |
+
record["match_size_" + task_cur] / record["groud_truth_" + task_cur]
|
| 236 |
+
if record["groud_truth_" + task_cur]
|
| 237 |
+
else 0
|
| 238 |
+
)
|
| 239 |
+
record["precision" + task_cur] = (
|
| 240 |
+
record["match_size_" + task_cur] / record["prediction_" + task_cur]
|
| 241 |
+
if record["prediction_" + task_cur]
|
| 242 |
+
else 0
|
| 243 |
+
)
|
| 244 |
+
record["f1" + task_cur] = (
|
| 245 |
+
2
|
| 246 |
+
* record["recall" + task_cur]
|
| 247 |
+
* record["precision" + task_cur]
|
| 248 |
+
/ (record["recall" + task_cur] + record["precision" + task_cur])
|
| 249 |
+
if (record["recall" + task_cur] + record["precision" + task_cur]) > 0
|
| 250 |
+
else 0
|
| 251 |
+
)
|
| 252 |
+
char_res = "span_level:\nprecision: {:.4f}, recall: {:.4f}, f1: {:.4f}".format(
|
| 253 |
+
record["precision" + task_cur],
|
| 254 |
+
record["recall" + task_cur],
|
| 255 |
+
record["f1" + task_cur],
|
| 256 |
+
)
|
| 257 |
+
record["case_recall_" + task_cur] = (
|
| 258 |
+
record["pos_true_cnt_" + task_cur]
|
| 259 |
+
/ (record["pos_true_cnt_" + task_cur] + record["neg_true_cnt_" + task_cur])
|
| 260 |
+
if (record["pos_true_cnt_" + task_cur] + record["neg_true_cnt_" + task_cur]) > 0
|
| 261 |
+
else 0
|
| 262 |
+
)
|
| 263 |
+
record["case_precision_" + task_cur] = (
|
| 264 |
+
record["pos_true_cnt_" + task_cur]
|
| 265 |
+
/ (record["pos_true_cnt_" + task_cur] + record["pos_false_cnt_" + task_cur])
|
| 266 |
+
if (record["pos_true_cnt_" + task_cur] + record["pos_false_cnt_" + task_cur]) > 0
|
| 267 |
+
else 0
|
| 268 |
+
)
|
| 269 |
+
record["f1_" + task_cur] = (
|
| 270 |
+
2
|
| 271 |
+
* record["case_recall_" + task_cur]
|
| 272 |
+
* record["case_precision_" + task_cur]
|
| 273 |
+
/ (record["case_recall_" + task_cur] + record["case_precision_" + task_cur])
|
| 274 |
+
if (record["case_recall_" + task_cur] + record["case_precision_" + task_cur]) > 0
|
| 275 |
+
else 0
|
| 276 |
+
)
|
| 277 |
+
case_res = "case_level:\nprecision: {:.4f}, recall: {:.4f}, f1: {:.4f}".format(
|
| 278 |
+
record["case_precision_" + task_cur],
|
| 279 |
+
record["case_recall_" + task_cur],
|
| 280 |
+
record["f1_" + task_cur],
|
| 281 |
+
)
|
| 282 |
+
print(case_res)
|
| 283 |
+
print(char_res)
|
| 284 |
+
return {
|
| 285 |
+
"task_type": task_cur,
|
| 286 |
+
"span_level": {
|
| 287 |
+
"precision": round(record["precision" + task_cur], 4),
|
| 288 |
+
"recall": round(record["recall" + task_cur], 4),
|
| 289 |
+
"f1": round(record["f1" + task_cur], 4),
|
| 290 |
+
"match_size": record["match_size_" + task_cur],
|
| 291 |
+
"prediction": record["prediction_" + task_cur],
|
| 292 |
+
"ground_truth": record["groud_truth_" + task_cur],
|
| 293 |
+
},
|
| 294 |
+
"case_level": {
|
| 295 |
+
"precision": round(record["case_precision_" + task_cur], 4),
|
| 296 |
+
"recall": round(record["case_recall_" + task_cur], 4),
|
| 297 |
+
"f1": round(record["f1_" + task_cur], 4),
|
| 298 |
+
"pos_true_cnt": record["pos_true_cnt_" + task_cur],
|
| 299 |
+
"neg_true_cnt": record["neg_true_cnt_" + task_cur],
|
| 300 |
+
"neg_false_cnt": record["neg_false_cnt_" + task_cur],
|
| 301 |
+
"pos_false_cnt": record["pos_false_cnt_" + task_cur],
|
| 302 |
+
},
|
| 303 |
+
}
|
| 304 |
+
|
| 305 |
+
|
| 306 |
+
def evaluate_results(
|
| 307 |
+
results: List[Dict[str, Any]],
|
| 308 |
+
record: Dict[str, int],
|
| 309 |
+
chosen_task: Sequence[str],
|
| 310 |
+
filepath: str,
|
| 311 |
+
) -> List[Dict[str, Any]]:
|
| 312 |
+
chosen = list(chosen_task) + ["All"]
|
| 313 |
+
for sample in results:
|
| 314 |
+
response = sample["response"]
|
| 315 |
+
labels = sample["labels"]
|
| 316 |
+
output = sample["output"]
|
| 317 |
+
task = sample["task_type"]
|
| 318 |
+
res = cal_metrics(response, labels, output)
|
| 319 |
+
(
|
| 320 |
+
temp_tp,
|
| 321 |
+
temp_pred_len,
|
| 322 |
+
temp_gold_len,
|
| 323 |
+
pos_true_cnt,
|
| 324 |
+
neg_true_cnt,
|
| 325 |
+
neg_false_cnt,
|
| 326 |
+
pos_false_cnt,
|
| 327 |
+
) = res
|
| 328 |
+
for task_cur in chosen:
|
| 329 |
+
if task_cur == task or task_cur == "All":
|
| 330 |
+
record["match_size_" + task_cur] += temp_tp
|
| 331 |
+
record["prediction_" + task_cur] += temp_pred_len
|
| 332 |
+
record["groud_truth_" + task_cur] += temp_gold_len
|
| 333 |
+
record["pos_true_cnt_" + task_cur] += pos_true_cnt
|
| 334 |
+
record["neg_true_cnt_" + task_cur] += neg_true_cnt
|
| 335 |
+
record["neg_false_cnt_" + task_cur] += neg_false_cnt
|
| 336 |
+
record["pos_false_cnt_" + task_cur] += pos_false_cnt
|
| 337 |
+
all_metrics = []
|
| 338 |
+
for task_cur in chosen:
|
| 339 |
+
all_metrics.append(print_metrics(task_cur, record))
|
| 340 |
+
print("chosen task: {}".format(chosen))
|
| 341 |
+
print("filepath: {}".format(filepath))
|
| 342 |
+
print("test_data_size: {}".format(len(results)))
|
| 343 |
+
return all_metrics
|
| 344 |
+
|
| 345 |
+
|
| 346 |
+
def average_precision_case_detection(results_subset: List[Dict[str, Any]]) -> float:
|
| 347 |
+
"""
|
| 348 |
+
样本级检测 Average Precision:正类为金标存在幻觉 span(labels 非空),
|
| 349 |
+
预测分数与 cal_metrics 的 case 口径一致:``output`` 为非空 list 则为 1,否则 0。
|
| 350 |
+
无正样本时返回 0.0。
|
| 351 |
+
"""
|
| 352 |
+
if not results_subset:
|
| 353 |
+
return 0.0
|
| 354 |
+
y_true: List[int] = []
|
| 355 |
+
y_score: List[float] = []
|
| 356 |
+
for s in results_subset:
|
| 357 |
+
y_true.append(1 if s.get("labels") else 0)
|
| 358 |
+
out = s.get("output")
|
| 359 |
+
y_score.append(1.0 if isinstance(out, list) and len(out) > 0 else 0.0)
|
| 360 |
+
n_pos = sum(y_true)
|
| 361 |
+
if n_pos == 0:
|
| 362 |
+
return 0.0
|
| 363 |
+
order = sorted(range(len(y_true)), key=lambda i: (-y_score[i], -i))
|
| 364 |
+
tp = 0
|
| 365 |
+
ap = 0.0
|
| 366 |
+
for rank, idx in enumerate(order, start=1):
|
| 367 |
+
if y_true[idx] == 1:
|
| 368 |
+
tp += 1
|
| 369 |
+
ap += tp / rank
|
| 370 |
+
return ap / n_pos
|
| 371 |
+
|
| 372 |
+
|
| 373 |
+
def evaluate_results_by_group_key(
|
| 374 |
+
results: List[Dict[str, Any]],
|
| 375 |
+
filepath: str,
|
| 376 |
+
group_key: str = "lang",
|
| 377 |
+
) -> List[Dict[str, Any]]:
|
| 378 |
+
"""
|
| 379 |
+
按样本字段 group_key(如 PsiloQA 的 lang)分组累计 span/case 指标,并写入
|
| 380 |
+
case_level.average_precision;最后为汇总桶 All。
|
| 381 |
+
返回 dict 中以 group_key 为顶层字段名(如 lang),替代原 task_type。
|
| 382 |
+
"""
|
| 383 |
+
|
| 384 |
+
def get_group(sample: Dict[str, Any]) -> str:
|
| 385 |
+
v = sample.get(group_key)
|
| 386 |
+
if v is None or v == "":
|
| 387 |
+
return "unknown"
|
| 388 |
+
return str(v)
|
| 389 |
+
|
| 390 |
+
groups = sorted({get_group(s) for s in results})
|
| 391 |
+
ordered = groups + ["All"]
|
| 392 |
+
records: Dict[str, Dict[str, Any]] = {b: collections.defaultdict(int) for b in ordered}
|
| 393 |
+
samples_per: Dict[str, List[Dict[str, Any]]] = {b: [] for b in groups}
|
| 394 |
+
samples_per["All"] = []
|
| 395 |
+
|
| 396 |
+
for sample in results:
|
| 397 |
+
samples_per[get_group(sample)].append(sample)
|
| 398 |
+
samples_per["All"].append(sample)
|
| 399 |
+
|
| 400 |
+
response = sample["response"]
|
| 401 |
+
labels = sample["labels"]
|
| 402 |
+
output = sample["output"]
|
| 403 |
+
res = cal_metrics(response, labels, output)
|
| 404 |
+
(
|
| 405 |
+
temp_tp,
|
| 406 |
+
temp_pred_len,
|
| 407 |
+
temp_gold_len,
|
| 408 |
+
pos_true_cnt,
|
| 409 |
+
neg_true_cnt,
|
| 410 |
+
neg_false_cnt,
|
| 411 |
+
pos_false_cnt,
|
| 412 |
+
) = res
|
| 413 |
+
for b in (get_group(sample), "All"):
|
| 414 |
+
task_cur = b
|
| 415 |
+
rec = records[b]
|
| 416 |
+
rec["match_size_" + task_cur] += temp_tp
|
| 417 |
+
rec["prediction_" + task_cur] += temp_pred_len
|
| 418 |
+
rec["groud_truth_" + task_cur] += temp_gold_len
|
| 419 |
+
rec["pos_true_cnt_" + task_cur] += pos_true_cnt
|
| 420 |
+
rec["neg_true_cnt_" + task_cur] += neg_true_cnt
|
| 421 |
+
rec["neg_false_cnt_" + task_cur] += neg_false_cnt
|
| 422 |
+
rec["pos_false_cnt_" + task_cur] += pos_false_cnt
|
| 423 |
+
|
| 424 |
+
all_metrics: List[Dict[str, Any]] = []
|
| 425 |
+
for b in ordered:
|
| 426 |
+
m = print_metrics(b, records[b])
|
| 427 |
+
m[group_key] = m.pop("task_type")
|
| 428 |
+
ap = average_precision_case_detection(samples_per[b])
|
| 429 |
+
m["case_level"]["average_precision"] = round(ap, 4)
|
| 430 |
+
print(" average_precision (case-level, nonempty output list = 1): {:.4f}".format(ap))
|
| 431 |
+
all_metrics.append(m)
|
| 432 |
+
print("group_by {}: {}".format(group_key, ordered))
|
| 433 |
+
print("filepath: {}".format(filepath))
|
| 434 |
+
print("test_data_size: {}".format(len(results)))
|
| 435 |
+
return all_metrics
|
| 436 |
+
|
| 437 |
+
|
| 438 |
+
def parse_output(output_str: str) -> List[str]:
|
| 439 |
+
output = re.findall(r"""{"hallucination list": \[.*?\]}""", output_str)
|
| 440 |
+
if not len(output):
|
| 441 |
+
return []
|
| 442 |
+
output = output[-1]
|
| 443 |
+
output = json_repair.loads(output)
|
| 444 |
+
if "hallucination list" in output:
|
| 445 |
+
return output["hallucination list"]
|
| 446 |
+
if isinstance(output, list):
|
| 447 |
+
return output
|
| 448 |
+
print("ERROR: hallucination list not found in output")
|
| 449 |
+
return []
|
| 450 |
+
|
| 451 |
+
|
| 452 |
+
def trans_instruction(ins_ori: str, task_word: str) -> str:
|
| 453 |
+
if "Your task" not in ins_ori:
|
| 454 |
+
print("error")
|
| 455 |
+
ins_ori = ins_ori.rsplit("Your task", 1)[0]
|
| 456 |
+
ins = ins_ori.strip() + "\n" + extra_sft_prompt.replace("<|task_word|>", task_word)
|
| 457 |
+
return ins
|
| 458 |
+
|
| 459 |
+
|
| 460 |
+
def trans_instruction_reasoning(ins_ori: str, task_word: str) -> str:
|
| 461 |
+
if "Your task" not in ins_ori:
|
| 462 |
+
print("error")
|
| 463 |
+
ins_ori = ins_ori.rsplit("Your task", 1)[0]
|
| 464 |
+
ins = (
|
| 465 |
+
ins_ori.strip()
|
| 466 |
+
+ "\n"
|
| 467 |
+
+ extra_sft_prompt_reasoning.replace("<|task_word|>", task_word)
|
| 468 |
+
)
|
| 469 |
+
return ins
|
| 470 |
+
|
| 471 |
+
|
| 472 |
+
def labels_have_any_supervision(results: List[Dict[str, Any]]) -> bool:
|
| 473 |
+
for s in results:
|
| 474 |
+
if s.get("labels"):
|
| 475 |
+
return True
|
| 476 |
+
return False
|
test_run_math_shepherd.py
ADDED
|
@@ -0,0 +1,107 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Offline regression tests for the release's Math-Shepherd evaluator."""
|
| 2 |
+
|
| 3 |
+
import contextlib
|
| 4 |
+
import hashlib
|
| 5 |
+
import io
|
| 6 |
+
import json
|
| 7 |
+
from pathlib import Path
|
| 8 |
+
import sys
|
| 9 |
+
import tempfile
|
| 10 |
+
import unittest
|
| 11 |
+
from unittest import mock
|
| 12 |
+
|
| 13 |
+
import pyarrow as pa
|
| 14 |
+
import pyarrow.parquet as pq
|
| 15 |
+
|
| 16 |
+
import run_math_shepherd as evaluator
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
class MathShepherdEvaluatorTests(unittest.TestCase):
|
| 20 |
+
def test_packaged_benchmark_has_614_rows_and_expected_hash(self):
|
| 21 |
+
path = Path(evaluator.__file__).with_name("math_shepherd_614_test_20260327.parquet")
|
| 22 |
+
self.assertEqual(pq.ParquetFile(path).metadata.num_rows, 614)
|
| 23 |
+
self.assertEqual(
|
| 24 |
+
hashlib.sha256(path.read_bytes()).hexdigest(),
|
| 25 |
+
"e01fabbc80b99f01307aa9095b9e186f13cae392ed0bff983dcbdd61ee0d1087",
|
| 26 |
+
)
|
| 27 |
+
|
| 28 |
+
def test_parquet_selection_includes_release_filename(self):
|
| 29 |
+
with tempfile.TemporaryDirectory() as directory:
|
| 30 |
+
path = Path(directory) / "math_shepherd_614_test_20260327.parquet"
|
| 31 |
+
path.touch()
|
| 32 |
+
self.assertEqual(evaluator.resolve_test_parquets(directory), [str(path)])
|
| 33 |
+
|
| 34 |
+
def test_gold_span_and_label_dependent_suffix(self):
|
| 35 |
+
steps = ["Correct", "Wrong", "Correct again"]
|
| 36 |
+
response, labels = evaluator.completions_to_response_and_gold(
|
| 37 |
+
steps, [True, False, True]
|
| 38 |
+
)
|
| 39 |
+
self.assertEqual(response, "Correct\nWrong\nCorrect again")
|
| 40 |
+
self.assertEqual(labels, [{"start": 8, "end": 14}])
|
| 41 |
+
tp, pred, gold, *_ = evaluator.cal_metrics_math_shepherd(
|
| 42 |
+
response, labels, ["Wrong"], steps
|
| 43 |
+
)
|
| 44 |
+
self.assertEqual((tp, pred, gold), (6, len(response) - 8, 6))
|
| 45 |
+
|
| 46 |
+
def test_metric_only_accepts_old_jsonl_without_completions(self):
|
| 47 |
+
with tempfile.TemporaryDirectory() as directory:
|
| 48 |
+
path = Path(directory) / "saved.jsonl"
|
| 49 |
+
path.write_text(json.dumps({
|
| 50 |
+
"response": "A\nB", "labels": [{"start": 2, "end": 3}],
|
| 51 |
+
"output": ["B"], "task_type": "Math",
|
| 52 |
+
}) + "\n", encoding="utf-8")
|
| 53 |
+
with mock.patch.object(sys, "argv", ["run_math_shepherd.py", "--filepath", str(path)]):
|
| 54 |
+
evaluator.main()
|
| 55 |
+
metrics = json.loads((Path(directory) / "saved_recomputed_metric.json").read_text(encoding="utf-8"))
|
| 56 |
+
self.assertEqual(metrics["test_data_size"], 1)
|
| 57 |
+
self.assertEqual(metrics["metrics"][1]["span_level"]["f1"], 1.0)
|
| 58 |
+
|
| 59 |
+
def test_full_mock_run_and_incomplete_run_detection(self):
|
| 60 |
+
with tempfile.TemporaryDirectory() as directory:
|
| 61 |
+
data_file = Path(directory) / "math_shepherd_614_test_20260327.parquet"
|
| 62 |
+
pq.write_table(pa.Table.from_pylist([
|
| 63 |
+
{"prompt": "Find x", "completions": ["A", "B"], "labels": [True, False]},
|
| 64 |
+
{"prompt": "Find y", "completions": ["C"], "labels": [True]},
|
| 65 |
+
]), data_file)
|
| 66 |
+
output_dir = Path(directory) / "results"
|
| 67 |
+
argv = [
|
| 68 |
+
"run_math_shepherd.py", "--data-file", str(data_file),
|
| 69 |
+
"--model-name", "demo/model", "--model-url", "http://localhost:7010/v1",
|
| 70 |
+
"--num-threads", "1", "--output-dir", str(output_dir),
|
| 71 |
+
]
|
| 72 |
+
fake_response = lambda prompt, **kwargs: (
|
| 73 |
+
'{"hallucination list": ["B"]}' if "Find x" in prompt
|
| 74 |
+
else '{"hallucination list": []}'
|
| 75 |
+
)
|
| 76 |
+
with mock.patch.object(sys, "argv", argv), mock.patch.object(
|
| 77 |
+
evaluator, "req_model_vllm", side_effect=fake_response
|
| 78 |
+
):
|
| 79 |
+
evaluator.main()
|
| 80 |
+
result_files = list(output_dir.glob("*.jsonl"))
|
| 81 |
+
self.assertEqual(len(result_files), 1)
|
| 82 |
+
self.assertEqual(len(result_files[0].read_text(encoding="utf-8").splitlines()), 2)
|
| 83 |
+
metric_files = list(output_dir.glob("*_metric.json"))
|
| 84 |
+
self.assertEqual(len(metric_files), 1)
|
| 85 |
+
metrics = json.loads(metric_files[0].read_text(encoding="utf-8"))
|
| 86 |
+
self.assertEqual(metrics["test_data_size"], 2)
|
| 87 |
+
self.assertEqual(metrics["model_name"], "demo/model")
|
| 88 |
+
self.assertEqual(metrics["metrics"][1]["span_level"]["f1"], 1.0)
|
| 89 |
+
|
| 90 |
+
with mock.patch.object(sys, "argv", argv), mock.patch.object(
|
| 91 |
+
evaluator, "req_model_vllm", return_value="malformed response"
|
| 92 |
+
), contextlib.redirect_stdout(io.StringIO()), contextlib.redirect_stderr(io.StringIO()):
|
| 93 |
+
with self.assertRaisesRegex(RuntimeError, "Only 0/2 rows evaluated"):
|
| 94 |
+
evaluator.main()
|
| 95 |
+
self.assertEqual(len(list(output_dir.glob("*.jsonl"))), 1)
|
| 96 |
+
|
| 97 |
+
def test_no_reasoning_changes_instruction(self):
|
| 98 |
+
steps = ["Step 1: 2+2=5"]
|
| 99 |
+
ordinary = evaluator.build_user_instruction("Compute 2+2", steps, True, False)
|
| 100 |
+
compact = evaluator.build_user_instruction("Compute 2+2", steps, False, False)
|
| 101 |
+
self.assertIn("step-by-step verification", ordinary)
|
| 102 |
+
self.assertNotIn("step-by-step verification", compact)
|
| 103 |
+
self.assertIn('"hallucination list"', compact)
|
| 104 |
+
|
| 105 |
+
|
| 106 |
+
if __name__ == "__main__":
|
| 107 |
+
unittest.main()
|