apetersson commited on
Commit
dc11375
·
verified ·
1 Parent(s): f6662df

v41 quant: payload refresh

Browse files
Files changed (1) hide show
  1. v41_quant_kernel_smoke.py +178 -0
v41_quant_kernel_smoke.py ADDED
@@ -0,0 +1,178 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Kernel-level smoke test for the quantised V4.1 expert blocks on a real ggml backend.
3
+
4
+ Loads expert tensors straight out of the artifact produced by ``v41_quant_experts.py``
5
+ (raw IQ2_XXS / Q2_K block bytes), multiplies them by an activation row through ggml's
6
+ ``ggml_mul_mat`` on the selected backend (CPU or CUDA), and compares the result with a
7
+ float32 reference computed from the original MXFP4 decode. Also reports achieved weight
8
+ bandwidth so the one-B200 throughput assumptions can be checked against hardware.
9
+
10
+ This proves the blocks execute on the target GPU. It is not a model run: no tokenizer, no
11
+ attention, no generation. Plan gates for a kernel qualification are rel-RMS <= 1% and
12
+ cosine >= 0.999 against the fp32 reference.
13
+
14
+ Usage:
15
+ python3 v41_quant_kernel_smoke.py --artifact OUT --ggml-lib /opt/llama.cpp/build/bin \\
16
+ --tensors 4 --json kernel-smoke.json
17
+ python3 v41_quant_kernel_smoke.py --artifact OUT --ggml-lib ... --cpu-only
18
+ """
19
+
20
+ from __future__ import annotations
21
+
22
+ import argparse
23
+ import json
24
+ import os
25
+ import sys
26
+ from pathlib import Path
27
+
28
+ import numpy as np
29
+
30
+ sys.path.insert(0, str(Path(__file__).resolve().parent))
31
+ from v41_quant_experts import ( # noqa: E402
32
+ GGML_TYPE_IDS,
33
+ decode_mxfp4,
34
+ read_safetensors_header,
35
+ )
36
+
37
+ from gguf.constants import GGMLQuantizationType # noqa: E402
38
+ from gguf.quants import dequantize # noqa: E402
39
+
40
+
41
+ def load_expert_tensor(artifact: Path, name: str, shard: str, shape: tuple[int, ...]) -> bytes:
42
+ header, start = read_safetensors_header(artifact / shard)
43
+ begin, end = header[name]["data_offsets"]
44
+ with open(artifact / shard, "rb") as fh:
45
+ fh.seek(start + begin)
46
+ return fh.read(end - begin)
47
+
48
+
49
+ def run_kernel(
50
+ kernel_bin: Path,
51
+ blocks: bytes,
52
+ rows: int,
53
+ cols: int,
54
+ ggml_type: str,
55
+ activation: np.ndarray,
56
+ work: Path,
57
+ ) -> tuple[np.ndarray, float]:
58
+ """Execute one quantised tensor through the ggml harness and return (result, GiB/s)."""
59
+ import subprocess
60
+ import tempfile
61
+
62
+ with tempfile.TemporaryDirectory(dir=work) as tmp:
63
+ tmp_path = Path(tmp)
64
+ (tmp_path / "blocks.bin").write_bytes(blocks)
65
+ (tmp_path / "act.f32").write_bytes(activation.astype(np.float32).tobytes())
66
+ out = tmp_path / "out.f32"
67
+ proc = subprocess.run(
68
+ [
69
+ str(kernel_bin),
70
+ str(tmp_path / "blocks.bin"),
71
+ str(rows),
72
+ str(cols),
73
+ str(GGML_TYPE_IDS[ggml_type]),
74
+ str(tmp_path / "act.f32"),
75
+ str(out),
76
+ str(os.cpu_count() or 4),
77
+ ],
78
+ capture_output=True,
79
+ text=True,
80
+ )
81
+ if proc.returncode != 0:
82
+ raise SystemExit(f"kernel_smoke failed: {proc.stderr.strip()}")
83
+ bandwidth = 0.0
84
+ for line in proc.stderr.splitlines():
85
+ if "GiB_per_s=" in line:
86
+ bandwidth = float(line.rsplit("GiB_per_s=", 1)[1])
87
+ result = np.frombuffer(out.read_bytes(), dtype=np.float32)
88
+ return result, bandwidth
89
+
90
+
91
+ def main() -> int:
92
+ parser = argparse.ArgumentParser(description=__doc__)
93
+ parser.add_argument("--artifact", type=Path, required=True)
94
+ parser.add_argument("--kernel-bin", type=Path, help="compiled kernel_smoke binary")
95
+ parser.add_argument("--tensors", type=int, default=4, help="expert tensors to test")
96
+ parser.add_argument("--seed", type=int, default=20260910)
97
+ parser.add_argument("--json", type=Path)
98
+ parser.add_argument("--work", type=Path, default=Path("/tmp"))
99
+ args = parser.parse_args()
100
+
101
+ plan = json.loads((args.artifact / "plan.json").read_text())
102
+ quantised = [
103
+ tensor
104
+ for shard in plan["shards"]
105
+ for tensor in shard["tensors"]
106
+ if tensor["role"] == "quantised"
107
+ ]
108
+ if not quantised:
109
+ raise SystemExit("artifact has no quantised expert tensors")
110
+
111
+ rng = np.random.default_rng(args.seed)
112
+ step = max(1, len(quantised) // args.tensors)
113
+ picked = quantised[::step][: args.tensors]
114
+
115
+ results = []
116
+ for tensor in picked:
117
+ raw = load_expert_tensor(
118
+ args.artifact, tensor["name"], tensor["out_shard"], tuple(tensor["out_shape"])
119
+ )
120
+ expected = int(np.prod(tensor["out_shape"]))
121
+ if len(raw) != expected:
122
+ raise SystemExit(f"{tensor['name']}: {len(raw)} bytes != planned {expected}")
123
+ rows, row_bytes = tensor["out_shape"]
124
+ block_bytes = 66 if tensor["ggml_type"] == "IQ2_XXS" else 84
125
+ cols = row_bytes // block_bytes * 256
126
+ entry = {
127
+ "name": tensor["name"],
128
+ "ggml_type": tensor["ggml_type"],
129
+ "rows": rows,
130
+ "cols": cols,
131
+ "bytes": len(raw),
132
+ }
133
+ if args.kernel_bin:
134
+ activation = rng.standard_normal(cols).astype(np.float32)
135
+ result, bandwidth = run_kernel(
136
+ args.kernel_bin, raw, rows, cols, tensor["ggml_type"], activation, args.work
137
+ )
138
+ blocks = np.frombuffer(raw, dtype=np.uint8)
139
+ qtype = GGMLQuantizationType[tensor["ggml_type"]]
140
+ reference = dequantize(blocks, qtype).reshape(rows, cols).astype(np.float64)
141
+ expected_vec = reference @ activation.astype(np.float64)
142
+ got = result.astype(np.float64)
143
+ cosine = float(expected_vec @ got / (np.linalg.norm(expected_vec) * np.linalg.norm(got)))
144
+ rel_rms = float(
145
+ np.sqrt(((expected_vec - got) ** 2).mean()) / np.sqrt((expected_vec**2).mean())
146
+ )
147
+ entry.update(
148
+ {
149
+ "cosine_vs_reference": round(cosine, 8),
150
+ "relative_rms_vs_reference": round(rel_rms, 8),
151
+ "weight_bandwidth_GiB_per_s": round(bandwidth, 3),
152
+ "finite": bool(np.isfinite(got).all()),
153
+ }
154
+ )
155
+ results.append(entry)
156
+
157
+ record = {
158
+ "artifact": str(args.artifact),
159
+ "kernel_bin": str(args.kernel_bin) if args.kernel_bin else None,
160
+ "tensors": results,
161
+ "gates": {"cosine_min": 0.999, "relative_rms_max": 0.01},
162
+ }
163
+ if args.kernel_bin:
164
+ ok = all(
165
+ r["cosine_vs_reference"] >= 0.999 and r["relative_rms_vs_reference"] <= 0.01
166
+ for r in results
167
+ )
168
+ # cosine here compares the kernel against its own dequantisation, so it must be exact;
169
+ # a relaxed gate would hide block-format errors.
170
+ record["kernel_agrees_with_dequantised_reference"] = ok
171
+ print(json.dumps(record, indent=1))
172
+ if args.json:
173
+ args.json.write_text(json.dumps(record, indent=1) + "\n")
174
+ return 0
175
+
176
+
177
+ if __name__ == "__main__":
178
+ sys.exit(main())