#!/usr/bin/env python3 """evaluate_benchmark.py -- scoring harness for the DGN math benchmark. Usage ----- python evaluate_benchmark.py --dataset \ --predictions \ [--out report.json] \ [--tiers exact,numeric,symbolic] [--quiet] The harness scores a predictions file against a dataset file. It extracts the final answer from each model response, compares it with the gold answer in a ladder of four comparison strengths (exact / numeric / symbolic), and reports overall accuracy, a per-tier breakdown, per-chapter / per-group / per-marker / per-source / per-verification breakdowns and a per-item table. Exit codes: 0 on success, 2 on a usage error (argparse), 1 on a file or input error. A malformed dataset row or prediction line never aborts the run: it is counted as an error and reported. See BENCHMARKING.md for the full description of the scoring model. """ from __future__ import annotations import argparse import json import os import re import sys import warnings from collections import OrderedDict # -------------------------------------------------------------------------- # optional dependencies # -------------------------------------------------------------------------- try: # sympy is required for the symbolic tier import sympy as sp from sympy.parsing.latex import parse_latex HAVE_SYMPY = True except Exception: # pragma: no cover - sympy is present in the project venv sp = None parse_latex = None HAVE_SYMPY = False try: from latex2sympy2_extended import latex2sympy as _latex2sympy except Exception: # pragma: no cover _latex2sympy = None # -------------------------------------------------------------------------- # constants # -------------------------------------------------------------------------- ACCEPT = "accept" REJECT = "reject" UNKNOWN = "unknown" ALL_TIERS = ("exact", "numeric", "symbolic") REL_TOL = 1e-6 # relative tolerance of the numeric tier ABS_TOL = 1e-9 # absolute tolerance around zero SYM_TOL = 1e-9 # tolerance of the symbolic numeric fallback N_SAMPLE_POINTS = 8 # evaluation points used by the symbolic tier UNITS = { "kg", "g", "mg", "m", "cm", "mm", "km", "h", "hr", "hrs", "min", "s", "sec", "l", "ml", "deg", "rad", "usd", "eur", "rubles", "units", "unit", "years", "year", "days", "day", "hours", "hour", "minutes", "minute", "seconds", "second", "degrees", "kmh", "mph", } # -------------------------------------------------------------------------- # small text utilities # -------------------------------------------------------------------------- _BOXED_RE = re.compile(r"\\boxed\s*\{") _ASSIGN_RE = re.compile(r"^\s*[A-Za-z](?:_\{?\d+(?:,\d+)?\}?|_?\d+)?\s*=\s*(.*)$", re.S) _NUMBER_RE = re.compile(r"[-+]?\d+(?:[.,]\d+)?(?:\s*/\s*\d+(?:[.,]\d+)?)?") _LATEXFRAC_RE = re.compile(r"\\[dt]?frac\s*\{([^{}]*)\}\s*\{([^{}]*)\}") def strip_outer_dollars(s: str) -> str: """Remove a single pair of surrounding ``$`` / ``$$`` delimiters.""" s = s.strip() for _ in range(2): if len(s) >= 4 and s.startswith("$$") and s.endswith("$$"): s = s[2:-2].strip() continue if len(s) >= 2 and s.startswith("$") and s.endswith("$") and "$" not in s[1:-1]: s = s[1:-1].strip() continue break return s def clean_math_text(s: str) -> str: """Strip the decorations the harness never needs. Removes outer ``$`` delimiters, a ``\\boxed{...}`` wrapper, ``\\text{...}`` wrappers, repairs the LaTeX decimal comma ``0{,}5`` and removes trailing periods. """ if not s: return "" s = str(s).strip() s = strip_outer_dollars(s) m = re.fullmatch(r"\\boxed\s*\{(.*)\}", s, re.S) if m: s = m.group(1).strip() s = strip_outer_dollars(s) s = re.sub(r"\\(?:text|mbox|textbf|textrm|mathrm)\s*\{([^{}]*)\}", r"\1", s) # LaTeX decimal comma -> decimal point (the dataset convention) s = re.sub(r"(?<=\d)\{,\}(?=\d)", ".", s) s = s.rstrip() while s.endswith("."): s = s[:-1].rstrip() return strip_outer_dollars(s).strip() def strip_assignment(s: str) -> str: """``x = 2`` -> ``2``. Only a *single symbol* left-hand side is stripped, so genuine equations such as ``2x+3=7`` are left alone.""" m = _ASSIGN_RE.match(s or "") if m: return m.group(1).strip() return (s or "").strip() def top_level_split(s: str, seps: str = ",;") -> list: """Split ``s`` on separators that are not nested in brackets or in ``$...$``.""" parts, buf = [], [] depth = 0 in_math = False i, n = 0, len(s) while i < n: ch = s[i] if ch == "\\" and i + 1 < n: nxt = s[i + 1] if nxt in "lr": # \left( ... \right) buf.append(s[i:i + 2]) i += 2 continue buf.append(s[i:i + 2]) i += 2 continue if not in_math: if ch == "$": in_math = True elif ch in "([{": depth += 1 elif ch in ")]}": depth -= 1 elif depth == 0 and ch in seps: # a comma between two digits is a decimal comma, not a separator if ch == "," and buf and buf[-1].isdigit() and i + 1 < n and s[i + 1].isdigit(): buf.append(ch) i += 1 continue parts.append("".join(buf)) buf = [] i += 1 continue else: if ch == "$": in_math = False buf.append(ch) i += 1 parts.append("".join(buf)) return [p.strip() for p in parts] _LABEL_RE = re.compile(r"(?:^|[\s(,;])([a-zA-Z]\))") def split_labeled(s: str): """Split ``a) 1 b) 2`` into its items. Returns None when there is no label.""" matches = list(_LABEL_RE.finditer(s)) if len(matches) < 2: return None items = [] for idx, m in enumerate(matches): start = m.start(1) end = matches[idx + 1].start(1) if idx + 1 < len(matches) else len(s) items.append(s[start:end]) return items def split_items(s: str) -> list: """Split an answer into the individual answers it lists.""" s = strip_outer_dollars(s or "").strip() if not s: return [] parts = top_level_split(s) if len(parts) == 1: labelled = split_labeled(s) if labelled: parts = labelled out = [] for p in parts: p = re.sub(r"^\(?[a-zA-Z]\)\s*", "", p).strip() if p: out.append(p) return out # -------------------------------------------------------------------------- # answer extraction from a model response # -------------------------------------------------------------------------- def extract_boxed_contents(text: str) -> list: """Return the content of every ``\\boxed{...}`` in ``text`` (brace balanced).""" out = [] for m in _BOXED_RE.finditer(text): start = m.end() depth = 1 i = start n = len(text) while i < n: ch = text[i] if ch == "\\": i += 2 continue if ch == "{": depth += 1 elif ch == "}": depth -= 1 if depth == 0: break i += 1 if depth == 0: out.append(text[start:i]) return out def find_math_spans(text: str) -> list: """Return the content of every ``$...$`` / ``$$...$$`` span, in order.""" spans = [] i, n = 0, len(text) while i < n: if text.startswith("$$", i): j = text.find("$$", i + 2) if j > 0: spans.append(text[i + 2:j]) i = j + 2 continue if text[i] == "$": j = text.find("$", i + 1) if j > 0: spans.append(text[i + 1:j]) i = j + 1 continue i += 1 return spans _MARKER_PATTERNS = [ r"final\s+answer\s*(?:is|:|=)", r"the\s+answer\s+is", r"answer\s*(?:is|:)", r"result\s+(?:is|:)", r"therefore", r"(?=!])=(?![=>])", r":", ] def find_marker_answer(text: str): """Return the text after the last answer marker, or None.""" best_end, best = -1, None for pat in _MARKER_PATTERNS: for m in re.finditer(pat, text, flags=re.I): if m.end() > best_end: best_end, best = m.end(), m if best is None: return None rest = text[best.end():] rest = rest.split("\n", 1)[0] rest = rest.strip() return rest or None def find_last_number(text: str): """Return the last number (or LaTeX fraction) that occurs in ``text``.""" cands = [] for m in _NUMBER_RE.finditer(text): cands.append((m.end(), m.group(0).strip())) for m in _LATEXFRAC_RE.finditer(text): cands.append((m.end(), m.group(0).strip())) if not cands: return None cands.sort(key=lambda t: t[0]) return cands[-1][1] def clean_candidate(s: str) -> str: """Strip prefixes, markdown wrappers, ``$`` delimiters and trailing periods.""" if s is None: return "" s = str(s).strip() for _ in range(3): if len(s) >= 2 and s[0] == "*" and s[-1] == "*": s = s[1:-1].strip() elif len(s) >= 2 and s[0] == "_" and s[-1] == "_": s = s[1:-1].strip() else: break s = re.sub( r"^\s*(?:so\s+|thus\s+|therefore\s+|hence\s+)?" r"(?:the\s+)?(?:final\s+|correct\s+)?(?:answer|result)\s*(?:is|:|=)\s*", "", s, flags=re.I, ) s = re.sub(r"^\s*(?:we\s+)?(?:get|obtain)\s*[:=]?\s*", "", s, flags=re.I) s = clean_math_text(s) return s.strip() def looks_like_bare_math(t: str) -> bool: """True when a whole response is one bare mathematical expression. Models frequently answer with raw LaTeX and no ``$`` delimiters (``x=\\frac{\\pi}{4}(4k+1)``, ``(-1,2)\\cup(3,6)``, ``7; 6; 5``). Taking the whole text preserves the answer; falling back to "the last number" would truncate it to a fragment. """ t = (t or "").strip() if not t or "\n" in t or len(t) > 300: return False if not re.search(r"[0-9\\^_=<>+\-*/()\[\]|]", t): return False stripped = re.sub(r"\\[a-zA-Z]+", " ", t) # drop LaTeX command names if re.search(r"[A-Za-z]{3,}", stripped): return False # prose return True def extract_answer(response): """Extract the predicted answer from a model response. Precedence: last ``\\boxed{...}`` > last ``$...$`` math span > a bare LaTeX answer > text after an answer marker > last number in the response. Returns ``(candidate, method)``. """ if response is None: return "", "none" text = str(response) if not text.strip(): return "", "empty" boxed = extract_boxed_contents(text) if boxed: cand = clean_candidate(boxed[-1]) if cand: return cand, "boxed" spans = find_math_spans(text) if spans: cand = clean_candidate(spans[-1]) if cand: return cand, "math" if looks_like_bare_math(text): cand = clean_candidate(text) if cand: return cand, "bare" marker = find_marker_answer(text) if marker: cand = clean_candidate(marker) if cand and is_parseable(cand): return cand, "marker" num = find_last_number(text) if num: return clean_candidate(num), "number" num = find_last_number(text) if num: return clean_candidate(num), "number" return "", "none" # -------------------------------------------------------------------------- # numeric parsing # -------------------------------------------------------------------------- def _to_float(tok: str): tok = (tok or "").strip().replace(" ", "") if not tok: return None if tok.count(",") == 1: a, b = tok.split(",") if a and b and a.lstrip("+-").isdigit() and b.isdigit(): tok = a + "." + b try: return float(tok) except ValueError: return None def to_numbers(s: str): """Return the list of numeric values ``s`` can denote, or None. A percentage yields two candidates (``50`` and ``0.5``) because both readings occur in the wild. """ s = clean_math_text(s or "") s = strip_assignment(s) if not s: return None m = re.fullmatch(r"([-+]?[\d.,]+)\s*(?:%|\\%|percent)", s) if m: v = _to_float(m.group(1)) return [v, v / 100.0] if v is not None else None m = re.fullmatch(r"([-+]?)\\[dt]?frac\s*\{([^{}]*)\}\s*\{([^{}]*)\}", s) if m: sign = -1.0 if m.group(1) == "-" else 1.0 a, b = _to_float(m.group(2)), _to_float(m.group(3)) if a is not None and b not in (None, 0.0): return [sign * a / b] return None m = re.fullmatch(r"([-+]?[\d.,]+)\s*/\s*([-+]?[\d.,]+)", s) if m: a, b = _to_float(m.group(1)), _to_float(m.group(2)) if a is not None and b not in (None, 0.0): return [a / b] return None m = re.fullmatch(r"([-+]?[\d.,]+)\s*([A-Za-z]+)?", s) if m: unit = (m.group(2) or "").lower() if unit and unit not in UNITS: return None v = _to_float(m.group(1)) if v is not None: return [v] return None return None def num_close(a: float, b: float) -> bool: """Numeric equality within the harness tolerance.""" if a == b: return True if max(abs(a), abs(b)) < 1e-6: return abs(a - b) <= ABS_TOL return abs(a - b) <= REL_TOL * max(abs(a), abs(b)) # -------------------------------------------------------------------------- # symbolic parsing # -------------------------------------------------------------------------- _sympy_cache = {} def to_sympy(s: str): """Convert a LaTeX answer to a sympy expression, or None.""" if not HAVE_SYMPY: return None s = clean_math_text(s or "") s = strip_assignment(s) if not s: return None if s in _sympy_cache: return _sympy_cache[s] expr = None if _latex2sympy is not None: try: expr = _latex2sympy(s) except Exception: expr = None if expr is None and parse_latex is not None: try: expr = parse_latex(s) except Exception: expr = None if expr is None: try: expr = sp.sympify(s) except Exception: expr = None if expr is not None and not isinstance(expr, (sp.Basic, bool)): expr = None if expr is not None and isinstance(expr, sp.Equality): # ``x = 2`` is read as the solution, not as an equation try: expr = expr.rhs except Exception: expr = None if expr is not None and isinstance(expr, sp.Set): try: if len(expr) == 1: expr = list(expr)[0] else: expr = None except Exception: expr = None _sympy_cache[s] = expr return expr def is_parseable(s: str) -> bool: """True when the answer contains any mathematics at all. A piecewise answer such as ``-25 for $a>0$; $25$ for $a<0$`` is prose around mathematics, so individual ``$...$`` spans are inspected as well. """ s2 = clean_math_text(s) if not s2: return False if to_numbers(s2) is not None: return True if to_sympy(s2) is not None: return True if parse_interval_set(s2) is not None: return True items = split_items(s2) if len(items) > 1 and any(to_numbers(i) is not None or to_sympy(i) is not None for i in items): return True for span in find_math_spans(s2): sp = clean_math_text(span) if sp and (to_numbers(sp) is not None or to_sympy(sp) is not None): return True return False # -------------------------------------------------------------------------- # intervals # -------------------------------------------------------------------------- class Interval(object): __slots__ = ("lo", "hi", "lo_closed", "hi_closed") def __init__(self, lo, hi, lo_closed, hi_closed): self.lo = lo self.hi = hi self.lo_closed = lo_closed self.hi_closed = hi_closed def _endpoint(s: str): """Parse one interval endpoint. Returns a sympy expression or None.""" t = (s or "").strip() if not t: return None t = t.replace("\\cdot", "*").replace("\\times", "*") if t in ("-\\infty", "-\\inf", "-∞", "-\\infty)", "-inf"): return -sp.oo if t in ("\\infty", "\\inf", "+∞", "∞", "inf", "+\\infty"): return sp.oo v = _to_float(t) if v is not None: return sp.Float(v) try: expr = to_sympy(t) except Exception: expr = None if expr is None: return None return expr def parse_interval_set(s: str): """Parse an answer as a set of intervals. Returns None when it is not one.""" t = clean_math_text(s) if not t: return None t = re.sub(r"^[A-Za-z](?:_\{?\d+(?:,\d+)?\}?|_?\d+)?\s*\\in\s*", "", t).strip() t = t.replace("\\bigcup", "|").replace("\\cup", "|").replace("\\cupdot", "|") t = t.replace("∪", "|").replace("\\;", "|") t = re.sub(r"\\left|\\right", "", t) # a discrete set of points, e.g. {1, 2, 3} if len(t) >= 2 and t.startswith("{") and t.endswith("}"): inner = t[1:-1].strip() vals = [p.strip() for p in top_level_split(inner, ",") if p.strip()] if len(vals) >= 1: pts = [] for v in vals: ep = _endpoint(v) if ep is None: return None pts.append(Interval(ep, ep, True, True)) return pts parts = [p.strip() for p in t.split("|") if p.strip()] if not parts: return None ivs = [] for p in parts: m = re.fullmatch(r"([\(\[])\s*([^()\[\]]*?)\s*[,;]\s*([^()\[\]]*?)\s*([\)\]])", p) if not m: return None lo = _endpoint(m.group(2)) hi = _endpoint(m.group(3)) if lo is None or hi is None: return None ivs.append(Interval(lo, hi, m.group(1) == "[", m.group(4) == "]")) return ivs def _is_inf(e): try: return e in (sp.oo, -sp.oo) except Exception: return False def endpoint_cmp(a, b, mode: str): """Compare two endpoints. Returns -1, 0, 1 or None (incomparable).""" if a is b: return 0 try: if _is_inf(a) or _is_inf(b): if _is_inf(a) and _is_inf(b): if (a == sp.oo) == (b == sp.oo): return 0 return -1 if (a == -sp.oo) else 1 if _is_inf(a): return -1 if (a == -sp.oo) else 1 return -1 if (b == sp.oo) else 1 d = sp.simplify(a - b) if d == 0: return 0 try: fa, fb = complex(sp.N(a)), complex(sp.N(b)) except Exception: fa = fb = 0.0 scale = max(1.0, abs(fa), abs(fb)) if mode == "exact": tol = 0.0 elif mode == "numeric": tol = max(ABS_TOL, REL_TOL * scale) else: tol = SYM_TOL * scale v = complex(sp.N(d)) if abs(v) <= tol: return 0 return -1 if v.real < 0 else 1 except Exception: return None def _iv_key(e): """Numeric sort key for an endpoint (``-2`` must sort before ``-1``).""" try: return (0, float(e), "") except Exception: return (1, 0.0, str(e)) def merge_intervals(ivs): """Merge overlapping intervals. Intervals that merely touch at a point where one of them is open are *not* merged, because the touching point is then missing from the union.""" if not ivs: return [] ordered = sorted(ivs, key=lambda i: (_iv_key(i.lo), _iv_key(i.hi))) out = [Interval(ordered[0].lo, ordered[0].hi, ordered[0].lo_closed, ordered[0].hi_closed)] for iv in ordered[1:]: cur = out[-1] c = endpoint_cmp(iv.lo, cur.hi, "symbolic") if c is None: out.append(Interval(iv.lo, iv.hi, iv.lo_closed, iv.hi_closed)) continue if c < 0: # overlapping ch = endpoint_cmp(iv.hi, cur.hi, "symbolic") if ch is not None and ch > 0: cur.hi = iv.hi cur.hi_closed = iv.hi_closed elif ch == 0: cur.hi_closed = cur.hi_closed and iv.hi_closed # otherwise iv is nested inside cur -- keep cur elif c == 0: # touching if cur.hi_closed and iv.lo_closed: cur.hi = iv.hi cur.hi_closed = iv.hi_closed else: out.append(Interval(iv.lo, iv.hi, iv.lo_closed, iv.hi_closed)) else: # disjoint out.append(Interval(iv.lo, iv.hi, iv.lo_closed, iv.hi_closed)) return out def interval_contained(inner: Interval, outer: Interval, mode: str): """True / False / None whether ``inner`` is contained in ``outer``.""" c1 = endpoint_cmp(outer.lo, inner.lo, mode) if c1 is None: return None if c1 > 0: return False if c1 == 0 and inner.lo_closed and not outer.lo_closed: return False c2 = endpoint_cmp(inner.hi, outer.hi, mode) if c2 is None: return None if c2 > 0: return False if c2 == 0 and inner.hi_closed and not outer.hi_closed: return False return True def interval_sets_equal(a, b, mode: str): """True / False / None: are the two interval sets the same set?""" if not a or not b: return None ma, mb = merge_intervals(a), merge_intervals(b) for side, other in ((a, mb), (b, ma)): for iv in side: contained = False for m in other: r = interval_contained(iv, m, mode) if r is True: contained = True break if r is None: return None if not contained: return False return True # -------------------------------------------------------------------------- # symbolic equality # -------------------------------------------------------------------------- def _align_symbols(a, b): """Give the two expressions the same free symbols when they have the same number of them (``k`` vs ``n``). Returns ``(a, b)``.""" if not HAVE_SYMPY: return a, b try: sa = sorted(a.free_symbols, key=str) sb = sorted(b.free_symbols, key=str) except Exception: return a, b if not sa or not sb: return a, b common = set(sa) & set(sb) extra_a = [s for s in sa if s not in common] extra_b = [s for s in sb if s not in common] if len(extra_a) == len(extra_b) and extra_a: mapping = {x: y for x, y in zip(extra_a, extra_b)} try: a = a.xreplace(mapping) except Exception: pass return a, b _SAMPLE_VALUES = [2, 3, 5, 7, 11, 13, 17, 19] def symbolic_equal(a, b) -> bool: """Mathematical equality of two sympy expressions.""" if not HAVE_SYMPY or a is None or b is None: return False try: if a == b: return True except Exception: pass try: if sp.simplify(a - b) == 0: return True except Exception: pass a, b = _align_symbols(a, b) try: syms = sorted(set(a.free_symbols) | set(b.free_symbols), key=str) except Exception: syms = [] if not syms: try: return abs(complex(sp.N(a)) - complex(sp.N(b))) <= SYM_TOL except Exception: return False vals = [float(v) for v in _SAMPLE_VALUES] ok = 0 tried = 0 for i in range(N_SAMPLE_POINTS): subs = {sym: vals[(i + j) % len(vals)] for j, sym in enumerate(syms)} try: with warnings.catch_warnings(): warnings.simplefilter("ignore") fa = sp.lambdify(syms, a, modules="numpy") fb = sp.lambdify(syms, b, modules="numpy") va = fa(*[subs[s] for s in syms]) vb = fb(*[subs[s] for s in syms]) va, vb = complex(sp.N(va)), complex(sp.N(vb)) except Exception: try: va = complex(sp.N(a.subs(subs))) vb = complex(sp.N(b.subs(subs))) except Exception: continue tried += 1 if abs(va - vb) <= SYM_TOL * max(1.0, abs(va), abs(vb)): ok += 1 return tried >= max(3, N_SAMPLE_POINTS // 2) and ok == tried # -------------------------------------------------------------------------- # \pm handling # -------------------------------------------------------------------------- def expand_pm(s: str): """Expand every ``\\pm`` into its two alternatives.""" s = s or "" if "\\pm" not in s: return [s] out = [s] cur = [s] while any("\\pm" in x for x in cur): nxt = [] for x in cur: if "\\pm" in x: nxt.append(x.replace("\\pm", "+", 1)) nxt.append(x.replace("\\pm", "-", 1)) else: nxt.append(x) cur = nxt out.extend(cur) return out _PM_PATTERN = re.compile( r"(?P
.*?)\(\s*(?P[+-]?\d*)\s*k\s*(?:\\pm|\+|-)\s*(?P[+-]?\d*)\s*\)"
)


