worked-examples-data / code /grader /math_equiv.py
nzhao721's picture
Add the deterministic grader code
62831c3 verified
Raw History Blame Contribute Delete
12.5 kB
#!/usr/bin/env python3
"""First-answer, math-equivalence grader for the worked-example holdout.
The released scorer (holdout_passn.is_correct) compares the last number after
the last "####"/"Answer:" in a sample with the last number of the pack's
final_answer. This grader changes both sides:
- Sample: the answer the model gives for the prompted problem, i.e. the text
before any follow-up "Problem:" the model invents, then the first "####"
field, else the first "Answer:" field, else the first line, up to the end of
that line.
- Gold: MetaMathQA's own final answer ("The answer is: ..."), recovered from
MetaMathQA-395K.json. The pack's final_answer keeps only the first number of
short answers and drops commas, so "1,2" became "12" and "\\frac{1}{8}" became
"1" (orig/metamath_parse.extract_final_answer).
Answers are compared numerically when both sides are plain numbers and with
math-verify otherwise (fractions, LaTeX, sets, tuples, "x=5").
Subcommands:
golds build gold_full.jsonl (instance_id -> full gold) and report how many
pack golds lose information
score Pass@N / PassRatio@N per arm under the released rule and this rule,
plus where the two rules disagree
The released paired analysis runs unchanged with this rule through the shim in
olmo_shim/ (see that file).
"""
from __future__ import annotations
import argparse
import importlib.util
import json
import re
import sys
from collections import Counter
from fractions import Fraction
from pathlib import Path
HERE = Path(__file__).resolve().parent
def _load(name: str, path: Path):
spec = importlib.util.spec_from_file_location(name, path)
mod = importlib.util.module_from_spec(spec)
sys.modules[name] = mod
spec.loader.exec_module(mod)
return mod
# Unmodified copies from OLMo-core 0f479cf0, loaded under their own names so the
# olmo_shim stand-in (also called holdout_passn) cannot shadow them.
released = _load('holdout_passn_released', HERE / 'orig' / 'holdout_passn.py')
metamath_parse = _load('metamath_parse_released', HERE / 'orig' / 'metamath_parse.py')
_NUM = re.compile(r'^[-+]?(\d{1,3}(,\d{3})+|\d+)(\.\d+)?$|^[-+]?\.\d+$')
_STRIP = re.compile(r'^\s*(\\\(|\\\[|\$)+|(\\\)|\\\]|\$)+\s*$')
def full_gold(response: str) -> str | None:
"""MetaMathQA's final answer, untruncated (same patterns as the pack builder)."""
text = response.strip()
for pat in metamath_parse.FINAL_PATTERNS:
m = pat.search(text)
if m:
ans = m.group(1).strip().rstrip('.').strip('`"\'').strip()
return ans or None
return None
_MARKER = re.compile(r'####|Answer:|(?i:the answer is):?') # "so the answer is 15 kg" states an answer as well
def first_answer(sample: str, strict: bool = False) -> str | None:
"""The sample's answer to the prompted problem (None if it gives none).
The answer is the rest of the line after the earliest of '####', 'Answer:' and 'The answer is'. Without any
marker the Direct condition (prompt ends in 'Answer:') takes the first line; strict=True (the Open condition)
returns None instead, so a sample that never states an answer is wrong and counted as unanswered."""
seg = sample
nxt = seg.find('Problem:', 1)
if nxt > 0:
seg = seg[:nxt]
m = _MARKER.search(seg)
if m:
line = seg[m.end():].strip().split('\n', 1)[0]
return line.strip() or None
if strict:
return None
line = seg.strip().split('\n', 1)[0].strip()
return line or None
def has_answer_field(sample: str) -> bool:
"""Whether the sample writes '####' or 'Answer:' before any follow-up problem."""
nxt = sample.find('Problem:', 1)
seg = sample[:nxt] if nxt > 0 else sample
return '####' in seg or 'Answer:' in seg
def _clean(s: str) -> str:
s = s.strip().rstrip('.').strip().strip('* ').rstrip('.').strip() # markdown bold: "**3**"
s = _STRIP.sub('', s).strip()
s = re.sub(r'^\\boxed\{(.*)\}$', r'\1', s)
return s.replace('\\$', '').replace('$', '').replace('\\%', '').replace('%', '').strip()
def _as_number(s: str):
t = s.replace(' ', '')
if _NUM.match(t):
t = t.replace(',', '')
try:
return Fraction(t)
except ValueError:
return None
m = re.fullmatch(r'([-+]?\d+)/(\d+)', t)
if m and int(m.group(2)) != 0:
return Fraction(int(m.group(1)), int(m.group(2)))
return None
_MV = None
_GOLD_CACHE: dict[str, object] = {}
def _math_verify(gold: str, pred: str) -> bool:
global _MV
if _MV is None:
from math_verify import ExprExtractionConfig, LatexExtractionConfig, parse, verify
_MV = (parse, verify, [LatexExtractionConfig(), ExprExtractionConfig()])
parse, verify, cfg = _MV
if len(pred) > 200 or len(gold) > 200: # math-verify has no timeout on Windows; skip pathological strings
return False
if gold not in _GOLD_CACHE:
_GOLD_CACHE[gold] = parse('$' + gold + '$', extraction_config=cfg, parsing_timeout=None)
g = _GOLD_CACHE[gold]
p = parse('$' + pred + '$', extraction_config=cfg, parsing_timeout=None)
return bool(g) and bool(p) and verify(g, p, timeout_seconds=None)
def equivalent(gold: str, pred: str | None) -> bool:
if pred is None:
return False
g, p = _clean(gold), _clean(pred)
if not p:
return False
if g == p:
return True
gn, pn = _as_number(g), _as_number(p)
if gn is not None and pn is not None:
return gn == pn
if gn is None and pn is not None and ':' in g:
return False # a ratio or a time ("3:1", "8:34 p.m."): math-verify would match the number before the colon
if gn is not None and pn is None:
# a unit word of two or more letters ("18 dollars", "5cm"); a single letter is a variable or i ("3i", "3x")
unit = re.fullmatch(r'([-+]?[\d,]*\.?\d+)\s*[a-zA-Z]{2,}[a-zA-Z .]*', p)
if unit and _as_number(unit.group(1)) is not None:
return _as_number(unit.group(1)) == gn
var = re.fullmatch(r'[A-Za-z]\s*=\s*(.+)', p) # "x = 5"
if var and _as_number(_clean(var.group(1))) is not None:
return _as_number(_clean(var.group(1))) == gn
if re.search(r'[A-Za-z=]', re.sub(r'\\[A-Za-z]+', '', p)):
return False # prose or an equation: only a number, a unit, "x = n" or a pure expression can match
p = _strip_unmatched_closers(p).rstrip(',;').rstrip() # "3)" from "(the answer is 3)"; "4," ends a clause
if not _well_formed(p):
return False # math-verify parses only the start of "3-6)", "2^" or "2 \times", which then equals the gold
if _as_number(p) is not None:
return _as_number(p) == gn
return _math_verify(g, p)
_PAIR = {')': '(', ']': '[', '}': '{'}
def _strip_unmatched_closers(s: str) -> str:
"""Drop closing brackets at the end that close nothing in the answer (they close the sentence's own bracket)."""
while s and s[-1] in _PAIR:
depth = sum(1 if c == _PAIR[s[-1]] else -1 if c == s[-1] else 0 for c in s)
if depth >= 0:
break
s = s[:-1].rstrip().rstrip('.').rstrip()
return s
def _well_formed(s: str) -> bool:
"""Balanced brackets and no operator dangling at either end, so math-verify reads the whole answer."""
stack = []
for c in s:
if c in '([{':
stack.append(c)
elif c in _PAIR:
if not stack or stack.pop() != _PAIR[c]:
return False
if stack:
return False
t = re.sub(r'\\(left|right)\b', '', s).strip()
if re.search(r'([-+*/^=,:_]|\\times|\\cdot|\\div|\\pm)$', t):
return False
return not re.match(r'([*/^=,:_]|\\times|\\cdot|\\div)', t)
def is_correct(sample: str, gold_full_answer: str, strict: bool = False) -> bool:
return equivalent(gold_full_answer, first_answer(sample, strict))
def load_gold_full(path: Path) -> dict[str, str]:
return {r['instance_id']: r['gold_full'] for r in map(json.loads, path.open(encoding='utf-8'))}
def cmd_golds(a) -> None:
ev = [json.loads(l) for l in a.holdout.open(encoding='utf-8') if l.strip()]
rows = json.load(a.metamath.open(encoding='utf-8'))
by_q: dict[str, list[dict]] = {}
for r in rows:
by_q.setdefault(r['query'].strip(), []).append(r)
out, stats = [], Counter()
for e in ev:
cands = by_q.get(e['question'].strip(), [])
# The MetaMathQA row the pack used: its lossy extraction equals the pack gold.
match = [r for r in cands if metamath_parse.extract_final_answer(r['response']) == e['final_answer']
and (r.get('type') or '') == e.get('type', '')]
if not match:
match = [r for r in cands if metamath_parse.extract_final_answer(r['response']) == e['final_answer']]
fulls = sorted({full_gold(r['response']) for r in match} - {None})
if not fulls:
stats['no_source_row'] += 1
g = e['final_answer']
else:
g = fulls[0]
stats['multiple_full_answers'] += len(fulls) > 1
lossy = not equivalent(g, e['final_answer'])
stats['lossy_pack_gold'] += lossy
out.append(dict(instance_id=e['instance_id'], gold_full=g, pack_gold=e['final_answer'], lossy=lossy))
with a.output.open('w', encoding='utf-8') as f:
for r in out:
f.write(json.dumps(r, ensure_ascii=False) + '\n')
print(json.dumps(dict(n_items=len(ev), **stats), indent=2))
for r in [r for r in out if r['lossy']][:a.examples]:
print(f" pack {r['pack_gold']!r:>10} full {r['gold_full']!r}")
def cmd_score(a) -> None:
items = released.load_holdout(a.holdout)
ids = [json.loads(l)['instance_id'] for l in a.holdout.open(encoding='utf-8') if l.strip()]
gold = load_gold_full(a.gold_full)
report = {}
for spec in a.arm:
arm, path = spec.split('=', 1)
gens = [json.loads(l)['gens'][:a.pass_n] for l in open(path, encoding='utf-8') if l.strip()]
if len(gens) != len(items):
raise SystemExit(f'{arm}: {len(gens)} prediction rows != {len(items)} holdout items')
old = [[released.is_correct(g, it.final_answer) for g in gs] for it, gs in zip(items, gens)]
new = [[is_correct(g, gold[i]) for g in gs] for i, gs in zip(ids, gens)]
disagree = Counter()
for o_row, n_row, gs in zip(old, new, gens):
for o, n, g in zip(o_row, n_row, gs):
if o != n:
disagree['released_only' if o else 'new_only'] += 1
if not has_answer_field(g):
disagree['no_answer_field'] += 1
report[arm] = dict(
released=released.aggregate_pass_metrics(old),
first_answer_equivalence=released.aggregate_pass_metrics(new),
samples=len(items) * a.pass_n,
credited_by_released_rule_only=disagree['released_only'],
credited_by_new_rule_only=disagree['new_only'],
samples_without_answer_field=disagree['no_answer_field'])
print(json.dumps(report, indent=2))
if a.output:
a.output.write_text(json.dumps(report, indent=2) + '\n', encoding='utf-8')
def main() -> None:
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
sub = ap.add_subparsers(dest='cmd', required=True)
g = sub.add_parser('golds')
g.add_argument('--holdout', type=Path, required=True)
g.add_argument('--metamath', type=Path, required=True, help='MetaMathQA-395K.json')
g.add_argument('--output', type=Path, required=True)
g.add_argument('--examples', type=int, default=15)
s = sub.add_parser('score')
s.add_argument('--holdout', type=Path, required=True)
s.add_argument('--gold-full', type=Path, required=True)
s.add_argument('--arm', action='append', required=True, help='ARM=predictions.jsonl')
s.add_argument('--pass-n', type=int, default=8)
s.add_argument('--output', type=Path)
a = ap.parse_args()
{'golds': cmd_golds, 'score': cmd_score}[a.cmd](a)
if __name__ == '__main__':
main()