File size: 7,333 Bytes
3ccaf5a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
"""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()