#!/usr/bin/env python3 """Score AIME++ JSONL predictions with deterministic exact matching.""" from __future__ import annotations import argparse import json import re from collections import defaultdict from pathlib import Path ROOT = Path(__file__).resolve().parents[1] CONFIG_FILES = { "all": ( "aime.jsonl", "aime-hard.jsonl", "aime-graduate.jsonl", "aime-researcher.jsonl", ), "aime": ("aime.jsonl",), "aime-hard": ("aime-hard.jsonl",), "aime-graduate": ("aime-graduate.jsonl",), "aime-researcher": ("aime-researcher.jsonl",), } STRICT_ANSWER = re.compile(r"\s*([0-9]{1,3})\s*") BOXED_ANSWER = re.compile(r"\\boxed\{\s*([0-9]{1,3})\s*\}") def parse_prediction(value: object, allow_boxed: bool) -> int | None: if isinstance(value, bool): return None if isinstance(value, int): return value if 0 <= value <= 999 else None if not isinstance(value, str): return None strict = STRICT_ANSWER.fullmatch(value) if strict: return int(strict.group(1)) if allow_boxed: boxed = BOXED_ANSWER.findall(value) if boxed: return int(boxed[-1]) return None def load_gold(data_dir: Path, config: str) -> dict[str, dict[str, object]]: gold: dict[str, dict[str, object]] = {} for filename in CONFIG_FILES[config]: path = data_dir / filename with path.open(encoding="utf-8") as handle: for line_number, line in enumerate(handle, start=1): record = json.loads(line) record_id = record["id"] if record_id in gold: raise ValueError(f"duplicate gold id {record_id!r} in {path}:{line_number}") gold[record_id] = record return gold def load_predictions(path: Path) -> dict[str, object]: predictions: dict[str, object] = {} with path.open(encoding="utf-8") as handle: for line_number, line in enumerate(handle, start=1): if not line.strip(): continue record = json.loads(line) if not isinstance(record, dict) or "id" not in record or "prediction" not in record: raise ValueError(f"{path}:{line_number}: expected fields 'id' and 'prediction'") record_id = record["id"] if not isinstance(record_id, str): raise ValueError(f"{path}:{line_number}: id must be a string") if record_id in predictions: raise ValueError(f"{path}:{line_number}: duplicate prediction id {record_id!r}") predictions[record_id] = record["prediction"] return predictions def main() -> int: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("predictions", type=Path, help="JSONL with id and prediction fields") parser.add_argument("--data-dir", type=Path, default=ROOT / "data") parser.add_argument( "--config", choices=tuple(CONFIG_FILES), default="all", help="gold configuration to score (default: all)", ) parser.add_argument( "--allow-boxed", action="store_true", help=r"also accept the last \boxed{N} found in a string; strict whole-string matching is the default", ) parser.add_argument("--json", action="store_true", help="emit machine-readable JSON") args = parser.parse_args() gold = load_gold(args.data_dir, args.config) predictions = load_predictions(args.predictions) unknown_ids = sorted(set(predictions) - set(gold)) correct = 0 valid = 0 submitted = 0 by_tier: dict[str, dict[str, int]] = defaultdict(lambda: {"correct": 0, "total": 0}) for record_id, record in gold.items(): tier = str(record["tier"]) by_tier[tier]["total"] += 1 if record_id not in predictions: continue submitted += 1 parsed = parse_prediction(predictions[record_id], args.allow_boxed) if parsed is None: continue valid += 1 if parsed == record["answer"]: correct += 1 by_tier[tier]["correct"] += 1 total = len(gold) report = { "config": args.config, "accuracy": correct / total if total else 0.0, "correct": correct, "total": total, "submitted": submitted, "valid": valid, "invalid": submitted - valid, "missing": total - submitted, "unknown_ids": unknown_ids, "tiers": { tier: { **counts, "accuracy": counts["correct"] / counts["total"] if counts["total"] else 0.0, } for tier, counts in by_tier.items() }, } if args.json: print(json.dumps(report, indent=2, sort_keys=True)) else: print(f"overall: {correct}/{total} ({report['accuracy']:.2%})") print( f"coverage: submitted={submitted}, valid={valid}, " f"invalid={submitted - valid}, missing={total - submitted}" ) for tier, counts in report["tiers"].items(): print(f"- {tier}: {counts['correct']}/{counts['total']} ({counts['accuracy']:.2%})") if unknown_ids: print(f"unknown prediction ids: {', '.join(unknown_ids)}") return 0 if __name__ == "__main__": raise SystemExit(main())