File size: 6,737 Bytes
1f36c95
 
 
 
 
3b7dff8
 
 
 
 
1f36c95
 
 
 
 
3b7dff8
1f36c95
 
 
 
 
 
 
645eff0
 
3b7dff8
1f36c95
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3b7dff8
 
 
 
 
 
 
 
1f36c95
 
3b7dff8
1f36c95
 
 
 
 
 
 
645eff0
 
 
1f36c95
645eff0
 
 
1f36c95
 
645eff0
1f36c95
 
 
 
 
 
 
 
 
 
 
 
 
3b7dff8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1f36c95
3b7dff8
1f36c95
 
 
 
3b7dff8
1f36c95
 
 
 
 
 
 
 
 
3b7dff8
 
 
 
 
1f36c95
 
 
 
 
 
 
 
 
3b7dff8
 
 
 
 
 
1f36c95
 
 
 
3b7dff8
 
 
1f36c95
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
#!/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())