Download v41_quant_kernel_smoke.py from apetersson/v41-quant-worker: direct link, hf CLI and curl.
- Browser
- Download file 6.76 kB
-
https://huggingface.co/datasets/apetersson/v41-quant-worker/resolve/main/v41_quant_kernel_smoke.py
- Command line
-
hf download hf://datasets/apetersson/v41-quant-worker/v41_quant_kernel_smoke.py
-
curl -L -o v41_quant_kernel_smoke.py https://huggingface.co/datasets/apetersson/v41-quant-worker/resolve/main/v41_quant_kernel_smoke.py
6.76 kB
| #!/usr/bin/env python3 | |
| """Kernel-level smoke test for the quantised V4.1 expert blocks on a real ggml backend. | |
| Loads expert tensors straight out of the artifact produced by ``v41_quant_experts.py`` | |
| (raw IQ2_XXS / Q2_K block bytes), multiplies them by an activation row through ggml's | |
| ``ggml_mul_mat`` on the selected backend (CPU or CUDA), and compares the result with a | |
| float32 reference computed from the original MXFP4 decode. Also reports achieved weight | |
| bandwidth so the one-B200 throughput assumptions can be checked against hardware. | |
| This proves the blocks execute on the target GPU. It is not a model run: no tokenizer, no | |
| attention, no generation. Plan gates for a kernel qualification are rel-RMS <= 1% and | |
| cosine >= 0.999 against the fp32 reference. | |
| Usage: | |
| python3 v41_quant_kernel_smoke.py --artifact OUT --ggml-lib /opt/llama.cpp/build/bin \\ | |
| --tensors 4 --json kernel-smoke.json | |
| python3 v41_quant_kernel_smoke.py --artifact OUT --ggml-lib ... --cpu-only | |
| """ | |
| from __future__ import annotations | |
| import argparse | |
| import json | |
| import os | |
| import sys | |
| from pathlib import Path | |
| import numpy as np | |
| sys.path.insert(0, str(Path(__file__).resolve().parent)) | |
| from v41_quant_experts import ( # noqa: E402 | |
| GGML_TYPE_IDS, | |
| decode_mxfp4, | |
| read_safetensors_header, | |
| ) | |
| from gguf.constants import GGMLQuantizationType # noqa: E402 | |
| from gguf.quants import dequantize # noqa: E402 | |
| def load_expert_tensor(artifact: Path, name: str, shard: str, shape: tuple[int, ...]) -> bytes: | |
| header, start = read_safetensors_header(artifact / shard) | |
| begin, end = header[name]["data_offsets"] | |
| with open(artifact / shard, "rb") as fh: | |
| fh.seek(start + begin) | |
| return fh.read(end - begin) | |
| def run_kernel( | |
| kernel_bin: Path, | |
| blocks: bytes, | |
| rows: int, | |
| cols: int, | |
| ggml_type: str, | |
| activation: np.ndarray, | |
| work: Path, | |
| ) -> tuple[np.ndarray, float]: | |
| """Execute one quantised tensor through the ggml harness and return (result, GiB/s).""" | |
| import subprocess | |
| import tempfile | |
| with tempfile.TemporaryDirectory(dir=work) as tmp: | |
| tmp_path = Path(tmp) | |
| (tmp_path / "blocks.bin").write_bytes(blocks) | |
| (tmp_path / "act.f32").write_bytes(activation.astype(np.float32).tobytes()) | |
| out = tmp_path / "out.f32" | |
| proc = subprocess.run( | |
| [ | |
| str(kernel_bin), | |
| str(tmp_path / "blocks.bin"), | |
| str(rows), | |
| str(cols), | |
| str(GGML_TYPE_IDS[ggml_type]), | |
| str(tmp_path / "act.f32"), | |
| str(out), | |
| str(os.cpu_count() or 4), | |
| ], | |
| capture_output=True, | |
| text=True, | |
| ) | |
| if proc.returncode != 0: | |
| raise SystemExit(f"kernel_smoke failed: {proc.stderr.strip()}") | |
| bandwidth = 0.0 | |
| for line in proc.stderr.splitlines(): | |
| if "GiB_per_s=" in line: | |
| bandwidth = float(line.rsplit("GiB_per_s=", 1)[1]) | |
| result = np.frombuffer(out.read_bytes(), dtype=np.float32) | |
| return result, bandwidth | |
| def main() -> int: | |
| parser = argparse.ArgumentParser(description=__doc__) | |
| parser.add_argument("--artifact", type=Path, required=True) | |
| parser.add_argument("--kernel-bin", type=Path, help="compiled kernel_smoke binary") | |
| parser.add_argument("--tensors", type=int, default=4, help="expert tensors to test") | |
| parser.add_argument("--seed", type=int, default=20260910) | |
| parser.add_argument("--json", type=Path) | |
| parser.add_argument("--work", type=Path, default=Path("/tmp")) | |
| args = parser.parse_args() | |
| plan = json.loads((args.artifact / "plan.json").read_text()) | |
| quantised = [ | |
| tensor | |
| for shard in plan["shards"] | |
| for tensor in shard["tensors"] | |
| if tensor["role"] == "quantised" | |
| ] | |
| if not quantised: | |
| raise SystemExit("artifact has no quantised expert tensors") | |
| rng = np.random.default_rng(args.seed) | |
| step = max(1, len(quantised) // args.tensors) | |
| picked = quantised[::step][: args.tensors] | |
| results = [] | |
| for tensor in picked: | |
| raw = load_expert_tensor( | |
| args.artifact, tensor["name"], tensor["out_shard"], tuple(tensor["out_shape"]) | |
| ) | |
| expected = int(np.prod(tensor["out_shape"])) | |
| if len(raw) != expected: | |
| raise SystemExit(f"{tensor['name']}: {len(raw)} bytes != planned {expected}") | |
| rows, row_bytes = tensor["out_shape"] | |
| block_bytes = 66 if tensor["ggml_type"] == "IQ2_XXS" else 84 | |
| cols = row_bytes // block_bytes * 256 | |
| entry = { | |
| "name": tensor["name"], | |
| "ggml_type": tensor["ggml_type"], | |
| "rows": rows, | |
| "cols": cols, | |
| "bytes": len(raw), | |
| } | |
| if args.kernel_bin: | |
| activation = rng.standard_normal(cols).astype(np.float32) | |
| result, bandwidth = run_kernel( | |
| args.kernel_bin, raw, rows, cols, tensor["ggml_type"], activation, args.work | |
| ) | |
| blocks = np.frombuffer(raw, dtype=np.uint8) | |
| qtype = GGMLQuantizationType[tensor["ggml_type"]] | |
| reference = dequantize(blocks, qtype).reshape(rows, cols).astype(np.float64) | |
| expected_vec = reference @ activation.astype(np.float64) | |
| got = result.astype(np.float64) | |
| cosine = float(expected_vec @ got / (np.linalg.norm(expected_vec) * np.linalg.norm(got))) | |
| rel_rms = float( | |
| np.sqrt(((expected_vec - got) ** 2).mean()) / np.sqrt((expected_vec**2).mean()) | |
| ) | |
| entry.update( | |
| { | |
| "cosine_vs_reference": round(cosine, 8), | |
| "relative_rms_vs_reference": round(rel_rms, 8), | |
| "weight_bandwidth_GiB_per_s": round(bandwidth, 3), | |
| "finite": bool(np.isfinite(got).all()), | |
| } | |
| ) | |
| results.append(entry) | |
| record = { | |
| "artifact": str(args.artifact), | |
| "kernel_bin": str(args.kernel_bin) if args.kernel_bin else None, | |
| "tensors": results, | |
| "gates": {"cosine_min": 0.999, "relative_rms_max": 0.01}, | |
| } | |
| if args.kernel_bin: | |
| ok = all( | |
| r["cosine_vs_reference"] >= 0.999 and r["relative_rms_vs_reference"] <= 0.01 | |
| for r in results | |
| ) | |
| # cosine here compares the kernel against its own dequantisation, so it must be exact; | |
| # a relaxed gate would hide block-format errors. | |
| record["kernel_agrees_with_dequantised_reference"] = ok | |
| print(json.dumps(record, indent=1)) | |
| if args.json: | |
| args.json.write_text(json.dumps(record, indent=1) + "\n") | |
| return 0 | |
| if __name__ == "__main__": | |
| sys.exit(main()) | |