interplane.Get Omega
Read in your language

CUDApp

CUDA++: AIEN’s GPU machine-code toolchain, runtime and driver client for NVIDIA GPUs without the CUDA toolkit. Hardware coverage and driver replacement limits are explicit.

Brought by drakestapleton

branch main Branches Tags History

CUDApp / evidence / amd-speed-20261114 / raw / amd-report / extracted / four-bit-bundle-10c93d3d / card_q4.py

349 lines · 16786 bytes Raw Blame History
1#!/usr/bin/env python3
2# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
3"""Card run for the Q4D8 kernels on the MI300X notebook (outside instrument; Omega kernels through the Omega
4KFD launcher, no HIP in the measured path).
5
6usage: python3 card_q4.py [--skip-download] [--only CLASS,...] (cwd = the unpacked bundle directory)
7
8Phases, each logged as one line in card_q4.log and kept resumable through card_q4.state.json:
9 0 env uname, rocminfo marketing name and gfx target, python/numpy, bundle sha256 check
10 1 weights download the source shards named in expected.json from Hugging Face at the pinned revision into
11 $Q4_WEIGHTS (default /tmp/qwen3.8-27b-fp8); sha256 must equal the pin
12 2 convert q4convert.py --only those shards; every converted shard's sha256 must equal the Spark's
13 3 kernels for each tensor class: the 4-bit kernel and the FP8 (or BF16) kernel on the same real tensor,
14 repeat 1 and repeat R; output bits of the 4-bit kernel against oracle_vec (exact), FP8 output
15 against a float64 reference (relative error reported)
16 4 final results.json, SHA256SUMS, q4card.tar.gz
17"""
18import hashlib
19import json
20import os
21import pathlib
22import platform
23import re
24import struct
25import subprocess
26import sys
27import time
28import urllib.request
29
30import numpy as np
31
32HERE = pathlib.Path(__file__).resolve().parent
33sys.path.insert(0, str(HERE))
34import q4format as F # noqa: E402
35import oracle_vec as OV # noqa: E402
36from q4convert import read_header, tensor_view # noqa: E402
37
38EXP = json.loads((HERE / "expected.json").read_text())
39REV = EXP["source_rev"]
40WD = pathlib.Path(os.environ.get("Q4_WEIGHTS", "/tmp/qwen3.8-27b-fp8"))
41CD = pathlib.Path(os.environ.get("Q4_CONTAINER", "/tmp/qwen3.8-27b-q4d8"))
42OUT = HERE / "out"
43LOG = HERE / "card_q4.log"
44STATE = HERE / "card_q4.state.json"
45REPEAT = int(os.environ.get("Q4_REPEAT", "50"))
46PFX = "model.language_model."
47# (class, tensor stem, shard, kind) kind: fp8 (baseline fp8gemv_b128f) or bf16 (baseline bf16gemv2)
48CLASSES = [
49 ("gdn in_proj_qkv 10240x5120 seg4", PFX + "layers.0.linear_attn.in_proj_qkv", "layers-0.safetensors", "fp8"),
50 ("gdn in_proj_z 6144x5120 seg4", PFX + "layers.0.linear_attn.in_proj_z", "layers-0.safetensors", "fp8"),
51 ("gdn out_proj 5120x6144", PFX + "layers.0.linear_attn.out_proj", "layers-0.safetensors", "fp8"),
52 ("mlp gate_proj 17408x5120", PFX + "layers.0.mlp.gate_proj", "layers-0.safetensors", "fp8"),
53 ("mlp up_proj 17408x5120", PFX + "layers.0.mlp.up_proj", "layers-0.safetensors", "fp8"),
54 ("mlp down_proj 5120x17408", PFX + "layers.0.mlp.down_proj", "layers-0.safetensors", "fp8"),
55 ("attn q_proj 12288x5120", PFX + "layers.3.self_attn.q_proj", "layers-3.safetensors", "fp8"),
56 ("attn k_proj 1024x5120", PFX + "layers.3.self_attn.k_proj", "layers-3.safetensors", "fp8"),
57 ("attn o_proj 5120x6144", PFX + "layers.3.self_attn.o_proj", "layers-3.safetensors", "fp8"),
58 ("lm_head 248320x5120", "lm_head", "outside.safetensors", "bf16"),
59]
60
61
62def log(*a):
63 line = time.strftime("%Y-%m-%dT%H:%M:%SZ ", time.gmtime()) + " ".join(str(x) for x in a)
64 print(line, flush=True)
65 with open(LOG, "a") as f:
66 f.write(line + "\n")
67
68
69def sha_file(p):
70 h = hashlib.sha256()
71 with open(p, "rb") as f:
72 for b in iter(lambda: f.read(1 << 24), b""):
73 h.update(b)
74 return h.hexdigest()
75
76
77def state():
78 return json.loads(STATE.read_text()) if STATE.exists() else {"done": [], "results": {}}
79
80
81def save(st):
82 tmp = STATE.with_suffix(".partial")
83 tmp.write_text(json.dumps(st, indent=1))
84 os.replace(tmp, STATE)
85
86
87def phase_env(st):
88 info = {"uname": platform.uname()._asdict(), "python": sys.version, "numpy": np.__version__}
89 try:
90 r = subprocess.run(["rocminfo"], capture_output=True, text=True, timeout=60).stdout
91 info["gfx"] = sorted(set(re.findall(r"gfx9\d\d", r)))
92 info["marketing"] = sorted(set(m.strip() for m in re.findall(r"Marketing Name:\s*(.*)", r)))
93 info["compute_units"] = sorted(set(re.findall(r"Compute Unit:\s*(\d+)", r)))
94 except Exception as e: # noqa: BLE001
95 info["rocminfo"] = "unavailable: %r" % e
96 bad = [n for n, h in EXP["bundle"].items() if sha_file(HERE / n) != h]
97 info["bundle_sha256_bad"] = bad
98 log("ENV", json.dumps(info))
99 if bad:
100 raise SystemExit("bundle sha256 mismatch: %s" % bad)
101 st["results"]["env"] = info
102
103
104def phase_weights(st):
105 WD.mkdir(parents=True, exist_ok=True)
106 need = sorted(set(EXP["source_shards"]) | {"config.json", "model.safetensors.index.json"})
107 for n in need:
108 p = WD / n
109 want = EXP["source_sha256"].get(n)
110 if p.exists() and (want is None or sha_file(p) == want):
111 log("WEIGHTS have", n)
112 continue
113 url = "https://huggingface.co/Qwen/Qwen3.8-27B-FP8/resolve/%s/%s" % (REV, n)
114 tmp = p.with_suffix(p.suffix + ".partial")
115 t0 = time.time()
116 with urllib.request.urlopen(url) as r, open(tmp, "wb") as f:
117 while True:
118 b = r.read(1 << 23)
119 if not b:
120 break
121 f.write(b)
122 if want is not None and sha_file(tmp) != want:
123 raise SystemExit("download sha256 mismatch " + n)
124 os.replace(tmp, p)
125 log("WEIGHTS downloaded", n, "bytes=%d s=%.0f" % (p.stat().st_size, time.time() - t0))
126 log("WEIGHTS sha256 verified %d files at %s" % (len(need), REV))
127
128
129def phase_convert(st):
130 shards = sorted(set(EXP["source_shards"]))
131 t0 = time.time()
132 r = subprocess.run([sys.executable, "-I", str(HERE / "q4convert.py"), str(WD), str(CD), "--workers",
133 str(min(16, os.cpu_count() or 1)), "--only", ",".join(shards)], capture_output=True, text=True)
134 (OUT / "convert.log").write_text(r.stdout + r.stderr)
135 if r.returncode:
136 raise SystemExit("convert failed rc=%d" % r.returncode)
137 rows = {}
138 for s in shards:
139 got = sha_file(CD / s)
140 rows[s] = {"card": got, "spark": EXP["container_sha256"][s], "equal": got == EXP["container_sha256"][s]}
141 log("CONVERT seconds=%.0f" % (time.time() - t0), json.dumps(rows))
142 st["results"]["convert"] = rows
143 if not all(v["equal"] for v in rows.values()):
144 raise SystemExit("container sha256 differs from the Spark's")
145
146
147def manifest(raw, outbytes, repeats, relocs, timeout_ns=0):
148 hdr = b"OMKFD001" + struct.pack("<QQQQQ", len(raw), outbytes, repeats, timeout_ns, len(relocs))
149 for off, idx in relocs:
150 hdr += struct.pack("<QQ", off, idx)
151 return hdr + raw
152
153
154def launch(code, kernel, gx, args_path, inputs, out_path):
155 cmd = [os.environ.get("Q4_LAUNCH", str(HERE / "launch-x86")), "run", str(code), kernel, str(gx), "1", str(args_path)] + \
156 [str(p) for p in inputs] + [str(out_path)]
157 t0 = time.time()
158 r = subprocess.run(cmd, capture_output=True, timeout=900)
159 m = re.search(rb"OMEGA dispatch_ns=(\d+) packets=(\d+)", r.stdout)
160 return r.returncode, (int(m.group(1)) if m else None), r.stdout, r.stderr, time.time() - t0
161
162
163def timed(code, kernel, gx, raw, outbytes, relocs, inputs, tag):
164 res = {}
165 for rep in (1, REPEAT):
166 ap = OUT / ("%s.r%d.args" % (tag, rep))
167 ap.write_bytes(manifest(raw, outbytes, rep, relocs))
168 op = OUT / ("%s.r%d.y" % (tag, rep))
169 ns = []
170 for k in range(3):
171 rc, d, so, se, wall = launch(code, kernel, gx, ap, inputs, op)
172 (OUT / ("%s.r%d.%d.stdout" % (tag, rep, k))).write_bytes(so)
173 (OUT / ("%s.r%d.%d.stderr" % (tag, rep, k))).write_bytes(se)
174 if rc != 0 or d is None:
175 return {"error": "rc=%d" % rc, "stderr": se[-300:].decode("utf-8", "replace")}
176 ns.append(d)
177 res["r%d_ns" % rep] = ns
178 m1 = float(np.median(res["r1_ns"]))
179 mR = float(np.median(res["r%d_ns" % REPEAT]))
180 res["per_dispatch_ms"] = (mR - m1) / (REPEAT - 1) / 1e6
181 res["repeat"] = REPEAT
182 return res
183
184
185FLUSH_BYTES = int(os.environ.get("Q4_TILE_BYTES", str(600 * 1000 * 1000)))
186
187
188def phase_kernels(st, only):
189 """Each tensor is tiled C times along rows so that one dispatch streams at least FLUSH_BYTES of 4-bit weights
190 (more than the 256 MB Infinity Cache), so repeat timings are not cache-resident. The FP8 baseline is tiled
191 by the same C. Outputs of the tiled rows must equal the oracle bit for bit."""
192 OUT.mkdir(exist_ok=True)
193 import mmap
194 import zlib
195 for cls, stem, shard, kind in CLASSES:
196 if only and not any(o in cls for o in only):
197 continue
198 if cls in st["results"].get("kernels", {}):
199 continue
200 rng = np.random.default_rng([20261113, zlib.crc32(cls.encode())])
201 hq, mq, bq = read_header(CD / shard)
202 hs, _, bs = read_header(WD / shard)
203 if mq.get("q4_format") != F.FORMAT:
204 raise SystemExit("container shard %s is not %s" % (shard, F.FORMAT))
205 seg = json.loads(mq["q4_seg"])[stem + ".weight_q4"]
206 with open(CD / shard, "rb") as fq, open(WD / shard, "rb") as fs:
207 mmq = mmap.mmap(fq.fileno(), 0, access=mmap.ACCESS_READ)
208 mms = mmap.mmap(fs.fileno(), 0, access=mmap.ACCESS_READ)
209 nib = np.ascontiguousarray(tensor_view(mmq, bq, hq[stem + ".weight_q4"]))
210 sb = np.ascontiguousarray(tensor_view(mmq, bq, hq[stem + ".weight_q4_scale"]))
211 M, half = nib.shape
212 T = half // 256
213 nseg = sb.shape[1] // 64
214 K = hs[stem + ".weight"]["shape"][1]
215 C = max(1, -(-FLUSH_BYTES // (nib.nbytes + sb.nbytes)))
216 x = (rng.standard_normal(K) * 0.5).astype(np.float32)
217 xq, xs = F.quantize_x(x)
218 xbuf = F.pack_x(xq, xs)
219 tag = stem.split(".")[-1] + "-" + shard.split(".")[0]
220 wq, xqp, sq = OUT / (tag + ".q4w"), OUT / (tag + ".q4x"), OUT / (tag + ".q4s")
221 with open(wq, "wb") as f:
222 for _ in range(C):
223 f.write(nib.tobytes())
224 xqp.write_bytes(xbuf)
225 with open(sq, "wb") as f:
226 for _ in range(C):
227 f.write(sb.astype("<u2").tobytes())
228 MB = M * C
229 raw = bytes(32) + struct.pack("<IIII", MB, T, seg, nseg * 128)
230 exp = np.tile(OV.expected_bits(nib, sb, xbuf, seg), C)
231 qbytes = int(C * (nib.nbytes + sb.nbytes))
232 res = {}
233 for name, code, kern, gx in (("q4", "q4gemv_d8.hsaco", "q4gemv_d8", MB),
234 ("q4r2", "q4gemv_d8r2.hsaco", "q4gemv_d8r2", MB // 2)):
235 if name == "q4r2" and MB % 2:
236 res[name] = {"error": "odd M"}
237 continue
238 r = timed(HERE / code, kern, gx, raw, 4 * MB, [(0, 0), (8, 1), (16, 2), (24, 3)],
239 [wq, xqp, sq], tag + "." + name)
240 if "error" not in r:
241 y = np.frombuffer((OUT / (tag + ".%s.r1.y" % name)).read_bytes(), dtype="<u4")
242 yR = np.frombuffer((OUT / (tag + ".%s.r%d.y" % (name, REPEAT))).read_bytes(), dtype="<u4")
243 r["output_bits_equal_oracle"] = int((y == exp).sum())
244 r["rows"] = int(MB)
245 r["repeat_output_equal"] = bool((yR == y).all())
246 r["verdict"] = "PASS" if r["output_bits_equal_oracle"] == MB and r["repeat_output_equal"] else "FAIL"
247 r["weight_bytes_per_dispatch"] = qbytes
248 r["per_tensor_ms"] = r["per_dispatch_ms"] / C
249 r["weight_GBps"] = qbytes / (r["per_dispatch_ms"] * 1e-3) / 1e9
250 res[name] = r
251 # baseline kernel on the same tensor in its source format, tiled by the same C
252 if kind == "fp8":
253 w8 = np.ascontiguousarray(tensor_view(mms, bs, hs[stem + ".weight"]))
254 s8 = np.ascontiguousarray(tensor_view(mms, bs, hs[stem + ".weight_scale_inv"]))
255 if M % 128:
256 raise SystemExit("FP8 tiling needs M % 128 == 0")
257 bw, bx, bsx = OUT / (tag + ".f8w"), OUT / (tag + ".f8x"), OUT / (tag + ".f8s")
258 with open(bw, "wb") as f:
259 for _ in range(C):
260 f.write(w8.tobytes())
261 bx.write_bytes(x.tobytes())
262 with open(bsx, "wb") as f:
263 for _ in range(C):
264 f.write(s8.astype("<u2").tobytes())
265 rawb = bytes(32) + struct.pack("<II", MB, K)
266 rb = timed(HERE / "fp8gemv_b128f.hsaco", "fp8gemv_b128f", MB, rawb, 4 * MB,
267 [(0, 0), (8, 1), (16, 2), (24, 3)], [bw, bx, bsx], tag + ".f8")
268 wbytes = int(C * (w8.nbytes + s8.nbytes))
269 real = F.e4m3_table()[w8].astype(np.float64)
270 sc = F.bf16_value(s8).astype(np.float64)
271 real *= sc[np.arange(M)[:, None] // 128, np.arange(K)[None, :] // 128]
272 ref = real @ x.astype(np.float64)
273 bsuf = ".f8"
274 else:
275 wb = np.ascontiguousarray(tensor_view(mms, bs, hs[stem + ".weight"]))
276 bw, bx = OUT / (tag + ".bfw"), OUT / (tag + ".bfx")
277 with open(bw, "wb") as f:
278 for _ in range(C):
279 f.write(wb.tobytes())
280 bx.write_bytes(x.tobytes())
281 rawb = bytes(24) + struct.pack("<II", MB, K)
282 rb = timed(HERE / "bf16gemv2.hsaco", "bf16gemv2", MB, rawb, 4 * MB, [(0, 0), (8, 1), (16, 2)],
283 [bw, bx], tag + ".bf")
284 wbytes = int(C * wb.nbytes)
285 ref = np.concatenate([F.bf16_value(wb[r:r + 8192]).astype(np.float64) @ x.astype(np.float64)
286 for r in range(0, M, 8192)])
287 bsuf = ".bf"
288 if "error" not in rb:
289 yb = np.frombuffer((OUT / (tag + bsuf + ".r1.y")).read_bytes(), dtype="<f4").astype(np.float64)
290 rb["rel_err_vs_float64"] = float(np.linalg.norm(yb[:M] - ref) / np.linalg.norm(ref))
291 rb["weight_bytes_per_dispatch"] = wbytes
292 rb["per_tensor_ms"] = rb["per_dispatch_ms"] / C
293 rb["weight_GBps"] = wbytes / (rb["per_dispatch_ms"] * 1e-3) / 1e9
294 for name in ("q4", "q4r2"):
295 r = res[name]
296 if "error" not in r:
297 y4 = np.frombuffer((OUT / (tag + ".%s.r1.y" % name)).read_bytes(), dtype="<f4").astype(np.float64)
298 r["rel_err_vs_source_float64"] = float(np.linalg.norm(y4[:M] - ref) / np.linalg.norm(ref))
299 row = {"q4": res["q4"], "q4r2": res["q4r2"], "baseline_kind": kind, "baseline": rb, "M": int(M), "K": int(K),
300 "seg": int(seg), "tile_copies": int(C)}
301 st["results"].setdefault("kernels", {})[cls] = row
302 save(st)
303 log("KERNEL", cls, json.dumps(row))
304 for q in OUT.glob(tag + ".*w"):
305 q.unlink()
306 for q in OUT.glob(tag + ".*s"):
307 if q.suffix in (".q4s", ".f8s"):
308 q.unlink()
309
310
311def phase_final(st):
312 res = OUT / "results.json"
313 res.write_text(json.dumps(st["results"], indent=1, sort_keys=True) + "\n")
314 files = sorted(p for p in OUT.iterdir() if p.is_file() and p.suffix not in (".q4w", ".q4x", ".q4s", ".f8w",
315 ".f8x", ".f8s", ".bfw", ".bfx"))
316 files += [LOG, STATE]
317 lines = "".join("%s %s\n" % (sha_file(p), p.name) for p in files)
318 (OUT / "SHA256SUMS").write_text(lines)
319 subprocess.run(["tar", "-czf", str(HERE / "q4card.tar.gz"), "-C", str(HERE), "out", LOG.name, STATE.name],
320 check=True)
321 log("FINAL tarball sha256=%s" % sha_file(HERE / "q4card.tar.gz"))
322 bad = [c for c, r in st["results"].get("kernels", {}).items()
323 for n in ("q4", "q4r2") if r[n].get("verdict") == "FAIL" or ("error" in r[n] and r[n]["error"] != "odd M")]
324 if bad:
325 log("CARD-Q4 FAIL output or launch failure in " + ", ".join(bad))
326 raise SystemExit(1)
327 log("CARD-Q4 COMPLETE all 4-bit outputs bit-exact")
328
329
330def main(argv):
331 st = state()
332 skip = "--skip-download" in argv
333 only = None
334 if "--only" in argv:
335 only = argv[argv.index("--only") + 1].split(",")
336 OUT.mkdir(exist_ok=True)
337 for name, fn in (("env", phase_env), ("weights", phase_weights), ("convert", phase_convert)):
338 if name in st["done"] or (name == "weights" and skip):
339 continue
340 fn(st)
341 st["done"].append(name)
342 save(st)
343 phase_kernels(st, only)
344 phase_final(st)
345 return 0
346
347
348if __name__ == "__main__":
349 sys.exit(main(sys.argv[1:]))