def _pm_shape(s: str):
    """Match ``A*(m*k +- n)``; returns ``(pre, m, n)`` or None."""
    s = strip_assignment(clean_math_text(s))
    m = _PM_PATTERN.search(s)
    if not m:
        return None
    coeff = m.group("m")
    const = m.group("n")
    coeff = 1 if coeff in ("", "+") else (-1 if coeff == "-" else int(coeff))
    const = 1 if const in ("", "+") else (-1 if const == "-" else int(const))
    return m.group("pre").strip(), coeff, const


def pm_pattern_equal(p: str, g: str) -> bool:
    """``\\frac{\\pi}{6}(2k\\pm1)`` vs ``\\frac{\\pi}{6}(4k\\pm2)``: the same
    answer written with a different integer multiplier."""
    ps, gs = _pm_shape(p), _pm_shape(g)
    if not ps or not gs:
        return False
    ppre, pm, pn = ps
    gpre, gm, gn = gs
    if pn == 0 or gn == 0:
        return False
    if abs(pm / pn - gm / gn) > 1e-9:
        return False
    pa, ga = to_sympy(ppre), to_sympy(gpre)
    if pa is None or ga is None:
        return ppre.strip() == gpre.strip()
    return symbolic_equal(pa, ga)


def pm_symbolic_match(p: str, g: str) -> bool:
    for a in expand_pm(p):
        for b in expand_pm(g):
            ea, eb = to_sympy(a), to_sympy(b)
            if ea is not None and eb is not None and symbolic_equal(ea, eb):
                return True
    return pm_pattern_equal(p, g)


