File size: 7,589 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
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
#!/usr/bin/env python3
"""Validate the AIME++ sample using only the Python standard library."""

from __future__ import annotations

import argparse
import hashlib
import json
import re
import sys
from dataclasses import dataclass
from pathlib import Path


ROOT = Path(__file__).resolve().parents[1]
FIELDS = {"id", "problem", "answer", "answer_str", "tier"}


@dataclass(frozen=True)
class FileSpec:
    path: str
    tier: str
    id_stem: str
    expected_count: int


FILE_SPECS = (
    FileSpec("data/aime.jsonl", "AIME", "aime", 34),
    FileSpec("data/aime-hard.jsonl", "AIME Hard", "hard", 98),
    FileSpec("data/aime-graduate.jsonl", "AIME-Graduate", "graduate", 20),
    FileSpec("data/aime-researcher.jsonl", "AIME-Researcher", "researcher", 5),
)


def normalized_problem(problem: str) -> str:
    return re.sub(r"\s+", " ", problem).strip().casefold()


def sha256(path: Path) -> str:
    digest = hashlib.sha256()
    with path.open("rb") as handle:
        for chunk in iter(lambda: handle.read(1024 * 1024), b""):
            digest.update(chunk)
    return digest.hexdigest()


def validate(root: Path) -> tuple[list[dict[str, object]], list[str]]:
    errors: list[str] = []
    stats: list[dict[str, object]] = []
    seen_ids: set[str] = set()
    seen_problems: dict[str, str] = {}

    for spec in FILE_SPECS:
        path = root / spec.path
        if not path.is_file():
            errors.append(f"missing file: {spec.path}")
            continue

        records: list[dict[str, object]] = []
        with path.open(encoding="utf-8") as handle:
            for line_number, line in enumerate(handle, start=1):
                if not line.strip():
                    errors.append(f"{spec.path}:{line_number}: blank lines are not allowed")
                    continue
                try:
                    record = json.loads(line)
                except json.JSONDecodeError as exc:
                    errors.append(f"{spec.path}:{line_number}: invalid JSON: {exc.msg}")
                    continue
                if not isinstance(record, dict):
                    errors.append(f"{spec.path}:{line_number}: record must be an object")
                    continue
                records.append(record)

        if len(records) != spec.expected_count:
            errors.append(
                f"{spec.path}: expected {spec.expected_count} records, found {len(records)}"
            )

        lengths: list[int] = []
        for index, record in enumerate(records, start=1):
            where = f"{spec.path}:{index}"
            if set(record) != FIELDS:
                missing = sorted(FIELDS - set(record))
                extra = sorted(set(record) - FIELDS)
                errors.append(f"{where}: schema mismatch; missing={missing}, extra={extra}")
                continue

            record_id = record["id"]
            expected_id = f"aimepp-{spec.id_stem}-{index:04d}"
            if record_id != expected_id:
                errors.append(f"{where}: expected id {expected_id!r}, found {record_id!r}")
            if not isinstance(record_id, str):
                errors.append(f"{where}: id must be a string")
            elif record_id in seen_ids:
                errors.append(f"{where}: duplicate id {record_id!r}")
            else:
                seen_ids.add(record_id)

            if record["tier"] != spec.tier:
                errors.append(f"{where}: expected tier {spec.tier!r}")

            problem = record["problem"]
            if not isinstance(problem, str) or not problem.strip():
                errors.append(f"{where}: problem must be non-empty text")
            else:
                lengths.append(len(problem))
                if problem != problem.strip():
                    errors.append(f"{where}: problem has leading or trailing whitespace")
                if any(ord(character) < 32 for character in problem):
                    errors.append(f"{where}: problem contains an ASCII control character")
                if problem.count("$") % 2:
                    errors.append(f"{where}: problem has unbalanced dollar-sign LaTeX delimiters")
                normalized = normalized_problem(problem)
                if normalized in seen_problems:
                    errors.append(
                        f"{where}: normalized duplicate of {seen_problems[normalized]}"
                    )
                else:
                    seen_problems[normalized] = where

            answer = record["answer"]
            if isinstance(answer, bool) or not isinstance(answer, int) or not 0 <= answer <= 999:
                errors.append(f"{where}: answer must be an integer in 0..999")
            elif record["answer_str"] != f"{answer:03d}":
                errors.append(f"{where}: answer_str must equal the zero-padded answer")

        stats.append(
            {
                "path": spec.path,
                "tier": spec.tier,
                "count": len(records),
                "min_chars": min(lengths) if lengths else 0,
                "max_chars": max(lengths) if lengths else 0,
                "mean_chars": round(sum(lengths) / len(lengths), 1) if lengths else 0,
                "sha256": sha256(path),
            }
        )

    checksums_path = root / "CHECKSUMS.sha256"
    if not checksums_path.is_file():
        errors.append("missing file: CHECKSUMS.sha256")
    else:
        declared: dict[str, str] = {}
        for line_number, line in enumerate(
            checksums_path.read_text(encoding="utf-8").splitlines(), start=1
        ):
            match = re.fullmatch(r"([0-9a-f]{64})  (data/[^\s]+\.jsonl)", line)
            if not match:
                errors.append(f"CHECKSUMS.sha256:{line_number}: malformed checksum line")
                continue
            declared[match.group(2)] = match.group(1)
        expected_paths = {spec.path for spec in FILE_SPECS}
        if set(declared) != expected_paths:
            errors.append("CHECKSUMS.sha256: file list does not match the release data files")
        for row in stats:
            path = str(row["path"])
            if declared.get(path) != row["sha256"]:
                errors.append(f"CHECKSUMS.sha256: digest mismatch for {path}")

    return stats, errors


def print_markdown(stats: list[dict[str, object]]) -> None:
    print("| Tier | Records | Min chars | Mean chars | Max chars |")
    print("|---|---:|---:|---:|---:|")
    for row in stats:
        print(
            f"| {row['tier']} | {row['count']} | {row['min_chars']} | "
            f"{row['mean_chars']} | {row['max_chars']} |"
        )
    print(f"\n**Total:** {sum(int(row['count']) for row in stats)} records")


def main() -> int:
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--root", type=Path, default=ROOT, help="dataset repository root")
    parser.add_argument("--markdown", action="store_true", help="print a Markdown statistics table")
    args = parser.parse_args()

    stats, errors = validate(args.root.resolve())
    if errors:
        print(f"FAILED: {len(errors)} validation error(s)", file=sys.stderr)
        for error in errors:
            print(f"- {error}", file=sys.stderr)
        return 1

    if args.markdown:
        print_markdown(stats)
    else:
        total = sum(int(row["count"]) for row in stats)
        print(f"PASS: {total} records across {len(stats)} tiers")
        for row in stats:
            print(f"- {row['path']}: {row['count']} records; sha256={row['sha256']}")
    return 0


if __name__ == "__main__":
    raise SystemExit(main())