#!/usr/bin/env python3 """Fidelity audit for the mixed-Q2 V4.1 expert checkpoint. For a sample of requantised expert tensors, decode the source MXFP4 blocks, decode the produced ggml blocks with the pinned llama.cpp gguf-py dequantisers, and report cosine similarity and relative RMS error per projection. Optionally recompute the quantisation on the current machine and compare digests with the stored manifest, which documents that the reference quantisers are deterministic per build and CPU target but not bit-identical between SIMD architectures (for example AVX-512 x86 versus ARM NEON). Read-only: it never writes to the artifact directory. """ from __future__ import annotations import argparse import hashlib import json import sys from pathlib import Path import numpy as np sys.path.insert(0, str(Path(__file__).resolve().parent)) from gguf.constants import GGMLQuantizationType from gguf.quants import dequantize from v41_quant_experts import GgmlQuantizer, decode_mxfp4, read_safetensors_header def sample_tensors(plan: dict, per_projection: int, rng: np.random.Generator) -> list[dict]: by_projection: dict[str, list[dict]] = {} for shard in plan["shards"]: for tensor in shard["tensors"]: if tensor["role"] != "quantised": continue by_projection.setdefault(tensor["ggml_type"], []).append(tensor) picked: list[dict] = [] for type_name, tensors in sorted(by_projection.items()): if tensors: index = rng.choice(len(tensors), size=min(per_projection, len(tensors)), replace=False) picked.extend(tensors[int(i)] for i in index) return picked def audit( source: Path, out: Path, plan: dict, per_projection: int, seed: int, ggml_libs: tuple[str, ...] = (), ) -> dict: rng = np.random.default_rng(seed) dropped = {(t["shard"], t["name"][: -len(".scale")]): t for t in plan["dropped"]} quantizer = GgmlQuantizer(ggml_libs) if ggml_libs else None rows = [] for tensor in sample_tensors(plan, per_projection, rng): scale = dropped.get((tensor["shard"], tensor["name"][: -len(".weight")])) if scale is None: raise RuntimeError(f"{tensor['name']}: missing source scale entry") with open(source / tensor["shard"], "rb") as fh: fh.seek(tensor["data_start"] + tensor["begin"]) packed = np.frombuffer( fh.read(tensor["end"] - tensor["begin"]), dtype=np.uint8 ).reshape(tensor["shape"]) fh.seek(scale["data_start"] + scale["begin"]) scales = np.frombuffer(fh.read(scale["end"] - scale["begin"]), dtype=np.uint8).reshape( scale["shape"] ) reference = decode_mxfp4(packed, scales) shard_manifest = json.loads((out / (tensor["out_shard"] + ".manifest.json")).read_text()) entry = next(t for t in shard_manifest["tensors"] if t["name"] == tensor["name"]) header, data_start = read_safetensors_header(out / tensor["out_shard"]) begin, end = header[tensor["name"]]["data_offsets"] with open(out / tensor["out_shard"], "rb") as fh: fh.seek(data_start + begin) blocks = np.frombuffer(fh.read(end - begin), dtype=np.uint8) qtype = GGMLQuantizationType[tensor["ggml_type"]] recovered = dequantize(blocks, qtype).reshape(reference.shape[0], -1) a = reference.ravel().astype(np.float64) b = recovered.ravel().astype(np.float64) cosine = float(a @ b / (np.linalg.norm(a) * np.linalg.norm(b))) rel_rms = float(np.sqrt(((a - b) ** 2).mean()) / np.sqrt((a**2).mean())) row = { "name": tensor["name"], "ggml_type": tensor["ggml_type"], "weights": int(reference.size), "cosine": round(cosine, 6), "relative_rms_error": round(rel_rms, 6), "output_sha256": entry["output_sha256"], } if quantizer is not None: importance = np.ones(reference.shape[1], dtype=np.float32) digest = hashlib.sha256( quantizer.quantize(reference, tensor["ggml_type"], importance).tobytes() ).hexdigest() again = hashlib.sha256( quantizer.quantize(reference, tensor["ggml_type"], importance).tobytes() ).hexdigest() row["recompute"] = { "deterministic": digest == again, "matches_stored": digest == entry["output_sha256"], "digest": digest, } rows.append(row) summary: dict[str, dict[str, float]] = {} for type_name in sorted({row["ggml_type"] for row in rows}): values = [row for row in rows if row["ggml_type"] == type_name] entry_summary = { "tensors": len(values), "weights": sum(v["weights"] for v in values), "cosine_min": min(v["cosine"] for v in values), "cosine_mean": round(float(np.mean([v["cosine"] for v in values])), 6), "relative_rms_error_max": max(v["relative_rms_error"] for v in values), "relative_rms_error_mean": round( float(np.mean([v["relative_rms_error"] for v in values])), 6 ), } recomputed = [v["recompute"] for v in values if "recompute" in v] if recomputed: entry_summary["recompute_deterministic"] = all(r["deterministic"] for r in recomputed) entry_summary["recompute_matches_stored"] = all(r["matches_stored"] for r in recomputed) summary[type_name] = entry_summary return {"seed": seed, "per_projection": per_projection, "summary": summary, "tensors": rows} def main() -> int: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--source", type=Path, required=True) parser.add_argument("--out", type=Path, required=True) parser.add_argument("--per-projection", type=int, default=8) parser.add_argument("--seed", type=int, default=20260910) parser.add_argument( "--ggml-lib", action="append", default=[], help="ggml shared library (repeat in load order) to enable the digest recompute check", ) parser.add_argument("--json", type=Path, help="write the audit record here") args = parser.parse_args() plan = json.loads((args.out / "plan.json").read_text()) record = audit( args.source, args.out, plan, args.per_projection, args.seed, tuple(args.ggml_lib) ) text = json.dumps(record, indent=1) if args.json: args.json.write_text(text + "\n") print(json.dumps(record["summary"], indent=1)) return 0 if __name__ == "__main__": sys.exit(main())