| """Independently verify a built Sudoku_DLM_Reasoning release.""" |
|
|
| from __future__ import annotations |
|
|
| import argparse |
| import csv |
| import hashlib |
| import json |
| from collections import Counter |
| from pathlib import Path |
|
|
| import pyarrow as pa |
| import pyarrow.parquet as pq |
|
|
|
|
| EXPECTED_BUCKETS = { |
| "train": {"original": 65_536, "r0": 65_536, "r1_4": 65_536}, |
| "validation": {"original": 2_048, "r0": 2_048, "r1_4": 2_048}, |
| "test": {"original": 1_000, "r0": 1_000, "r1_4": 1_000, "r5_19": 1_000}, |
| "test_ood_confirm": {"r5_19": 4_000}, |
| } |
|
|
| EXPECTED_SUBBUCKETS = { |
| "test": { |
| "original": 1_000, |
| "r0": 1_000, |
| "r1_2": 250, |
| "r2_3": 250, |
| "r3_4": 250, |
| "r4_5": 250, |
| "r5_7": 250, |
| "r8_11": 250, |
| "r12_15": 250, |
| "r16_19": 250, |
| }, |
| "test_ood_confirm": { |
| "r5_7": 1_000, |
| "r8_11": 1_000, |
| "r12_15": 1_000, |
| "r16_19": 1_000, |
| }, |
| } |
|
|
| EXPECTED_SCHEMA = pa.schema( |
| [ |
| pa.field("example_id", pa.string(), nullable=False), |
| pa.field("puzzle_id", pa.string(), nullable=False), |
| pa.field("digit_normalized_id", pa.string(), nullable=False), |
| pa.field("puzzle", pa.string(), nullable=False), |
| pa.field("solution", pa.string(), nullable=False), |
| pa.field("difficulty_bucket", pa.string(), nullable=False), |
| pa.field("difficulty_subbucket", pa.string(), nullable=False), |
| pa.field("source_family", pa.string(), nullable=False), |
| pa.field("source_collection", pa.string(), nullable=False), |
| pa.field("official_rating", pa.float64(), nullable=True), |
| pa.field("rating_type", pa.string(), nullable=False), |
| pa.field("clues", pa.int16(), nullable=False), |
| pa.field("upstream_split", pa.string(), nullable=False), |
| pa.field("release_split", pa.string(), nullable=False), |
| pa.field("evaluation_role", pa.string(), nullable=False), |
| pa.field("is_ood", pa.bool_(), nullable=False), |
| pa.field("source_file", pa.string(), nullable=False), |
| pa.field("source_row_index", pa.int64(), nullable=False), |
| pa.field("stratum", pa.string(), nullable=False), |
| ] |
| ) |
|
|
| VERIFY_COLUMNS = [ |
| "example_id", |
| "puzzle_id", |
| "digit_normalized_id", |
| "puzzle", |
| "solution", |
| "difficulty_bucket", |
| "difficulty_subbucket", |
| "clues", |
| "upstream_split", |
| "release_split", |
| "evaluation_role", |
| "is_ood", |
| "source_row_index", |
| ] |
|
|
|
|
| def sha256_text(value: str) -> str: |
| return hashlib.sha256(value.encode("utf-8")).hexdigest() |
|
|
|
|
| def sha256_file(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 digit_normalized_id(puzzle: str, solution: str) -> str: |
| mapping: dict[str, str] = {} |
| for digit in solution: |
| mapping.setdefault(digit, str(len(mapping) + 1)) |
| if len(mapping) != 9: |
| raise AssertionError("solution does not contain all digits") |
| normalized_puzzle = "".join("0" if digit == "0" else mapping[digit] for digit in puzzle) |
| normalized_solution = "".join(mapping[digit] for digit in solution) |
| return sha256_text(f"{normalized_puzzle}|{normalized_solution}") |
|
|
|
|
| def validate_sudoku(puzzle: str, solution: str) -> None: |
| assert len(puzzle) == 81 and set(puzzle) <= set("0123456789") |
| assert len(solution) == 81 and set(solution) <= set("123456789") |
| assert all(clue == "0" or clue == solution[index] for index, clue in enumerate(puzzle)) |
| expected = set("123456789") |
| units = [solution[index : index + 9] for index in range(0, 81, 9)] |
| units.extend(solution[index::9] for index in range(9)) |
| for box_row in range(3): |
| for box_col in range(3): |
| units.append( |
| "".join( |
| solution[row * 9 + box_col * 3 : row * 9 + box_col * 3 + 3] |
| for row in range(box_row * 3, box_row * 3 + 3) |
| ) |
| ) |
| assert all(set(unit) == expected for unit in units) |
|
|
|
|
| def expected_role(split: str, bucket: str) -> tuple[str, bool]: |
| if split == "train": |
| return "train_id", False |
| if split == "validation": |
| return "validation_id", False |
| if split == "test": |
| return ("test_ood", True) if bucket == "r5_19" else ("test_id", False) |
| return "confirm_ood", True |
|
|
|
|
| def verify_split(path: Path, split: str) -> tuple[dict[str, set[str]], dict[str, object]]: |
| file_schema = pq.read_schema(path) |
| if not file_schema.equals(EXPECTED_SCHEMA, check_metadata=False): |
| raise AssertionError(f"{split}: schema mismatch\n{file_schema}\n!=\n{EXPECTED_SCHEMA}") |
| table = pq.read_table(path, columns=VERIFY_COLUMNS) |
| expected_rows = sum(EXPECTED_BUCKETS[split].values()) |
| assert table.num_rows == expected_rows, (split, table.num_rows, expected_rows) |
| columns = table.to_pydict() |
| ids = {name: set() for name in ("example_id", "puzzle_id", "digit_normalized_id")} |
| buckets: Counter[str] = Counter() |
| subbuckets: Counter[str] = Counter() |
| expected_upstream = "train" if split in {"train", "validation"} else "test" |
|
|
| for index in range(table.num_rows): |
| puzzle = columns["puzzle"][index] |
| solution = columns["solution"][index] |
| bucket = columns["difficulty_bucket"][index] |
| validate_sudoku(puzzle, solution) |
| assert columns["example_id"][index] == sha256_text(f"{puzzle}|{solution}") |
| assert columns["puzzle_id"][index] == sha256_text(puzzle) |
| assert columns["digit_normalized_id"][index] == digit_normalized_id(puzzle, solution) |
| assert columns["clues"][index] == sum(value != "0" for value in puzzle) |
| assert columns["upstream_split"][index] == expected_upstream |
| assert columns["release_split"][index] == split |
| role, is_ood = expected_role(split, bucket) |
| assert columns["evaluation_role"][index] == role |
| assert columns["is_ood"][index] is is_ood |
| assert columns["source_row_index"][index] >= 0 |
| buckets[bucket] += 1 |
| subbuckets[columns["difficulty_subbucket"][index]] += 1 |
| for name in ids: |
| value = columns[name][index] |
| if value in ids[name]: |
| raise AssertionError(f"{split}: duplicate {name} {value}") |
| ids[name].add(value) |
|
|
| assert dict(buckets) == EXPECTED_BUCKETS[split], (split, buckets) |
| if split in EXPECTED_SUBBUCKETS: |
| assert dict(subbuckets) == EXPECTED_SUBBUCKETS[split], (split, subbuckets) |
| return ids, { |
| "rows": table.num_rows, |
| "difficulty_buckets": dict(sorted(buckets.items())), |
| "difficulty_subbuckets": dict(sorted(subbuckets.items())), |
| "sha256": sha256_file(path), |
| } |
|
|
|
|
| def count_csv_rows(path: Path) -> int: |
| with path.open("r", encoding="utf-8", newline="") as handle: |
| reader = csv.reader(handle) |
| next(reader) |
| return sum(1 for _ in reader) |
|
|
|
|
| def verify_raw_snapshot(root: Path, manifest: dict[str, object]) -> dict[str, object] | None: |
| raw_manifest_name = manifest.get("raw_snapshot_file") |
| if raw_manifest_name is None: |
| return None |
| raw_manifest = json.loads((root / str(raw_manifest_name)).read_text(encoding="utf-8")) |
| assert raw_manifest["label"] == "raw" |
| rows = 0 |
| for relative_path, declared in raw_manifest["files"].items(): |
| path = root / relative_path |
| assert relative_path.startswith("raw/"), relative_path |
| assert path.is_file(), relative_path |
| assert path.stat().st_size == declared["bytes"], relative_path |
| assert sha256_file(path) == declared["sha256"], relative_path |
| observed_rows = count_csv_rows(path) |
| assert observed_rows == declared["rows"], relative_path |
| release_declared = manifest["files"][relative_path] |
| assert release_declared["sha256"] == declared["sha256"], relative_path |
| assert release_declared["rows"] == observed_rows, relative_path |
| rows += observed_rows |
| assert rows == raw_manifest["candidate_rows"] |
| return {"label": "raw", "files": len(raw_manifest["files"]), "rows": rows} |
|
|
|
|
| def verify_release( |
| root: Path, |
| expected_version: str | None = None, |
| expected_seed: str | None = None, |
| ) -> dict[str, object]: |
| manifest = json.loads((root / "metadata/manifest.json").read_text(encoding="utf-8")) |
| audit = json.loads((root / "metadata/audit.json").read_text(encoding="utf-8")) |
| split_spec = json.loads( |
| (root / "metadata/split_spec.json").read_text(encoding="utf-8") |
| ) |
| assert manifest["dataset_id"] == "stwistzz/Sudoku_DLM_Reasoning" |
| dataset_version = str(manifest["dataset_version"]) |
| if expected_version is not None: |
| assert dataset_version == expected_version, (dataset_version, expected_version) |
| selection_seed = str(manifest["seed"]) |
| if expected_seed is not None: |
| assert selection_seed == expected_seed, (selection_seed, expected_seed) |
| assert audit["dataset_version"] == dataset_version |
| assert split_spec["dataset_version"] == dataset_version |
| assert str(audit["seed"]) == selection_seed |
| assert str(split_spec["seed"]) == selection_seed |
|
|
| split_ids: dict[str, dict[str, set[str]]] = {} |
| summaries: dict[str, object] = {} |
| for split in EXPECTED_BUCKETS: |
| relative_path = f"data/{split}.parquet" |
| ids, summary = verify_split(root / relative_path, split) |
| split_ids[split] = ids |
| summaries[split] = summary |
| declared = manifest["files"][relative_path] |
| assert declared["rows"] == summary["rows"] |
| assert declared["sha256"] == summary["sha256"] |
|
|
| split_names = list(EXPECTED_BUCKETS) |
| overlaps: dict[str, dict[str, int]] = {} |
| for left_index, left in enumerate(split_names): |
| for right in split_names[left_index + 1 :]: |
| key = f"{left}__vs__{right}" |
| overlaps[key] = { |
| name: len(split_ids[left][name] & split_ids[right][name]) |
| for name in split_ids[left] |
| } |
| assert not any(value for result in overlaps.values() for value in result.values()) |
| assert audit["pairwise_overlap"] == overlaps |
| assert audit["strict_selected_rows_verified"] == sum( |
| sum(counts.values()) for counts in EXPECTED_BUCKETS.values() |
| ) |
|
|
| for relative_path, declared in manifest["files"].items(): |
| path = root / relative_path |
| assert path.is_file(), relative_path |
| assert path.stat().st_size == declared["bytes"], relative_path |
| assert sha256_file(path) == declared["sha256"], relative_path |
|
|
| raw_summary = verify_raw_snapshot(root, manifest) |
| return { |
| "dataset_version": dataset_version, |
| "selection_seed": selection_seed, |
| "splits": summaries, |
| "pairwise_overlap": overlaps, |
| "raw_snapshot": raw_summary, |
| } |
|
|
|
|
| def main() -> None: |
| parser = argparse.ArgumentParser(description=__doc__) |
| parser.add_argument("release_dir", type=Path) |
| parser.add_argument("--expected-version") |
| parser.add_argument("--expected-seed") |
| args = parser.parse_args() |
| result = verify_release( |
| args.release_dir.resolve(), args.expected_version, args.expected_seed |
| ) |
| print(json.dumps(result, indent=2, sort_keys=True)) |
| print("VERIFICATION_OK") |
|
|
|
|
| if __name__ == "__main__": |
| main() |
|
|