from __future__ import annotations import argparse import csv import hashlib import json import os import platform import random import shutil import signal import subprocess import sys import threading import time import urllib.error import urllib.request import uuid from collections import Counter from pathlib import Path from typing import Any BENCHMARK_DIR = Path(__file__).resolve().parent if str(BENCHMARK_DIR) not in sys.path: sys.path.insert(0, str(BENCHMARK_DIR)) API_WORKFLOW_PATH = BENCHMARK_DIR / "workflows" / "krea2_benchmark_api.json" EXTRA_PATHS_PATH = BENCHMARK_DIR / "extra_model_paths.yaml" VENDOR_DIR = BENCHMARK_DIR / ".vendor" def enable_analysis_vendor() -> None: if not VENDOR_DIR.is_dir(): raise RuntimeError(f"Analysis dependencies are not installed: {VENDOR_DIR}") value = str(VENDOR_DIR) if value not in sys.path: # Append so ComfyUI's CUDA-enabled torch/numpy remain authoritative. sys.path.append(value) def atomic_json(path: Path, value: Any) -> None: path.parent.mkdir(parents=True, exist_ok=True) temporary = path.with_suffix(path.suffix + ".tmp") temporary.write_text(json.dumps(value, ensure_ascii=False, indent=2, sort_keys=True), encoding="utf-8") temporary.replace(path) def append_jsonl(path: Path, value: Any) -> None: path.parent.mkdir(parents=True, exist_ok=True) with path.open("a", encoding="utf-8", newline="\n") as stream: stream.write(json.dumps(value, ensure_ascii=False, sort_keys=True) + "\n") def sha256_file(path: Path, chunk_size: int = 32 * 1024 * 1024) -> str: digest = hashlib.sha256() with path.open("rb") as stream: while chunk := stream.read(chunk_size): digest.update(chunk) return digest.hexdigest() def sha256_json(value: Any) -> str: raw = json.dumps(value, ensure_ascii=False, sort_keys=True, separators=(",", ":")).encode("utf-8") return hashlib.sha256(raw).hexdigest() def deep_merge(base: dict[str, Any], overlay: dict[str, Any]) -> dict[str, Any]: merged = dict(base) for key, value in overlay.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] = value return merged def read_configuration(path: Path, seen: set[Path] | None = None) -> tuple[dict[str, Any], list[Path]]: resolved = path.resolve() seen = set() if seen is None else seen if resolved in seen: raise ValueError(f"Configuration inheritance cycle: {resolved}") seen.add(resolved) raw = json.loads(resolved.read_text(encoding="utf-8")) parent_name = raw.get("extends") if not parent_name: return raw, [resolved] parent, sources = read_configuration((resolved.parent / parent_name).resolve(), seen) return deep_merge(parent, raw), sources + [resolved] def run_command(command: list[str], cwd: Path | None = None, timeout: int = 60) -> dict[str, Any]: started = time.time() completed = subprocess.run(command, cwd=cwd, capture_output=True, text=True, encoding="utf-8", errors="replace", timeout=timeout) return { "command": command, "returncode": completed.returncode, "stdout": completed.stdout.strip(), "stderr": completed.stderr.strip(), "duration_seconds": time.time() - started, } def load_configuration(path: Path) -> dict[str, Any]: config, sources = read_configuration(path) if config.get("schema_version") not in {1, 2}: raise ValueError(f"Unsupported configuration schema: {config.get('schema_version')}") base = path.resolve().parent resolved = dict(config) resolved["_config_path"] = str(path.resolve()) resolved["_config_sources"] = [str(source) for source in sources] resolved["_config_sha256"] = sha256_file(path) if len(sources) == 1 else sha256_json(config) resolved["_portable_root"] = str((base / config["paths"]["portable_root"]).resolve()) resolved["_models_dir"] = str((base / config["paths"]["models_dir"]).resolve()) resolved["_results_dir"] = str((base / config["paths"]["results_dir"]).resolve()) if config["paths"].get("base_results_dir"): resolved["_base_results_dir"] = str((base / config["paths"]["base_results_dir"]).resolve()) return resolved def active_formats(config: dict[str, Any]) -> list[str]: selected = list(config["campaign"].get("active_formats", config["formats"])) unknown = [format_id for format_id in selected if format_id not in config["formats"]] if unknown: raise ValueError(f"Unknown active formats: {unknown}") return selected def expected_scored_runs(config: dict[str, Any]) -> int: return len(config["prompts"]) * int(config["campaign"]["replicates"]) * len(config["formats"]) def benchmark_seed(benchmark_id: str, prompt_id: str, replicate: int) -> int: value = f"{benchmark_id}|{prompt_id}|{replicate}".encode("utf-8") return int.from_bytes(hashlib.sha256(value).digest()[:8], "big") & 0x7FFFFFFFFFFFFFFF def url_json(method: str, url: str, payload: dict[str, Any] | None = None, timeout: int = 30) -> Any: data = None if payload is None else json.dumps(payload).encode("utf-8") request = urllib.request.Request(url, data=data, method=method, headers={"Content-Type": "application/json"}) try: with urllib.request.urlopen(request, timeout=timeout) as response: raw = response.read() return json.loads(raw.decode("utf-8")) if raw else None except urllib.error.HTTPError as error: body = error.read().decode("utf-8", errors="replace") raise RuntimeError(f"ComfyUI HTTP {error.code} for {url}: {body}") from error class NvidiaTelemetry: HEADER = [ "timestamp", "name", "utilization_gpu_percent", "utilization_memory_percent", "memory_used_mib", "memory_total_mib", "power_draw_w", "temperature_gpu_c", "clocks_sm_mhz", "clocks_memory_mhz", "pstate", ] def __init__(self, path: Path, interval_seconds: float): self.path = path self.interval_ms = max(100, int(interval_seconds * 1000)) self.process: subprocess.Popen | None = None self.stream = None def start(self) -> None: self.path.parent.mkdir(parents=True, exist_ok=True) self.stream = self.path.open("w", encoding="utf-8", newline="") self.stream.write(",".join(self.HEADER) + "\n") self.stream.flush() query = ",".join( [ "timestamp", "name", "utilization.gpu", "utilization.memory", "memory.used", "memory.total", "power.draw", "temperature.gpu", "clocks.sm", "clocks.mem", "pstate", ] ) self.process = subprocess.Popen( ["nvidia-smi", f"--query-gpu={query}", "--format=csv,noheader,nounits", f"--loop-ms={self.interval_ms}"], stdout=self.stream, stderr=subprocess.STDOUT, text=True, ) def stop(self) -> None: if self.process is not None and self.process.poll() is None: self.process.terminate() try: self.process.wait(timeout=5) except subprocess.TimeoutExpired: self.process.kill() self.process.wait(timeout=5) if self.stream is not None: self.stream.flush() self.stream.close() class SystemTelemetry: def __init__(self, path: Path, interval_seconds: float): self.path = path self.interval_seconds = max(0.1, interval_seconds) self.stop_event = threading.Event() self.thread: threading.Thread | None = None self.pid: int | None = None def start(self, pid: int) -> None: self.pid = pid self.path.parent.mkdir(parents=True, exist_ok=True) self.thread = threading.Thread(target=self._run, name=f"system-telemetry-{pid}", daemon=True) self.thread.start() def _run(self) -> None: import psutil with self.path.open("w", encoding="utf-8", newline="") as stream: writer = csv.writer(stream) writer.writerow(["unix_time", "system_ram_used_bytes", "system_ram_available_bytes", "comfy_process_tree_rss_bytes", "system_cpu_percent"]) process = psutil.Process(self.pid) while not self.stop_event.is_set(): memory = psutil.virtual_memory() rss = 0 try: rss += process.memory_info().rss for child in process.children(recursive=True): try: rss += child.memory_info().rss except (psutil.NoSuchProcess, psutil.AccessDenied): pass except (psutil.NoSuchProcess, psutil.AccessDenied): pass writer.writerow([time.time(), memory.used, memory.available, rss, psutil.cpu_percent(interval=None)]) stream.flush() self.stop_event.wait(self.interval_seconds) def stop(self) -> None: self.stop_event.set() if self.thread is not None: self.thread.join(timeout=5) class ComfyServer: def __init__(self, config: dict[str, Any], format_id: str, results_dir: Path): self.config = config self.format_id = format_id self.results_dir = results_dir self.host = config["server"]["host"] self.port = int(config["server"]["port"]) self.base_url = f"http://{self.host}:{self.port}" portable = Path(config["_portable_root"]) self.python = portable / "python_embeded" / "python.exe" self.comfy_dir = portable / "ComfyUI" self.process: subprocess.Popen | None = None self.log_stream = None self.telemetry = NvidiaTelemetry( results_dir / "telemetry" / f"{format_id}.csv", float(config["server"]["telemetry_interval_seconds"]), ) self.system_telemetry = SystemTelemetry( results_dir / "telemetry" / f"system_{format_id}.csv", float(config["server"]["telemetry_interval_seconds"]), ) def start(self) -> None: logs_dir = self.results_dir / "logs" logs_dir.mkdir(parents=True, exist_ok=True) self.log_stream = (logs_dir / f"comfy_{self.format_id}.log").open("w", encoding="utf-8", errors="replace") command = [ str(self.python), "main.py", "--listen", self.host, "--port", str(self.port), "--disable-auto-launch", "--preview-method", "none", "--extra-model-paths-config", str(EXTRA_PATHS_PATH), "--output-directory", str(self.results_dir / "comfy_output"), ] if self.config["server"].get("memory_mode") == "lowvram": command.append("--lowvram") environment = os.environ.copy() environment["PYTHONIOENCODING"] = "utf-8" environment["KREA_BENCHMARK_OUTPUT_ROOT"] = str(self.results_dir) self.telemetry.start() self.process = subprocess.Popen( command, cwd=self.comfy_dir, env=environment, stdout=self.log_stream, stderr=subprocess.STDOUT, text=True, ) self.system_telemetry.start(self.process.pid) deadline = time.monotonic() + int(self.config["server"]["startup_timeout_seconds"]) last_error = None while time.monotonic() < deadline: if self.process.poll() is not None: raise RuntimeError(f"ComfyUI exited during startup for {self.format_id}; see {self.log_stream.name}") try: url_json("GET", self.base_url + "/system_stats", timeout=5) object_info = url_json("GET", self.base_url + "/object_info/KreaBenchmarkSampler", timeout=10) if "KreaBenchmarkSampler" not in object_info: raise RuntimeError("KreaBenchmarkSampler was not registered") return except Exception as error: last_error = error time.sleep(1) raise TimeoutError(f"Timed out waiting for ComfyUI startup: {last_error}") def stop(self) -> None: if self.process is not None and self.process.poll() is None: try: url_json("POST", self.base_url + "/free", {"unload_models": True, "free_memory": True}, timeout=10) except Exception: pass self.process.terminate() try: self.process.wait(timeout=30) except subprocess.TimeoutExpired: self.process.kill() self.process.wait(timeout=10) self.system_telemetry.stop() self.telemetry.stop() if self.log_stream is not None: self.log_stream.flush() self.log_stream.close() def execute(self, workflow: dict[str, Any], timeout_seconds: int) -> dict[str, Any]: client_id = str(uuid.uuid4()) queued = url_json("POST", self.base_url + "/prompt", {"prompt": workflow, "client_id": client_id}, timeout=30) if queued.get("node_errors"): raise RuntimeError(f"ComfyUI rejected workflow: {json.dumps(queued['node_errors'], ensure_ascii=False)}") prompt_id = queued["prompt_id"] deadline = time.monotonic() + timeout_seconds while time.monotonic() < deadline: if self.process is not None and self.process.poll() is not None: raise RuntimeError(f"ComfyUI exited while executing prompt {prompt_id}") history = url_json("GET", self.base_url + f"/history/{prompt_id}", timeout=30) if prompt_id in history: record = history[prompt_id] status = record.get("status", {}) if status.get("status_str") == "error" or status.get("completed") is False: raise RuntimeError(f"ComfyUI execution failed: {json.dumps(status, ensure_ascii=False)}") return record time.sleep(0.5) raise TimeoutError(f"Prompt {prompt_id} did not finish within {timeout_seconds} seconds") def build_workflow(config: dict[str, Any], format_id: str, prompt: dict[str, str], replicate: int, run_id: str, scored: bool, capture_steps: bool) -> tuple[dict[str, Any], int]: workflow = json.loads(API_WORKFLOW_PATH.read_text(encoding="utf-8")) controls = config["controls"] seed = benchmark_seed(config["benchmark_id"], prompt["id"], replicate) format_config = config["formats"][format_id] if format_config.get("loader", "unet") == "gguf": workflow["1"] = { "class_type": "UnetLoaderGGUF", "inputs": {"unet_name": format_config["checkpoint"]}, } else: workflow["1"] = { "class_type": "UNETLoader", "inputs": {"unet_name": format_config["checkpoint"], "weight_dtype": "default"}, } workflow["2"]["inputs"].update( { "clip_name": controls["text_encoder"], "type": controls["clip_type"], "device": controls["clip_device"], } ) workflow["3"]["inputs"]["vae_name"] = controls["vae"] workflow["4"]["inputs"]["text"] = prompt["text"] workflow["6"]["inputs"].update( { "width": int(controls["width"]), "height": int(controls["height"]), "batch_size": int(controls["batch_size"]), } ) workflow["7"]["inputs"].update( { "seed": seed, "steps": int(controls["steps"]), "cfg": float(controls["cfg"]), "sampler_name": controls["sampler_name"], "scheduler": controls["scheduler"], "denoise": float(controls["denoise"]), "run_id": run_id, "capture_steps": bool(capture_steps), } ) workflow["8"]["inputs"]["run_id"] = run_id workflow["9"]["inputs"].update( { "run_id": run_id, "format_id": format_id, "prompt_id": prompt["id"], "prompt_text": prompt["text"], "seed": seed, "scored": bool(scored), } ) return workflow, seed def inspect_safetensors(path: Path) -> dict[str, Any]: from safetensors import safe_open with safe_open(path, framework="pt", device="cpu") as tensors: keys = list(tensors.keys()) dtypes = Counter(str(tensors.get_slice(key).get_dtype()) for key in keys) metadata = tensors.metadata() or {} return { "tensor_count": len(keys), "dtype_tensor_counts": dict(sorted(dtypes.items())), "metadata_keys": sorted(metadata), "metadata_value_lengths": {key: len(value) for key, value in sorted(metadata.items())}, "first_tensor_keys": keys[:10], } def inspect_gguf(path: Path) -> dict[str, Any]: import gguf reader = gguf.GGUFReader(str(path), mode="r") qtypes = Counter(getattr(tensor.tensor_type, "name", str(tensor.tensor_type)) for tensor in reader.tensors) metadata = {} for key in ("general.architecture", "general.name", "general.description", "general.file_type", "general.quantization_version"): field = reader.get_field(key) if field is None: continue try: part = field.parts[field.data[-1]] metadata[key] = part.decode("utf-8") if isinstance(part, (bytes, bytearray)) else part.item() if hasattr(part, "item") else str(part) except Exception: metadata[key] = "unreadable" return { "tensor_count": len(reader.tensors), "quantization_type_counts": dict(sorted(qtypes.items())), "metadata": metadata, "metadata_field_count": len(reader.fields), "original_shape_fields": sum(key.startswith("comfy.gguf.orig_shape.") for key in reader.fields), "first_tensor_keys": [tensor.name for tensor in reader.tensors[:10]], } def collect_manifest(config: dict[str, Any], skip_hashes: bool) -> dict[str, Any]: import importlib.metadata portable = Path(config["_portable_root"]) comfy = portable / "ComfyUI" models_dir = Path(config["_models_dir"]) python = portable / "python_embeded" / "python.exe" model_names = [item["checkpoint"] for item in config["formats"].values()] + [config["controls"]["text_encoder"], config["controls"]["vae"]] models = {} for name in model_names: path = models_dir / name if not path.is_file(): raise FileNotFoundError(path) entry = { "path": str(path), "bytes": path.stat().st_size, "gib": path.stat().st_size / (1024 ** 3), "file_format": path.suffix.lower().lstrip("."), } if path.suffix.lower() == ".gguf": entry["gguf"] = inspect_gguf(path) else: entry["safetensors"] = inspect_safetensors(path) matching_formats = [item for item in config["formats"].values() if item["checkpoint"] == name] if matching_formats and matching_formats[0].get("source"): entry["source"] = matching_formats[0]["source"] if not skip_hashes: print(f"Hashing {name}...", flush=True) entry["sha256"] = sha256_file(path) entry["expected_sha256"] = config["integrity"]["expected_sha256"][name] entry["publisher_hash_match"] = entry["sha256"] == entry["expected_sha256"] if not entry["publisher_hash_match"]: raise RuntimeError(f"Publisher SHA-256 mismatch for {name}: {entry['sha256']} != {entry['expected_sha256']}") models[name] = entry git = run_command(["git", "-C", str(comfy), "log", "-1", "--date=iso-strict", "--format=%H%n%cd%n%s"], timeout=30) gpu = run_command( [ "nvidia-smi", "--query-gpu=name,uuid,driver_version,memory.total,compute_cap,pci.bus_id", "--format=csv,noheader,nounits", ], timeout=30, ) runtime = run_command( [ str(python), "-c", "import json,torch,importlib.metadata as m,importlib.util as u; print(json.dumps({'python':__import__('sys').version,'torch':torch.__version__,'cuda':torch.version.cuda,'device':torch.cuda.get_device_name(0),'capability':torch.cuda.get_device_capability(0),'comfy_kitchen':m.version('comfy-kitchen'),'gguf':m.version('gguf') if u.find_spec('gguf') else None,'transformers':m.version('transformers'),'numpy':m.version('numpy')}))", ], timeout=60, ) disk = shutil.disk_usage(config["_results_dir"] if Path(config["_results_dir"]).exists() else BENCHMARK_DIR) vendor_versions = {} if VENDOR_DIR.is_dir(): for distribution in importlib.metadata.distributions(path=[str(VENDOR_DIR)]): name = distribution.metadata.get("Name") if name: vendor_versions[name] = distribution.version gguf_node_dir = comfy / "custom_nodes" / "ComfyUI-GGUF" gguf_node = run_command(["git", "-C", str(gguf_node_dir), "rev-parse", "HEAD"], timeout=30) if gguf_node_dir.is_dir() else None lineage = None if config.get("_base_results_dir"): base_manifest = Path(config["_base_results_dir"]) / "manifest.json" lineage = { "base_results_dir": config["_base_results_dir"], "base_manifest_sha256": sha256_file(base_manifest) if base_manifest.is_file() else None, } return { "benchmark_id": config["benchmark_id"], "created_unix": time.time(), "config_path": config["_config_path"], "config_sha256": config["_config_sha256"], "configuration": {key: value for key, value in config.items() if not key.startswith("_")}, "platform": {"system": platform.system(), "release": platform.release(), "version": platform.version(), "machine": platform.machine()}, "comfy_git": git, "gpu": gpu, "runtime": runtime, "comfyui_gguf": gguf_node, "lineage": lineage, "analysis_vendor_versions": dict(sorted(vendor_versions.items(), key=lambda item: item[0].lower())), "disk": {"total_bytes": disk.total, "used_bytes": disk.used, "free_bytes": disk.free}, "models": models, } def import_base_results(config: dict[str, Any], results_dir: Path) -> None: if not config.get("_base_results_dir"): return base_dir = Path(config["_base_results_dir"]) marker = results_dir / "extension_import.json" base_manifest_path = base_dir / "manifest.json" if not base_manifest_path.is_file(): raise FileNotFoundError(base_manifest_path) base_manifest_hash = sha256_file(base_manifest_path) if marker.is_file(): recorded = json.loads(marker.read_text(encoding="utf-8")) if recorded.get("base_manifest_sha256") != base_manifest_hash: raise RuntimeError("The base benchmark manifest changed after the extension import") return base_manifest = json.loads(base_manifest_path.read_text(encoding="utf-8")) base_config = base_manifest["configuration"] for key in ("benchmark_id", "controls", "prompts"): if base_config.get(key) != config.get(key): raise RuntimeError(f"Cannot extend results: base {key} differs from the extension configuration") imported_formats = list(base_config["formats"]) if any(format_id not in config["formats"] for format_id in imported_formats): raise RuntimeError("The extension configuration omits a base format") linked_files = 0 source_captures = base_dir / "captures" for source in source_captures.rglob("*"): if not source.is_file(): continue relative = source.relative_to(source_captures) destination = results_dir / "captures" / relative destination.parent.mkdir(parents=True, exist_ok=True) if destination.exists(): if destination.stat().st_size != source.stat().st_size: raise RuntimeError(f"Imported capture size mismatch: {destination}") continue os.link(source, destination) linked_files += 1 copied_files = 0 for directory_name in ("telemetry", "advanced_metric_cache", "validation"): source_root = base_dir / directory_name if not source_root.is_dir(): continue for source in source_root.rglob("*"): if not source.is_file(): continue destination = results_dir / directory_name / source.relative_to(source_root) destination.parent.mkdir(parents=True, exist_ok=True) if not destination.exists(): shutil.copy2(source, destination) copied_files += 1 source_runs = base_dir / "runs.jsonl" destination_runs = results_dir / "runs.jsonl" if source_runs.is_file() and not destination_runs.exists(): shutil.copy2(source_runs, destination_runs) copied_files += 1 atomic_json( marker, { "complete": True, "base_results_dir": str(base_dir), "base_manifest_sha256": base_manifest_hash, "imported_formats": imported_formats, "hardlinked_capture_files": linked_files, "copied_support_files": copied_files, "completed_unix": time.time(), }, ) def completed_capture(results_dir: Path, run_id: str) -> dict[str, Any] | None: directory = results_dir / "captures" / run_id metadata_path = directory / "metadata.json" required = [metadata_path, directory / "image.png", directory / "decoded_float32.npy", directory / "final_latent_float32.npy"] if not all(path.is_file() for path in required): return None metadata = json.loads(metadata_path.read_text(encoding="utf-8")) return metadata if {"sampling", "vae_decode", "output"}.issubset(metadata) else None def run_one(server: ComfyServer, config: dict[str, Any], format_id: str, prompt: dict[str, str], replicate: int, run_id: str, scored: bool, capture_steps: bool, phase: str) -> dict[str, Any]: existing = completed_capture(server.results_dir, run_id) if existing is not None: return {"run_id": run_id, "format_id": format_id, "phase": phase, "scored": scored, "status": "skipped_complete", "metadata": existing} workflow, seed = build_workflow(config, format_id, prompt, replicate, run_id, scored, capture_steps) started = time.time() record = { "run_id": run_id, "format_id": format_id, "format_label": config["formats"][format_id]["label"], "checkpoint": config["formats"][format_id]["checkpoint"], "phase": phase, "scored": scored, "capture_steps": capture_steps, "prompt_id": prompt["id"], "prompt_category": prompt["category"], "replicate": replicate, "seed": seed, "api_started_unix": started, } try: history = server.execute(workflow, int(config["server"]["prompt_timeout_seconds"])) record["api_finished_unix"] = time.time() record["api_duration_seconds"] = record["api_finished_unix"] - started record["status"] = "complete" record["history_status"] = history.get("status", {}) metadata = completed_capture(server.results_dir, run_id) if metadata is None: raise RuntimeError(f"ComfyUI completed {run_id}, but benchmark artifacts are incomplete") record["metadata"] = metadata except Exception as error: record["api_finished_unix"] = time.time() record["api_duration_seconds"] = record["api_finished_unix"] - started record["status"] = "error" record["error_type"] = type(error).__name__ record["error"] = str(error) append_jsonl(server.results_dir / "runs.jsonl", record) raise append_jsonl(server.results_dir / "runs.jsonl", record) return record def write_run_matrix(config: dict[str, Any], results_dir: Path) -> list[dict[str, Any]]: matrix = [] for prompt in config["prompts"]: for replicate in range(int(config["campaign"]["replicates"])): seed = benchmark_seed(config["benchmark_id"], prompt["id"], replicate) for format_id, format_config in config["formats"].items(): matrix.append( { "run_id": f"{prompt['id']}__r{replicate}__{format_id}", "prompt_id": prompt["id"], "category": prompt["category"], "replicate": replicate, "seed": seed, "format_id": format_id, "checkpoint": format_config["checkpoint"], } ) atomic_json(results_dir / "run_matrix.json", matrix) return matrix def run_preflight(config: dict[str, Any], results_dir: Path, capture_steps: bool) -> None: prompt = config["prompts"][0] for format_id in active_formats(config): print(f"Preflight: {format_id}", flush=True) server = ComfyServer(config, f"preflight_{format_id}", results_dir) try: server.start() run_one( server, config, format_id, prompt, 0, f"preflight__{format_id}", scored=False, capture_steps=capture_steps, phase="preflight", ) finally: server.stop() noise_hashes = [] for format_id in config["formats"]: metadata = completed_capture(results_dir, f"preflight__{format_id}") if metadata is None: raise RuntimeError(f"Missing preflight result for {format_id}") noise_hashes.append(metadata["sampling"]["noise_sha256"]) if len(set(noise_hashes)) != 1: raise RuntimeError(f"Initial noise differs across formats: {noise_hashes}") atomic_json(results_dir / "preflight.json", {"passed": True, "completed_unix": time.time(), "noise_sha256": noise_hashes[0]}) def run_campaign(config: dict[str, Any], results_dir: Path, capture_steps: bool) -> None: preflight_path = results_dir / "preflight.json" if not preflight_path.is_file() or not json.loads(preflight_path.read_text(encoding="utf-8")).get("passed"): raise RuntimeError("Preflight must pass before the scored generation campaign") bridge_formats = list(config["campaign"].get("bridge_formats", [])) bridge_repeats = int(config["campaign"].get("bridge_repeats", 0)) bridge_marker = results_dir / "bridge_complete.json" if bridge_formats and bridge_repeats and not bridge_marker.is_file(): first_prompt = config["prompts"][0] bridge_rows = [] for format_id in bridge_formats: server = ComfyServer(config, f"bridge_{format_id}", results_dir) try: server.start() for repeat in range(bridge_repeats): record = run_one( server, config, format_id, first_prompt, 0, f"bridge__{format_id}__{repeat}", scored=False, capture_steps=False, phase="bridge", ) bridge_rows.append({"format_id": format_id, "repeat": repeat, "sampling_seconds": record["metadata"]["sampling"]["duration_seconds"]}) finally: server.stop() atomic_json(bridge_marker, {"complete": True, "rows": bridge_rows, "completed_unix": time.time()}) format_order = active_formats(config) random.Random(int(config["campaign"]["format_order_seed"])).shuffle(format_order) atomic_json(results_dir / "format_order.json", {"active_extension_order": format_order}) first_prompt = config["prompts"][0] for format_id in format_order: print(f"Campaign format: {format_id}", flush=True) server = ComfyServer(config, format_id, results_dir) try: server.start() repeatability = [] for repeat in range(3): record = run_one( server, config, format_id, first_prompt, 0, f"repeatability__{format_id}__{repeat}", scored=False, capture_steps=False, phase="repeatability", ) repeatability.append(record["metadata"]["output"]["image_sha256"]) if len(set(repeatability)) != 1: raise RuntimeError(f"Repeatability failed for {format_id}: {repeatability}") for prompt in config["prompts"]: for replicate in range(int(config["campaign"]["replicates"])): run_id = f"{prompt['id']}__r{replicate}__{format_id}" print(f" {run_id}", flush=True) run_one( server, config, format_id, prompt, replicate, run_id, scored=True, capture_steps=capture_steps, phase="scored", ) finally: server.stop() missing = [] for prompt in config["prompts"]: for replicate in range(int(config["campaign"]["replicates"])): for format_id in config["formats"]: run_id = f"{prompt['id']}__r{replicate}__{format_id}" if completed_capture(results_dir, run_id) is None: missing.append(run_id) if missing: raise RuntimeError(f"Campaign incomplete; missing {len(missing)} captures: {missing[:10]}") atomic_json( results_dir / "campaign_complete.json", { "passed": True, "completed_unix": time.time(), "scored_runs": expected_scored_runs(config), "new_scored_runs": len(config["prompts"]) * int(config["campaign"]["replicates"]) * len(active_formats(config)), }, ) def ensure_results(config: dict[str, Any], skip_hashes: bool) -> Path: results_dir = Path(config["_results_dir"]) results_dir.mkdir(parents=True, exist_ok=True) manifest_path = results_dir / "manifest.json" if manifest_path.exists(): manifest = json.loads(manifest_path.read_text(encoding="utf-8")) if manifest.get("config_sha256") != config["_config_sha256"]: raise RuntimeError("Existing results were created with a different configuration; use a new results directory") else: atomic_json(manifest_path, collect_manifest(config, skip_hashes=skip_hashes)) write_run_matrix(config, results_dir) import_base_results(config, results_dir) return results_dir def parse_args() -> argparse.Namespace: parser = argparse.ArgumentParser(description="Reproducible Krea 2 Turbo checkpoint-format benchmark") parser.add_argument("stage", choices=["preflight", "weights", "generate", "analyze", "sheets", "report", "verify", "all"]) parser.add_argument("--config", type=Path, default=BENCHMARK_DIR / "config.json") parser.add_argument("--skip-hashes", action="store_true") parser.add_argument("--no-step-capture", action="store_true") return parser.parse_args() def main() -> int: args = parse_args() config = load_configuration(args.config) results_dir = ensure_results(config, skip_hashes=args.skip_hashes) capture_steps = bool(config["campaign"]["capture_steps"]) and not args.no_step_capture if args.stage in {"preflight", "all"}: run_preflight(config, results_dir, capture_steps=capture_steps) if args.stage in {"weights", "all"}: import weight_audit weight_audit.audit(config, results_dir) if args.stage in {"generate", "all"}: run_campaign(config, results_dir, capture_steps=capture_steps) if args.stage in {"analyze", "all"}: enable_analysis_vendor() import analysis_core import advanced_metrics import performance_analysis analysis_core.analyze(config, results_dir) advanced_metrics.analyze(config, results_dir) performance_analysis.analyze(config, results_dir) if args.stage in {"sheets", "all"}: enable_analysis_vendor() import comparison_sheets comparison_sheets.generate(config, results_dir) if args.stage in {"report", "all"}: import report_generator report_generator.generate(config, results_dir) if args.stage in {"verify", "all"}: import verify_results result = verify_results.verify(config, results_dir) print(json.dumps(result, indent=2, sort_keys=True)) return 0 if __name__ == "__main__": try: raise SystemExit(main()) except KeyboardInterrupt: print("Interrupted", file=sys.stderr) raise SystemExit(130)