# --------------------------------------------------------------------------
# tier comparison
# --------------------------------------------------------------------------
def item_compare(p: str, g: str, tier: str) -> str:
    """Compare two single answers at one tier: ACCEPT / REJECT / UNKNOWN."""
    p = clean_math_text(p)
    g = clean_math_text(g)
    if not p or not g:
        return UNKNOWN

    if tier == "exact":
        return ACCEPT if norm_exact(p) == norm_exact(g) and norm_exact(p) != "" else UNKNOWN

    if tier == "numeric":
        a, b = to_numbers(p), to_numbers(g)
        if a is None or b is None:
            return UNKNOWN
        for x in a:
            for y in b:
                if num_close(x, y):
                    return ACCEPT
        return REJECT

    # symbolic
    if "\\pm" in p or "\\pm" in g:
        return ACCEPT if pm_symbolic_match(p, g) else REJECT
    a, b = to_sympy(p), to_sympy(g)
    if a is None or b is None:
        # last resort: the (m*k +- n) shape with a different integer multiplier
        return ACCEPT if pm_pattern_equal(p, g) else UNKNOWN
    if symbolic_equal(a, b):
        return ACCEPT
    # the same solution set written with a different integer multiplier,
    # e.g. \frac{\pi}{6}(2k+1) vs \frac{\pi}{6}(4k+2)
    return ACCEPT if pm_pattern_equal(p, g) else REJECT


