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 / tests / amd-exec / gemv2.py
| 1 | #!/usr/bin/env python3 |
| 2 | # SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception |
| 3 | """Test-only exact Fraction oracle. No kernel or executor code derives expectations. |
| 4 | Recorded arithmetic: chunk=256, lane owns 4 consecutive columns; ascending k per lane; |
| 5 | simultaneous XOR stages 32,16,8,4,2,1, each with IEEE nearest-even binary32 addition. |
| 6 | Large fixtures retain actual M/K and sample first/middle/last rows through row-probe. |
| 7 | """ |
| 8 | import pathlib |
| 9 | import runpy |
| 10 | import struct |
| 11 | import subprocess |
| 12 | import sys |
| 13 | |
| 14 | HERE = pathlib.Path(__file__).parent |
| 15 | SG = runpy.run_path(str(HERE/'sgemm.py')) |
| 16 | FP = runpy.run_path(str(HERE/'fp8gemv.py')) |
| 17 | BF = runpy.run_path(str(HERE/'bf16gemv.py')) |
| 18 | SHAPES = tuple(sorted(set(FP['SHAPES']) | set(BF['SHAPES']) | |
| 19 | {(m, k) for m in (1, 2, 65) for k in (255, 256, 257, 1023, 1024, 1025, 2049)})) |
| 20 | LARGE = ((17408, 5120), (5120, 17408), (5120, 5120)) |
| 21 | TREE = (32, 16, 8, 4, 2, 1) |
| 22 | |
| 23 | |
| 24 | def result(weights, xs, decoder, scale=None): |
| 25 | partial = [0]*64 |
| 26 | for lane in range(64): |
| 27 | for chunk in range(0, len(xs), 256): |
| 28 | for j in range(4): |
| 29 | k = chunk+4*lane+j |
| 30 | if k < len(xs): |
| 31 | partial[lane] = SG['fma'](decoder(weights[k]), xs[k], partial[lane]) |
| 32 | for distance in TREE: |
| 33 | before = partial |
| 34 | partial = [SG['fma'](before[lane], 0x3f800000, before[lane ^ distance]) for lane in range(64)] |
| 35 | answer = partial[0] |
| 36 | if scale is not None: |
| 37 | answer = SG['fma'](scale, answer, (scale ^ answer) & 0x80000000) |
| 38 | return answer |
| 39 | |
| 40 | |
| 41 | def fixture(kind, m, k, special=False, rows=None, witness=False): |
| 42 | fp = kind == 'fp8gemv2' |
| 43 | size = 1 if fp else 2 |
| 44 | wp = 64 if fp else 66 |
| 45 | xp = (wp + m*k*size+19) & ~3 |
| 46 | sp = xp+4*k+16 |
| 47 | yp = sp+4*m+16 if fp else sp |
| 48 | data = bytearray([0xa5])*(yp+4*m+64) |
| 49 | if fp: |
| 50 | struct.pack_into('<QQQQII', data, 0, wp, xp, sp, yp, m, k) |
| 51 | else: |
| 52 | struct.pack_into('<QQQII', data, 0, wp, xp, yp, m, k) |
| 53 | rows = range(m) if rows is None else rows |
| 54 | finite = (0x3f800000, 0xbf800000, 0x3f800001, 0x3eaaaaab, 1, 0x80000001, 0, 0x80000000) |
| 55 | vals = SG['VALUES'] if special else finite |
| 56 | xs = [vals[(i*3+1) % len(vals)] for i in range(k)] |
| 57 | if witness: |
| 58 | assert (m, k) == (1, 129) |
| 59 | xs = [0]*k |
| 60 | xs[0], xs[64], xs[128] = 0x4b800000, 0x3f800000, 0xcb800000 |
| 61 | for i, value in enumerate(xs): |
| 62 | struct.pack_into('<I', data, xp+4*i, value) |
| 63 | expected_values = {} |
| 64 | for row in rows: |
| 65 | if fp: |
| 66 | weights = [(i*13+row*7+56) & 255 for i in range(k)] |
| 67 | if not special: |
| 68 | weights = [0x7f if w == 0x80 else w for w in weights] |
| 69 | scale = (SG['VALUES'] if special else (0x3f800000, 0xbf000000, 0x40000000))[row % (len(SG['VALUES']) if special else 3)] |
| 70 | if witness: |
| 71 | weights, scale = [0x40]*k, 0x3f800000 |
| 72 | data[wp+row*k:wp+(row+1)*k] = bytes(weights) |
| 73 | struct.pack_into('<I', data, sp+4*row, scale) |
| 74 | decoder = FP['decode'] |
| 75 | else: |
| 76 | values = BF['VALUES'] if special else (0x3f80, 0xbf80, 0x3f81, 0x3eab, 1, 0x8001, 0, 0x8000) |
| 77 | weights = [values[(row*7+i*11) % len(values)] for i in range(k)] |
| 78 | if witness: |
| 79 | weights = [0x3f80]*k |
| 80 | for i, w in enumerate(weights): |
| 81 | struct.pack_into('<H', data, wp+2*(row*k+i), w) |
| 82 | scale, decoder = None, BF['decode'] |
| 83 | expected_values[row] = result(weights, xs, decoder, scale) |
| 84 | expected = bytearray(data) |
| 85 | for row, bits in expected_values.items(): |
| 86 | struct.pack_into('<I', expected, yp+4*row, bits) |
| 87 | return data, expected, expected_values |
| 88 | |
| 89 | |
| 90 | def check(exe, text, out, kind, m, k, special=False, rows=None, witness=False): |
| 91 | memory = pathlib.Path(out)/'gemv2-memory.bin' |
| 92 | data, expected, values = fixture(kind, m, k, special, rows, witness) |
| 93 | memory.write_bytes(data) |
| 94 | args = [str((m+1)*64), '1'] if rows is None else list(map(str, (*rows, m))) |
| 95 | completed = subprocess.run([exe, str(text), str(memory), *args], capture_output=True, timeout=600) |
| 96 | assert completed.returncode == 0 and not completed.stdout and not completed.stderr, completed |
| 97 | actual = memory.read_bytes() |
| 98 | if actual != expected: |
| 99 | offset = next(i for i, (a, b) in enumerate(zip(actual, expected)) if a != b) |
| 100 | raise AssertionError(f'{kind} bit mismatch M={m} K={k} byte={offset} got={actual[offset]:02x} expected={expected[offset]:02x}') |
| 101 | return values |
| 102 | |
| 103 | |
| 104 | def mutate(source, out): |
| 105 | text = pathlib.Path(source).read_text() |
| 106 | stem = pathlib.Path(source).stem |
| 107 | first = 'I 5 255 2 15 21\nL 128\nI 11 0 15 4 5\nI 4 0xc07f 12\nI 5 260 5 4 1\n' |
| 108 | second = 'I 5 192 2 15 21\nI 11 0 15 4 5\nI 4 0xc07f 12\nI 5 260 5 4 1\n' |
| 109 | changes = { |
| 110 | 'order': (first+second, second+first), |
| 111 | 'tail': ('I 2 16 129 17 1\nI 4 @3 5', 'I 2 16 129 17 1\nI 4 @3 4'), |
| 112 | 'stride': ('I 9 6 645 257 13', 'I 9 6 645 257 12'), |
| 113 | } |
| 114 | for name, (old, new) in changes.items(): |
| 115 | assert text.count(old) == 1, (name, text.count(old)) |
| 116 | (pathlib.Path(out)/(stem+'-'+name+'.isa')).write_text(text.replace(old, new)) |
| 117 | |
| 118 | |
| 119 | def suite(exe, probe, out): |
| 120 | out = pathlib.Path(out) |
| 121 | rows_receipt = ['kernel\tM\tK\trow\tFP32_bits'] |
| 122 | for kind in ('fp8gemv2', 'bf16gemv2'): |
| 123 | code = out/(kind+'.text') |
| 124 | for special in (False, True): |
| 125 | for m, k in SHAPES: |
| 126 | check(exe, code, out, kind, m, k, special) |
| 127 | print(f'PASS {kind} M={m} K={k} inputs={"special" if special else "finite"} every-output-bit all-memory-guards', flush=True) |
| 128 | check(exe, code, out, kind, 1, 129, witness=True) |
| 129 | for label, shape in [('order', (1, 129)), ('tail', (1, 3)), ('stride', (3, 257))]: |
| 130 | try: |
| 131 | check(exe, out/(kind+'-'+label+'.text'), out, kind, *shape, witness=label == 'order') |
| 132 | except AssertionError as error: |
| 133 | assert str(error).startswith(kind+' bit mismatch'), error |
| 134 | print(f'CONTROL {kind}-{label} CAUGHT {error}', flush=True) |
| 135 | else: |
| 136 | raise AssertionError(f'escaped {kind}-{label}') |
| 137 | for m, k in LARGE: |
| 138 | rows = (0, m//2, m-1) |
| 139 | values = check(probe, code, out, kind, m, k, rows=rows) |
| 140 | rows_receipt += [f'{kind}\t{m}\t{k}\t{r}\t{b:08x}' for r, b in values.items()] |
| 141 | print(f'PASS {kind} M={m} K={k} sampled-rows={",".join(map(str, rows))} actual-full-row-stride every-sampled-bit all-unsampled-outputs-untouched', flush=True) |
| 142 | (out/'gemv2-sampled-rows.tsv').write_text('\n'.join(rows_receipt)+'\n') |
| 143 | print(f'PASS gemv2 kernels=fp8gemv2,bf16gemv2 shapes={len(SHAPES)} cases-per-kernel={2*len(SHAPES)+1} sampled-shapes={len(LARGE)} sampled-rows-per-shape=3 hardware=NOT_RUN', flush=True) |
| 144 | |
| 145 | |
| 146 | if __name__ == '__main__': |
| 147 | {'mutate': mutate, 'suite': suite}[sys.argv[1]](*sys.argv[2:]) |