from __future__ import annotations import argparse import csv import gc import importlib import importlib.util import json import math import sys import time from pathlib import Path from typing import Any import torch from safetensors import safe_open FIELDS = [ "format_id", "parameter", "subsystem", "quantized", "reference_dtype", "candidate_dtype", "storage_dtype", "elements", "mae", "rmse", "mean_signed_error", "relative_l2", "cosine_similarity", "snr_db", "max_abs_error", "abs_error_p50_sampled", "abs_error_p95_sampled", "abs_error_p99_sampled", "abs_error_p999_sampled", "storage_endpoint_rate", "sum_abs_error", "sum_squared_error", "sum_signed_error", "reference_sum_squared", "candidate_sum_squared", "dot_product", ] def subsystem(name: str) -> str: if name.startswith("blocks."): if ".attn." in name: return "main_blocks.attention" if ".mlp." in name: return "main_blocks.mlp" return "main_blocks.norm_modulation" if name.startswith("txtfusion.layerwise_blocks"): return "text_fusion.layerwise" if name.startswith("txtfusion.refiner_blocks"): return "text_fusion.refiner" if name.startswith("txtfusion"): return "text_fusion.other" if name.startswith("first"): return "input_projection" if name.startswith("last"): return "output_projection" if name.startswith("tmlp") or name.startswith("tproj") or name.startswith("txtmlp"): return "conditioning_projection" return "other" def endpoint_rate(parameter: torch.Tensor) -> float | None: qdata = getattr(parameter, "_qdata", None) if qdata is None: return None qdata = qdata.detach().cpu() layout = str(getattr(parameter, "_layout_cls", getattr(parameter, "layout_type", ""))) if "ConvRotW4A4" in layout: packed = qdata.to(torch.uint8).reshape(-1) low = (packed & 0x0F).to(torch.int16) high = ((packed >> 4) & 0x0F).to(torch.int16) low = torch.where(low >= 8, low - 16, low) high = torch.where(high >= 8, high - 16, high) values = torch.cat((low, high)) return float(((values <= -8) | (values >= 7)).float().mean()) if qdata.dtype == torch.int8: return float((qdata.to(torch.int16).abs() >= 127).float().mean()) if qdata.dtype in {torch.float8_e4m3fn, torch.float8_e5m2}: maximum = torch.finfo(qdata.dtype).max return float((qdata.float().abs() >= maximum).float().mean()) return None def load_comfyui_gguf(comfy_dir: Path): package_dir = comfy_dir / "custom_nodes" / "ComfyUI-GGUF" init_path = package_dir / "__init__.py" if not init_path.is_file(): raise RuntimeError(f"ComfyUI-GGUF is not installed at {package_dir}") package_name = "krea_benchmark_comfyui_gguf" if package_name not in sys.modules: spec = importlib.util.spec_from_file_location(package_name, init_path, submodule_search_locations=[str(package_dir)]) if spec is None or spec.loader is None: raise RuntimeError(f"Could not load ComfyUI-GGUF from {init_path}") module = importlib.util.module_from_spec(spec) sys.modules[package_name] = module spec.loader.exec_module(module) return importlib.import_module(f"{package_name}.loader"), importlib.import_module(f"{package_name}.dequant") def parameter_metrics(reference: torch.Tensor, candidate: torch.Tensor, sample_limit: int = 65536, chunk_size: int = 4_194_304) -> dict[str, float]: if reference.shape != candidate.shape: raise ValueError(f"Shape mismatch: reference={reference.shape}, candidate={candidate.shape}") ref_flat = reference.detach().cpu().reshape(-1) candidate_flat = candidate.detach().cpu().reshape(-1) count = ref_flat.numel() sum_abs = 0.0 sum_sq = 0.0 sum_signed = 0.0 ref_sq = 0.0 candidate_sq = 0.0 dot = 0.0 maximum = 0.0 for start in range(0, count, chunk_size): end = min(count, start + chunk_size) ref = ref_flat[start:end].float() cand = candidate_flat[start:end].float() error = cand - ref sum_abs += float(error.abs().double().sum()) sum_sq += float(error.double().square().sum()) sum_signed += float(error.double().sum()) ref_sq += float(ref.double().square().sum()) candidate_sq += float(cand.double().square().sum()) dot += float((ref.double() * cand.double()).sum()) maximum = max(maximum, float(error.abs().max())) sample_count = min(count, sample_limit) if sample_count == count: indices = None errors = (candidate_flat.float() - ref_flat.float()).abs() else: indices = torch.linspace(0, count - 1, sample_count, dtype=torch.float64).round().long() errors = (candidate_flat[indices].float() - ref_flat[indices].float()).abs() quantiles = torch.quantile(errors, torch.tensor([0.5, 0.95, 0.99, 0.999], dtype=torch.float32)).tolist() eps = 1e-300 return { "elements": count, "mae": sum_abs / count, "rmse": math.sqrt(sum_sq / count), "mean_signed_error": sum_signed / count, "relative_l2": math.sqrt(sum_sq / max(ref_sq, eps)), "cosine_similarity": dot / max(math.sqrt(ref_sq * candidate_sq), eps), "snr_db": 10.0 * math.log10(max(ref_sq, eps) / max(sum_sq, eps)), "max_abs_error": maximum, "abs_error_p50_sampled": quantiles[0], "abs_error_p95_sampled": quantiles[1], "abs_error_p99_sampled": quantiles[2], "abs_error_p999_sampled": quantiles[3], "sum_abs_error": sum_abs, "sum_squared_error": sum_sq, "sum_signed_error": sum_signed, "reference_sum_squared": ref_sq, "candidate_sum_squared": candidate_sq, "dot_product": dot, } def aggregate(rows: list[dict[str, Any]]) -> dict[str, Any]: count = sum(int(row["elements"]) for row in rows) sum_abs = sum(float(row["sum_abs_error"]) for row in rows) sum_sq = sum(float(row["sum_squared_error"]) for row in rows) sum_signed = sum(float(row["sum_signed_error"]) for row in rows) ref_sq = sum(float(row["reference_sum_squared"]) for row in rows) candidate_sq = sum(float(row["candidate_sum_squared"]) for row in rows) dot = sum(float(row["dot_product"]) for row in rows) eps = 1e-300 return { "parameter_tensors": len(rows), "quantized_parameter_tensors": sum(bool(row["quantized"]) for row in rows), "elements": count, "mae": sum_abs / count, "rmse": math.sqrt(sum_sq / count), "mean_signed_error": sum_signed / count, "relative_l2": math.sqrt(sum_sq / max(ref_sq, eps)), "cosine_similarity": dot / max(math.sqrt(ref_sq * candidate_sq), eps), "snr_db": 10.0 * math.log10(max(ref_sq, eps) / max(sum_sq, eps)), "max_abs_error": max(float(row["max_abs_error"]) for row in rows), } def write_rows(path: Path, rows: list[dict[str, Any]]) -> None: path.parent.mkdir(parents=True, exist_ok=True) temporary = path.with_suffix(path.suffix + ".tmp") with temporary.open("w", encoding="utf-8", newline="") as stream: writer = csv.DictWriter(stream, fieldnames=FIELDS, extrasaction="ignore") writer.writeheader() writer.writerows(rows) temporary.replace(path) def audit(config: dict[str, Any], results_dir: Path) -> None: comfy_dir = Path(config["_portable_root"]) / "ComfyUI" if str(comfy_dir) not in sys.path: sys.path.insert(0, str(comfy_dir)) import comfy.sd from comfy.quant_ops import QuantizedTensor models_dir = Path(config["_models_dir"]) reference_path = models_dir / config["formats"]["bf16"]["checkpoint"] output_dir = results_dir / "metrics" output_dir.mkdir(parents=True, exist_ok=True) summaries = { "bf16": { "reference": True, "parameter_tensors": 430, "quantized_parameter_tensors": 0, "mae": 0.0, "rmse": 0.0, "relative_l2": 0.0, "cosine_similarity": 1.0, "snr_db": None, } } combined_rows = [] gguf_loader = gguf_dequant = None for format_id, format_config in config["formats"].items(): if format_id == "bf16": continue print(f"Weight audit: {format_id}", flush=True) started = time.time() rows = [] ignored_storage_tensors = [] patcher = model = None with safe_open(reference_path, framework="pt", device="cpu") as reference_file: reference_keys = set(reference_file.keys()) checkpoint_path = models_dir / format_config["checkpoint"] if format_config.get("loader", "unet") == "gguf": if gguf_loader is None: gguf_loader, gguf_dequant = load_comfyui_gguf(comfy_dir) state_dict, _extra = gguf_loader.gguf_sd_loader(str(checkpoint_path)) ignored_storage_tensors = sorted(set(state_dict) - reference_keys) candidates = [(name, value) for name, value in state_dict.items() if name in reference_keys] for index, (name, parameter) in enumerate(candidates, start=1): if name not in reference_keys: raise KeyError(f"Logical GGUF parameter {name!r} is absent from BF16 checkpoint") is_quantized = bool(gguf_dequant.is_quantized(parameter)) candidate = gguf_dequant.dequantize_tensor(parameter, dtype=torch.float32) if is_quantized else parameter.detach() reference = reference_file.get_tensor(name) metrics = parameter_metrics(reference, candidate) tensor_type = getattr(parameter, "tensor_type", None) rows.append( { "format_id": format_id, "parameter": name, "subsystem": subsystem(name), "quantized": is_quantized, "reference_dtype": str(reference.dtype), "candidate_dtype": str(candidate.dtype), "storage_dtype": getattr(tensor_type, "name", str(tensor_type or parameter.dtype)), "storage_endpoint_rate": None, **metrics, } ) if index % 20 == 0: print(f" {index}/{len(candidates)} parameters", flush=True) del reference, candidate del state_dict, candidates else: patcher = comfy.sd.load_diffusion_model(str(checkpoint_path)) model = patcher.model.diffusion_model candidates = list(model.named_parameters()) for index, (name, parameter) in enumerate(candidates, start=1): if name not in reference_keys: raise KeyError(f"Logical parameter {name!r} is absent from BF16 checkpoint") is_quantized = isinstance(parameter, QuantizedTensor) candidate = parameter.dequantize() if is_quantized else parameter.detach() reference = reference_file.get_tensor(name) metrics = parameter_metrics(reference, candidate) rows.append( { "format_id": format_id, "parameter": name, "subsystem": subsystem(name), "quantized": is_quantized, "reference_dtype": str(reference.dtype), "candidate_dtype": str(candidate.dtype), "storage_dtype": str(getattr(parameter, "_qdata", parameter).dtype), "storage_endpoint_rate": endpoint_rate(parameter), **metrics, } ) if index % 20 == 0: print(f" {index}/{len(candidates)} parameters", flush=True) del reference, candidate write_rows(output_dir / f"weight_parameters_{format_id}.csv", rows) combined_rows.extend(rows) summary = aggregate(rows) summary["duration_seconds"] = time.time() - started summary["ignored_storage_tensors"] = ignored_storage_tensors by_subsystem = {} for group in sorted({row["subsystem"] for row in rows}): by_subsystem[group] = aggregate([row for row in rows if row["subsystem"] == group]) summary["by_subsystem"] = by_subsystem summaries[format_id] = summary (output_dir / f"weight_summary_{format_id}.json").write_text(json.dumps(summary, indent=2, sort_keys=True), encoding="utf-8") del model, patcher, rows gc.collect() if torch.cuda.is_available(): torch.cuda.empty_cache() write_rows(output_dir / "weight_parameters_all.csv", combined_rows) (output_dir / "weight_summary.json").write_text(json.dumps(summaries, indent=2, sort_keys=True), encoding="utf-8") def main() -> int: parser = argparse.ArgumentParser() parser.add_argument("--config", type=Path, required=True) args = parser.parse_args() import krea_benchmark config = krea_benchmark.load_configuration(args.config) results_dir = Path(config["_results_dir"]) audit(config, results_dir) return 0 if __name__ == "__main__": raise SystemExit(main())