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
CUDApp / evidence / amd-speed-20261114 / raw / spec-decode / card-rho / spec_rho.py
| 1 | #!/usr/bin/env python3 |
| 2 | """spec-decode card measurement (instrument; runs on the MI300X notebook, Python + numpy only). |
| 3 | Per-dispatch time of the one-row GEMVs fp8gemv_b128f / bf16gemv2 (CUDApp dc536882 code, objects written by hsaco.om) |
| 4 | against their R-row variants _r2, _r3, _r8, through the unmodified native launcher's generic `run` command |
| 5 | (launch-x86 sha256 08a50491...). Matrices exceed the 256 MB last-level cache so each repeat reads from HBM. |
| 6 | Per dispatch = (time at repeat N - time at repeat 1) / (N - 1), median of TRIALS. Correctness on hardware: every row |
| 7 | of each R-row output must be bit-identical to the one-row kernel run on that row alone. |
| 8 | Writes rho-results.json after every case (verdict PARTIAL until the end) and prints RHO lines. Every launcher call has |
| 9 | its own timeout (SPEC_RHO_TIMEOUT seconds, default 60) after which its whole process group is killed; a timed-out case |
| 10 | is recorded as TIMEOUT and the run continues with the next kernel. |
| 11 | Usage: spec_rho.py DIR (DIR holds launch-x86 and the .hsaco files)""" |
| 12 | import json, os, re, signal, struct, subprocess, sys, time |
| 13 | import numpy as np |
| 14 | D = sys.argv[1]; L = os.path.join(D, 'launch-x86') |
| 15 | DRY = os.environ.get('SPEC_RHO_DRY') == '1' # CPU check without a device: tiny sizes, launcher must exit 77 |
| 16 | W = os.path.join(D, 'work'); os.makedirs(W, exist_ok=True) |
| 17 | N, TRIALS = 20, 5 |
| 18 | TMO = float(os.environ.get('SPEC_RHO_TIMEOUT', '60')) |
| 19 | rng = np.random.default_rng(20261114) |
| 20 | class Timeout(Exception): pass |
| 21 | def manifest(kernarg_len, out_bytes, repeat, relocs, kernarg): |
| 22 | h = b'OMKFD001' + struct.pack('<5Q', kernarg_len, out_bytes, repeat, 0, len(relocs)) |
| 23 | return h + b''.join(struct.pack('<2Q', o, i) for o, i in relocs) + kernarg |
| 24 | def call(cmd, tmo=None): |
| 25 | """Run cmd in its own session; on timeout kill the whole process group and raise Timeout.""" |
| 26 | p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, start_new_session=True) |
| 27 | try: so, se = p.communicate(timeout=tmo or TMO) |
| 28 | except subprocess.TimeoutExpired: |
| 29 | os.killpg(p.pid, signal.SIGKILL); p.communicate() |
| 30 | print('TIMEOUT', ' '.join(cmd[:4])[-120:], f'after {tmo or TMO:.0f}s: process group killed', flush=True) |
| 31 | raise Timeout(cmd) |
| 32 | return p.returncode, so, se |
| 33 | def run(obj, kern, gx, args, inputs, out): |
| 34 | cmd = [L, 'run', obj, kern, str(gx), '1', args, *inputs, out] |
| 35 | if DRY: cmd = ['qemu-x86_64'] + cmd |
| 36 | rc, so, se = call(cmd) |
| 37 | if DRY: |
| 38 | ok = rc == 77 and 'OMEGA device=absent' in so # manifest and ELF checks precede /dev/kfd |
| 39 | if not ok: raise SystemExit(f'DRY launcher exit {rc}: {so[-600:]} {se[-300:]}') |
| 40 | raise StopIteration |
| 41 | m = re.search(r'OMEGA dispatch_ns=(\d+) packets=(\d+)', so) |
| 42 | if rc != 0 or not m: raise SystemExit(f'launcher exit {rc}: {so[-800:]} {se[-800:]}') |
| 43 | return int(m.group(1)), int(m.group(2)) |
| 44 | res = dict(schema='spec-decode-card-rho-v2', N=N, trials=TRIALS, timeout_s=TMO, kernels={}, timeouts=[], verdict='PARTIAL') |
| 45 | def save(): |
| 46 | tmp = os.path.join(D, 'rho-results.json.tmp') |
| 47 | with open(tmp, 'w') as f: json.dump(res, f, indent=1) |
| 48 | os.replace(tmp, os.path.join(D, 'rho-results.json')) |
| 49 | cases = [('fp8gemv_b128f', 81920, 5120), ('bf16gemv2', 248320, 5120)] |
| 50 | if DRY: |
| 51 | cases = [('fp8gemv_b128f', 256, 1024), ('bf16gemv2', 256, 1024)] |
| 52 | for kern, M, K in cases: |
| 53 | for R in (1, 2, 3, 8): |
| 54 | name = f'{kern}_r{R}'; obj = os.path.join(D, name + '.hsaco') |
| 55 | karg = bytes(32 if kern == 'fp8gemv_b128f' else 24) + struct.pack('<II', M, K) |
| 56 | rel = [(0, 0), (8, 1), (16, 2), (24, 3)] if kern == 'fp8gemv_b128f' else [(0, 0), (8, 1), (16, 2)] |
| 57 | ins = [] |
| 58 | for i, n in enumerate([M * K, R * K * 4] + ([((M + 127) // 128) * ((K + 127) // 128) * 2] if kern == 'fp8gemv_b128f' else [])): |
| 59 | f = os.path.join(W, f'dry{i}'); open(f, 'wb').write(bytes(n)); ins.append(f) |
| 60 | if kern == 'bf16gemv2': open(ins[0], 'wb').write(bytes(2 * M * K)) |
| 61 | a = os.path.join(W, 'adry'); open(a, 'wb').write(manifest(len(karg), R * M * 4, 3, rel, karg)) |
| 62 | try: run(obj, name, M, a, ins, os.path.join(W, 'ydry')) |
| 63 | except StopIteration: print('DRY OK', name, flush=True) |
| 64 | bad = bytearray(open(a, 'rb').read()); bad[0] ^= 1; open(a, 'wb').write(bad) # control: bad magic |
| 65 | rc, _, _ = call(['qemu-x86_64', L, 'run', obj, name, str(M), '1', a, *ins, os.path.join(W, 'ydry')]) |
| 66 | assert rc == 64, ('bad-magic control not refused', rc) |
| 67 | print('DRY CONTROL bad-magic refused 64', name, flush=True) |
| 68 | t = time.time() # control: a hung child (and its own child) is killed on time |
| 69 | try: call(['sh', '-c', 'sleep 30 & sleep 30'], 2); raise SystemExit('DRY timeout control did not fire') |
| 70 | except Timeout: pass |
| 71 | assert time.time() - t < 10, 'timeout control took too long' |
| 72 | print('DRY CONTROL timeout killed process group', flush=True) |
| 73 | sys.exit(0) |
| 74 | for kern, M, K in cases: |
| 75 | t0 = time.time() |
| 76 | if kern == 'fp8gemv_b128f': |
| 77 | w = rng.integers(0, 256, M * K, dtype=np.uint8); w[(w & 0x7f) == 0x7f] ^= 1 # no E4M3 NaN |
| 78 | sc = (0x3f00 + rng.integers(0, 0x100, ((M + 127) // 128) * ((K + 127) // 128))).astype(np.uint16) |
| 79 | files = {'W': w.tobytes(), 'S': sc.tobytes()}; karg_len = 40 |
| 80 | else: |
| 81 | w = (0x3a00 + rng.integers(0, 0x700, M * K)).astype(np.uint16) | (rng.integers(0, 2, M * K).astype(np.uint16) << 15) |
| 82 | files = {'W': w.tobytes()}; karg_len = 32 |
| 83 | for n, b in files.items(): open(os.path.join(W, f'{kern}.{n}'), 'wb').write(b) |
| 84 | del w, files |
| 85 | X = rng.uniform(-2, 2, 8 * K).astype(np.float32) |
| 86 | rows = {} |
| 87 | try: |
| 88 | for R in (1, 2, 3, 8): |
| 89 | obj = os.path.join(D, f'{kern}_r{R}.hsaco'); name = f'{kern}_r{R}' |
| 90 | xf = os.path.join(W, f'x{R}'); open(xf, 'wb').write(X[:R * K].tobytes()) |
| 91 | if kern == 'fp8gemv_b128f': |
| 92 | karg = bytes(32) + struct.pack('<II', M, K); rel = [(0, 0), (8, 1), (16, 2), (24, 3)] |
| 93 | inputs = [os.path.join(W, f'{kern}.W'), xf, os.path.join(W, f'{kern}.S')] |
| 94 | else: |
| 95 | karg = bytes(24) + struct.pack('<II', M, K); rel = [(0, 0), (8, 1), (16, 2)] |
| 96 | inputs = [os.path.join(W, f'{kern}.W'), xf] |
| 97 | out = os.path.join(W, f'y{R}') |
| 98 | a1 = os.path.join(W, 'a1'); open(a1, 'wb').write(manifest(karg_len, R * M * 4, 1, rel, karg)) |
| 99 | aN = os.path.join(W, 'aN'); open(aN, 'wb').write(manifest(karg_len, R * M * 4, N, rel, karg)) |
| 100 | per = [] |
| 101 | for t in range(TRIALS): |
| 102 | t1, _ = run(obj, name, M, a1, inputs, out); tn, pk = run(obj, name, M, aN, inputs, out) |
| 103 | per.append((tn - t1) / (N - 1)) |
| 104 | y = np.fromfile(out, dtype=np.uint32).reshape(R, M) |
| 105 | ident = None |
| 106 | if R == 1: |
| 107 | rows[0] = y[0].copy() |
| 108 | for r in range(1, 8): # one-row reference for every activation row |
| 109 | open(xf, 'wb').write(X[r * K:(r + 1) * K].tobytes()); run(obj, name, M, a1, inputs, out) |
| 110 | rows[r] = np.fromfile(out, dtype=np.uint32).copy() |
| 111 | else: |
| 112 | ident = all(np.array_equal(y[r], rows[r]) for r in range(R)) |
| 113 | finite = bool(np.all(((y >> 23) & 0xff) != 0xff)) |
| 114 | med = float(np.median(per)) |
| 115 | res['kernels'][name] = dict(M=M, K=K, R=R, per_dispatch_ns=per, median_ns=med, rows_bit_identical_to_one_row=ident, |
| 116 | finite=finite, weight_bytes=M * K * (1 if kern == 'fp8gemv_b128f' else 2)) |
| 117 | if R > 1: |
| 118 | one = res['kernels'][f'{kern}_r1']['median_ns']; res['kernels'][name]['rho'] = (med / one - 1) / (R - 1) |
| 119 | save() |
| 120 | print('RHO', name, f'M={M} K={K} median_us={med / 1000:.3f}', 'identical' if ident in (None, True) else 'DIFFERENT', |
| 121 | 'finite' if finite else 'NONFINITE', f"rho={res['kernels'][name].get('rho', 0):.4f}" if R > 1 else '', flush=True) |
| 122 | except Timeout: |
| 123 | res['timeouts'].append(dict(kernel=kern, R=R, timeout_s=TMO)); save() |
| 124 | print('TIME', kern, f'{time.time() - t0:.0f}s', flush=True) |
| 125 | ok = not res['timeouts'] and all(v['rows_bit_identical_to_one_row'] in (None, True) and v['finite'] for v in res['kernels'].values()) |
| 126 | res['verdict'] = 'PASS' if ok else 'FAIL' |
| 127 | save() |
| 128 | print('SPEC-RHO', res['verdict'], 'hardware=MI300X', flush=True) |