AIME-Plus-Plus / scripts /validate_dataset.py
przemekch's picture
Publish AIME++ sample v0.1.0
8e38bba verified
Raw
History Blame Contribute Delete
7.59 kB
#!/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())