def norm_exact(s: str) -> str:
    """Normalised string used by the exact tier."""
    s = (s or "").strip().lower()
    s = s.replace("\\left", "").replace("\\right", "")
    s = s.replace("\\!", "").replace("\\,", "").replace("\\;", "")
    s = s.replace("\\dfrac", "\\frac").replace("\\tfrac", "\\frac")
    s = s.replace("\\cdot", "*").replace("\\times", "*")
    s = s.replace("\\ ", " ")
    s = s.replace("$", "")
    s = re.sub(r"\s+", "", s)
    while s.endswith("."):
        s = s[:-1]
    return s


def multiset_match(pl, gl, tier: str) -> bool:
    """Unordered multiset match of two lists of answers."""
    n, m = len(pl), len(gl)
    if n != m:
        return False
    used = [False] * m

    def rec(i):
        if i == n:
            return True
        for j in range(m):
            if used[j]:
                continue
            if item_compare(pl[i], gl[j], tier) == ACCEPT:
                used[j] = True
                if rec(i + 1):
                    return True
                used[j] = False
        return False

    return rec(0)


def tier_compare(p: str, g: str, tier: str) -> str:
    """Compare a whole predicted answer with a whole gold answer at one tier."""
    p = clean_math_text(p)
    g = clean_math_text(g)
    if not p or not g:
        return UNKNOWN

    if tier == "exact":
        # the exact tier is normalised string identity
        if norm_exact(p) != "" and norm_exact(p) == norm_exact(g):
            return ACCEPT

    pi, gi = parse_interval_set(p), parse_interval_set(g)
    if pi is not None and gi is not None:
        r = interval_sets_equal(pi, gi, tier)
        if r is None:
            return UNKNOWN
        return ACCEPT if r else (UNKNOWN if tier == "exact" else REJECT)
    if (pi is None) != (gi is None):
        # one side is an interval set, the other is not
        return UNKNOWN

    pl, gl = split_items(p), split_items(g)
    if len(pl) > 1 or len(gl) > 1:
        if len(pl) != len(gl):
            return UNKNOWN if tier == "exact" else REJECT
        ok = multiset_match(pl, gl, tier)
        if ok:
            return ACCEPT
        if tier == "exact":
            return UNKNOWN
        # a pair that cannot be compared at this strength is not a refutation:
        # let the next tier decide
        for pi_ in pl:
            for gi_ in gl:
                if item_compare(pi_, gi_, tier) == UNKNOWN:
                    return UNKNOWN
        return REJECT

    return item_compare(pl[0] if pl else "", gl[0] if gl else "", tier)


