File size: 5,358 Bytes
8e38bba
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/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())