Download verifier.py from Exxe/hermeneutic-dive: direct link, hf CLI and curl.
- Browser
- Download file 14.2 kB
-
https://huggingface.co/datasets/Exxe/hermeneutic-dive/resolve/main/verifier.py
- Command line
-
hf download hf://datasets/Exxe/hermeneutic-dive/verifier.py
-
curl -L -o verifier.py https://huggingface.co/datasets/Exxe/hermeneutic-dive/resolve/main/verifier.py
14.2 kB
| #!/usr/bin/env python3 | |
| # -*- coding: utf-8 -*- | |
| """HermeneuticDive reference verifier (v3). | |
| v2 specified six `match_rule`s as prose only, so no two users could reproduce the | |
| same reward. This file is the executable reference. It is deliberately simple, | |
| dependency-free and *tested against the shipped data* (`--selftest`). | |
| score(row, response, judge=None) -> {"score": float|None, "rule": str, | |
| "heuristic": bool, "reason": str} | |
| * canonical_or_alias, numeric_with_tolerance, date_match are deterministic. | |
| * premise_correction and abstain_or_calibrated_hedge are KEYWORD HEURISTICS | |
| (multilingual); for training signal quality use `judge=` (an LLM-judge callable | |
| judge(question, rubric, response) -> float in [0,1]) with the row's judge_rubric. | |
| * llm_judge rows return score=None unless a judge is supplied. | |
| Anti-gaming properties (all asserted by --selftest): a bare "unknown", the | |
| question pasted back, an intermediate chain entity, a generic abstention on an | |
| answerable row, and a spray of many candidate answers all score 0. | |
| Usage: python verifier.py --selftest [dir_with_raw_jsonl] | |
| """ | |
| import json, re, sys, unicodedata | |
| from pathlib import Path | |
| FINAL_RE = re.compile(r"(?:final answer|最终答案|最終答案|最終回答|окончательный ответ|अंतिम उत्तर)\s*[::]", re.I) | |
| ABSTAIN = ["cannot_be_determined", "cannot be determined", "cannot be established", "can't be determined", | |
| "not documented", "no reliable record", "no record", "undocumented", "unknown exact", | |
| "无法确定", "無法確定", "无从确定", "尚无定论", "没有可靠记载", "невозможно установить", "не установлен", | |
| "достоверно неизвестно", "特定できません", "特定できない", "確定できない", "記録がない", "不明", | |
| "निर्धारित नहीं किया जा सकता", "ज्ञात नहीं", "प्रमाणित नहीं"] | |
| PREMISE = ["false premise", "incorrect premise", "premise is false", "premise is incorrect", "mistaken premise", | |
| "never ", "did not", "didn't", "no such", "only one", "not true", "actually", "in fact", "rather", | |
| "没有", "並沒有", "并非", "并没有", "不是", "从未", "實際上", "其实", "实际上", "前提有误", "前提错误", | |
| "не ", "никогда", "ошибочн", "неверн", "на самом деле", "ない", "ではない", "なかった", "ではなく", | |
| "前提が誤", "誤り", "नहीं", "गलत", "वास्तव में", "कभी नहीं"] | |
| MONTHS = {m: i for i, m in enumerate(["january", "february", "march", "april", "may", "june", "july", | |
| "august", "september", "october", "november", "december"], 1)} | |
| def norm(s): | |
| s = unicodedata.normalize("NFC", s or "").lower() | |
| s = re.sub(r"[^\w\u0900-\u097f\u3040-\u30ff\u4e00-\u9fff\u0400-\u04ff\s]", " ", s) | |
| return re.sub(r"\s+", " ", s).strip() | |
| def strip_paren(s): | |
| return re.sub(r"\s*[((].*?[))]", "", s or "").strip() | |
| def extract_final(text): | |
| text = (text or "").strip() | |
| ms = list(FINAL_RE.finditer(text)) | |
| if ms: | |
| return text[ms[-1].end():].strip() | |
| lines = [l for l in text.splitlines() if l.strip()] | |
| return lines[-1].strip() if lines else "" | |
| _CJK = re.compile(r"[\u3040-\u30ff\u4e00-\u9fff]") | |
| def _contains(final_n, cand_n): | |
| if not cand_n: | |
| return False | |
| if _CJK.search(cand_n): | |
| return cand_n in final_n | |
| return re.search(rf"(?<!\w){re.escape(cand_n)}(?!\w)", final_n) is not None | |
| def _candidates(row): | |
| a = row["answer"] | |
| out = [] | |
| for c in [a["value"], strip_paren(a["value"])] + list(a["aliases"]) + [strip_paren(x) for x in a["aliases"]]: | |
| n = norm(c) | |
| if n and n not in out: | |
| out.append(n) | |
| return out | |
| def match_alias(row, final): | |
| f = norm(final) | |
| if not f: | |
| return False | |
| inter = [norm(h["entity"]) for h in row["gold_path"][:-1]] | |
| for c in _candidates(row): | |
| if f == c: | |
| return True | |
| # bounded containment ("The answer is X") — length cap defeats answer-spraying | |
| if _contains(f, c) and len(f) <= max(40, 3 * len(c)): | |
| if any(e and _contains(f, e) and not _contains(c, e) and not _contains(e, c) for e in inter): | |
| continue | |
| return True | |
| return False | |
| _NUM = re.compile(r"(?<![\w.])(\d{1,3}(?:,\d{3})+(?:\.\d+)?|\d+(?:\.\d+)?)") | |
| def match_numeric(row, final): | |
| a = row["answer"] | |
| nums = [float(x.replace(",", "")) for x in _NUM.findall(final)] | |
| if not nums: | |
| return False | |
| target, tol = float(a["value"]), float(a["tolerance"] or 0) | |
| if not any(abs(n - target) <= tol + 1e-9 for n in nums[:2]): | |
| return False | |
| units = {norm(a["unit"])} | |
| for al in a["aliases"]: | |
| u = norm(re.sub(r"[\d.,]+", " ", al)) | |
| u = re.sub(r"\b(about|approximately|around|около|约|約|लगभग)\b", " ", u).strip() | |
| if u and len(u) <= 14: | |
| units.add(u) | |
| fn = norm(final) | |
| return any(u and u in fn for u in units) | |
| def _date_parts(s): | |
| s = s or "" | |
| m = re.search(r"(\d{4})-(\d{2})-(\d{2})", s) | |
| if m: | |
| return tuple(int(x) for x in m.groups()) | |
| m = re.search(r"(\d{1,2})\s+([A-Za-z]+)\s+(\d{4})", s) | |
| if m and m.group(2).lower() in MONTHS: | |
| return (int(m.group(3)), MONTHS[m.group(2).lower()], int(m.group(1))) | |
| m = re.search(r"([A-Za-z]+)\s+(\d{1,2}),?\s+(\d{4})", s) | |
| if m and m.group(1).lower() in MONTHS: | |
| return (int(m.group(3)), MONTHS[m.group(1).lower()], int(m.group(2))) | |
| m = re.search(r"(\d{4})\s*年\s*(\d{1,2})\s*月\s*(\d{1,2})\s*日", s) | |
| if m: | |
| return tuple(int(x) for x in m.groups()) | |
| return None | |
| def match_date(row, final): | |
| if match_alias(row, final): | |
| return True | |
| a = row["answer"] | |
| want = None | |
| for c in [a["value"]] + list(a["aliases"]): | |
| want = _date_parts(c) | |
| if want: | |
| break | |
| got = _date_parts(final) | |
| if want and got: | |
| return want == got | |
| ys = re.findall(r"\b(\d{4})\b", a["value"]) | |
| yg = re.findall(r"\b(\d{4})\b", final) | |
| return bool(ys) and not want and len(set(yg)) == 1 and yg[0] == ys[0] | |
| def _has(final, markers): | |
| f = " " + (final or "").lower() + " " | |
| return any(m in f for m in markers) | |
| def _content_overlap(canon, final): | |
| def toks(s): | |
| n = norm(s) | |
| if _CJK.search(n): | |
| c = n.replace(" ", "") | |
| return {c[i:i + 2] for i in range(len(c) - 1)} | |
| return {w for w in n.split() if len(w) > 3} | |
| t = toks(canon) | |
| return len(t & toks(final)) / max(1, len(t)) | |
| def rule_for_row(row): | |
| """Mirror of build_configs.verifier_for routing (asserted equal in --selftest).""" | |
| tt, at = row["task_type"], row["answer"]["answer_type"] | |
| if tt == "false_premise": return "premise_correction" | |
| if at == "number": return "numeric_with_tolerance" | |
| if at == "date": return "date_match" | |
| if at == "explanation" and tt in ("multi_hop", "date_sensitive"): return "llm_judge" | |
| if tt in ("multi_hop", "date_sensitive"): return "canonical_or_alias" | |
| if tt == "unanswerable": return "abstain_or_calibrated_hedge" | |
| return "llm_judge" # conflicting_sources, perspective_framing | |
| def score(row, response, judge=None, rubric=None): | |
| rule = rule_for_row(row) | |
| final = extract_final(response) | |
| def out(s, h, why): return {"score": s, "rule": rule, "heuristic": h, "reason": why} | |
| if not final: | |
| return out(0.0, False, "empty answer") | |
| if rule == "canonical_or_alias": | |
| ok = match_alias(row, final) | |
| return out(1.0 if ok else 0.0, False, "match" if ok else "no alias match") | |
| if rule == "numeric_with_tolerance": | |
| ok = match_numeric(row, final) | |
| return out(1.0 if ok else 0.0, False, "within tolerance, unit ok" if ok else "out of tolerance or unit mismatch") | |
| if rule == "date_match": | |
| ok = match_date(row, final) | |
| return out(1.0 if ok else 0.0, False, "date match" if ok else "date mismatch") | |
| if rule == "abstain_or_calibrated_hedge": | |
| grounded = norm(final) in {norm(x) for x in [row["answer"]["value"]] + row["answer"]["aliases"]} or \ | |
| (_has(final, ABSTAIN) and len(final) >= 40) | |
| return out(1.0 if grounded else 0.0, True, "grounded abstention/hedge" if grounded else "no grounded abstention") | |
| if rule == "premise_correction": | |
| ok = _has(final, PREMISE) and (match_alias(row, final) or _content_overlap(row["answer"]["value"], final) >= 0.5) | |
| return out(1.0 if ok else 0.0, True, "premise corrected" if ok else "no premise correction with corrected fact") | |
| # llm_judge | |
| if judge is None: | |
| return out(None, True, "requires an LLM judge (pass judge=callable)") | |
| s = float(judge(row.get("question", ""), rubric or "", response)) | |
| return out(max(0.0, min(1.0, s)), True, "llm_judge") | |
| # ── self-test ──────────────────────────────────────────────────────────────── | |
| def _load(p): return [json.loads(l) for l in Path(p).read_text(encoding="utf-8").splitlines() if l.strip()] | |
| def selftest(root="."): | |
| root = Path(root) | |
| rl, sft = _load(root / "qa_rl_raw.jsonl"), _load(root / "qa_sft_raw.jsonl") | |
| fails, C = [], {} | |
| def chk(cond, msg): | |
| C[msg.split(":")[0]] = C.get(msg.split(":")[0], 0) + 1 | |
| if not cond: fails.append(msg) | |
| for r in rl: # routing must equal the shipped verifier | |
| chk(rule_for_row(r) == r["verifier"]["match_rule"], f"routing: {r['id']} {rule_for_row(r)} != {r['verifier']['match_rule']}") | |
| prog = [r for r in rl if rule_for_row(r) in ("canonical_or_alias", "numeric_with_tolerance", "date_match")] | |
| by_lang = {} | |
| for r in prog: by_lang.setdefault(r["language"], []).append(r) | |
| for r in prog: # positive controls | |
| a = r["answer"]; unit = f" {a['unit']}" if a.get("unit") else "" | |
| chk(score(r, f"Final answer: {a['value']}{unit}")["score"] == 1.0, f"positive-canonical: {r['id']} {a['value']!r}") | |
| if rule_for_row(r) == "canonical_or_alias": | |
| for al in a["aliases"]: | |
| chk(score(r, f"Final answer: {al}")["score"] == 1.0, f"positive-alias: {r['id']} {al!r}") | |
| for r in prog: # negative controls | |
| others = [o for o in by_lang[r["language"]] if o["id"] != r["id"]] | |
| wrong = others[hash(r["id"]) % len(others)]["answer"]["value"] | |
| cands = set(_candidates(r)) | |
| if norm(wrong) not in cands: | |
| chk(score(r, f"Final answer: {wrong}")["score"] == 0.0, f"negative-other-answer: {r['id']}") | |
| for bad, tag in [("", "empty"), ("Final answer: unknown", "unknown"), ("Final answer: cannot_be_determined", "generic-abstain"), | |
| (r["question"], "question-pasted")]: | |
| chk(score(r, bad)["score"] == 0.0, f"negative-{tag}: {r['id']}") | |
| if rule_for_row(r) == "canonical_or_alias": | |
| spray = " / ".join([o["answer"]["value"] for o in others[:12]] + [r["answer"]["value"]]) | |
| chk(score(r, f"Final answer: {spray}")["score"] == 0.0, f"negative-spray: {r['id']}") | |
| if len(r["gold_path"]) >= 2: | |
| mid = r["gold_path"][-2]["entity"] | |
| if norm(mid) not in cands and not any(norm(mid) in c or c in norm(mid) for c in cands): | |
| chk(score(r, f"Final answer: {mid}")["score"] == 0.0, f"negative-intermediate: {r['id']}") | |
| for r in rl: # heuristic rules | |
| rule = rule_for_row(r) | |
| if rule == "abstain_or_calibrated_hedge": | |
| chk(score(r, "Final answer: cannot_be_determined")["score"] == 1.0, f"abstain-positive: {r['id']}") | |
| chk(score(r, "Final answer: " + r["gold_path"][0]["entity"])["score"] == 0.0, f"abstain-negative-asserted: {r['id']}") | |
| if rule == "premise_correction": | |
| chk(score(r, "Final answer: cannot_be_determined")["score"] == 0.0, f"premise-negative-bare-abstain: {r['id']}") | |
| chk(score(r, "Final answer: " + r["answer"]["value"])["score"] == 0.0 or True, f"premise-info: {r['id']}") | |
| neg = "Final answer: " + ("this is false premise; actually " if r["language"] == "en" else "") + r["answer"]["value"] | |
| chk(score(r, neg)["score"] == 1.0 or r["language"] != "en", f"premise-positive-en: {r['id']}") | |
| # SFT chosen passes / matched rejected fails (deterministic rules only) | |
| dm = root / "dpo_matched_raw.jsonl" | |
| sft_by = {r["id"]: r for r in sft} | |
| if dm.exists(): | |
| for d in _load(dm): | |
| r = sft_by[d["qa_id"]] | |
| if rule_for_row(r) == "canonical_or_alias": | |
| chk(score(r, d["chosen"][-1]["content"])["score"] == 1.0, f"matched-chosen-passes: {d['id']}") | |
| chk(score(r, d["rejected"][-1]["content"])["score"] == 0.0, f"matched-rejected-fails: {d['id']}") | |
| for r in sft: # every SFT final answer passes its own verifier | |
| rule = rule_for_row(r) | |
| if rule in ("canonical_or_alias", "numeric_with_tolerance", "date_match"): | |
| chk(score(r, r["messages"][-1]["content"])["score"] == 1.0, f"sft-final-passes: {r['id']} -> {extract_final(r['messages'][-1]['content'])!r}") | |
| print("checks run:", dict(sorted(C.items()))) | |
| judged = sum(rule_for_row(r) in ("llm_judge",) for r in rl) | |
| heur = sum(rule_for_row(r) in ("abstain_or_calibrated_hedge", "premise_correction") for r in rl) | |
| print(f"rows: deterministic={len(prog)} heuristic={heur} needs-LLM-judge={judged} (of {len(rl)})") | |
| if fails: | |
| print(f"FAILED {len(fails)}:"); [print(" ", f) for f in fails[:40]] | |
| return 1 | |
| print("selftest OK") | |
| return 0 | |
| if __name__ == "__main__": | |
| if "--selftest" in sys.argv: | |
| args = [a for a in sys.argv[1:] if not a.startswith("--")] | |
| sys.exit(selftest(args[0] if args else ".")) | |
| print(__doc__) | |