# --------------------------------------------------------------------------
# scoring
# --------------------------------------------------------------------------
def score_answer(pred_text, gold_text, tiers):
    """Score one item.

    Returns a dict with ``correct``, ``tier``, ``reason``, ``unparsed``,
    ``pred`` and ``gold``.
    """
    gold = clean_math_text(gold_text)
    pred_raw, method = extract_answer(pred_text)
    pred = clean_candidate(pred_raw)
    out = {
        "correct": False,
        "tier": None,
        "reason": "",
        "unparsed": False,
        "pred": pred,
        "gold": gold,
        "extract": method,
    }
    if not gold:
        out["reason"] = "no_gold"
        return out
    if not pred:
        out["reason"] = "no_answer_extracted"
        out["unparsed"] = True
        return out
    out["unparsed"] = not is_parseable(pred)

    # A response that reproduces the gold answer in full is correct, even when
    # the extractor picks a fragment out of it -- a single number, or the tail
    # after a comma.  Without this check a verbatim-correct answer is scored
    # wrong, because the fragment is compared against the whole gold string.
    if "exact" in tiers:
        whole = clean_candidate(pred_text)
        if whole and norm_exact(gold) and norm_exact(whole) == norm_exact(gold):
            out["correct"] = True
            out["tier"] = "exact"
            out["reason"] = "accepted"
            out["pred"] = whole
            out["unparsed"] = not is_parseable(whole)
            out["extract"] = method + "+whole"
            return out

    last = None
    for tier in tiers:
        last = tier
        status = tier_compare(pred, gold, tier)
        if status == ACCEPT:
            out["correct"] = True
            out["tier"] = tier
            out["reason"] = "accepted"
            return out
        if status == REJECT:
            out["tier"] = tier
            out["reason"] = "rejected"
            return out
    out["tier"] = last
    out["reason"] = "not_accepted"
    return out


