Merserk's picture
Upload 1393 files
0760102 verified
Raw
History Blame Contribute Delete
10.7 kB
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
FORMATS = ("bf16", "fp8_scaled", "int8_convrot", "mxfp8", "nvfp4", "int4_convrot", "gguf_q8_0", "gguf_q4_k_m")
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 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] = []
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(not parquet_path.is_file(), f"missing viewer parquet: {parquet_path}", 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("*"):
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 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"):
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:
import pyarrow.parquet as pq
parquet_file = pq.ParquetFile(str(parquet_path))
fail(parquet_file.metadata.num_rows != expected_rows, f"parquet rows: {parquet_file.metadata.num_rows}", errors)
first_image = parquet_file.read_row_group(0, columns=["image"]).column("image")[0].as_py()
fail(not (isinstance(first_image, dict) and first_image.get("bytes")), "parquet image column is not embedded", errors)
except Exception as exc:
errors.append(f"parquet inspection failed: {exc}")
try:
from datasets import load_dataset
dataset = load_dataset(str(root), split="train")
fail(dataset.num_rows != expected_rows, f"dataset rows: {dataset.num_rows}", errors)
fail("image" not in dataset.features, "dataset is missing the image feature", errors)
_ = dataset[0]["image"]
except Exception as exc:
errors.append(f"dataset load failed: {exc}")
try:
import yaml
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())