"""Dataset registry and the dev / fast-dev / pool / contest-train build. python -m pocket_math.data build --out data_out """ from __future__ import annotations import argparse import datetime import hashlib import importlib.util import random import re from collections import Counter, defaultdict from collections.abc import Iterable from dataclasses import replace from functools import cache from pathlib import Path from typing import Any import yaml from pocket_math.decontam import COMMON_IN_TRAIN, COPY_SCORE, DEFAULT_MODEL, decontaminate from pocket_math.grading import grade_many, parseable from pocket_math.io import sha256_file, write_json, write_jsonl from pocket_math.types import Problem REGISTRY = Path(__file__).resolve().parent.parent / "configs" / "datasets.yaml" MAX_ANSWER_CHARS = 64 ROLES = ("dev", "pool", "contest_train") @cache def registry() -> dict[str, Any]: return yaml.safe_load(REGISTRY.read_text(encoding="utf-8")) def sources(role: str) -> list[str]: return [name for name, spec in registry()["sources"].items() if spec["role"] == role] @cache def revision(hf_id: str) -> str: from huggingface_hub import HfApi return HfApi().dataset_info(hf_id).sha def _rows(spec: dict[str, Any]) -> Iterable[dict[str, Any]]: from datasets import load_dataset extra = {"columns": spec["columns"]} if "columns" in spec else {} return load_dataset(spec["hf_id"], spec.get("config"), split=spec["split"], revision=revision(spec["hf_id"]), streaming=spec.get("streaming", False), **extra) def _field(row: dict[str, Any], path: str) -> Any: for part in path.split("."): row = row[part] return row CHOICE_MARK = re.compile(r"\(\s*(?:\\(?:mathrm|textrm)\s*\{)?\s*([A-E])\s*\}?\s*\)") # Wrapper left at the end of the text before a choice marker, as in "\qquad \textbf{" before "(B)". CHOICE_LEAD = re.compile(r"(?:\\q?quad|\\ |~|\s)*(?:\\(?:textbf|textrm|text|mathrm)\s*\{)?\s*$") def choice_value(problem: str, letter: str) -> str | None: """The text of one multiple-choice option, read from the "(A) ... (E)" list at the end of the problem.""" marks = list(CHOICE_MARK.finditer(problem)) for i in range(len(marks) - 4, -1, -1): if "".join(m.group(1) for m in marks[i : i + 5]) == "ABCDE": marks = marks[i : i + 5] break else: return None if letter not in "ABCDE" or len(letter) != 1: return None k = "ABCDE".index(letter) end = marks[k + 1].start() if k < 4 else len(problem) value = problem[marks[k].end() : end] if k < 4: value = CHOICE_LEAD.sub("", value) value = re.sub(r"^(?:\s|\\ |\$)*\}?(?:\\ |~|\s|\$)*", "", value) value = re.sub(r"(?:\$|\s|\\)+$", "", value) # A wrapper such as "\mathrm{(A) \ 48 }" leaves its closing brace on the value. while value.endswith("}") and value.count("}") > value.count("{"): value = value[:-1].rstrip() if not value or value.count("{") != value.count("}"): return None return value def _year(spec: dict[str, Any], row: dict[str, Any]) -> int | None: if "year_field" not in spec: return spec.get("year") value = _field(row, spec["year_field"]) if value is not None and "year_regex" in spec: match = re.search(spec["year_regex"], str(value)) value = match.group(1) if match else None try: return None if value is None else int(value) except ValueError: return None def _to_problem(name: str, spec: dict[str, Any], index: int, row: dict[str, Any]) -> Problem | None: for col, allowed in spec.get("where", {}).items(): if _field(row, col) not in (allowed if isinstance(allowed, list) else [allowed]): return None problem, answer = row[spec["problem"]], row[spec["answer"]] if problem is not None and "problem_strip" in spec: problem = re.sub(spec["problem_strip"], "", str(problem)) if problem is None or answer is None or not str(problem).strip() or not str(answer).strip(): return None answer = str(answer).strip() if answer in spec.get("drop_answers", ()): return None if spec.get("answer_from_choices"): answer = choice_value(str(problem), answer) if answer is None: return None year = _year(spec, row) if "max_year" in spec and (year is None or year > spec["max_year"]): return None meta = {} if "difficulty" in spec: meta["difficulty"] = row[spec["difficulty"]] if "min_difficulty" in spec and (meta["difficulty"] is None or float(meta["difficulty"]) < spec["min_difficulty"]): return None key = _field(row, spec["key"]) if "key" in spec else index return Problem(uid=f"{name}/{key}", source=name, problem=str(problem).strip(), answer=answer, year=year, meta=meta) def load_source(name: str) -> list[Problem]: spec = registry()["sources"][name] problems = [_to_problem(name, spec, i, row) for i, row in enumerate(_rows(spec))] return [p for p in problems if p is not None] def build_dev() -> list[Problem]: return [p for name in sources("dev") for p in load_source(name)] def _quotas(sizes: dict[str, int], n: int) -> dict[str, int]: """Split n across groups in proportion to size (largest remainder, ties by name).""" total = sum(sizes.values()) n = min(n, total) exact = {s: n * k / total for s, k in sizes.items()} quotas = {s: int(x) for s, x in exact.items()} for s in sorted(sizes, key=lambda s: (quotas[s] - exact[s], s))[: n - sum(quotas.values())]: quotas[s] += 1 return quotas def fast_dev(dev: list[Problem], n: int = 120, seed: int = 0) -> list[Problem]: """A fixed subset of dev, with each source represented in proportion to its size. Keeps dev order.""" by_source: dict[str, list[Problem]] = defaultdict(list) for p in dev: by_source[p.source].append(p) quotas = _quotas({s: len(ps) for s, ps in by_source.items()}, n) rng = random.Random(seed) chosen = set() for s in sorted(by_source): chosen.update(p.uid for p in rng.sample(sorted(by_source[s], key=lambda p: p.uid), quotas[s])) return [p for p in dev if p.uid in chosen] def normalize_whitespace(text: str) -> str: text = re.sub(r"[ \t\r\f\v]+", " ", text) text = re.sub(r" ?\n ?", "\n", text) return re.sub(r"\n{3,}", "\n\n", text).strip() def text_hash(text: str) -> str: """Hash that ignores case, spacing, $ signs, LaTeX sizing commands and closing punctuation, so trivially reformatted copies collide.""" key = re.sub(r"\s+|\$|\\left(?![a-z])|\\right(?![a-z])|\\displaystyle|\\[,;:!]", "", text.lower()) key = key.replace("\\dfrac", "\\frac").replace("\\tfrac", "\\frac").rstrip(".?!") return hashlib.sha1(key.encode("utf-8")).hexdigest() def dedup(problems: list[Problem]) -> list[Problem]: """Keep the first problem of each text_hash; callers order problems by source priority.""" seen: set[str] = set() kept = [] for p in problems: h = text_hash(p.problem) if h not in seen: seen.add(h) kept.append(p) return kept def usable_answers(answers: list[str], workers: int = 4) -> set[str]: """Answers that are short, that grade as correct against themselves when boxed, and that Math-Verify parses (so a differently written correct answer can still match).""" short = sorted({a for a in answers if len(a) <= MAX_ANSWER_CHARS}) graded = grade_many([("\\boxed{" + a + "}", a) for a in short], workers=workers) parsed = parseable(short, workers=workers) return {a for a, g, p in zip(short, graded, parsed, strict=True) if g and p} def _prepare(role: str) -> dict[str, list[Problem]]: loaded = [replace(p, problem=normalize_whitespace(p.problem)) for name in sources(role) for p in load_source(name)] usable = usable_answers([p.answer for p in loaded]) answered = [p for p in loaded if p.answer in usable] return {"loaded": loaded, "usable_answer": answered, "unique": dedup(answered)} def build_pool(evals: list[Problem], embed_limit: int | None = None) -> tuple[list[Problem], list[dict]]: """Distillation and RL problems: usable answers, DeepMath difficulty >= 5, deduplicated, decontaminated.""" return decontaminate(_prepare("pool")["unique"], evals, embed_limit=embed_limit) def _by_source(problems: list[Problem]) -> dict[str, int]: return dict(Counter(p.source for p in problems)) def build(out: Path, embed_limit: int | None = None) -> dict[str, Any]: dev = build_dev() fast = fast_dev(dev) stages = {role: _prepare(role) for role in ("pool", "contest_train")} # One pass over all training problems, so stock contest wording is counted across the whole training set. train = [p for st in stages.values() for p in st["unique"]] clean, rows = decontaminate(train, dev, embed_limit=embed_limit) role_of = {p.uid: registry()["sources"][p.source]["role"] for p in train} for role, st in stages.items(): st["clean"] = [p for p in clean if role_of[p.uid] == role] outputs = {"dev.jsonl": dev, "fastdev.jsonl": fast, "pool.jsonl": stages["pool"]["clean"], "contest_train.jsonl": stages["contest_train"]["clean"]} files = {} for name, problems in outputs.items(): write_jsonl(out / name, (p.to_json() for p in problems)) files[name] = {"rows": len(problems), "sha256": sha256_file(out / name), "rows_by_source": _by_source(problems)} write_jsonl(out / "decontam_report.jsonl", rows) files["decontam_report.jsonl"] = {"rows": len(rows), "sha256": sha256_file(out / "decontam_report.jsonl"), "rows_by_method": dict(Counter(r["method"] for r in rows))} def flagged(method: str) -> dict[str, int]: return dict(Counter(role_of[uid] for uid in {r["pool_uid"] for r in rows if r["method"] == method})) if importlib.util.find_spec("sentence_transformers") is None: embedding_scope = "skipped: sentence-transformers not installed" elif embed_limit is None or embed_limit >= len(clean): embedding_scope = f"all {len(clean)} training problems left after the n-gram pass" else: embedding_scope = (f"the {embed_limit} of {len(clean)} training problems left after the n-gram pass with the " "most word overlap with any dev problem (decontam.lexical_overlap; ties at the cut kept in " "registry order), for CPU time") manifest = { "built_at": datetime.datetime.now(datetime.timezone.utc).isoformat(timespec="seconds"), "registry_sha256": sha256_file(REGISTRY), "sources": {name: {k: spec.get(k) for k in ("hf_id", "config", "split", "role")} | {"revision": revision(spec["hf_id"])} for name, spec in registry()["sources"].items()}, "dropped_sources": registry()["dropped"], "files": files, "stages": {role: {stage: _by_source(ps) for stage, ps in st.items()} for role, st in stages.items()}, "rules": {"answer": f"at most {MAX_ANSWER_CHARS} chars, grades True against itself when boxed, and " "Math-Verify parses it (grading.parseable)", "dedup": "text_hash, first source in registry order wins", "fastdev": {"n": 120, "seed": 0}}, "decontam": {"evals": "dev", "ngram_n": 13, "copy_score": COPY_SCORE, "common_in_train": COMMON_IN_TRAIN, "embedding_model": DEFAULT_MODEL, "embedding_threshold": 0.85, "embedding_scope": embedding_scope, "ngram_removed": flagged("ngram"), "marked_for_judge": flagged("embedding")}, } write_json(out / "manifest.json", manifest) return manifest def main(argv: list[str] | None = None) -> None: parser = argparse.ArgumentParser(prog="python -m pocket_math.data") sub = parser.add_subparsers(dest="command", required=True) b = sub.add_parser("build", help="download every registry source and write the data files") b.add_argument("--out", type=Path, default=Path("data_out")) b.add_argument("--embed-limit", type=int, default=None, help="embed only this many training problems (those with the most word overlap with dev)") args = parser.parse_args(argv) manifest = build(args.out, args.embed_limit) for name, info in manifest["files"].items(): print(f"{name:24} {info['rows']:>7} {info['sha256']}") if __name__ == "__main__": main()