# --------------------------------------------------------------------------
# dataset / predictions loading
# --------------------------------------------------------------------------
def load_dataset(path: str):
    rows = []
    if path.endswith(".parquet"):
        import pyarrow.parquet as pq

        table = pq.read_table(path)
        rows = table.to_pylist()
    else:
        with open(path, "r", encoding="utf-8") as fh:
            for lineno, line in enumerate(fh, 1):
                line = line.strip()
                if not line:
                    continue
                try:
                    obj = json.loads(line)
                except Exception as exc:
                    raise ValueError("bad JSON on line %d: %s" % (lineno, exc))
                if not isinstance(obj, dict):
                    raise ValueError("line %d is not a JSON object" % lineno)
                rows.append(obj)
    return rows


RESPONSE_KEYS = ("response", "prediction", "output", "answer", "pred", "text")


def load_predictions(path: str):
    """Return ``(preds, malformed, duplicates)``.

    ``preds`` maps id -> response string.
    """
    preds = OrderedDict()
    malformed = 0
    duplicates = 0
    with open(path, "r", encoding="utf-8") as fh:
        for lineno, line in enumerate(fh, 1):
            line = line.strip()
            if not line:
                continue
            try:
                obj = json.loads(line)
            except Exception:
                malformed += 1
                continue
            if not isinstance(obj, dict):
                malformed += 1
                continue
            pid = obj.get("id", obj.get("problem_id", obj.get("idx")))
            if pid is None:
                malformed += 1
                continue
            pid = str(pid)
            response = None
            for key in RESPONSE_KEYS:
                if key in obj and obj[key] is not None:
                    response = obj[key]
                    break
            if response is None:
                malformed += 1
                continue
            if pid in preds:
                duplicates += 1
            preds[pid] = response
    return preds, malformed, duplicates


# --------------------------------------------------------------------------
# reporting
# --------------------------------------------------------------------------
def _blank_bucket():
    return {"total": 0, "correct": 0, "unparsed": 0, "errors": 0}


def _finalize(bucket):
    total = bucket["total"]
    bucket["accuracy"] = (bucket["correct"] / total) if total else 0.0
    return bucket


