from __future__ import annotations import argparse import csv import hashlib import json import math import re from collections import Counter from pathlib import Path from urllib.parse import unquote import yaml FORMATS = ("bf16", "fp8_scaled", "int8_convrot", "mxfp8", "nvfp4", "int4_convrot", "gguf_q8_0", "gguf_q4_k_m") IMAGEFOLDER_GLOB = "data/train/**" LOCAL_REPAIR_DIRS = {".viewer_fix_venv", "viewer_fix_output", "__pycache__"} LOCAL_REPAIR_FILES = { "imagefolder_viewer_diagnostics.json", "imagefolder_viewer_fix.log", "viewer_server_diagnostics.json", } def strict_json_loads(payload: str) -> object: return json.loads(payload, parse_constant=lambda value: (_ for _ in ()).throw(ValueError(f"invalid JSON constant: {value}"))) def has_nonfinite_number(value: object) -> bool: if isinstance(value, float): return not math.isfinite(value) if isinstance(value, dict): return any(has_nonfinite_number(item) for item in value.values()) if isinstance(value, list): return any(has_nonfinite_number(item) for item in value) return False def checksum(path: Path) -> str: value = hashlib.sha256() with path.open("rb") as stream: while block := stream.read(8 * 1024 * 1024): value.update(block) return value.hexdigest() def fail(condition: bool, message: str, errors: list[str]) -> None: if condition: errors.append(message) def validate_dataset_card(root: Path, errors: list[str]) -> None: readme = (root / "README.md").read_text(encoding="utf-8") match = re.match(r"\A---\s*\n(.*?)\n---\s*\n", readme, re.DOTALL) if not match: errors.append("README.md has no valid YAML front matter") return try: metadata = yaml.safe_load(match.group(1)) or {} except yaml.YAMLError as exc: errors.append(f"README.md YAML is invalid: {exc}") return configs = metadata.get("configs") if not isinstance(configs, list): errors.append("README.md must define a configs list") return defaults = [ config for config in configs if isinstance(config, dict) and config.get("config_name") == "default" ] if len(defaults) != 1: errors.append("README.md must define exactly one default config") return config = defaults[0] fail(config.get("default") is not True, "default config is not marked default", errors) fail(config.get("drop_labels") is not True, "default config must set drop_labels: true", errors) fail("data_dir" in config, "default config must not use data_dir", errors) data_files = config.get("data_files") expected = [{"split": "train", "path": IMAGEFOLDER_GLOB}] fail( data_files != expected, f"default config data_files must equal {expected!r}, found {data_files!r}", errors, ) def is_local_repair_artifact(root: Path, path: Path) -> bool: relative = path.relative_to(root) return ( any(part in LOCAL_REPAIR_DIRS for part in relative.parts) or path.name in LOCAL_REPAIR_FILES or (path.name.startswith("viewer_fix_") and path.suffix == ".log") ) def main() -> int: parser = argparse.ArgumentParser(description="Validate the Hugging Face benchmark release") parser.add_argument("--root", type=Path, default=Path(__file__).resolve().parents[1]) parser.add_argument("--full", action="store_true", help="Decode all images, inspect all arrays, verify all SHA-256 values, and load ImageFolder") args = parser.parse_args() root = args.root.resolve() errors: list[str] = [] validate_dataset_card(root, errors) metadata_path = root / "data" / "train" / "metadata.jsonl" rows = [] for line_number, line in enumerate(metadata_path.read_text(encoding="utf-8").splitlines(), start=1): if not line.strip(): continue try: row = strict_json_loads(line) except ValueError as exc: errors.append(f"metadata.jsonl:{line_number}: {exc}") continue if not isinstance(row, dict): errors.append(f"metadata.jsonl:{line_number}: expected object row") continue fail(has_nonfinite_number(row), f"metadata.jsonl:{line_number}: contains non-finite numeric value", errors) rows.append(row) expected_rows = 30 * len(FORMATS) fail(len(rows) != expected_rows, f"metadata rows: expected {expected_rows}, found {len(rows)}", errors) fail(len({row["run_id"] for row in rows}) != expected_rows, "run_id values are not unique", errors) counts = Counter(row["format_id"] for row in rows) for fmt in FORMATS: fail(counts[fmt] != 30, f"{fmt}: expected 30, found {counts[fmt]}", errors) required_paths = [] for row in rows: for key in ("file_name", "decoded_array_path", "final_latent_path", "trajectory_path", "capture_metadata_path"): base = metadata_path.parent if key == "file_name" else root path = base / row[key] required_paths.append(path) fail(not path.is_file(), f"missing {key}: {path}", errors) fail(len(list((root / "data" / "train" / "images").rglob("*.png"))) != expected_rows, f"expected {expected_rows} PNG images", errors) parquet_path = root / "data" / "train-00000-of-00001.parquet" fail(parquet_path.exists(), f"obsolete Viewer parquet is present: {parquet_path}", errors) fail((root / "viewer_data").exists(), "obsolete viewer_data directory is present", errors) fail(len(list((root / "raw").rglob("*.npy"))) != expected_rows * 2, f"expected {expected_rows * 2} NPY files", errors) fail(len(list((root / "raw").rglob("*.npz"))) != expected_rows, f"expected {expected_rows} NPZ files", errors) fail(len(list((root / "comparison_sheets").rglob("*.*"))) != 93, "expected 93 comparison artifacts", errors) fail(len(list((root / "telemetry").glob("*.csv"))) != 20, "expected 20 scored/bridge telemetry files", errors) expected_metric_rows = { "image_core.csv": 240, "image_advanced.csv": 240, "latency_components.csv": 240, "performance_runs.csv": 240, "trajectory.csv": 3360, "weight_parameters_all.csv": 3010, } for filename, expected in expected_metric_rows.items(): with (root / "metrics" / filename).open("r", encoding="utf-8", newline="") as stream: metric_rows = list(csv.DictReader(stream)) fail(len(metric_rows) != expected, f"{filename}: expected {expected} rows, found {len(metric_rows)}", errors) if filename in {"image_core.csv", "image_advanced.csv", "latency_components.csv", "performance_runs.csv"}: fail(len({row["run_id"] for row in metric_rows}) != expected_rows, f"{filename}: run_id values are not unique", errors) forbidden_names = {".vendor", "advanced_metric_cache", "logs", "comfy_output", "__pycache__", ".cache", "cache"} for path in root.rglob("*"): if is_local_repair_artifact(root, path): continue fail(any(part in forbidden_names for part in path.parts), f"forbidden path: {path}", errors) if path.is_file(): fail(path.suffix.lower() in {".safetensors", ".ckpt", ".gguf", ".pyc"}, f"forbidden file: {path}", errors) text_suffixes = {".md", ".json", ".jsonl", ".csv", ".yaml", ".yml", ".txt", ".cff", ".py", ".ps1", ".sh"} path_pattern = re.compile(r"E:\\\\Benchmark Krea 2 Turbo Formats|C:\\\\Users\\\\|GPU-[0-9a-fA-F-]{8,}|[0-9A-Fa-f]{8}:[0-9A-Fa-f]{2}:[0-9A-Fa-f]{2}\\.[0-7]|mihai", re.IGNORECASE) for path in root.rglob("*"): if is_local_repair_artifact(root, path): continue if path.is_file() and (path.suffix.lower() in text_suffixes or path.name in {"README.md", ".gitignore", ".gitattributes"}): if path.relative_to(root).as_posix() in {"scripts/prepare_release.py", "scripts/validate_release.py"}: continue text = path.read_text(encoding="utf-8", errors="replace") fail(bool(path_pattern.search(text)), f"private machine identifier in {path.relative_to(root)}", errors) link_pattern = re.compile(r"\[[^\]]*\]\(([^)]+)\)") for markdown in root.rglob("*.md"): if is_local_repair_artifact(root, markdown): continue for target in link_pattern.findall(markdown.read_text(encoding="utf-8")): target = target.strip().strip("<>") if target.startswith(("http://", "https://", "mailto:", "#")): continue relative = unquote(target.split("#", 1)[0]) if relative and not (markdown.parent / relative).exists(): errors.append(f"broken Markdown link in {markdown.relative_to(root)}: {target}") audit = strict_json_loads((root / "validation" / "completion_audit.json").read_text(encoding="utf-8")) sampler = strict_json_loads((root / "validation" / "sampler_equivalence.json").read_text(encoding="utf-8")) fail(not audit.get("passed") or bool(audit.get("failures")), "completion audit is not passing", errors) fail(not sampler.get("image_bit_exact") or not sampler.get("latent_bit_exact"), "sampler equivalence is not bit exact", errors) if args.full: import numpy as np from PIL import Image for row in rows: image_path = metadata_path.parent / row["file_name"] with Image.open(image_path) as image: fail(image.size != (1024, 1024), f"unexpected image size: {image_path}", errors) image.verify() expected_shapes = {"decoded_array_path": (1, 1024, 1024, 3), "final_latent_path": (1, 16, 1, 128, 128)} for key in ("decoded_array_path", "final_latent_path"): array = np.load(root / row[key], mmap_mode="r", allow_pickle=False) fail(array.dtype != np.float32, f"{key} is not float32 for {row['run_id']}", errors) fail(array.shape != expected_shapes[key], f"unexpected {key} shape for {row['run_id']}: {array.shape}", errors) fail(not np.isfinite(array).all(), f"nonfinite values in {key} for {row['run_id']}", errors) with np.load(root / row["trajectory_path"], allow_pickle=False) as trajectory: fail(set(trajectory.files) != {"x", "x0"}, f"unexpected trajectory keys for {row['run_id']}: {trajectory.files}", errors) for name in trajectory.files: fail(trajectory[name].shape != (8, 1, 16, 1, 128, 128), f"unexpected trajectory shape {name} for {row['run_id']}: {trajectory[name].shape}", errors) fail(trajectory[name].dtype != np.float32, f"trajectory {name} is not float32 for {row['run_id']}", errors) fail(not np.isfinite(trajectory[name]).all(), f"nonfinite trajectory {name} for {row['run_id']}", errors) checksum_lines = (root / "checksums" / "SHA256SUMS").read_text(encoding="utf-8").splitlines() for line in checksum_lines: expected, relative = line.split(" ", 1) path = root / relative fail(not path.is_file(), f"checksum target missing: {relative}", errors) if path.is_file(): fail(checksum(path) != expected, f"checksum mismatch: {relative}", errors) try: from datasets import load_dataset configured_splits = load_dataset( "imagefolder", data_files={"train": str(root / IMAGEFOLDER_GLOB)}, drop_labels=True, ) fail( list(configured_splits) != ["train"], f"configured ImageFolder splits must be ['train'], found {list(configured_splits)!r}", errors, ) configured_dataset = configured_splits["train"] fail( configured_dataset.num_rows != expected_rows, f"configured ImageFolder rows: {configured_dataset.num_rows}", errors, ) fail( "image" not in configured_dataset.features, "configured ImageFolder is missing the image feature", errors, ) first_image = configured_dataset[0]["image"] fail(first_image.size != (1024, 1024), f"first dataset image has size {first_image.size}", errors) fail(first_image.mode != "RGB", f"first dataset image has mode {first_image.mode}", errors) except Exception as exc: errors.append(f"dataset load failed: {exc}") try: citation = yaml.safe_load((root / "CITATION.cff").read_text(encoding="utf-8")) fail(citation.get("cff-version") != "1.2.0" or citation.get("type") != "dataset", "CITATION.cff metadata is invalid", errors) except Exception as exc: errors.append(f"CITATION.cff parse failed: {exc}") result = {"passed": not errors, "errors": errors, "rows": len(rows), "format_counts": dict(counts), "full": args.full} print(json.dumps(result, indent=2)) return 0 if not errors else 1 if __name__ == "__main__": raise SystemExit(main())