File size: 6,761 Bytes
dc11375
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
#!/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())