def evaluate(dataset_path, predictions_path, tiers, show_items="auto"):
    rows = load_dataset(dataset_path)
    preds, malformed, duplicates = load_predictions(predictions_path)

    index = {}
    data_errors = 0
    for row in rows:
        rid = row.get("id")
        if rid is None:
            data_errors += 1
            continue
        index[str(rid)] = row

    items = []
    skipped_no_gold = 0
    missing = 0
    unknown_ids = 0

    for rid, row in index.items():
        gold = row.get("final_answer_boxed") or row.get("final_answer") or ""
        if not str(gold).strip():
            skipped_no_gold += 1
            if rid in preds:
                unknown_ids -= 0  # the prediction matched a real id; nothing to score
            continue
        if rid not in preds:
            missing += 1
            rec = {
                "id": rid,
                "correct": False,
                "tier": None,
                "reason": "missing_prediction",
                "unparsed": False,
                "pred": "",
                "gold": clean_math_text(gold),
            }
        else:
            try:
                rec = score_answer(preds[rid], gold, tiers)
            except Exception as exc:  # never crash on a malformed row
                rec = {
                    "id": rid,
                    "correct": False,
                    "tier": None,
                    "reason": "error: %s" % exc,
                    "unparsed": False,
                    "pred": "",
                    "gold": clean_math_text(gold),
                    "error": True,
                }
            rec["id"] = rid
        rec["chapter"] = row.get("chapter")
        rec["group"] = row.get("group") or ""
        rec["marker"] = row.get("difficulty") or row.get("marker") or ""
        rec["source"] = row.get("source") or ""
        rec["verification"] = row.get("answer_status") or row.get("verification") or ""
        rec["chapter_title"] = row.get("chapter_title") or ""
        items.append(rec)

    items.sort(key=lambda r: _sort_key(r["id"]))

    for rid in preds:
        if rid not in index:
            unknown_ids += 1

    scored = len(items)
    correct = sum(1 for r in items if r["correct"])
    unparsed = sum(1 for r in items if r["unparsed"])
    errors = sum(1 for r in items if r.get("error"))
    strict_correct = sum(1 for r in items if r["correct"] and r["tier"] == "exact")

    per_tier = OrderedDict()
    for tier in tiers:
        bucket = _blank_bucket()
        for r in items:
            if r["tier"] == tier:
                bucket["total"] += 1
                if r["correct"]:
                    bucket["correct"] += 1
                if r["unparsed"]:
                    bucket["unparsed"] += 1
        per_tier[tier] = _finalize(bucket)

    def breakdown(field):
        buckets = OrderedDict()
        for r in items:
            key = str(r.get(field) if r.get(field) is not None else "")
            buckets.setdefault(key, _blank_bucket())
            b = buckets[key]
            b["total"] += 1
            if r["correct"]:
                b["correct"] += 1
            if r["unparsed"]:
                b["unparsed"] += 1
        for b in buckets.values():
            _finalize(b)
        return OrderedDict(sorted(buckets.items(), key=lambda kv: _sort_key(kv[0])))

    report = {
        "dataset": os.path.abspath(dataset_path),
        "predictions": os.path.abspath(predictions_path),
        "tiers": list(tiers),
        "totals": {
            "dataset_rows": len(rows),
            "dataset_ids": len(index),
            "dataset_errors": data_errors,
            "scored": scored,
            "correct": correct,
            "accuracy": (correct / scored) if scored else 0.0,
            "strict_correct": strict_correct,
            "strict_accuracy": (strict_correct / scored) if scored else 0.0,
            "unparsed": unparsed,
            "missing_predictions": missing,
            "skipped_no_gold": skipped_no_gold,
            "unknown_prediction_ids": unknown_ids,
            "malformed_prediction_lines": malformed,
            "duplicate_prediction_ids": duplicates,
            "errors": errors,
        },
        "per_tier": per_tier,
        "by_chapter": breakdown("chapter"),
        "by_group": breakdown("group"),
        "by_marker": breakdown("marker"),
        "by_difficulty": breakdown("marker"),
        "by_source": breakdown("source"),
        "by_verification": breakdown("verification"),
        "by_answer_status": breakdown("verification"),
        "items": items,
    }
    return report


def _sort_key(value):
    s = str(value)
    m = re.match(r"^(?:[A-Za-z_]+_)?(\d+)\.(\d+)$", s)
    if m:
        return (0, int(m.group(1)), int(m.group(2)), s)
    m = re.match(r"^syn\.(\d+)$", s)
    if m:
        return (1, 0, int(m.group(1)), "")
    m = re.match(r"^(?:[A-Za-z_]+_)?(\d+)$", s)
    if m:
        return (2, 0, int(m.group(1)), s)
    return (3, 0, 0, s)


# --------------------------------------------------------------------------
# stdout report
# --------------------------------------------------------------------------
def _pct(x):
    return "%.2f%%" % (100.0 * x)


