from __future__ import annotations import argparse import csv import hashlib import json import math import re import shutil from collections import Counter from pathlib import Path from typing import Any, Iterable FORMATS = ("bf16", "fp8_scaled", "int8_convrot", "mxfp8", "nvfp4", "int4_convrot", "gguf_q8_0", "gguf_q4_k_m") FORMAT_LABELS = { "bf16": "BF16", "fp8_scaled": "FP8 Scaled", "int8_convrot": "INT8 ConvRot", "mxfp8": "MXFP8", "nvfp4": "NVFP4", "int4_convrot": "INT4 ConvRot W4A4", "gguf_q8_0": "GGUF Q8_0", "gguf_q4_k_m": "GGUF Q4_K_M", } FIDELITY_ORDER = ("bf16", "int8_convrot", "gguf_q8_0", "mxfp8", "fp8_scaled", "gguf_q4_k_m", "nvfp4", "int4_convrot") MODEL_SUBDIRS = { "qwen3vl_4b_bf16.safetensors": "text_encoders", "qwen_image_vae.safetensors": "vae", } SCORING_TABLES = { "core": "image_core.csv", "advanced": "image_advanced.csv", "performance": "performance_runs.csv", "latency": "latency_components.csv", } IDENTIFIER_COLUMNS = {"run_id", "format_id", "prompt_id", "replicate", "seed", "category"} CAPTURE_RE = re.compile(rf"^(p\d+_.+)__r(\d+)__({'|'.join(re.escape(fmt) for fmt in FORMATS)})$") ABSOLUTE_WINDOWS_PATH_RE = re.compile(r"[A-Za-z]:\\") GPU_UUID_RE = re.compile(r"GPU-[0-9a-fA-F-]{8,}") PCI_BUS_RE = re.compile(r"(?:[0-9A-Fa-f]{8}:)?[0-9A-Fa-f]{2}:[0-9A-Fa-f]{2}\.[0-7]") def json_load(path: Path) -> Any: return json.loads(path.read_text(encoding="utf-8")) def json_dump(path: Path, value: Any) -> None: path.parent.mkdir(parents=True, exist_ok=True) sanitized = sanitize_json_value(value) path.write_text( json.dumps(sanitized, indent=2, ensure_ascii=False, sort_keys=True, allow_nan=False) + "\n", encoding="utf-8", ) def jsonl_load(path: Path) -> list[dict[str, Any]]: return [json.loads(line) for line in path.read_text(encoding="utf-8").splitlines() if line.strip()] def jsonl_dump(path: Path, rows: Iterable[dict[str, Any]]) -> None: path.parent.mkdir(parents=True, exist_ok=True) with path.open("w", encoding="utf-8", newline="\n") as stream: for row in rows: sanitized = sanitize_json_value(row) stream.write(json.dumps(sanitized, ensure_ascii=False, sort_keys=True, allow_nan=False) + "\n") def sanitize_json_value(value: Any) -> Any: if isinstance(value, float): return value if math.isfinite(value) else None if isinstance(value, dict): return {key: sanitize_json_value(item) for key, item in value.items()} if isinstance(value, list): return [sanitize_json_value(item) for item in value] if isinstance(value, tuple): return [sanitize_json_value(item) for item in value] return value def csv_rows(path: Path) -> list[dict[str, str]]: with path.open("r", encoding="utf-8", newline="") as stream: return list(csv.DictReader(stream)) def write_csv(path: Path, rows: list[dict[str, Any]], fieldnames: list[str] | None = None) -> None: path.parent.mkdir(parents=True, exist_ok=True) if fieldnames is None: fieldnames = list(rows[0]) if rows else [] with path.open("w", encoding="utf-8", newline="") as stream: writer = csv.DictWriter(stream, fieldnames=fieldnames, extrasaction="ignore") writer.writeheader() writer.writerows(rows) def coerce(value: str | None) -> Any: if value is None or value == "": return None lowered = value.lower() if lowered == "true": return True if lowered == "false": return False if re.fullmatch(r"[-+]?\d+", value): try: return int(value) except ValueError: pass try: return float(value) except ValueError: return value def sha256(path: Path, block_size: int = 8 * 1024 * 1024) -> str: digest = hashlib.sha256() with path.open("rb") as stream: while block := stream.read(block_size): digest.update(block) return digest.hexdigest() def parse_command_json(command_record: dict[str, Any]) -> dict[str, Any]: stdout = command_record.get("stdout", "") try: return json.loads(stdout) except (TypeError, json.JSONDecodeError): return {} def deep_merge(base: dict[str, Any], override: dict[str, Any]) -> dict[str, Any]: merged = json.loads(json.dumps(base)) for key, value in override.items(): if key == "extends": continue if isinstance(value, dict) and isinstance(merged.get(key), dict): merged[key] = deep_merge(merged[key], value) else: merged[key] = json.loads(json.dumps(value)) return merged def load_configuration(path: Path, seen: set[Path] | None = None) -> dict[str, Any]: resolved = path.resolve() seen = set() if seen is None else seen if resolved in seen: raise RuntimeError(f"Configuration inheritance cycle: {resolved}") seen.add(resolved) raw = json_load(resolved) parent_name = raw.get("extends") if not parent_name: return raw return deep_merge(load_configuration(resolved.parent / parent_name, seen), raw) def sanitize_configuration(configuration: dict[str, Any]) -> dict[str, Any]: cleaned = json.loads(json.dumps(configuration)) cleaned["paths"] = { "portable_root": "", "models_dir": "", "results_dir": configuration.get("paths", {}).get("results_dir", "results/krea2_formats_v2_extended"), } return cleaned def sanitize_manifest(source: dict[str, Any]) -> dict[str, Any]: git_lines = source.get("comfy_git", {}).get("stdout", "").splitlines() gpu_parts = [part.strip() for part in source.get("gpu", {}).get("stdout", "").split(",")] runtime = parse_command_json(source.get("runtime", {})) models: dict[str, Any] = {} for name, entry in source.get("models", {}).items(): models[name] = {key: value for key, value in entry.items() if key != "path"} return { "schema_version": 1, "benchmark_id": source.get("benchmark_id"), "created_unix": source.get("created_unix"), "source_config_sha256": source.get("config_sha256"), "configuration": sanitize_configuration(source.get("configuration", {})), "comfyui": { "commit": git_lines[0] if len(git_lines) > 0 else None, "commit_date": git_lines[1] if len(git_lines) > 1 else None, "commit_subject": git_lines[2] if len(git_lines) > 2 else None, }, "comfyui_gguf": { "commit": source.get("comfyui_gguf", {}).get("stdout") or None, "gguf_python": runtime.get("gguf"), }, "lineage": { "base_manifest_sha256": source.get("lineage", {}).get("base_manifest_sha256"), "base_results_dir": "results/krea2_formats_v1" if source.get("lineage") else None, }, "gpu": { "name": gpu_parts[0] if len(gpu_parts) > 0 else runtime.get("device"), "driver_version": gpu_parts[2] if len(gpu_parts) > 2 else None, "memory_total_mib": coerce(gpu_parts[3]) if len(gpu_parts) > 3 else None, "compute_capability": gpu_parts[4] if len(gpu_parts) > 4 else None, }, "platform": source.get("platform", {}), "runtime": runtime, "analysis_packages": source.get("analysis_vendor_versions", {}), "models": models, } def assert_source_complete(results: Path) -> None: audit = json_load(results / "validation" / "completion_audit.json") if not audit.get("passed") or audit.get("failures"): raise RuntimeError("Source completion audit did not pass") expected_runs = 30 * len(FORMATS) if audit.get("scored_runs") != expected_runs: raise RuntimeError(f"Expected {expected_runs} scored runs, found {audit.get('scored_runs')}") if any(audit.get("format_counts", {}).get(fmt) != 30 for fmt in FORMATS): raise RuntimeError("Source format counts are incomplete") if not json_load(results / "validation" / "sampler_equivalence.json").get("image_bit_exact"): raise RuntimeError("Sampler-equivalence validation is not bit exact") def copy_tree(source: Path, destination: Path) -> None: shutil.copytree( source, destination, copy_function=shutil.copy2, ignore=shutil.ignore_patterns("__pycache__", "*.pyc", "*.pyo", ".vendor", ".cache", "cache"), ) def build_model_manifest(config: dict[str, Any], manifest: dict[str, Any]) -> dict[str, Any]: integrity = config["integrity"] names = [item["checkpoint"] for item in config["formats"].values()] names.extend([config["controls"]["text_encoder"], config["controls"]["vae"]]) format_by_checkpoint = {item["checkpoint"]: item for item in config["formats"].values()} format_id_by_checkpoint = {item["checkpoint"]: format_id for format_id, item in config["formats"].items()} files = [] for name in names: subdir = MODEL_SUBDIRS.get(name, "diffusion_models") format_config = format_by_checkpoint.get(name, {}) source = format_config.get("source") if source: repo = source["repository"] revision = source["revision"] remote_path = source["url"].split("/resolve/", 1)[1].split("/", 1)[1] source_url = source["url"] else: repo = integrity["publisher_repository"] revision = integrity["publisher_revision"] remote_path = f"{subdir}/{name}" source_url = f"https://huggingface.co/{repo}/resolve/{revision}/{remote_path}" entry = manifest["models"][name] files.append( { "filename": name, "format_id": format_id_by_checkpoint.get(name), "comfyui_subdirectory": subdir, "repository": repo, "revision": revision, "repository_path": remote_path, "download_url": f"https://huggingface.co/{repo}/resolve/{revision}/{remote_path}", "source_url": source_url, "bytes": entry["bytes"], "gib": entry["gib"], "sha256": integrity["expected_sha256"][name], } ) return { "schema_version": 2, "license": "Krea 2 Community License", "license_url": "https://huggingface.co/krea/Krea-2-Turbo", "total_bytes": sum(item["bytes"] for item in files), "files": files, } def parse_decision_table(report: Path) -> list[dict[str, str]]: rows: list[dict[str, str]] = [] for line in report.read_text(encoding="utf-8").splitlines(): if not line.startswith("| ") or line.startswith("| ---") or line.startswith("| Format"): continue fields = [field.strip() for field in line.strip().strip("|").split("|")] if len(fields) == 10 and fields[0] in FORMAT_LABELS.values(): rows.append( dict( zip( [ "format", "file_gib", "lpips_alex_median", "dists_median", "dinov2_cosine_median", "final_latent_relative_l2_median", "weight_snr_db", "sampling_seconds_median", "peak_vram_mib", "energy_joules_mean", ], fields, ) ) ) if len(rows) == len(FORMATS): break if len(rows) != len(FORMATS): raise RuntimeError(f"Could not parse {len(FORMATS)}-row decision table from technical report") return rows def build_metric_dictionary(metrics_dir: Path) -> list[dict[str, str]]: directions = { "lpips": "lower", "dists": "lower", "mae": "lower", "mse": "lower", "rmse": "lower", "relative_l2": "lower", "max_abs": "lower", "delta_e": "lower", "histogram_js": "lower", "nonfinite": "lower", "seconds": "lower", "energy": "lower", "vram": "lower", "psnr": "higher", "ssim": "higher", "cosine": "higher", "prompt_score": "higher", "pickscore": "higher", "hpsv2": "higher", "maniqa": "higher", "musiq": "higher", "topiq": "higher", } rows: list[dict[str, str]] = [] for group, filename in SCORING_TABLES.items(): with (metrics_dir / filename).open("r", encoding="utf-8", newline="") as stream: columns = next(csv.reader(stream)) for column in columns: if column in IDENTIFIER_COLUMNS: continue lowered = column.lower() direction = "descriptive" for token, candidate in directions.items(): if token in lowered: direction = candidate break unit = "seconds" if "seconds" in lowered else "joules" if "joules" in lowered else "MiB" if "mib" in lowered else "unitless" rows.append( { "metadata_column": f"{group}_{column}", "source_table": filename, "source_column": column, "group": group, "preferred_direction": direction, "unit": unit, "description": column.replace("_", " "), } ) return rows def build_readme() -> str: return """--- language: - en license: cc-by-4.0 pretty_name: Krea 2 Turbo ComfyUI Format Fidelity Benchmark size_categories: - n<1K configs: - config_name: default default: true data_files: - split: train path: "data/train/**" drop_labels: true task_categories: - text-to-image tags: - image - tabular - comfyui - krea-2 - quantization - benchmark - bf16 - fp8 - int8 - mxfp8 - nvfp4 - int4 - gguf - q8-0 - q4-k-m --- # Krea 2 Turbo ComfyUI Format Fidelity Benchmark This release is a paired, deterministic comparison of eight Krea 2 Turbo checkpoint formats in ComfyUI: BF16, FP8 Scaled, INT8 ConvRot, MXFP8, NVFP4, INT4 ConvRot W4A4, GGUF Q8_0, and GGUF Q4_K_M. It contains 240 scored 1024×1024 images, saved float32 decoded tensors and final latents, every denoising trajectory, raw metric tables, telemetry, statistical comparisons, and reproduction code. ![Eight-format contact sheet](comparison_sheets/contact_sheet_replicate0.png) ## Main result 1. **BF16** is the highest-fidelity reference because it is the unquantized published checkpoint. 2. **INT8 ConvRot** narrowly leads the preregistered LPIPS-Alex endpoint. **GGUF Q8_0** is statistically tied with it on that endpoint (Holm-adjusted permutation p=0.9067) and leads INT8 on DISTS, DINO similarity, and reconstructed-weight SNR. 3. **GGUF Q8_0** is the highest-fidelity of the three added formats. 4. **MXFP8** ranks fourth in fidelity (LPIPS 0.071229) and halves checkpoint size versus BF16, but its native SM 10.0 fast path was unavailable on this Ada GPU, resulting in 31.929 s fallback sampling. 5. **FP8 Scaled** ranks fifth (LPIPS 0.093701) at 12.239 GiB and was the fastest of the original five formats at 19.503 s on this GPU. 6. **GGUF Q4_K_M** is a storage-quality compromise: 6.972 GiB and much closer to BF16 than INT4 ConvRot, but slow on this Ada GPU under ComfyUI-GGUF dequantized execution. 7. **NVFP4** is 7.147 GiB with moderate fidelity loss (LPIPS 0.205124). Like MXFP8, its native fast multiplication requires SM 10.0; the recorded 24.925 s sampling time uses the fallback path. 8. **INT4 ConvRot W4A4** is the smallest checkpoint and fastest of the three additions on this RTX 4060 Ti, but has the largest measured fidelity loss. No weighted composite score is used. See [the full technical report](TECHNICAL_REPORT.md) and [`tables/decision_table.csv`](tables/decision_table.csv). ## Important performance limitation The test GPU was an NVIDIA GeForce RTX 4060 Ti 16 GB (SM 8.9). MXFP8 and NVFP4 native fast matrix multiplication requires SM 10.0 in the tested runtime. GGUF Q8_0 and Q4_K_M use the pinned ComfyUI-GGUF on-demand dequantized matrix-multiplication path. These Ada timings must not be projected to native Blackwell execution. The original five formats and the three additions were measured in separate sessions. Five unscored BF16 and INT8 ConvRot bridge repeats quantify drift. INT8 crossed the preregistered 5% drift threshold, so exact old-versus-new timing comparisons remain caveated; fidelity comparisons remain paired to the same saved BF16 prompt/seed outputs. ## Dataset organization - `data/train/metadata.jsonl` and `data/train/images/` are the Dataset Viewer and loading source, using Hugging Face ImageFolder. The dataset card explicitly limits the `train` split to this tree so scientific JSON files elsewhere in the repository are not inferred as dataset splits. Each metadata row links an image to its prompt, seed, format, checkpoint provenance, raw scientific artifacts, and flattened metric values. - `raw/` contains `decoded_float32.npy`, `final_latent_float32.npy`, `trajectory.npz`, and capture `metadata.json` for every scored run. - `metrics/` contains raw per-image, per-parameter, paired-statistics, summary, trajectory, latency, and performance tables. - `comparison_sheets/` contains eight-format sheets, BF16-relative difference maps, and automatically selected detail crops. - `telemetry/` contains scored GPU/system telemetry plus the BF16/INT8 bridge telemetry. - `provenance/` contains sanitized environment, model, run, and release manifests. - `reproduction/` contains the ComfyUI workflows, custom capture node, benchmark driver, analyzers, model downloader, and exact instructions. Load the image table locally: ```python from datasets import load_dataset dataset = load_dataset("Merserk/Krea-2-Turbo-Checkpoint-Format-Benchmark", split="train") print(dataset.num_rows) # 240 ``` ## Fixed inference controls - 15 prompts × 2 deterministic seeds × 8 checkpoint formats = 240 scored images - 1024×1024, batch size 1 - 8 steps, CFG 1.0, Euler sampler, simple scheduler, denoise 1.0 - Shared `qwen3vl_4b_bf16.safetensors` text encoder and `qwen_image_vae.safetensors` VAE - Zeroed positive conditioning used as negative conditioning - No prompt rewriting, LoRAs, previews, upscaling, or post-processing - Identical initial-noise SHA-256 for every eight-format prompt/seed group ## Reproduce or verify Follow [`reproduction/README.md`](reproduction/README.md). A complete rerun downloads about 104 GiB of upstream model files and should have at least 150 GiB free for models, captures, analysis caches, and reports. The published benchmark was tested on Windows 11 with a 16 GB NVIDIA GPU; lower-memory configurations are not certified. Validate this downloaded release: ```bash python scripts/validate_release.py --root . --full ``` Upload a locally rebuilt copy: ```bash hf auth login python scripts/upload_to_huggingface.py OWNER/DATASET --root . ``` ## Licenses and responsible use Generated images, data, and reports are released under CC BY 4.0. Benchmark scripts are MIT licensed. Model weights are not redistributed and remain governed by the Krea 2 Community License. Krea states that it does not claim intellectual-property rights over user-generated outputs, while users remain responsible for their prompts, outputs, and downstream use. Review the [official Krea 2 Turbo model card and license](https://huggingface.co/krea/Krea-2-Turbo) before downloading or running the checkpoints. The prompt suite avoids requests for real people, explicit content, unlawful activity, or protected logos. Generated images can still contain model errors, stereotypes, malformed text, or unintended resemblance. This benchmark evaluates checkpoint fidelity on one controlled campaign; it is not a universal ranking of human aesthetic preference or all hardware. ## Citation See [`CITATION.cff`](CITATION.cff). The project attribution name is **Krea 2 Turbo Formats Benchmark Contributors**. """ def build_reproduction_readme() -> str: return r"""# Reproducing the Krea 2 Turbo Format Benchmark ## Tested reference environment - Windows 11, NVIDIA GeForce RTX 4060 Ti 16 GB, driver 610.74, compute capability 8.9 - ComfyUI commit `917faef771a2fd2f14f44af94f17da3d0b2803a3` - Python 3.13.12, PyTorch 2.13.0+cu130, CUDA runtime 13.0 - comfy-kitchen 0.2.18, transformers 5.13.1, NumPy 2.5.1 - About 104 GiB for required model files; at least 150 GiB free is recommended for models, captures, analysis caches, and reports Use the pinned ComfyUI commit for a strict reproduction. A newer ComfyUI build may run the workflow but is a different software condition and must be reported as such. ## 1. Accept the upstream terms and download models Review and accept the Krea 2 Community License at https://huggingface.co/krea/Krea-2-Turbo and authenticate if required: ```bash hf auth login python download_models.py --models-dir ../models --all --accept-krea-license ``` The downloader uses the exact pinned revisions recorded in `provenance/model_manifest.json`: Comfy-Org for the original checkpoints and shared components, Winnougan for INT4 ConvRot, and vantagewithai for both GGUF files. It verifies all ten SHA-256 hashes and does not place weights in this dataset repository. ## 2. Configure ComfyUI Install the pinned GGUF loader into ComfyUI: ```bash cd ComfyUI/custom_nodes git clone https://github.com/city96/ComfyUI-GGUF.git cd ComfyUI-GGUF git checkout 6ea2651e7df66d7585f6ffee804b20e92fb38b8a python -m pip install gguf==0.19.0 ``` Change into `reproduction/benchmark`, copy `config_base.example.json` to `config.json`, copy `config_extended.example.json` to `config_extended.json`, and set the common paths in `config.json`: - `paths.portable_root`: root containing `ComfyUI/` and, for Windows portable, `python_embeded/python.exe` - `paths.models_dir`: directory containing all seven downloaded files - `paths.results_dir`: keep `results/krea2_formats_v1`; the extension imports this immutable base into `results/krea2_formats_v2_extended` Copy `extra_model_paths.yaml.example` to `extra_model_paths.yaml`, replace the common parent placeholder, and expose `custom_nodes/krea2_benchmark` through that file. Forward slashes are recommended in YAML on Windows. For a standard Linux ComfyUI checkout, run the benchmark from the same Python environment as ComfyUI and adapt the launcher paths in `config.json`. The generated API workflow and analysis stages are platform-neutral; the supplied PowerShell launcher exactly matches the tested Windows portable environment. ## 3. Install analysis dependencies The benchmark deliberately reuses ComfyUI's CUDA-enabled PyTorch and installs analysis-only packages into `.vendor`: ```powershell .\install_analysis.ps1 ``` Equivalent shell command: ```bash python -m pip install --target .vendor -r requirements-analysis.txt ``` ## 4. Execute the campaign Run the original five-format base campaign first: ```powershell .\run_benchmark.ps1 preflight .\run_benchmark.ps1 weights .\run_benchmark.ps1 generate .\run_benchmark.ps1 analyze .\run_benchmark.ps1 sheets .\run_benchmark.ps1 report .\run_benchmark.ps1 verify ``` Then run the three-format extension and unified eight-format analysis: ```powershell .\run_benchmark.ps1 preflight -Config .\config_extended.json .\run_benchmark.ps1 weights -Config .\config_extended.json .\run_benchmark.ps1 generate -Config .\config_extended.json .\run_benchmark.ps1 analyze -Config .\config_extended.json .\run_benchmark.ps1 sheets -Config .\config_extended.json .\run_benchmark.ps1 report -Config .\config_extended.json .\run_benchmark.ps1 verify -Config .\config_extended.json ``` The base campaign produces 150 scored images. The extension hard-links the immutable base captures, runs five BF16 and INT8 bridge repeats, generates 90 new scored images, and analyzes all 240 rows. Do not compare formats if initial-noise hashes, sampler equivalence, bridge evidence, or either completion audit fails. ## 5. Rebuild this Hugging Face release From the dataset repository root after the reproduced campaign has completed: ```bash python scripts/prepare_release.py --benchmark-root reproduction/benchmark --destination ../krea2-benchmark-release python ../krea2-benchmark-release/scripts/validate_release.py --root ../krea2-benchmark-release --full ``` The builder refuses an existing destination. Move or remove a previous generated release deliberately before rebuilding. ## Metric interpretation - LPIPS-Alex is the preregistered primary paired fidelity endpoint; lower is better. - DISTS and final-latent relative L2 are secondary fidelity endpoints; lower is better. - DINOv2 and image cosine similarity measure semantic/feature preservation; higher is better. - Artifact probes measure clipping, gradient behavior, grid boundaries, high-frequency power, flat-region noise, and color change. - Weight reconstruction streams each native quantized layout against BF16 and reports element-weighted error, cosine, and SNR. - Prompt-alignment and no-reference IQA scores supplement fidelity metrics but do not replace paired BF16 comparisons. - GPU speed results are hardware/runtime-specific. MXFP8 and NVFP4 used fallback paths, while GGUF used on-demand dequantized matrix multiplication on the tested SM 8.9 GPU. """ def build_download_script() -> str: return '''from __future__ import annotations import argparse import hashlib import json import shutil from pathlib import Path from huggingface_hub import hf_hub_download def digest(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 main() -> int: parser = argparse.ArgumentParser(description="Download and verify Krea 2 benchmark models") parser.add_argument("--models-dir", type=Path, required=True) parser.add_argument("--manifest", type=Path, default=Path(__file__).resolve().parents[1] / "provenance" / "model_manifest.json") parser.add_argument("--all", action="store_true", help="Download all eight formats plus text encoder and VAE") parser.add_argument("--format", choices=["bf16", "fp8_scaled", "int8_convrot", "mxfp8", "nvfp4", "int4_convrot", "gguf_q8_0", "gguf_q4_k_m"], action="append") parser.add_argument("--accept-krea-license", action="store_true") args = parser.parse_args() if not args.accept_krea_license: parser.error("Review the Krea 2 Community License, then pass --accept-krea-license") selected = set(args.format or []) if not args.all and not selected: parser.error("Choose --all or at least one --format") manifest = json.loads(args.manifest.read_text(encoding="utf-8")) args.models_dir.mkdir(parents=True, exist_ok=True) common = {"qwen3vl_4b_bf16.safetensors", "qwen_image_vae.safetensors"} wanted = common | {item["filename"] for item in manifest["files"] if item.get("format_id") in selected} if args.all: wanted = {item["filename"] for item in manifest["files"]} for item in manifest["files"]: if item["filename"] not in wanted: continue destination = args.models_dir / item["filename"] if destination.exists() and digest(destination) == item["sha256"]: print(f"verified {destination.name}") continue cached = Path(hf_hub_download(repo_id=item["repository"], revision=item["revision"], filename=item["repository_path"])) shutil.copy2(cached, destination) actual = digest(destination) if actual != item["sha256"]: destination.unlink(missing_ok=True) raise RuntimeError(f"SHA-256 mismatch for {item['filename']}: {actual}") print(f"downloaded and verified {destination.name}") return 0 if __name__ == "__main__": raise SystemExit(main()) ''' def build_upload_script() -> str: return '''from __future__ import annotations import argparse import subprocess import sys from pathlib import Path from huggingface_hub import HfApi def main() -> int: parser = argparse.ArgumentParser(description="Upload the validated benchmark release to Hugging Face") parser.add_argument("repo_id", metavar="OWNER/DATASET") parser.add_argument("--root", type=Path, default=Path(__file__).resolve().parents[1]) parser.add_argument("--private", action="store_true") parser.add_argument("--dry-run", action="store_true") args = parser.parse_args() root = args.root.resolve() required = [root / "README.md", root / "data" / "train" / "metadata.jsonl", root / "checksums" / "SHA256SUMS"] missing = [str(path) for path in required if not path.is_file()] if missing: raise RuntimeError("Release is incomplete: " + ", ".join(missing)) if (root / "viewer_data").exists() or (root / "data" / "train-00000-of-00001.parquet").exists(): raise RuntimeError("Obsolete Dataset Viewer Parquet artifacts are present") subprocess.run( [sys.executable, str(root / "scripts" / "validate_release.py"), "--root", str(root)], check=True, ) files = [path for path in root.rglob("*") if path.is_file()] total = sum(path.stat().st_size for path in files) print(f"ready: {len(files)} files, {total / 1024**3:.3f} GiB -> datasets/{args.repo_id}") if args.dry_run: return 0 api = HfApi() api.create_repo(repo_id=args.repo_id, repo_type="dataset", private=args.private, exist_ok=True) api.upload_large_folder( repo_id=args.repo_id, repo_type="dataset", folder_path=str(root), private=args.private, ignore_patterns=[ ".cache/**", ".viewer_fix_venv/**", "viewer_data/**", "viewer_fix_output/**", "**/__pycache__/**", "*.pyc", "viewer_fix_*.log", ], num_workers=4, print_report_every=30, ) print(f"https://huggingface.co/datasets/{args.repo_id}") return 0 if __name__ == "__main__": raise SystemExit(main()) ''' def build_release(benchmark_root: Path, destination: Path, config_path: Path) -> None: benchmark_root = benchmark_root.resolve() config_path = config_path if config_path.is_absolute() else benchmark_root / config_path config = load_configuration(config_path) results = benchmark_root / config["paths"]["results_dir"] expected_rows = len(config["prompts"]) * int(config["campaign"]["replicates"]) * len(FORMATS) if destination.exists(): raise FileExistsError(f"Destination already exists: {destination}") assert_source_complete(results) source_manifest = json_load(results / "manifest.json") scored_runs = [row for row in jsonl_load(results / "runs.jsonl") if row.get("scored") and row.get("status") == "complete"] if len(scored_runs) != expected_rows: raise RuntimeError(f"Expected {expected_rows} successful scored run records, found {len(scored_runs)}") run_by_id = {row["run_id"]: row for row in scored_runs} prompt_by_id = {prompt["id"]: prompt for prompt in config["prompts"]} metric_maps: dict[str, dict[str, dict[str, str]]] = {} for group, filename in SCORING_TABLES.items(): rows = csv_rows(results / "metrics" / filename) metric_maps[group] = {row["run_id"]: row for row in rows} if len(metric_maps[group]) != expected_rows: raise RuntimeError(f"{filename}: expected {expected_rows} run rows") destination.mkdir(parents=True) image_root = destination / "data" / "train" / "images" raw_root = destination / "raw" metadata_rows: list[dict[str, Any]] = [] capture_dirs = [path for path in (results / "captures").iterdir() if path.is_dir() and CAPTURE_RE.match(path.name)] if len(capture_dirs) != expected_rows: raise RuntimeError(f"Expected {expected_rows} scored capture directories, found {len(capture_dirs)}") for capture in sorted(capture_dirs, key=lambda path: path.name): match = CAPTURE_RE.match(capture.name) assert match run_id = capture.name fmt = match.group(3) run = run_by_id[run_id] prompt = prompt_by_id[run["prompt_id"]] image_relative = Path("images") / fmt / f"{run_id}.png" release_image = image_root.parent / image_relative release_image.parent.mkdir(parents=True, exist_ok=True) shutil.copy2(capture / "image.png", release_image) raw_relative = Path("raw") / fmt / run_id release_raw = destination / raw_relative release_raw.mkdir(parents=True, exist_ok=True) for filename in ("decoded_float32.npy", "final_latent_float32.npy", "trajectory.npz", "metadata.json"): shutil.copy2(capture / filename, release_raw / filename) checkpoint = config["formats"][fmt]["checkpoint"] source = config["formats"][fmt].get("source", {}) row: dict[str, Any] = { "file_name": image_relative.as_posix(), "run_id": run_id, "prompt_id": prompt["id"], "prompt_category": prompt["category"], "prompt": prompt["text"], "replicate": run["replicate"], "seed": run["seed"], "format_id": fmt, "format_label": FORMAT_LABELS[fmt], "checkpoint_filename": checkpoint, "checkpoint_sha256": config["integrity"]["expected_sha256"][checkpoint], "publisher_repository": source.get("repository", config["integrity"]["publisher_repository"]), "publisher_revision": source.get("revision", config["integrity"]["publisher_revision"]), "checkpoint_source_url": source.get("url"), "width": config["controls"]["width"], "height": config["controls"]["height"], "steps": config["controls"]["steps"], "cfg": config["controls"]["cfg"], "sampler": config["controls"]["sampler_name"], "scheduler": config["controls"]["scheduler"], "denoise": config["controls"]["denoise"], "text_encoder": config["controls"]["text_encoder"], "vae": config["controls"]["vae"], "negative_conditioning": config["controls"]["negative_mode"], "decoded_array_path": (raw_relative / "decoded_float32.npy").as_posix(), "final_latent_path": (raw_relative / "final_latent_float32.npy").as_posix(), "trajectory_path": (raw_relative / "trajectory.npz").as_posix(), "capture_metadata_path": (raw_relative / "metadata.json").as_posix(), } for group, mapping in metric_maps.items(): metric_row = mapping[run_id] for key, value in metric_row.items(): if key not in IDENTIFIER_COLUMNS: row[f"{group}_{key}"] = coerce(value) metadata_rows.append(row) jsonl_dump(destination / "data" / "train" / "metadata.jsonl", metadata_rows) copy_tree(results / "metrics", destination / "metrics") copy_tree(results / "comparison_sheets", destination / "comparison_sheets") (destination / "telemetry").mkdir() for source in sorted((results / "telemetry").glob("*.csv")): if source.stem in set(FORMATS) | {f"system_{fmt}" for fmt in FORMATS} or source.stem.startswith(("bridge_", "system_bridge_")): shutil.copy2(source, destination / "telemetry" / source.name) copy_tree(results / "validation", destination / "validation") report_text = (results / "TECHNICAL_REPORT.md").read_text(encoding="utf-8") report_text = re.sub( r"^- GPU: `[^`]+`$", "- GPU: `NVIDIA GeForce RTX 4060 Ti; driver 610.74; 16380 MiB; compute capability 8.9`", report_text, flags=re.MULTILINE, ) (destination / "TECHNICAL_REPORT.md").write_text(report_text, encoding="utf-8") provenance = destination / "provenance" sanitized_manifest = sanitize_manifest(source_manifest) json_dump(provenance / "manifest.json", sanitized_manifest) json_dump(provenance / "model_manifest.json", build_model_manifest(config, source_manifest)) json_dump(provenance / "run_matrix.json", json_load(results / "run_matrix.json")) jsonl_dump(provenance / "runs_scored.jsonl", scored_runs) json_dump( provenance / "environment-lock.json", { "comfyui": sanitized_manifest["comfyui"], "comfyui_gguf": sanitized_manifest["comfyui_gguf"], "lineage": sanitized_manifest["lineage"], "gpu": sanitized_manifest["gpu"], "platform": sanitized_manifest["platform"], "runtime": sanitized_manifest["runtime"], "analysis_packages": sanitized_manifest["analysis_packages"], }, ) repeatability: dict[str, Any] = {"passed": True, "formats": {}} all_runs = jsonl_load(results / "runs.jsonl") for fmt in FORMATS: hashes = [ row.get("metadata", {}).get("output", {}).get("image_sha256") for row in all_runs if row.get("phase") == "repeatability" and row.get("format_id") == fmt and row.get("status") == "complete" ] hashes = [value for value in hashes if value] repeatability["formats"][fmt] = {"runs": len(hashes), "unique_image_hashes": sorted(set(hashes)), "bit_exact": len(set(hashes)) == 1} repeatability["passed"] = repeatability["passed"] and len(hashes) >= 2 and len(set(hashes)) == 1 json_dump(destination / "validation" / "repeatability.json", repeatability) decision_rows = parse_decision_table(results / "TECHNICAL_REPORT.md") write_csv(destination / "tables" / "decision_table.csv", decision_rows) decision_by_label = {row["format"]: row for row in decision_rows} fidelity_order = sorted(FORMATS, key=lambda fmt: float(decision_by_label[FORMAT_LABELS[fmt]]["lpips_alex_median"])) ranking_rows = [ { "fidelity_rank": rank, "format_id": fmt, "format_label": FORMAT_LABELS[fmt], "scope": "BF16-relative checkpoint fidelity; no aesthetic composite score", "basis": "BF16 reference" if fmt == "bf16" else "LPIPS-Alex primary endpoint with supporting DISTS, DINOv2, latent, and weight evidence", } for rank, fmt in enumerate(fidelity_order, 1) ] write_csv(destination / "tables" / "format_ranking.csv", ranking_rows) metric_dictionary = build_metric_dictionary(results / "metrics") write_csv(destination / "tables" / "metric_dictionary.csv", metric_dictionary) json_dump( destination / "tables" / "metadata_schema.json", { "schema_version": 1, "rows": expected_rows, "identifiers": ["run_id", "prompt_id", "replicate", "seed", "format_id"], "image_field": "file_name", "raw_artifact_fields": ["decoded_array_path", "final_latent_path", "trajectory_path", "capture_metadata_path"], "metric_prefixes": {group: filename for group, filename in SCORING_TABLES.items()}, "columns": sorted(metadata_rows[0]), }, ) reproduction = destination / "reproduction" reproduction.mkdir() source_files = [ "advanced_metrics.py", "analysis_core.py", "comparison_sheets.py", "krea_benchmark.py", "performance_analysis.py", "report_generator.py", "verify_results.py", "weight_audit.py", ] benchmark_release = reproduction / "benchmark" benchmark_release.mkdir() for name in source_files: shutil.copy2(benchmark_root / name, benchmark_release / name) copy_tree(benchmark_root / "workflows", benchmark_release / "workflows") copy_tree(benchmark_root / "custom_nodes", benchmark_release / "custom_nodes") shutil.copy2(benchmark_root / "requirements-analysis.txt", benchmark_release / "requirements-analysis.txt") (reproduction / "README.md").write_text(build_reproduction_readme(), encoding="utf-8") (reproduction / "download_models.py").write_text(build_download_script(), encoding="utf-8") base_config = load_configuration(benchmark_root / "config.json") (benchmark_release / "config_base.example.json").write_text(json.dumps(sanitize_configuration(base_config), indent=2, ensure_ascii=False) + "\n", encoding="utf-8") extended_template = json_load(config_path) extended_template["extends"] = "config.json" (benchmark_release / "config_extended.example.json").write_text(json.dumps(extended_template, indent=2, ensure_ascii=False) + "\n", encoding="utf-8") (benchmark_release / "extra_model_paths.yaml.example").write_text( "krea_benchmark:\n base_path: \n diffusion_models: models\n text_encoders: models\n vae: models\n custom_nodes: Huggingface datasets/reproduction/benchmark/custom_nodes\n", encoding="utf-8", ) (benchmark_release / "run_benchmark.sh").write_text( "#!/usr/bin/env bash\nset -euo pipefail\npython \"$(dirname \"$0\")/krea_benchmark.py\" \"${1:?stage required}\" --config \"${2:-$(dirname \"$0\")/config.json}\"\n", encoding="utf-8", ) (benchmark_release / "run_benchmark.ps1").write_text( "param(\n" " [ValidateSet('preflight','weights','generate','analyze','sheets','report','verify','all')][string]$Stage='all',\n" " [string]$Config=\"$PSScriptRoot\\config.json\", [string]$Python, [switch]$SkipHashes, [switch]$NoStepCapture\n" ")\n$ErrorActionPreference='Stop'\n" "if (-not $Python) { $cfg=Get-Content -LiteralPath $Config -Raw|ConvertFrom-Json; $base=Split-Path -Parent (Resolve-Path -LiteralPath $Config); $portable=Join-Path $base $cfg.paths.portable_root; $Python=Join-Path $portable 'python_embeded\\python.exe' }\n" "if (-not (Test-Path -LiteralPath $Python)) { throw \"Python not found at $Python; pass -Python explicitly\" }\n" "$a=@(\"$PSScriptRoot\\krea_benchmark.py\",$Stage,'--config',$Config); if($SkipHashes){$a+='--skip-hashes'}; if($NoStepCapture){$a+='--no-step-capture'}; & $Python @a; exit $LASTEXITCODE\n", encoding="utf-8", ) (benchmark_release / "install_analysis.ps1").write_text( "param([string]$Config=\"$PSScriptRoot\\config.json\",[string]$Python)\n$ErrorActionPreference='Stop'\n" "if (-not $Python) { $cfg=Get-Content -LiteralPath $Config -Raw|ConvertFrom-Json; $base=Split-Path -Parent (Resolve-Path -LiteralPath $Config); $portable=Join-Path $base $cfg.paths.portable_root; $Python=Join-Path $portable 'python_embeded\\python.exe' }\n" "if (-not (Test-Path -LiteralPath $Python)) { throw \"Python not found at $Python; pass -Python explicitly\" }\n" "& $Python -m pip install --target \"$PSScriptRoot\\.vendor\" --upgrade -r \"$PSScriptRoot\\requirements-analysis.txt\"; exit $LASTEXITCODE\n", encoding="utf-8", ) (reproduction / "requirements-release.txt").write_text( "datasets==5.0.0\nhuggingface_hub==1.23.0\nhf-xet==1.5.1\nnumpy==2.4.6\nPillow==12.3.0\nPyYAML==6.0.3\n", encoding="utf-8", ) scripts = destination / "scripts" scripts.mkdir() source_tool_dir = Path(__file__).resolve().parent shutil.copy2(source_tool_dir / "prepare_release.py", scripts / "prepare_release.py") shutil.copy2(source_tool_dir / "validate_release.py", scripts / "validate_release.py") (scripts / "upload_to_huggingface.py").write_text(build_upload_script(), encoding="utf-8") (destination / "README.md").write_text(build_readme(), encoding="utf-8") (destination / "LICENSE-DATA").write_text( "Creative Commons Attribution 4.0 International (CC BY 4.0)\n\n" "Copyright (c) 2026 Krea 2 Turbo Formats Benchmark Contributors\n\n" "This work is licensed under the Creative Commons Attribution 4.0 International License. " "To view the complete legal code, visit https://creativecommons.org/licenses/by/4.0/legalcode .\n", encoding="utf-8", ) (destination / "LICENSE-CODE").write_text( "MIT License\n\nCopyright (c) 2026 Krea 2 Turbo Formats Benchmark Contributors\n\n" "Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files " "(the \"Software\"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, " "publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, " "subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.\n\n" "THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF " "MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR " "ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE " "SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n", encoding="utf-8", ) (destination / "CITATION.cff").write_text( "cff-version: 1.2.0\nmessage: If you use this benchmark, please cite it.\ntitle: Krea 2 Turbo ComfyUI Format Fidelity Benchmark\n" "type: dataset\nversion: 2.0.0\ndate-released: 2026-07-13\nauthors:\n - name: Krea 2 Turbo Formats Benchmark Contributors\n" "license: CC-BY-4.0\n", encoding="utf-8", ) (destination / ".gitattributes").write_text( "*.png filter=lfs diff=lfs merge=lfs -text\n*.npy filter=lfs diff=lfs merge=lfs -text\n*.npz filter=lfs diff=lfs merge=lfs -text\n*.parquet filter=lfs diff=lfs merge=lfs -text\n", encoding="utf-8", ) (destination / ".gitignore").write_text( "**/__pycache__/\n*.py[cod]\n**/.vendor/\n**/.cache/\n**/cache/\n**/logs/\n**/comfy_output/\n**/results/\n*.safetensors\n*.ckpt\n*.gguf\n.env\n.env.*\n!*.example\n", encoding="utf-8", ) files_before_manifest = [path for path in destination.rglob("*") if path.is_file()] category_counts = Counter(path.relative_to(destination).parts[0] for path in files_before_manifest) release_manifest = { "schema_version": 1, "benchmark_id": config["benchmark_id"], "dataset_rows": expected_rows, "format_counts": dict(Counter(row["format_id"] for row in metadata_rows)), "file_counts_by_top_level": dict(sorted(category_counts.items())), "payload_bytes_before_checksums": sum(path.stat().st_size for path in files_before_manifest), "exclusions": [ "model checkpoints", "analysis dependency vendor directory", "advanced metric evaluator cache", "logs and ComfyUI output", "integration smoke outputs", "preflight, warmup, repeatability, and sampler-validation captures", "Python bytecode and temporary caches", ], } json_dump(provenance / "release_manifest.json", release_manifest) checksum_dir = destination / "checksums" checksum_dir.mkdir() checksum_lines = [] for path in sorted((item for item in destination.rglob("*") if item.is_file()), key=lambda item: item.relative_to(destination).as_posix()): relative = path.relative_to(destination).as_posix() if relative == "checksums/SHA256SUMS": continue checksum_lines.append(f"{sha256(path)} {relative}") (checksum_dir / "SHA256SUMS").write_text("\n".join(checksum_lines) + "\n", encoding="utf-8") def main() -> int: parser = argparse.ArgumentParser(description="Build the clean Hugging Face release for the Krea 2 benchmark") parser.add_argument("--benchmark-root", type=Path, default=Path(__file__).resolve().parents[1]) parser.add_argument("--config", type=Path, default=Path("config_extended.json")) parser.add_argument("--destination", type=Path, required=True) args = parser.parse_args() build_release(args.benchmark_root, args.destination.resolve(), args.config) print(args.destination.resolve()) return 0 if __name__ == "__main__": raise SystemExit(main())