"""判分器:模型自由文本 → ①抽 ANSWER 行 → ②按类型归一化 → ③与 gold 比对。 设计要点(详见 `dataset/eval/README.md`) ------------------------------------------ * **抽取优先,降级兜底**:先找最后一条 `ANSWER: ...`;找不到才用最后一行, 并置 `fallback=True`。fallback 率单独报——它衡量的是格式合规,不是能力。 * **invalid 与 empty 单列**:有输出但解析不出(invalid)、没输出(empty)都算错, 但分开统计,否则"不会排版"会被当成"不会做题"。 * **序列给部分分**:LCP(最长正确前缀)和 PosAcc 是序列任务的核心诊断量, Exact 才是主指标。 * **CI 按图聚类**:同一张图有 21 道题,必须按 graph 做 cluster bootstrap, 否则 49k 条会被当成独立样本,CI 窄 3 倍。 用法: python -m dataset.eval.score --self-test python -m dataset.eval.score --dump-prompts prompts.jsonl python -m dataset.eval.score --pred preds.jsonl --bootstrap 1000 """ from __future__ import annotations import argparse import json import random import re import sys from collections import defaultdict from dataclasses import dataclass from pathlib import Path from typing import Any, Iterable ROOT = Path(__file__).resolve().parents[2] if str(ROOT) not in sys.path: sys.path.insert(0, str(ROOT)) from dataset.build.common import DATASET # noqa: E402 FILES: dict[str, Path] = { "node_degree": DATASET / "01-base" / "01-node" / "instances.jsonl", "edge_existence": DATASET / "01-base" / "02-edge" / "instances.jsonl", "path_length": DATASET / "01-base" / "03-connection" / "instances.jsonl", "partition_modularity": DATASET / "02-mid" / "01-community" / "instances.jsonl", "triangle_count": DATASET / "02-mid" / "02-triangle" / "instances.jsonl", "dismantle_order": DATASET / "02-mid" / "03-dismantle" / "instances.jsonl", } ANSWER_LINE = re.compile(r"answer\s*[::]\s*(.*)", re.I) PAREN = re.compile(r"\([^)]*\)|([^)]*)") THOUSANDS = re.compile(r"-?\d{1,3}(?:,\d{3})+") INT = re.compile(r"-?\d+") TOKEN = re.compile(r"[a-z]+|是|否") LETTER = re.compile(r"(? str: body = { "int": "ANSWER: ", "bool": "ANSWER: yes\nor\nANSWER: no", "choice": "ANSWER: ", "sequence": f"ANSWER: <{n_seq} integers separated by commas>", }[answer_type] return f"End your reply with exactly one final line:\n{body}" def build_prompt(rec: dict, with_format: bool = True) -> str: """题面 + 固定格式后缀。所有实验都必须走这个函数,别自己拼。""" if not with_format: return rec["question"] at = rec["answer"]["type"] n = len(rec["answer"]["value"]) if at == "sequence" else 10 return f"{rec['question']}\n\n{format_suffix(at, n)}" def format_answer(rec: dict) -> str: """把 gold 渲染成符合格式的字符串(自检 / few-shot 用)。""" at, v = rec["answer"]["type"], rec["answer"]["value"] if at == "bool": return "yes" if v else "no" if at == "sequence": return ", ".join(str(x) for x in v) return str(v) # ---------------------------------------------------------------- 抽取 @dataclass class Parsed: status: str # ok | invalid | empty chunk: str fallback: bool def _clean(s: str) -> str: return s.strip().strip("*`_ \t") def extract(text: str | None) -> Parsed: """抽答案片段:优先最后一条 ANSWER 行,降级到最后非空行。""" if text is None: return Parsed("empty", "", True) lines = [ln for ln in str(text).splitlines() if ln.strip()] if not lines: return Parsed("empty", "", True) for ln in reversed(lines): m = ANSWER_LINE.match(_clean(ln)) if m: return Parsed("ok", _clean(m.group(1)), False) return Parsed("ok", _clean(lines[-1]), True) # ---------------------------------------------------------------- 归一化 def parse_int(chunk: str) -> int | None: s = PAREN.sub(" ", chunk).strip() if THOUSANDS.fullmatch(s): # 整段就是 "4,575" return int(s.replace(",", "")) nums = INT.findall(s) return int(nums[-1]) if nums else None def parse_bool(chunk: str) -> bool | None: s = PAREN.sub(" ", chunk).lower() toks = TOKEN.findall(s) ys = any(t in YES_WORDS for t in toks) ns = any(t in NO_WORDS for t in toks) if ys == ns: # 都有 → 歧义;都没有 → 解析不出 return None return ys def parse_choice(chunk: str) -> str | None: letters = set(LETTER.findall(chunk.upper())) return letters.pop() if len(letters) == 1 else None def parse_sequence(chunk: str) -> list[int] | None: s = PAREN.sub(" ", chunk) # 不处理千分位:会把 "12, 123" 并成 12123 nums = INT.findall(s) return [int(x) for x in nums] if nums else None PARSERS = { "int": parse_int, "bool": parse_bool, "choice": parse_choice, "sequence": parse_sequence, } # ---------------------------------------------------------------- 判分 @dataclass class Row: id: str task: str graph: str split: str status: str = "ok" # ok | invalid | empty correct: bool = False fallback: bool = False lcp: int | None = None pos: float | None = None def score_one(rec: dict, text: str | None) -> Row: row = Row(rec["id"], rec["task"], rec["graph"], rec["split"]) p = extract(text) row.fallback = p.fallback if p.status == "empty": row.status = "empty" return row at, gold = rec["answer"]["type"], rec["answer"]["value"] val = PARSERS[at](p.chunk) if val is None: row.status = "invalid" return row if at == "sequence": g = list(gold) k = next((i for i, (a, b) in enumerate(zip(val, g)) if a != b), min(len(val), len(g))) row.lcp = k row.pos = sum(1 for a, b in zip(val, g) if a == b) / len(g) row.correct = len(val) == len(g) and val == g elif at == "bool": row.correct = bool(val) == bool(gold) else: row.correct = val == gold return row # ---------------------------------------------------------------- 汇总 def load_records(tasks: Iterable[str] | None = None) -> list[dict]: out: list[dict] = [] for task, path in FILES.items(): if tasks and task not in tasks: continue if not path.exists(): raise SystemExit(f"[x] 缺 {path};先跑 build/gen_base.py / gen_mid.py") with open(path, encoding="utf-8") as f: out += [json.loads(ln) for ln in f] return out def load_preds(path: Path) -> dict[str, str]: preds: dict[str, str] = {} with open(path, encoding="utf-8") as f: for i, ln in enumerate(f, 1): ln = ln.strip() if not ln: continue try: obj = json.loads(ln) except json.JSONDecodeError as e: raise SystemExit(f"[x] {path.name}:{i} 不是 JSON:{e}") if "id" not in obj: raise SystemExit(f"[x] {path.name}:{i} 缺 id") for key in ("output", "prediction", "response", "answer", "text"): if key in obj: preds[obj["id"]] = obj[key] break else: preds[obj["id"]] = "" return preds def boot_ci(pairs: list[tuple[str, float]], iters: int, seed: int = 13) -> tuple[float, float]: """按图 cluster bootstrap:有放回重采样图,图内所有题一起进入。""" by: dict[str, list[float]] = defaultdict(list) for g, c in pairs: by[g].append(c) keys = list(by) if not keys or iters <= 0: return (float("nan"), float("nan")) rng = random.Random(seed) vals = [] for _ in range(iters): s = 0.0 n = 0 for _ in range(len(keys)): k = keys[rng.randrange(len(keys))] s += sum(by[k]) n += len(by[k]) vals.append(s / n if n else 0.0) vals.sort() return vals[int(0.025 * iters)], vals[int(0.975 * iters) - 1] def summarize(rows: list[Row], iters: int) -> dict[str, dict]: """按任务汇总。exact 的分母 = 全部题(invalid/empty 算错)。""" agg: dict[str, dict[str, Any]] = {} for r in rows: a = agg.setdefault(r.task, {"rows": [], "n": 0, "correct": 0, "invalid": 0, "empty": 0, "fallback": 0, "lcp": [], "pos": []}) a["rows"].append(r) a["n"] += 1 a["correct"] += int(r.correct) a["invalid"] += int(r.status == "invalid") a["empty"] += int(r.status == "empty") a["fallback"] += int(r.fallback) if r.lcp is not None: a["lcp"].append(r.lcp) a["pos"].append(r.pos or 0.0) for a in agg.values(): a["exact"] = a["correct"] / a["n"] if a["n"] else 0.0 a["ci"] = boot_ci([(r.graph, float(r.correct)) for r in a["rows"]], iters) return agg def print_summary(agg: dict[str, dict], iters: int) -> None: tot = sum(a["n"] for a in agg.values()) cor = sum(a["correct"] for a in agg.values()) inv = sum(a["invalid"] for a in agg.values()) emp = sum(a["empty"] for a in agg.values()) fb = sum(a["fallback"] for a in agg.values()) head = (f"{'task':<22}{'n':>7}{'exact':>8}{'95% CI':>17}" f"{'invalid%':>10}{'empty%':>8}{'fallback%':>11}") print(head) print("-" * len(head)) for task in FILES: if task not in agg: continue a = agg[task] lo, hi = a["ci"] print(f"{task:<22}{a['n']:>7}{a['exact']:>8.3f}" f"{f'[{lo:.3f},{hi:.3f}]':>17}" f"{a['invalid'] / a['n'] * 100:>10.1f}{a['empty'] / a['n'] * 100:>8.1f}" f"{a['fallback'] / a['n'] * 100:>11.1f}") print("-" * len(head)) all_rows = [r for a in agg.values() for r in a["rows"]] lo, hi = boot_ci([(r.graph, float(r.correct)) for r in all_rows], iters) print(f"{'overall':<22}{tot:>7}{cor / tot:>8.3f}{f'[{lo:.3f},{hi:.3f}]':>17}" f"{inv / tot * 100:>10.1f}{emp / tot * 100:>8.1f}{fb / tot * 100:>11.1f}") seq = [r for r in all_rows if r.lcp is not None] if seq: lcp = sum(r.lcp for r in seq) / len(seq) pos = sum(r.pos or 0.0 for r in seq) / len(seq) print(f"\nsequence 诊断(n={len(seq)}): LCP 均值 {lcp:.2f}/10 PosAcc 均值 {pos:.3f}") # ---------------------------------------------------------------- 自检 def _self_test() -> int: recs = load_records() by_task: dict[str, dict] = {} for r in recs: by_task.setdefault(r["task"], r) fails = 0 def chk(name: str, cond: bool) -> None: nonlocal fails fails += int(not cond) print(f" {'ok ' if cond else 'FAIL'} {name}") print("[1] oracle:gold 按格式输出 → exact=1") for task, rec in by_task.items(): row = score_one(rec, f"reasoning...\nANSWER: {format_answer(rec)}") chk(f"{task}", row.correct and row.status == "ok" and not row.fallback) print("[2] 格式噪声:粗体/全角冒号/多余空格/括号 → 仍应解析且不算 fallback") for task, rec in by_task.items(): ans = format_answer(rec) for style in (f"**ANSWER:** {ans}", f"answer: {ans}", f" ANSWER : {ans} "): row = score_one(rec, f"...\n{style}") chk(f"{task} {style!r}", row.correct and not row.fallback) print("[3] 降级:只有正文没有 ANSWER 行 → 应能解析但标记 fallback") for task, rec in by_task.items(): row = score_one(rec, f"The answer is {format_answer(rec)}") chk(f"{task}", row.correct and row.fallback) print("[4] 故意答错 → exact=0") for task, rec in by_task.items(): v = rec["answer"]["value"] if rec["answer"]["type"] == "bool": bad = "no" if v else "yes" elif rec["answer"]["type"] == "choice": bad = {"A": "B", "B": "C", "C": "A"}[v] elif rec["answer"]["type"] == "sequence": bad = ", ".join(str(x + 1) for x in v) else: bad = str(v + 1) row = score_one(rec, f"ANSWER: {bad}") chk(f"{task} wrong → {bad[:20]}", not row.correct and row.fallback is False) print("[5] 边界:空输出 / 废话 / 歧义 yes-no / 多字母") chk("空字符串 → empty", score_one(by_task["node_degree"], "").status == "empty") chk("None → empty", score_one(by_task["node_degree"], None).status == "empty") chk("废话 → invalid", score_one(by_task["node_degree"], "I cannot determine this.").status == "invalid") chk("yes 与 no 并存 → invalid", score_one(by_task["edge_existence"], "ANSWER: yes or no").status == "invalid") chk("A 与 B 并存 → invalid", score_one(by_task["partition_modularity"], "ANSWER: A or B").status == "invalid") print("[6] 序列部分分:只改第 4 位 → lcp=3, pos=0.9, exact=0") rec = by_task["dismantle_order"] g = rec["answer"]["value"] bad = list(g) bad[3] = bad[3] + 7 row = score_one(rec, "ANSWER: " + ", ".join(map(str, bad))) chk(f"lcp={row.lcp}", row.lcp == 3) chk(f"pos={row.pos:.2f}", abs((row.pos or 0) - 0.9) < 1e-9) chk("exact=False", not row.correct) print("[7] int 千分位:'4,575' 应读成 4575;括号内容不干扰") rec = next(r for r in recs if r["answer"]["type"] == "int" and r["answer"]["value"] > 1000) chk("千分位", score_one(rec, f"ANSWER: {rec['answer']['value']:,}").correct) chk("括号", score_one(rec, f"ANSWER: {rec['answer']['value']} (computed above)").correct) print(f"\n{'[ok] 自检全部通过' if fails == 0 else f'[x] {fails} 项失败'}") return 0 if fails == 0 else 1 # ---------------------------------------------------------------- CLI def main() -> int: ap = argparse.ArgumentParser(description="拓扑 QA 判分器") ap.add_argument("--pred", type=Path, help="预测 jsonl:{id, output}") ap.add_argument("--dump-prompts", type=Path, help="导出带格式后缀的 prompt jsonl") ap.add_argument("--tasks", nargs="*", help="只跑指定任务") ap.add_argument("--bootstrap", type=int, default=400, help="cluster bootstrap 次数") ap.add_argument("--self-test", action="store_true") args = ap.parse_args() if args.self_test: return _self_test() recs = load_records(args.tasks) if args.dump_prompts: args.dump_prompts.parent.mkdir(parents=True, exist_ok=True) with open(args.dump_prompts, "w", encoding="utf-8", newline="\n") as f: for r in recs: f.write(json.dumps({"id": r["id"], "task": r["task"], "split": r["split"], "graph": r["graph"], "prompt": build_prompt(r)}, ensure_ascii=False) + "\n") print(f"[ok] {len(recs)} 条 prompt → {args.dump_prompts}") return 0 if not args.pred: ap.error("需要 --pred 或 --dump-prompts 或 --self-test") preds = load_preds(args.pred) rows = [score_one(r, preds.get(r["id"])) for r in recs] miss = sum(1 for r in rows if r.status == "empty" and r.id not in preds) agg = summarize(rows, args.bootstrap) print_summary(agg, args.bootstrap) if miss: print(f"\n[!] {miss}/{len(rows)} 条在预测文件里找不到(已按 empty 计)") return 0 if __name__ == "__main__": raise SystemExit(main())