def print_report(report, show_items="auto"):
    t = report["totals"]
    out = sys.stdout
    out.write("=== evaluate_benchmark ===\n")
    out.write("dataset:     %s\n" % report["dataset"])
    out.write("predictions: %s\n" % report["predictions"])
    out.write("tiers:       %s\n" % ",".join(report["tiers"]))
    out.write("\n-- overall --\n")
    out.write("scored items            : %d\n" % t["scored"])
    out.write("correct                 : %d\n" % t["correct"])
    out.write("accuracy                : %s (%d/%d)\n" % (_pct(t["accuracy"]), t["correct"], t["scored"]))
    out.write("strict accuracy (exact) : %s (%d/%d)\n"
              % (_pct(t["strict_accuracy"]), t["strict_correct"], t["scored"]))
    out.write("unparsed predictions    : %d\n" % t["unparsed"])
    out.write("missing predictions     : %d\n" % t["missing_predictions"])
    out.write("skipped (no gold answer): %d\n" % t["skipped_no_gold"])
    out.write("unknown prediction ids  : %d\n" % t["unknown_prediction_ids"])
    out.write("malformed prediction ln : %d\n" % t["malformed_prediction_lines"])
    out.write("duplicate prediction ids: %d\n" % t["duplicate_prediction_ids"])
    out.write("dataset rows w/o id     : %d\n" % t["dataset_errors"])
    out.write("errors                  : %d\n" % t["errors"])
    if "exact" not in report["tiers"]:
        out.write("note: the exact tier is disabled, so strict accuracy is 0 by construction\n")

    out.write("\n-- decided by tier --\n")
    out.write("%-10s %8s %8s %10s\n" % ("tier", "decided", "correct", "accuracy"))
    for tier, b in report["per_tier"].items():
        out.write("%-10s %8d %8d %10s\n" % (tier, b["total"], b["correct"], _pct(b["accuracy"])))
    undecided = t["scored"] - sum(b["total"] for b in report["per_tier"].values())
    out.write("%-10s %8d\n" % ("(none)", undecided))

    for label, key in (
        ("by chapter", "by_chapter"),
        ("by group", "by_group"),
        ("by marker", "by_marker"),
        ("by source", "by_source"),
        ("by verification", "by_verification"),
    ):
        out.write("\n-- %s --\n" % label)
        out.write("%-16s %7s %8s %10s %9s\n" % ("value", "items", "correct", "accuracy", "unparsed"))
        for name, b in report[key].items():
            out.write("%-16s %7d %8d %10s %9d\n"
                      % (name or "(none)", b["total"], b["correct"], _pct(b["accuracy"]), b["unparsed"]))

    items = report["items"]
    mode = show_items
    if mode == "auto":
        mode = "all" if len(items) <= 500 else "failures"
    out.write("\n-- per-item --\n")
    if mode == "none":
        out.write("(suppressed)\n")
        return
    if mode == "all":
        shown = items
    else:
        shown = [r for r in items if not r["correct"]]
    out.write("%-14s %-9s %-5s %-4s %s\n" % ("id", "tier", "ok", "par", "pred | gold"))
    shown_now = shown[:200]
    for r in shown_now:
        out.write("%-14s %-9s %-5s %-4s %s | %s\n"
                  % (r["id"], r["tier"] or "-", "yes" if r["correct"] else "NO",
                     "no" if r["unparsed"] else "ok",
                     _short(r.get("pred", ""), 40), _short(r.get("gold", ""), 40)))
    if mode == "failures" and len(shown) > len(shown_now):
        out.write("... %d further failures omitted; use --out report.json for the full table\n"
                  % (len(shown) - len(shown_now)))
    if mode == "failures":
        out.write("%d failure(s) shown\n" % len(shown_now))
    else:
        out.write("%d item(s) shown\n" % len(shown_now))


def _short(s, n):
    s = re.sub(r"\s+", " ", str(s or "")).strip()
    if len(s) > n:
        return s[: n - 3] + "..."
    return s


# --------------------------------------------------------------------------
# CLI
# --------------------------------------------------------------------------
def parse_tiers(spec: str):
    tiers = []
    for raw in spec.split(","):
        name = raw.strip().lower()
        if not name:
            continue
        if name not in ALL_TIERS:
            raise ValueError("unknown tier %r (choose from %s)" % (name, ", ".join(ALL_TIERS)))
        if name not in tiers:
            tiers.append(name)
    if not tiers:
        raise ValueError("--tiers must name at least one tier")
    return tiers


def main(argv=None):
    ap = argparse.ArgumentParser(
        prog="evaluate_benchmark.py",
        description="Score a predictions file against the DGN math benchmark.",
    )
    ap.add_argument("--dataset", required=True, help="dataset file (.jsonl or .parquet)")
    ap.add_argument("--predictions", required=True, help="predictions file (.jsonl)")
    ap.add_argument("--out", default=None, help="write the JSON report to this file")
    ap.add_argument("--tiers", default="exact,numeric,symbolic",
                    help="comma separated tiers to use, in order (default: exact,numeric,symbolic)")
    ap.add_argument("--quiet", action="store_true", help="do not print the report to stdout")
    ap.add_argument("--show-items", choices=("auto", "all", "failures", "none"), default="auto",
                    help="how much of the per-item table to print (default: auto)")
    args = ap.parse_args(argv)

    try:
        tiers = parse_tiers(args.tiers)
    except ValueError as exc:
        sys.stderr.write("error: %s\n" % exc)
        return 1

    for label, path in (("dataset", args.dataset), ("predictions", args.predictions)):
        if not os.path.isfile(path):
            sys.stderr.write("error: %s file not found: %s\n" % (label, path))
            return 1

    if not HAVE_SYMPY:
        sys.stderr.write("error: sympy is required for the symbolic tier\n")
        return 1

    try:
        report = evaluate(args.dataset, args.predictions, tiers, args.show_items)
    except Exception as exc:
        sys.stderr.write("error: %s\n" % exc)
        return 1

    if args.out:
        try:
            with open(args.out, "w", encoding="utf-8") as fh:
                json.dump(report, fh, ensure_ascii=False, indent=2)
        except Exception as exc:
            sys.stderr.write("error: cannot write %s: %s\n" % (args.out, exc))
            return 1

    if not args.quiet:
        print_report(report, args.show_items)
    return 0


if __name__ == "__main__":
    sys.exit(main())