"""LaTeX-aware accuracy evaluation. Addresses the answer-equivalence rabbit hole flagged in the paper (\\left(3,\\frac{\\pi}{2}\\right) == (3,\\frac{\\pi}{2})) by delegating to HuggingFace's `math_verify` library, which parses LaTeX + symbolic forms and checks equivalence via SymPy. Two entry points: 1. A library function `compute_accuracy(jsonl_path, benchmark)` reusable from the figure scripts (e.g. make_ablation_figure.py loading the FP16 reference accuracy). 2. A CLI that writes an accuracy JSON next to the input jsonl so downstream scripts can avoid redoing the work. Input jsonls may be: - Raw inference outputs (has: `output`, `gold_answer`) - Segmented outputs (has: `final_answer`, possibly `gold_answer`) - Diagnosed outputs (has: `is_correct_final` already — we skip and just count) """ import argparse import json import os import re from functools import lru_cache from typing import List, Optional, Tuple # --------------------------------------------------------------------------- # Gold-answer loader (cached per benchmark) # --------------------------------------------------------------------------- @lru_cache(maxsize=8) def _load_gold(benchmark: str): from datasets import load_dataset if benchmark == "gsm8k": ds = load_dataset("openai/gsm8k", "main", split="test") return {f"gsm8k_{i}": ex["answer"].split("####")[-1].strip() for i, ex in enumerate(ds)} if benchmark == "math500": ds = load_dataset("HuggingFaceH4/MATH-500", split="test") return {f"math500_{i}": ex["answer"] for i, ex in enumerate(ds)} if benchmark == "gpqa": ds = load_dataset("Idavidrein/gpqa", "gpqa_diamond", split="train") return {f"gpqa_{i}": ex.get("Correct Answer", "") for i, ex in enumerate(ds)} raise ValueError(f"Unknown benchmark: {benchmark}") # --------------------------------------------------------------------------- # Answer extraction + equivalence # --------------------------------------------------------------------------- def _balanced_extract(raw: str) -> Optional[str]: """Return the contents of the LAST `\\boxed{...}` in `raw`, handling arbitrarily nested braces. Returns None if no closed `\\boxed{...}` exists. Regex with one level of bracket nesting (as used by some upstream pipelines including stepprobe.segment) silently truncates `\\frac{14}{3}` to `\\frac{14` — hence this hand-written scanner. """ idx = raw.rfind(r"\boxed{") if idx < 0: return None start = idx + len(r"\boxed{") depth = 1 i = start while i < len(raw): ch = raw[i] if ch == "{": depth += 1 elif ch == "}": depth -= 1 if depth == 0: return raw[start:i] i += 1 return None def _looks_balanced(s: str) -> bool: """Cheap sanity check: equal open/close braces AND no trailing backslash.""" return s.count("{") == s.count("}") and not s.endswith("\\") def extract_pred(trace: dict) -> str: """Pull out the model's final answer. Prefers `final_answer` if it has balanced braces; otherwise re-extracts from the raw output with a balanced-brace scanner. """ pred = (trace.get("final_answer") or "").strip() if pred and _looks_balanced(pred): return pred raw = trace.get("output") or trace.get("raw_output") or "" rescued = _balanced_extract(raw) return rescued or pred def _equiv(pred: str, gold: str) -> bool: """math_verify-based equivalence; degrades gracefully to string match.""" if not pred or not gold: return False try: from math_verify import parse, verify # math_verify prefers LaTeX wrapped in \\boxed{...}; synthesize if needed. p_str = pred if pred.startswith("\\boxed") else f"\\boxed{{{pred}}}" g_str = gold if gold.startswith("\\boxed") else f"\\boxed{{{gold}}}" return bool(verify(parse(g_str), parse(p_str))) except Exception: # SymPy timeouts / parse errors — fall back to a permissive # normalized string match so we never block on a single weird trace. def norm(s): return (s or "").strip().strip("$").replace(" ", "").replace(",", "").lower() return norm(pred) == norm(gold) # --------------------------------------------------------------------------- # Public API # --------------------------------------------------------------------------- def compute_accuracy(jsonl_path: str, benchmark: str, use_cache: bool = True) -> Optional[Tuple[int, int]]: """Return (n_correct, n_total) for one jsonl file, or None if missing. Writes a small `.acc.json` sidecar next to the jsonl so repeated calls are O(1) rather than O(n_problems). """ if not os.path.exists(jsonl_path): return None cache_path = jsonl_path + ".acc.json" if use_cache and os.path.exists(cache_path): with open(cache_path) as f: d = json.load(f) return d["n_correct"], d["n_total"] # If the file already has `is_correct_final`, trust it — this matches # the convention used elsewhere in the pipeline for diagnosed files. traces = [] has_verdict = True with open(jsonl_path) as f: for line in f: t = json.loads(line) traces.append(t) if "is_correct_final" not in t: has_verdict = False if has_verdict and traces: n_correct = sum(1 for t in traces if t.get("is_correct_final")) n_total = len(traces) else: golds = _load_gold(benchmark) n_correct, n_total = 0, 0 for t in traces: pid = t.get("problem_id") gold = t.get("gold_answer") or golds.get(pid, "") pred = extract_pred(t) n_total += 1 if _equiv(pred, gold): n_correct += 1 if use_cache: with open(cache_path, "w") as f: json.dump({"n_correct": n_correct, "n_total": n_total, "accuracy": n_correct / n_total if n_total else None, "benchmark": benchmark}, f) return n_correct, n_total def accuracy(jsonl_path: str, benchmark: str) -> Optional[float]: r = compute_accuracy(jsonl_path, benchmark) if r is None or r[1] == 0: return None return r[0] / r[1] # --------------------------------------------------------------------------- # CLI # --------------------------------------------------------------------------- def main(): parser = argparse.ArgumentParser() parser.add_argument("--jsonl", required=True, help="Inference/segmented/diagnosis jsonl") parser.add_argument("--benchmark", required=True, choices=["gsm8k", "math500", "gpqa"]) parser.add_argument("--no-cache", action="store_true") args = parser.parse_args() r = compute_accuracy(args.jsonl, args.benchmark, use_cache=not args.no_cache) if r is None: print(f"missing: {args.jsonl}") return n_correct, n_total = r print(f"{args.jsonl}") print(f" accuracy: {n_correct}/{n_total} = {n_correct/n_total:.3f}" if n_total else " (no traces)") if __name__ == "__main__": main()