Add the deterministic grader code
Browse files- README.md +1 -1
- code/README.md +22 -0
- code/grader/math_equiv.py +291 -0
- code/grader/orig/__init__.py +0 -0
- code/grader/orig/holdout_passn.py +190 -0
- code/grader/orig/metamath_parse.py +104 -0
- code/grader/test_math_equiv.py +36 -0
- code/score_parallel.py +100 -0
- code/score_samples.py +83 -0
README.md
CHANGED
|
@@ -308,7 +308,7 @@ Pass@8 is `any(judge_correct)` and PassRatio@8 is the mean of `judge_correct`; t
|
|
| 308 |
judge's grades. The judge is Claude Sonnet 5.5. It graded the eight samples of one prompt together, shown in random
|
| 309 |
order without the model's name, with the prompt in `grades/judge_prompt.md`. The deterministic grader takes the
|
| 310 |
first answer field of a sample (in the open condition, after `####`, `Answer:` or `The answer is`); a numeric answer must
|
| 311 |
-
equal the gold exactly as a number, any other answer is compared with math-verify, and prose never counts.
|
| 312 |
|
| 313 |
## Licensing
|
| 314 |
|
|
|
|
| 308 |
judge's grades. The judge is Claude Sonnet 5.5. It graded the eight samples of one prompt together, shown in random
|
| 309 |
order without the model's name, with the prompt in `grades/judge_prompt.md`. The deterministic grader takes the
|
| 310 |
first answer field of a sample (in the open condition, after `####`, `Answer:` or `The answer is`); a numeric answer must
|
| 311 |
+
equal the gold exactly as a number, any other answer is compared with math-verify, and prose never counts. Its code is in `code/` (see `code/README.md`).
|
| 312 |
|
| 313 |
## Licensing
|
| 314 |
|
code/README.md
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Deterministic grader
|
| 2 |
+
|
| 3 |
+
The rule grader behind the `rule_*` fields in `grades/`. The LLM judge's prompt is `grades/judge_prompt.md`.
|
| 4 |
+
|
| 5 |
+
| File | What it does |
|
| 6 |
+
|---|---|
|
| 7 |
+
| `grader/math_equiv.py` | the grader: `first_answer` takes the first answer field of a sample (in the open condition, after `####`, `Answer:` or `The answer is`; in the direct condition, the first line), and `equivalent` compares it with the full gold: plain numbers exactly as fractions (commas, a dollar sign, a percent sign and a unit word are ignored), anything else with math-verify, and prose never counts |
|
| 8 |
+
| `grader/test_math_equiv.py` | regression cases (`python grader/test_math_equiv.py`) |
|
| 9 |
+
| `grader/orig/` | the experiment's original scorer and answer parser, which `math_equiv.py` imports |
|
| 10 |
+
| `score_samples.py` | scores a samples file against an evaluation config: Pass@8, PassRatio@8 and maj@8 overall and by type, plus the share of samples that state an answer and that hit the length cap |
|
| 11 |
+
| `score_parallel.py` | the same, with each distinct (gold, answer) pair graded in worker processes and a 20-second limit per pair (a pair over the limit counts as wrong); this is the version that produced the released grades |
|
| 12 |
+
|
| 13 |
+
Requirements: Python 3.10 or later with `math-verify` 0.9.0 (which brings `sympy` 1.14.0, `latex2sympy2_extended`
|
| 14 |
+
1.11.0 and `antlr4-python3-runtime` 4.13.2).
|
| 15 |
+
|
| 16 |
+
Example, reproducing the rule grades for the complete arm on the GSM8K test set under the open condition:
|
| 17 |
+
|
| 18 |
+
```bash
|
| 19 |
+
python score_parallel.py samples/gsm8k_test/open/complete.jsonl data/gsm8k_test.jsonl --out complete_scored.jsonl --mode open
|
| 20 |
+
```
|
| 21 |
+
|
| 22 |
+
This prints Pass@8 16.45% and PassRatio@8 3.65%, as in `grades/gsm8k_test/open/complete.jsonl`.
|
code/grader/math_equiv.py
ADDED
|
@@ -0,0 +1,291 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""First-answer, math-equivalence grader for the worked-example holdout.
|
| 3 |
+
|
| 4 |
+
The released scorer (holdout_passn.is_correct) compares the last number after
|
| 5 |
+
the last "####"/"Answer:" in a sample with the last number of the pack's
|
| 6 |
+
final_answer. This grader changes both sides:
|
| 7 |
+
|
| 8 |
+
- Sample: the answer the model gives for the prompted problem, i.e. the text
|
| 9 |
+
before any follow-up "Problem:" the model invents, then the first "####"
|
| 10 |
+
field, else the first "Answer:" field, else the first line, up to the end of
|
| 11 |
+
that line.
|
| 12 |
+
- Gold: MetaMathQA's own final answer ("The answer is: ..."), recovered from
|
| 13 |
+
MetaMathQA-395K.json. The pack's final_answer keeps only the first number of
|
| 14 |
+
short answers and drops commas, so "1,2" became "12" and "\\frac{1}{8}" became
|
| 15 |
+
"1" (orig/metamath_parse.extract_final_answer).
|
| 16 |
+
|
| 17 |
+
Answers are compared numerically when both sides are plain numbers and with
|
| 18 |
+
math-verify otherwise (fractions, LaTeX, sets, tuples, "x=5").
|
| 19 |
+
|
| 20 |
+
Subcommands:
|
| 21 |
+
golds build gold_full.jsonl (instance_id -> full gold) and report how many
|
| 22 |
+
pack golds lose information
|
| 23 |
+
score Pass@N / PassRatio@N per arm under the released rule and this rule,
|
| 24 |
+
plus where the two rules disagree
|
| 25 |
+
The released paired analysis runs unchanged with this rule through the shim in
|
| 26 |
+
olmo_shim/ (see that file).
|
| 27 |
+
"""
|
| 28 |
+
from __future__ import annotations
|
| 29 |
+
|
| 30 |
+
import argparse
|
| 31 |
+
import importlib.util
|
| 32 |
+
import json
|
| 33 |
+
import re
|
| 34 |
+
import sys
|
| 35 |
+
from collections import Counter
|
| 36 |
+
from fractions import Fraction
|
| 37 |
+
from pathlib import Path
|
| 38 |
+
|
| 39 |
+
HERE = Path(__file__).resolve().parent
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
def _load(name: str, path: Path):
|
| 43 |
+
spec = importlib.util.spec_from_file_location(name, path)
|
| 44 |
+
mod = importlib.util.module_from_spec(spec)
|
| 45 |
+
sys.modules[name] = mod
|
| 46 |
+
spec.loader.exec_module(mod)
|
| 47 |
+
return mod
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
# Unmodified copies from OLMo-core 0f479cf0, loaded under their own names so the
|
| 51 |
+
# olmo_shim stand-in (also called holdout_passn) cannot shadow them.
|
| 52 |
+
released = _load('holdout_passn_released', HERE / 'orig' / 'holdout_passn.py')
|
| 53 |
+
metamath_parse = _load('metamath_parse_released', HERE / 'orig' / 'metamath_parse.py')
|
| 54 |
+
|
| 55 |
+
_NUM = re.compile(r'^[-+]?(\d{1,3}(,\d{3})+|\d+)(\.\d+)?$|^[-+]?\.\d+$')
|
| 56 |
+
_STRIP = re.compile(r'^\s*(\\\(|\\\[|\$)+|(\\\)|\\\]|\$)+\s*$')
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
def full_gold(response: str) -> str | None:
|
| 60 |
+
"""MetaMathQA's final answer, untruncated (same patterns as the pack builder)."""
|
| 61 |
+
text = response.strip()
|
| 62 |
+
for pat in metamath_parse.FINAL_PATTERNS:
|
| 63 |
+
m = pat.search(text)
|
| 64 |
+
if m:
|
| 65 |
+
ans = m.group(1).strip().rstrip('.').strip('`"\'').strip()
|
| 66 |
+
return ans or None
|
| 67 |
+
return None
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
_MARKER = re.compile(r'####|Answer:|(?i:the answer is):?') # "so the answer is 15 kg" states an answer as well
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
def first_answer(sample: str, strict: bool = False) -> str | None:
|
| 74 |
+
"""The sample's answer to the prompted problem (None if it gives none).
|
| 75 |
+
|
| 76 |
+
The answer is the rest of the line after the earliest of '####', 'Answer:' and 'The answer is'. Without any
|
| 77 |
+
marker the Direct condition (prompt ends in 'Answer:') takes the first line; strict=True (the Open condition)
|
| 78 |
+
returns None instead, so a sample that never states an answer is wrong and counted as unanswered."""
|
| 79 |
+
seg = sample
|
| 80 |
+
nxt = seg.find('Problem:', 1)
|
| 81 |
+
if nxt > 0:
|
| 82 |
+
seg = seg[:nxt]
|
| 83 |
+
m = _MARKER.search(seg)
|
| 84 |
+
if m:
|
| 85 |
+
line = seg[m.end():].strip().split('\n', 1)[0]
|
| 86 |
+
return line.strip() or None
|
| 87 |
+
if strict:
|
| 88 |
+
return None
|
| 89 |
+
line = seg.strip().split('\n', 1)[0].strip()
|
| 90 |
+
return line or None
|
| 91 |
+
|
| 92 |
+
|
| 93 |
+
def has_answer_field(sample: str) -> bool:
|
| 94 |
+
"""Whether the sample writes '####' or 'Answer:' before any follow-up problem."""
|
| 95 |
+
nxt = sample.find('Problem:', 1)
|
| 96 |
+
seg = sample[:nxt] if nxt > 0 else sample
|
| 97 |
+
return '####' in seg or 'Answer:' in seg
|
| 98 |
+
|
| 99 |
+
|
| 100 |
+
def _clean(s: str) -> str:
|
| 101 |
+
s = s.strip().rstrip('.').strip().strip('* ').rstrip('.').strip() # markdown bold: "**3**"
|
| 102 |
+
s = _STRIP.sub('', s).strip()
|
| 103 |
+
s = re.sub(r'^\\boxed\{(.*)\}$', r'\1', s)
|
| 104 |
+
return s.replace('\\$', '').replace('$', '').replace('\\%', '').replace('%', '').strip()
|
| 105 |
+
|
| 106 |
+
|
| 107 |
+
def _as_number(s: str):
|
| 108 |
+
t = s.replace(' ', '')
|
| 109 |
+
if _NUM.match(t):
|
| 110 |
+
t = t.replace(',', '')
|
| 111 |
+
try:
|
| 112 |
+
return Fraction(t)
|
| 113 |
+
except ValueError:
|
| 114 |
+
return None
|
| 115 |
+
m = re.fullmatch(r'([-+]?\d+)/(\d+)', t)
|
| 116 |
+
if m and int(m.group(2)) != 0:
|
| 117 |
+
return Fraction(int(m.group(1)), int(m.group(2)))
|
| 118 |
+
return None
|
| 119 |
+
|
| 120 |
+
|
| 121 |
+
_MV = None
|
| 122 |
+
_GOLD_CACHE: dict[str, object] = {}
|
| 123 |
+
|
| 124 |
+
|
| 125 |
+
def _math_verify(gold: str, pred: str) -> bool:
|
| 126 |
+
global _MV
|
| 127 |
+
if _MV is None:
|
| 128 |
+
from math_verify import ExprExtractionConfig, LatexExtractionConfig, parse, verify
|
| 129 |
+
_MV = (parse, verify, [LatexExtractionConfig(), ExprExtractionConfig()])
|
| 130 |
+
parse, verify, cfg = _MV
|
| 131 |
+
if len(pred) > 200 or len(gold) > 200: # math-verify has no timeout on Windows; skip pathological strings
|
| 132 |
+
return False
|
| 133 |
+
if gold not in _GOLD_CACHE:
|
| 134 |
+
_GOLD_CACHE[gold] = parse('$' + gold + '$', extraction_config=cfg, parsing_timeout=None)
|
| 135 |
+
g = _GOLD_CACHE[gold]
|
| 136 |
+
p = parse('$' + pred + '$', extraction_config=cfg, parsing_timeout=None)
|
| 137 |
+
return bool(g) and bool(p) and verify(g, p, timeout_seconds=None)
|
| 138 |
+
|
| 139 |
+
|
| 140 |
+
def equivalent(gold: str, pred: str | None) -> bool:
|
| 141 |
+
if pred is None:
|
| 142 |
+
return False
|
| 143 |
+
g, p = _clean(gold), _clean(pred)
|
| 144 |
+
if not p:
|
| 145 |
+
return False
|
| 146 |
+
if g == p:
|
| 147 |
+
return True
|
| 148 |
+
gn, pn = _as_number(g), _as_number(p)
|
| 149 |
+
if gn is not None and pn is not None:
|
| 150 |
+
return gn == pn
|
| 151 |
+
if gn is None and pn is not None and ':' in g:
|
| 152 |
+
return False # a ratio or a time ("3:1", "8:34 p.m."): math-verify would match the number before the colon
|
| 153 |
+
if gn is not None and pn is None:
|
| 154 |
+
# a unit word of two or more letters ("18 dollars", "5cm"); a single letter is a variable or i ("3i", "3x")
|
| 155 |
+
unit = re.fullmatch(r'([-+]?[\d,]*\.?\d+)\s*[a-zA-Z]{2,}[a-zA-Z .]*', p)
|
| 156 |
+
if unit and _as_number(unit.group(1)) is not None:
|
| 157 |
+
return _as_number(unit.group(1)) == gn
|
| 158 |
+
var = re.fullmatch(r'[A-Za-z]\s*=\s*(.+)', p) # "x = 5"
|
| 159 |
+
if var and _as_number(_clean(var.group(1))) is not None:
|
| 160 |
+
return _as_number(_clean(var.group(1))) == gn
|
| 161 |
+
if re.search(r'[A-Za-z=]', re.sub(r'\\[A-Za-z]+', '', p)):
|
| 162 |
+
return False # prose or an equation: only a number, a unit, "x = n" or a pure expression can match
|
| 163 |
+
p = _strip_unmatched_closers(p).rstrip(',;').rstrip() # "3)" from "(the answer is 3)"; "4," ends a clause
|
| 164 |
+
if not _well_formed(p):
|
| 165 |
+
return False # math-verify parses only the start of "3-6)", "2^" or "2 \times", which then equals the gold
|
| 166 |
+
if _as_number(p) is not None:
|
| 167 |
+
return _as_number(p) == gn
|
| 168 |
+
return _math_verify(g, p)
|
| 169 |
+
|
| 170 |
+
|
| 171 |
+
_PAIR = {')': '(', ']': '[', '}': '{'}
|
| 172 |
+
|
| 173 |
+
|
| 174 |
+
def _strip_unmatched_closers(s: str) -> str:
|
| 175 |
+
"""Drop closing brackets at the end that close nothing in the answer (they close the sentence's own bracket)."""
|
| 176 |
+
while s and s[-1] in _PAIR:
|
| 177 |
+
depth = sum(1 if c == _PAIR[s[-1]] else -1 if c == s[-1] else 0 for c in s)
|
| 178 |
+
if depth >= 0:
|
| 179 |
+
break
|
| 180 |
+
s = s[:-1].rstrip().rstrip('.').rstrip()
|
| 181 |
+
return s
|
| 182 |
+
|
| 183 |
+
|
| 184 |
+
def _well_formed(s: str) -> bool:
|
| 185 |
+
"""Balanced brackets and no operator dangling at either end, so math-verify reads the whole answer."""
|
| 186 |
+
stack = []
|
| 187 |
+
for c in s:
|
| 188 |
+
if c in '([{':
|
| 189 |
+
stack.append(c)
|
| 190 |
+
elif c in _PAIR:
|
| 191 |
+
if not stack or stack.pop() != _PAIR[c]:
|
| 192 |
+
return False
|
| 193 |
+
if stack:
|
| 194 |
+
return False
|
| 195 |
+
t = re.sub(r'\\(left|right)\b', '', s).strip()
|
| 196 |
+
if re.search(r'([-+*/^=,:_]|\\times|\\cdot|\\div|\\pm)$', t):
|
| 197 |
+
return False
|
| 198 |
+
return not re.match(r'([*/^=,:_]|\\times|\\cdot|\\div)', t)
|
| 199 |
+
|
| 200 |
+
|
| 201 |
+
def is_correct(sample: str, gold_full_answer: str, strict: bool = False) -> bool:
|
| 202 |
+
return equivalent(gold_full_answer, first_answer(sample, strict))
|
| 203 |
+
|
| 204 |
+
|
| 205 |
+
def load_gold_full(path: Path) -> dict[str, str]:
|
| 206 |
+
return {r['instance_id']: r['gold_full'] for r in map(json.loads, path.open(encoding='utf-8'))}
|
| 207 |
+
|
| 208 |
+
|
| 209 |
+
def cmd_golds(a) -> None:
|
| 210 |
+
ev = [json.loads(l) for l in a.holdout.open(encoding='utf-8') if l.strip()]
|
| 211 |
+
rows = json.load(a.metamath.open(encoding='utf-8'))
|
| 212 |
+
by_q: dict[str, list[dict]] = {}
|
| 213 |
+
for r in rows:
|
| 214 |
+
by_q.setdefault(r['query'].strip(), []).append(r)
|
| 215 |
+
out, stats = [], Counter()
|
| 216 |
+
for e in ev:
|
| 217 |
+
cands = by_q.get(e['question'].strip(), [])
|
| 218 |
+
# The MetaMathQA row the pack used: its lossy extraction equals the pack gold.
|
| 219 |
+
match = [r for r in cands if metamath_parse.extract_final_answer(r['response']) == e['final_answer']
|
| 220 |
+
and (r.get('type') or '') == e.get('type', '')]
|
| 221 |
+
if not match:
|
| 222 |
+
match = [r for r in cands if metamath_parse.extract_final_answer(r['response']) == e['final_answer']]
|
| 223 |
+
fulls = sorted({full_gold(r['response']) for r in match} - {None})
|
| 224 |
+
if not fulls:
|
| 225 |
+
stats['no_source_row'] += 1
|
| 226 |
+
g = e['final_answer']
|
| 227 |
+
else:
|
| 228 |
+
g = fulls[0]
|
| 229 |
+
stats['multiple_full_answers'] += len(fulls) > 1
|
| 230 |
+
lossy = not equivalent(g, e['final_answer'])
|
| 231 |
+
stats['lossy_pack_gold'] += lossy
|
| 232 |
+
out.append(dict(instance_id=e['instance_id'], gold_full=g, pack_gold=e['final_answer'], lossy=lossy))
|
| 233 |
+
with a.output.open('w', encoding='utf-8') as f:
|
| 234 |
+
for r in out:
|
| 235 |
+
f.write(json.dumps(r, ensure_ascii=False) + '\n')
|
| 236 |
+
print(json.dumps(dict(n_items=len(ev), **stats), indent=2))
|
| 237 |
+
for r in [r for r in out if r['lossy']][:a.examples]:
|
| 238 |
+
print(f" pack {r['pack_gold']!r:>10} full {r['gold_full']!r}")
|
| 239 |
+
|
| 240 |
+
|
| 241 |
+
def cmd_score(a) -> None:
|
| 242 |
+
items = released.load_holdout(a.holdout)
|
| 243 |
+
ids = [json.loads(l)['instance_id'] for l in a.holdout.open(encoding='utf-8') if l.strip()]
|
| 244 |
+
gold = load_gold_full(a.gold_full)
|
| 245 |
+
report = {}
|
| 246 |
+
for spec in a.arm:
|
| 247 |
+
arm, path = spec.split('=', 1)
|
| 248 |
+
gens = [json.loads(l)['gens'][:a.pass_n] for l in open(path, encoding='utf-8') if l.strip()]
|
| 249 |
+
if len(gens) != len(items):
|
| 250 |
+
raise SystemExit(f'{arm}: {len(gens)} prediction rows != {len(items)} holdout items')
|
| 251 |
+
old = [[released.is_correct(g, it.final_answer) for g in gs] for it, gs in zip(items, gens)]
|
| 252 |
+
new = [[is_correct(g, gold[i]) for g in gs] for i, gs in zip(ids, gens)]
|
| 253 |
+
disagree = Counter()
|
| 254 |
+
for o_row, n_row, gs in zip(old, new, gens):
|
| 255 |
+
for o, n, g in zip(o_row, n_row, gs):
|
| 256 |
+
if o != n:
|
| 257 |
+
disagree['released_only' if o else 'new_only'] += 1
|
| 258 |
+
if not has_answer_field(g):
|
| 259 |
+
disagree['no_answer_field'] += 1
|
| 260 |
+
report[arm] = dict(
|
| 261 |
+
released=released.aggregate_pass_metrics(old),
|
| 262 |
+
first_answer_equivalence=released.aggregate_pass_metrics(new),
|
| 263 |
+
samples=len(items) * a.pass_n,
|
| 264 |
+
credited_by_released_rule_only=disagree['released_only'],
|
| 265 |
+
credited_by_new_rule_only=disagree['new_only'],
|
| 266 |
+
samples_without_answer_field=disagree['no_answer_field'])
|
| 267 |
+
print(json.dumps(report, indent=2))
|
| 268 |
+
if a.output:
|
| 269 |
+
a.output.write_text(json.dumps(report, indent=2) + '\n', encoding='utf-8')
|
| 270 |
+
|
| 271 |
+
|
| 272 |
+
def main() -> None:
|
| 273 |
+
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
|
| 274 |
+
sub = ap.add_subparsers(dest='cmd', required=True)
|
| 275 |
+
g = sub.add_parser('golds')
|
| 276 |
+
g.add_argument('--holdout', type=Path, required=True)
|
| 277 |
+
g.add_argument('--metamath', type=Path, required=True, help='MetaMathQA-395K.json')
|
| 278 |
+
g.add_argument('--output', type=Path, required=True)
|
| 279 |
+
g.add_argument('--examples', type=int, default=15)
|
| 280 |
+
s = sub.add_parser('score')
|
| 281 |
+
s.add_argument('--holdout', type=Path, required=True)
|
| 282 |
+
s.add_argument('--gold-full', type=Path, required=True)
|
| 283 |
+
s.add_argument('--arm', action='append', required=True, help='ARM=predictions.jsonl')
|
| 284 |
+
s.add_argument('--pass-n', type=int, default=8)
|
| 285 |
+
s.add_argument('--output', type=Path)
|
| 286 |
+
a = ap.parse_args()
|
| 287 |
+
{'golds': cmd_golds, 'score': cmd_score}[a.cmd](a)
|
| 288 |
+
|
| 289 |
+
|
| 290 |
+
if __name__ == '__main__':
|
| 291 |
+
main()
|
code/grader/orig/__init__.py
ADDED
|
File without changes
|
code/grader/orig/holdout_passn.py
ADDED
|
@@ -0,0 +1,190 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Holdout Pass@N / PassRatio@N for worked-examples CPT (W&B-safe metric names).
|
| 3 |
+
|
| 4 |
+
Reads ``eval/holdout_bare.jsonl`` (bare problem prompts + ``final_answer``).
|
| 5 |
+
Logs validator-safe names (no whitespace):
|
| 6 |
+
|
| 7 |
+
- ``eval/pass_at_n``
|
| 8 |
+
- ``eval/pass_ratio_at_n``
|
| 9 |
+
|
| 10 |
+
Can run standalone after a checkpoint, or be imported by the train callback.
|
| 11 |
+
"""
|
| 12 |
+
|
| 13 |
+
from __future__ import annotations
|
| 14 |
+
|
| 15 |
+
import argparse
|
| 16 |
+
import json
|
| 17 |
+
import logging
|
| 18 |
+
import re
|
| 19 |
+
from dataclasses import dataclass
|
| 20 |
+
from pathlib import Path
|
| 21 |
+
from typing import Iterable, List, Optional, Sequence, Tuple
|
| 22 |
+
|
| 23 |
+
log = logging.getLogger(__name__)
|
| 24 |
+
|
| 25 |
+
_NUM = re.compile(r"[-+]?\d[\d,]*(?:\.\d+)?")
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
def normalize_answer(text: str) -> str:
|
| 29 |
+
text = text.strip()
|
| 30 |
+
if "####" in text:
|
| 31 |
+
text = text.split("####")[-1].strip()
|
| 32 |
+
if "Answer:" in text:
|
| 33 |
+
text = text.split("Answer:")[-1].strip()
|
| 34 |
+
text = text.replace(",", "")
|
| 35 |
+
m = _NUM.findall(text)
|
| 36 |
+
if m:
|
| 37 |
+
return m[-1].lstrip("+")
|
| 38 |
+
return text.lower()
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
def is_correct(pred: str, gold: str) -> bool:
|
| 42 |
+
return normalize_answer(pred) == normalize_answer(gold)
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
@dataclass
|
| 46 |
+
class HoldoutItem:
|
| 47 |
+
prompt: str
|
| 48 |
+
final_answer: str
|
| 49 |
+
family_id: Optional[str] = None
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
def load_holdout(path: Path, *, max_items: int = 0) -> List[HoldoutItem]:
|
| 53 |
+
items: List[HoldoutItem] = []
|
| 54 |
+
with path.open(encoding="utf-8") as f:
|
| 55 |
+
for line in f:
|
| 56 |
+
line = line.strip()
|
| 57 |
+
if not line:
|
| 58 |
+
continue
|
| 59 |
+
row = json.loads(line)
|
| 60 |
+
q = row.get("question") or row.get("problem") or row.get("prompt")
|
| 61 |
+
if q is None and "text" in row:
|
| 62 |
+
# fall back: strip Answer: if present
|
| 63 |
+
q = str(row["text"]).split("Answer:")[0].strip()
|
| 64 |
+
ans = row.get("final_answer") or row.get("answer")
|
| 65 |
+
if q is None or ans is None:
|
| 66 |
+
raise ValueError(f"holdout row missing question/answer keys: {row.keys()}")
|
| 67 |
+
prompt = q if str(q).startswith("Problem:") else f"Problem: {q}\n"
|
| 68 |
+
if not prompt.endswith("\n"):
|
| 69 |
+
prompt += "\n"
|
| 70 |
+
items.append(
|
| 71 |
+
HoldoutItem(
|
| 72 |
+
prompt=prompt,
|
| 73 |
+
final_answer=str(ans),
|
| 74 |
+
family_id=row.get("family_id") or row.get("original_question"),
|
| 75 |
+
)
|
| 76 |
+
)
|
| 77 |
+
if max_items and len(items) >= max_items:
|
| 78 |
+
break
|
| 79 |
+
return items
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
def pass_at_n_and_ratio(correct_flags: Sequence[bool]) -> Tuple[float, float]:
|
| 83 |
+
"""Per-item: Pass@N = any correct; PassRatio@N = mean correct."""
|
| 84 |
+
if not correct_flags:
|
| 85 |
+
return 0.0, 0.0
|
| 86 |
+
any_ok = 1.0 if any(correct_flags) else 0.0
|
| 87 |
+
ratio = sum(1.0 for c in correct_flags if c) / len(correct_flags)
|
| 88 |
+
return any_ok, ratio
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
def aggregate_pass_metrics(
|
| 92 |
+
per_item_correct: Iterable[Sequence[bool]],
|
| 93 |
+
) -> dict[str, float]:
|
| 94 |
+
pass_scores: List[float] = []
|
| 95 |
+
ratio_scores: List[float] = []
|
| 96 |
+
for flags in per_item_correct:
|
| 97 |
+
p, r = pass_at_n_and_ratio(flags)
|
| 98 |
+
pass_scores.append(p)
|
| 99 |
+
ratio_scores.append(r)
|
| 100 |
+
n = max(len(pass_scores), 1)
|
| 101 |
+
return {
|
| 102 |
+
"eval/pass_at_n": sum(pass_scores) / n,
|
| 103 |
+
"eval/pass_ratio_at_n": sum(ratio_scores) / n,
|
| 104 |
+
"eval/n_items": float(len(pass_scores)),
|
| 105 |
+
}
|
| 106 |
+
|
| 107 |
+
|
| 108 |
+
def score_generations(
|
| 109 |
+
items: Sequence[HoldoutItem],
|
| 110 |
+
generations: Sequence[Sequence[str]],
|
| 111 |
+
) -> dict[str, float]:
|
| 112 |
+
if len(items) != len(generations):
|
| 113 |
+
raise ValueError("items and generations length mismatch")
|
| 114 |
+
per_item = [
|
| 115 |
+
[is_correct(gen, item.final_answer) for gen in gens]
|
| 116 |
+
for item, gens in zip(items, generations)
|
| 117 |
+
]
|
| 118 |
+
return aggregate_pass_metrics(per_item)
|
| 119 |
+
|
| 120 |
+
|
| 121 |
+
def log_metrics_to_wandb(
|
| 122 |
+
metrics: dict[str, float],
|
| 123 |
+
*,
|
| 124 |
+
entity: str = "eduLLM",
|
| 125 |
+
project: str = "pretraining",
|
| 126 |
+
group: Optional[str] = None,
|
| 127 |
+
name: Optional[str] = None,
|
| 128 |
+
tags: Optional[List[str]] = None,
|
| 129 |
+
step: Optional[int] = None,
|
| 130 |
+
) -> None:
|
| 131 |
+
"""Log Pass@N metrics to W&B (optional; requires WANDB_API_KEY)."""
|
| 132 |
+
import os
|
| 133 |
+
|
| 134 |
+
import wandb
|
| 135 |
+
|
| 136 |
+
if "WANDB_API_KEY" not in os.environ:
|
| 137 |
+
log.warning("WANDB_API_KEY missing; skipping W&B log")
|
| 138 |
+
return
|
| 139 |
+
run = wandb.run
|
| 140 |
+
created = False
|
| 141 |
+
if run is None:
|
| 142 |
+
wandb.init(entity=entity, project=project, group=group, name=name, tags=tags or [])
|
| 143 |
+
created = True
|
| 144 |
+
run = wandb.run
|
| 145 |
+
assert run is not None
|
| 146 |
+
payload = {k: float(v) for k, v in metrics.items()}
|
| 147 |
+
if step is None:
|
| 148 |
+
run.log(payload)
|
| 149 |
+
else:
|
| 150 |
+
run.log(payload, step=step)
|
| 151 |
+
if created:
|
| 152 |
+
wandb.finish()
|
| 153 |
+
|
| 154 |
+
|
| 155 |
+
def main() -> None:
|
| 156 |
+
logging.basicConfig(level=logging.INFO)
|
| 157 |
+
ap = argparse.ArgumentParser(description=__doc__)
|
| 158 |
+
ap.add_argument("--holdout", type=Path, required=True, help="Path to holdout_bare.jsonl")
|
| 159 |
+
ap.add_argument("--predictions", type=Path, required=True, help="JSONL: {gens: [str,...]}")
|
| 160 |
+
ap.add_argument("--max-items", type=int, default=0)
|
| 161 |
+
ap.add_argument("--wandb", action="store_true")
|
| 162 |
+
ap.add_argument("--wandb-entity", default="eduLLM")
|
| 163 |
+
ap.add_argument("--wandb-project", default="pretraining")
|
| 164 |
+
ap.add_argument("--wandb-group", default=None)
|
| 165 |
+
ap.add_argument("--wandb-name", default=None)
|
| 166 |
+
args = ap.parse_args()
|
| 167 |
+
|
| 168 |
+
items = load_holdout(args.holdout, max_items=args.max_items)
|
| 169 |
+
gens: List[List[str]] = []
|
| 170 |
+
with args.predictions.open(encoding="utf-8") as f:
|
| 171 |
+
for line in f:
|
| 172 |
+
row = json.loads(line)
|
| 173 |
+
gens.append([str(x) for x in row["gens"]])
|
| 174 |
+
if len(gens) != len(items):
|
| 175 |
+
raise SystemExit(f"prediction rows {len(gens)} != holdout items {len(items)}")
|
| 176 |
+
|
| 177 |
+
metrics = score_generations(items, gens)
|
| 178 |
+
print(json.dumps(metrics, indent=2))
|
| 179 |
+
if args.wandb:
|
| 180 |
+
log_metrics_to_wandb(
|
| 181 |
+
metrics,
|
| 182 |
+
entity=args.wandb_entity,
|
| 183 |
+
project=args.wandb_project,
|
| 184 |
+
group=args.wandb_group,
|
| 185 |
+
name=args.wandb_name,
|
| 186 |
+
)
|
| 187 |
+
|
| 188 |
+
|
| 189 |
+
if __name__ == "__main__":
|
| 190 |
+
main()
|
code/grader/orig/metamath_parse.py
ADDED
|
@@ -0,0 +1,104 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Parse MetaMathQA rows into steps + final answer (no LLM)."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import hashlib
|
| 6 |
+
import re
|
| 7 |
+
from typing import Any
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
CALC_RE = re.compile(r"<<.*?>>")
|
| 11 |
+
# MetaMath often ends with "The answer is: X" or GSM-style #### X
|
| 12 |
+
FINAL_PATTERNS = [
|
| 13 |
+
re.compile(r"The answer is:\s*(.+?)\s*$", re.IGNORECASE | re.MULTILINE),
|
| 14 |
+
re.compile(r"The answer is\s+(.+?)\s*$", re.IGNORECASE | re.MULTILINE),
|
| 15 |
+
re.compile(r"####\s*(.+)"),
|
| 16 |
+
]
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
def family_id_from_original(original_question: str) -> str:
|
| 20 |
+
h = hashlib.sha1(original_question.strip().encode("utf-8")).hexdigest()[:12]
|
| 21 |
+
return f"mm_{h}"
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
def extract_final_answer(response: str) -> str | None:
|
| 25 |
+
text = response.strip()
|
| 26 |
+
for pat in FINAL_PATTERNS:
|
| 27 |
+
m = pat.search(text)
|
| 28 |
+
if not m:
|
| 29 |
+
continue
|
| 30 |
+
ans = m.group(1).strip()
|
| 31 |
+
# Trim trailing punctuation / quotes
|
| 32 |
+
ans = ans.strip().rstrip(".")
|
| 33 |
+
ans = ans.strip("`\"'")
|
| 34 |
+
# Prefer last numeric token if the capture is noisy
|
| 35 |
+
num = re.search(r"[-+]?\d[\d,]*(?:\.\d+)?", ans)
|
| 36 |
+
if num and (ans == num.group(0) or len(ans) <= 32):
|
| 37 |
+
return num.group(0).replace(",", "")
|
| 38 |
+
if ans:
|
| 39 |
+
return ans
|
| 40 |
+
return None
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
def split_steps(response: str) -> list[str]:
|
| 44 |
+
"""Split CoT body (before final-answer line) into steps."""
|
| 45 |
+
body = response.strip()
|
| 46 |
+
for pat in FINAL_PATTERNS:
|
| 47 |
+
m = pat.search(body)
|
| 48 |
+
if m:
|
| 49 |
+
body = body[: m.start()].strip()
|
| 50 |
+
break
|
| 51 |
+
|
| 52 |
+
cleaned_lines: list[str] = []
|
| 53 |
+
for line in body.splitlines():
|
| 54 |
+
line = line.strip()
|
| 55 |
+
if not line:
|
| 56 |
+
continue
|
| 57 |
+
# Drop leading "Step N:" / "N." numbering noise into content
|
| 58 |
+
line = re.sub(r"^(?:step\s*)?\d+[\.:)\]]\s*", "", line, flags=re.IGNORECASE)
|
| 59 |
+
line = CALC_RE.sub("", line).strip()
|
| 60 |
+
line = re.sub(r"\s+", " ", line)
|
| 61 |
+
if line:
|
| 62 |
+
cleaned_lines.append(line)
|
| 63 |
+
|
| 64 |
+
if not cleaned_lines:
|
| 65 |
+
return []
|
| 66 |
+
if len(cleaned_lines) >= 2:
|
| 67 |
+
return cleaned_lines
|
| 68 |
+
|
| 69 |
+
text = cleaned_lines[0]
|
| 70 |
+
parts = [p.strip() for p in re.split(r"(?<=[.!?])\s+", text) if p.strip()]
|
| 71 |
+
return parts if len(parts) >= 2 else [text]
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
def parse_metamath_row(
|
| 75 |
+
row: dict[str, Any],
|
| 76 |
+
*,
|
| 77 |
+
instance_id: str,
|
| 78 |
+
split: str,
|
| 79 |
+
) -> dict[str, Any] | None:
|
| 80 |
+
query = (row.get("query") or "").strip()
|
| 81 |
+
response = (row.get("response") or "").strip()
|
| 82 |
+
original = (row.get("original_question") or query).strip()
|
| 83 |
+
typ = (row.get("type") or "").strip()
|
| 84 |
+
if not query or not response:
|
| 85 |
+
return None
|
| 86 |
+
|
| 87 |
+
steps = split_steps(response)
|
| 88 |
+
final = extract_final_answer(response)
|
| 89 |
+
if not final or not steps:
|
| 90 |
+
return None
|
| 91 |
+
|
| 92 |
+
return {
|
| 93 |
+
"family_id": family_id_from_original(original),
|
| 94 |
+
"instance_id": instance_id,
|
| 95 |
+
"split": split,
|
| 96 |
+
"source": "meta-math/MetaMathQA",
|
| 97 |
+
"type": typ,
|
| 98 |
+
"question": query,
|
| 99 |
+
"original_question": original,
|
| 100 |
+
"steps": steps,
|
| 101 |
+
"final_answer": final,
|
| 102 |
+
"answer_raw": response,
|
| 103 |
+
"n_steps": len(steps),
|
| 104 |
+
}
|
code/grader/test_math_equiv.py
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Regression cases for math_equiv.equivalent (run: python test_math_equiv.py, or pytest).
|
| 2 |
+
|
| 3 |
+
The false-positive cases came from the 2026-11-08 judge-vs-rule comparison on fade_ordered's Open samples: before the
|
| 4 |
+
fix the grader read "3i" and "$3-6$)." as 3 and "3" as the ratio "3:1"."""
|
| 5 |
+
import sys
|
| 6 |
+
from pathlib import Path
|
| 7 |
+
|
| 8 |
+
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
| 9 |
+
import math_equiv # noqa: E402
|
| 10 |
+
|
| 11 |
+
CASES = [
|
| 12 |
+
# (gold, answer, expected)
|
| 13 |
+
("3", "3i", False), ("2", "2i", False), ("3", "3x", False), # a single letter is i or a variable, not a unit
|
| 14 |
+
("3", "$3-6$).", False), ("3", "3-6", False), # a whole expression must equal the gold
|
| 15 |
+
("2", "2^", False), ("2", r"2 \times", False), ("4", "((2+2)", False), # dangling operator, unbalanced bracket
|
| 16 |
+
("3:1", "3", False), ("3", "-3", False), ("3", "3, 4", False), ("5", "5 m", False),
|
| 17 |
+
("3", "3 dollars", True), ("12", "12 apples.", True), ("5", "5cm", True), ("10", "10%", True),
|
| 18 |
+
("3", "3)", True), ("4", "4]", True), ("4", "(4)", True), ("4", r"\left(4\right)", True),
|
| 19 |
+
("3", "x = 3", True), ("3", "3.", True), ("3", "$3$", True), ("3", r"\boxed{3}", True),
|
| 20 |
+
("3", r"\frac{6}{2}", True), ("3", "6/2", True), ("0.5", r"\frac12", True), ("6", r"2 \times 3", True),
|
| 21 |
+
("8", "2^3", True), ("8", "2^{3}", True), ("4", r"\sqrt{16}", True), ("3", "3 + 0", True),
|
| 22 |
+
(r"\frac{1}{2}", "1/2", True), ("3:1", "3:1", True), ("(-1,0]", "(-1,0]", True),
|
| 23 |
+
("1011_2", "1011", True), (r"10^\circ", "10", True),
|
| 24 |
+
("7", "* 7", True), ("3", "** **3**", True), ("3", "**3**.", True), ("4", "$4,$", True), ("4", "4;", True),
|
| 25 |
+
("3", "3a", False), ("9", "$9a$", False), ("16", '[["$16^2$,", " $16$"]', False),
|
| 26 |
+
]
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
def test_cases():
|
| 30 |
+
bad = [(g, a, want) for g, a, want in CASES if math_equiv.equivalent(g, a) != want]
|
| 31 |
+
assert not bad, bad
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
if __name__ == "__main__":
|
| 35 |
+
test_cases()
|
| 36 |
+
print(len(CASES), "cases pass")
|
code/score_parallel.py
ADDED
|
@@ -0,0 +1,100 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Parallel front end for score_samples.py (math-verify has no working timeout on Windows, so one pathological answer
|
| 2 |
+
can hang the serial scorer for hours).
|
| 3 |
+
|
| 4 |
+
Every distinct (gold, first answer) pair is graded once, in worker processes; a worker stuck on one pair for 20 s is
|
| 5 |
+
killed and the pair counts as wrong (the pairs are listed in TIMEOUTS_JSON). Then score_samples.main runs unchanged
|
| 6 |
+
with those results.
|
| 7 |
+
|
| 8 |
+
usage: score_parallel.py SAMPLES_JSONL HOLDOUT_JSONL --out PER_PROMPT_JSONL [--mode direct|open] [--workers 7]
|
| 9 |
+
Run with the grader venv's Python so math-verify can be imported.
|
| 10 |
+
"""
|
| 11 |
+
import json
|
| 12 |
+
import multiprocessing as mp
|
| 13 |
+
import sys
|
| 14 |
+
import time
|
| 15 |
+
from pathlib import Path
|
| 16 |
+
|
| 17 |
+
HERE = Path(__file__).resolve().parent
|
| 18 |
+
sys.path.insert(0, str(HERE))
|
| 19 |
+
sys.path.insert(0, str(HERE / "grader"))
|
| 20 |
+
LIMIT = 20.0
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
def worker(conn):
|
| 24 |
+
import math_equiv
|
| 25 |
+
while True:
|
| 26 |
+
gold, ans = conn.recv()
|
| 27 |
+
try:
|
| 28 |
+
conn.send(bool(math_equiv.equivalent(gold, ans)))
|
| 29 |
+
except Exception:
|
| 30 |
+
conn.send(False)
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def spawn():
|
| 34 |
+
a, b = mp.Pipe()
|
| 35 |
+
p = mp.Process(target=worker, args=(b,), daemon=True)
|
| 36 |
+
p.start()
|
| 37 |
+
return {"p": p, "c": a, "job": None, "t": 0.0}
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
def main(samples, holdout, out, mode="direct", workers=7):
|
| 41 |
+
import math_equiv
|
| 42 |
+
import score_samples
|
| 43 |
+
from score_samples import read_jsonl
|
| 44 |
+
strict = mode == "open"
|
| 45 |
+
gold = {h["instance_id"]: h["final_answer"] for h in read_jsonl(holdout)}
|
| 46 |
+
pairs = set()
|
| 47 |
+
for r in read_jsonl(samples):
|
| 48 |
+
if r["instance_id"] in gold:
|
| 49 |
+
a = math_equiv.first_answer(r["text"], strict)
|
| 50 |
+
if a:
|
| 51 |
+
pairs.add((gold[r["instance_id"]], a))
|
| 52 |
+
todo, res, timeouts, t0 = list(pairs), {}, [], time.time()
|
| 53 |
+
print(len(pairs), "distinct (gold, answer) pairs", flush=True)
|
| 54 |
+
ws = [spawn() for _ in range(workers)]
|
| 55 |
+
last = 0
|
| 56 |
+
while todo or any(w["job"] for w in ws):
|
| 57 |
+
for i, w in enumerate(ws):
|
| 58 |
+
if w["job"] is not None:
|
| 59 |
+
try:
|
| 60 |
+
ready = w["c"].poll()
|
| 61 |
+
if ready:
|
| 62 |
+
res[w["job"]] = w["c"].recv()
|
| 63 |
+
w["job"] = None
|
| 64 |
+
except (BrokenPipeError, EOFError, OSError):
|
| 65 |
+
# the worker died while grading this answer (a crash inside math-verify / SymPy): count it wrong
|
| 66 |
+
res[w["job"]] = False
|
| 67 |
+
timeouts.append(w["job"])
|
| 68 |
+
w["p"].kill()
|
| 69 |
+
ws[i] = w = spawn()
|
| 70 |
+
ready = False
|
| 71 |
+
if w["job"] is None:
|
| 72 |
+
pass
|
| 73 |
+
elif ready:
|
| 74 |
+
pass
|
| 75 |
+
elif time.time() - w["t"] > LIMIT:
|
| 76 |
+
res[w["job"]] = False
|
| 77 |
+
timeouts.append(w["job"])
|
| 78 |
+
w["p"].kill()
|
| 79 |
+
ws[i] = w = spawn()
|
| 80 |
+
if w["job"] is None and todo:
|
| 81 |
+
w["job"] = todo.pop()
|
| 82 |
+
w["t"] = time.time()
|
| 83 |
+
w["c"].send(w["job"])
|
| 84 |
+
if time.time() - last > 60:
|
| 85 |
+
last = time.time()
|
| 86 |
+
print(f"{len(res)}/{len(pairs)} graded, {len(timeouts)} timeouts, {int(last - t0)} s", flush=True)
|
| 87 |
+
time.sleep(0.005)
|
| 88 |
+
for w in ws:
|
| 89 |
+
w["p"].kill()
|
| 90 |
+
print(f"graded {len(res)} pairs in {int(time.time() - t0)} s; {len(timeouts)} timed out (counted wrong)", flush=True)
|
| 91 |
+
Path(out).with_suffix(".timeouts.json").write_text(json.dumps([[g[:200], a[:200]] for g, a in timeouts]))
|
| 92 |
+
math_equiv.equivalent = lambda g, a: bool(a) and res[(g, a)]
|
| 93 |
+
score_samples.main(samples, holdout, out, mode)
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
if __name__ == "__main__":
|
| 97 |
+
mp.freeze_support()
|
| 98 |
+
a = sys.argv[1:]
|
| 99 |
+
main(a[0], a[1], a[a.index("--out") + 1], a[a.index("--mode") + 1] if "--mode" in a else "direct",
|
| 100 |
+
int(a[a.index("--workers") + 1]) if "--workers" in a else 7)
|
code/score_samples.py
ADDED
|
@@ -0,0 +1,83 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Score sampler output on a holdout with the first-answer, math-equivalence grader (gen/grader/math_equiv.py).
|
| 2 |
+
|
| 3 |
+
A sample is correct when its first answer field is equivalent to the prompt's full gold (numbers compared exactly,
|
| 4 |
+
a bare expression with math-verify, prose never). Reports Pass@N, PassRatio@N and maj@N (the most common answer among
|
| 5 |
+
the samples is correct) overall and by source and type, plus the share of samples that state an answer, hit the token
|
| 6 |
+
cap, and their mean length. Run it with the grader venv's Python so math-verify can be imported. The paired
|
| 7 |
+
family-cluster analysis across arms is the released analyze_passn_eval.py, run through gen/grader/olmo_shim with the
|
| 8 |
+
files sampler_to_preds.py writes.
|
| 9 |
+
|
| 10 |
+
usage: score_samples.py SAMPLES_JSONL HOLDOUT_JSONL [--out PER_PROMPT_JSONL] [--mode direct|open]
|
| 11 |
+
direct (default): prompt ended in "Answer:", a sample with no marker answers with its first line
|
| 12 |
+
open: prompt was "Problem: q", a sample must state an answer after '####', 'Answer:' or 'The answer is'
|
| 13 |
+
"""
|
| 14 |
+
import json
|
| 15 |
+
import sys
|
| 16 |
+
from collections import Counter, defaultdict
|
| 17 |
+
from pathlib import Path
|
| 18 |
+
|
| 19 |
+
sys.path.insert(0, str(Path(__file__).resolve().parent / "grader"))
|
| 20 |
+
import math_equiv # noqa: E402
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
def read_jsonl(path):
|
| 25 |
+
with open(path, encoding="utf-8") as f:
|
| 26 |
+
return [json.loads(line) for line in f if line.strip()]
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
def write_jsonl(path, rows):
|
| 30 |
+
Path(path).parent.mkdir(parents=True, exist_ok=True)
|
| 31 |
+
with open(path, "w", encoding="utf-8", newline="\n") as f:
|
| 32 |
+
for r in rows:
|
| 33 |
+
f.write(json.dumps(r, ensure_ascii=False) + "\n")
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
def answer_key(ans):
|
| 37 |
+
c = math_equiv._clean(ans)
|
| 38 |
+
n = math_equiv._as_number(c)
|
| 39 |
+
return ("n", n) if n is not None else ("s", c.lower())
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
def main(samples, holdout, out=None, mode="direct"):
|
| 43 |
+
strict = mode == "open"
|
| 44 |
+
by = defaultdict(dict)
|
| 45 |
+
for r in read_jsonl(samples):
|
| 46 |
+
by[r["instance_id"]][r["sample"]] = r
|
| 47 |
+
per, groups = [], defaultdict(list)
|
| 48 |
+
for h in read_jsonl(holdout):
|
| 49 |
+
got = by.get(h["instance_id"])
|
| 50 |
+
if not got:
|
| 51 |
+
continue
|
| 52 |
+
ks = sorted(got)
|
| 53 |
+
answers = [math_equiv.first_answer(got[k]["text"], strict) for k in ks]
|
| 54 |
+
flags = [math_equiv.equivalent(h["final_answer"], a) for a in answers]
|
| 55 |
+
votes = Counter(answer_key(a) for a in answers if a)
|
| 56 |
+
maj = False
|
| 57 |
+
if votes:
|
| 58 |
+
top = votes.most_common(1)[0][0]
|
| 59 |
+
maj = flags[next(i for i, a in enumerate(answers) if a and answer_key(a) == top)]
|
| 60 |
+
rec = {"instance_id": h["instance_id"], "family_id": h["family_id"], "type": h["type"], "n": len(flags),
|
| 61 |
+
"any_correct": any(flags), "ratio": sum(flags) / len(flags), "maj": maj,
|
| 62 |
+
"answered": sum(a is not None for a in answers) / len(answers),
|
| 63 |
+
"capped": sum(got[k].get("stop") == "cap" for k in ks) / len(ks),
|
| 64 |
+
"tokens": sum(got[k].get("new_tokens", 0) for k in ks) / len(ks)}
|
| 65 |
+
per.append(rec)
|
| 66 |
+
groups["all"].append(rec)
|
| 67 |
+
groups["source " + h.get("source", h["type"].split("_")[0].lower())].append(rec)
|
| 68 |
+
groups["type " + h["type"]].append(rec)
|
| 69 |
+
print(f"{len(per)} prompts scored ({mode} mode)")
|
| 70 |
+
for k in sorted(groups):
|
| 71 |
+
g = groups[k]
|
| 72 |
+
pct = lambda f: 100 * sum(r[f] for r in g) / len(g) # noqa: E731
|
| 73 |
+
print(f" {k:22s} n={len(g):6d} Pass@N {pct('any_correct'):6.2f}% PassRatio@N {pct('ratio'):6.2f}% "
|
| 74 |
+
f"maj@N {pct('maj'):6.2f}% answered {pct('answered'):6.2f}% capped {pct('capped'):5.2f}% "
|
| 75 |
+
f"mean tokens {sum(r['tokens'] for r in g) / len(g):6.1f}")
|
| 76 |
+
if out:
|
| 77 |
+
write_jsonl(out, per)
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
if __name__ == "__main__":
|
| 81 |
+
a = sys.argv[1:]
|
| 82 |
+
main(a[0], a[1], a[a.index("--out") + 1] if "--out" in a else None,
|
| 83 |
+
a[a.index("--mode") + 1] if "--mode" in a else "direct")
|