Datasets:
File size: 47,363 Bytes
566d308 a8c4a88 566d308 7a790d9 566d308 a8c4a88 566d308 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 | #!/usr/bin/env python3
"""evaluate_benchmark.py -- scoring harness for the DGN math benchmark.
Usage
-----
python evaluate_benchmark.py --dataset <dataset.jsonl|dataset.parquet> \
--predictions <predictions.jsonl> \
[--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<pre>.*?)\(\s*(?P<m>[+-]?\d*)\s*k\s*(?:\\pm|\+|-)\s*(?P<n>[+-]?\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())
|