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 / fp8gemv.py
| 1 | #!/usr/bin/env python3 |
| 2 | # SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception |
| 3 | """Test only. FP8 format definition -> exact Fraction -> nearest-even binary32. |
| 4 | The table, fixtures and results are recorded by the gate; no host FP8 library is used. |
| 5 | """ |
| 6 | from fractions import Fraction |
| 7 | import itertools |
| 8 | import pathlib |
| 9 | import runpy |
| 10 | import struct |
| 11 | import subprocess |
| 12 | import sys |
| 13 | |
| 14 | SG = runpy.run_path(str(pathlib.Path(__file__).with_name('sgemm.py'))) |
| 15 | SHAPES = tuple(itertools.product((1, 63, 64, 65), (0, 1, 3, 64, 65))) + ((0, 3),) |
| 16 | SCALES = (0x40000000, 0xbf000000, 0, 0x80000000, 1, 0x80000001, 0x7f7fffff) |
| 17 | |
| 18 | |
| 19 | def decode(byte): |
| 20 | # MI300 ISA PDF p58: bias8, unsigned zero, sole NaN0x80; exponent15 is finite. |
| 21 | if byte == 0x80: |
| 22 | return 0x7fc00000 # documented host canonical-NaN policy |
| 23 | exponent, fraction = (byte >> 3) & 15, byte & 7 |
| 24 | value = Fraction(fraction if exponent == 0 else 8 + fraction, 8) |
| 25 | value *= Fraction(2) ** ((exponent if exponent else 1) - 8) |
| 26 | if byte & 128: |
| 27 | value = -value |
| 28 | return SG['round32'](value) |
| 29 | |
| 30 | |
| 31 | def fixture(m, k, special=False, all_bytes=False): |
| 32 | wp = 64 |
| 33 | xp = (wp + m*k + 19) & ~3 |
| 34 | sp = xp + 4*k + 16 |
| 35 | yp = sp + 4*m + 16 |
| 36 | data = bytearray([0xa5] * (yp + 4*m + 64)) |
| 37 | struct.pack_into('<QQQQII', data, 0, wp, xp, sp, yp, m, k) |
| 38 | weights = [((i*13 + i//max(k, 1) + 56) & 255) for i in range(m*k)] |
| 39 | if not special: |
| 40 | weights = [0x7f if w == 0x80 else w for w in weights] |
| 41 | values = SG['VALUES'] if special else SG['FINITE'] |
| 42 | xs = [values[(i*3+3) % len(values)] for i in range(k)] |
| 43 | scales = [(SG['VALUES'] if special else SCALES)[i % len(SG['VALUES'] if special else SCALES)] for i in range(m)] |
| 44 | if all_bytes: |
| 45 | assert (m, k) == (256, 1) |
| 46 | weights, xs, scales = list(range(256)), [0x3f800000], [0x3f800000]*256 |
| 47 | data[wp:wp+m*k] = bytes(weights) |
| 48 | for i, bits in enumerate(xs): struct.pack_into('<I', data, xp+4*i, bits) |
| 49 | for i, bits in enumerate(scales): struct.pack_into('<I', data, sp+4*i, bits) |
| 50 | expected = bytearray(data) |
| 51 | for row in range(m): |
| 52 | acc = 0 |
| 53 | for inner in range(k): |
| 54 | acc = SG['fma'](decode(weights[row*k+inner]), xs[inner], acc) |
| 55 | answer = SG['fma'](scales[row], acc, (scales[row]^acc)&0x80000000) |
| 56 | struct.pack_into('<I', expected, yp+4*row, answer) |
| 57 | return data, expected |
| 58 | |
| 59 | |
| 60 | def check(exe, text, out, m, k, special=False, all_bytes=False): |
| 61 | memory = pathlib.Path(out)/'fp8gemv-memory.bin' |
| 62 | data, expected = fixture(m, k, special, all_bytes) |
| 63 | memory.write_bytes(data) |
| 64 | result = subprocess.run([exe, str(text), str(memory), str(m+64), '1'], capture_output=True, timeout=180) |
| 65 | assert result.returncode == 0 and not result.stdout and not result.stderr, result |
| 66 | actual = memory.read_bytes() |
| 67 | if actual != expected: |
| 68 | offset = next(i for i, (a,b) in enumerate(zip(actual, expected)) if a != b) |
| 69 | raise AssertionError(f'fp8gemv bit mismatch M={m} K={k} byte={offset}') |
| 70 | |
| 71 | |
| 72 | def suite(exe, text, ocp_exe, no_scale, out): |
| 73 | for special in (False, True): |
| 74 | for m, k in SHAPES: |
| 75 | check(exe, text, out, m, k, special) |
| 76 | print(f'PASS fp8gemv M={m} K={k} inputs={"special" if special else "finite"} ordered-FMA row-scale every-bit all-guards', flush=True) |
| 77 | check(exe, text, out, 256, 1, all_bytes=True) |
| 78 | table = pathlib.Path(out)/'fp8-all256.tsv' |
| 79 | table.write_text('byte\tE4M3FNUZ_FP32_bits\n' + ''.join(f'{b:02x}\t{decode(b):08x}\n' for b in range(256))) |
| 80 | print('PASS fp8gemv all256 E4M3FNUZ table exact Fraction oracle including sole-NaN80 unsigned-zero subnormals exponent15 finite', flush=True) |
| 81 | for label, binary, code in [('OCP-E4M3FN-bias7', ocp_exe, text), ('dropped-row-scale', exe, no_scale)]: |
| 82 | try: |
| 83 | check(binary, code, out, 1, 1) |
| 84 | except AssertionError as error: |
| 85 | assert str(error).startswith('fp8gemv bit mismatch'), error |
| 86 | print(f'CONTROL fp8gemv-{label} CAUGHT {error}', flush=True) |
| 87 | else: |
| 88 | raise AssertionError(f'escaped {label}') |
| 89 | |
| 90 | |
| 91 | def mutate(source, target): |
| 92 | text = pathlib.Path(source).read_text() |
| 93 | begin = text.index('fn fp8bits ') |
| 94 | end = text.index('fn vecalu ', begin) |
| 95 | # Complete OCP E4M3FN mutant: bias7, signed zero and NaN +/-0x7f (not FNUZ). |
| 96 | replacement = '''fn fp8bits a ulong to ulong |
| 97 | v = and a 255 |
| 98 | m = and v 127 |
| 99 | if eq m 127 |
| 100 | ret 0x7fc00000 |
| 101 | end |
| 102 | if eq m 0 |
| 103 | ret shl and v 128 24 |
| 104 | end |
| 105 | e = shr m 3 |
| 106 | f = and m 7 |
| 107 | if eq e 0 |
| 108 | e = 121 |
| 109 | while lt f 8 bound 3 |
| 110 | f = shl f 1 |
| 111 | e = sub e 1 |
| 112 | end |
| 113 | else |
| 114 | e = add e 120 |
| 115 | end |
| 116 | ret or shl and v 128 24 or shl e 23 shl and f 7 20 |
| 117 | end |
| 118 | ''' |
| 119 | pathlib.Path(target).write_text(text[:begin]+replacement+text[end:]) |
| 120 | |
| 121 | |
| 122 | def scale_mutant(source, target): |
| 123 | text = pathlib.Path(source).read_text() |
| 124 | needle = 'I 5 263 4 4 5\n' |
| 125 | assert text.count(needle) == 1 |
| 126 | pathlib.Path(target).write_text(text.replace(needle, 'I 8 260 1 4\n')) |
| 127 | |
| 128 | |
| 129 | NESTED_WAVE = """while true bound 999999 |
| 130 | c = ulong 0 |
| 131 | while lt c 999998 bound 999999 |
| 132 | if not step pc |
| 133 | ret |
| 134 | end |
| 135 | pc = get st 5 |
| 136 | c = add c 1 |
| 137 | end |
| 138 | end |
| 139 | """ |
| 140 | FLAT_WAVE = """while true bound 999999 |
| 141 | if not step pc |
| 142 | ret |
| 143 | end |
| 144 | pc = get st 5 |
| 145 | end |
| 146 | """ |
| 147 | |
| 148 | |
| 149 | def flat_mutant(source, target): |
| 150 | # The executor before the fix: one wave loop bound 999999 (the pinned compiler's largest bound). |
| 151 | text = pathlib.Path(source).read_text() |
| 152 | assert text.count(NESTED_WAVE) == 1 |
| 153 | pathlib.Path(target).write_text(text.replace(NESTED_WAVE, FLAT_WAVE)) |
| 154 | |
| 155 | |
| 156 | def long_wave(exe, flat_exe, text, out): |
| 157 | # K=100000: eleven wave steps per k (two loads, wait, convert, FMA, four address adds, counter, branch), so one wave runs past 999999 steps. |
| 158 | check(exe, text, out, 1, 100000) |
| 159 | print('PASS fp8gemv M=1 K=100000 one wave past 999999 steps every-bit all-guards', flush=True) |
| 160 | memory = pathlib.Path(out)/'fp8gemv-memory.bin' |
| 161 | memory.write_bytes(fixture(1, 100000)[0]) |
| 162 | result = subprocess.run([flat_exe, str(text), str(memory), '65', '1'], capture_output=True, timeout=600) |
| 163 | assert result.returncode == 104, result.returncode |
| 164 | print('CONTROL single-loop executor CAUGHT trap exit=104 on the same run', flush=True) |
| 165 | |
| 166 | |
| 167 | NESTED_GRID = """y = ulong 0 |
| 168 | while lt y ny bound 999999 |
| 169 | c = ulong 0 |
| 170 | while and lt y ny lt c 999998 bound 999999 |
| 171 | g = ulong 0 |
| 172 | while lt g groups bound 999999 |
| 173 | d = ulong 0 |
| 174 | while and lt g groups lt d 999998 bound 999999 |
| 175 | wave g y |
| 176 | g = add g 1 |
| 177 | d = add d 1 |
| 178 | end |
| 179 | end |
| 180 | y = add y 1 |
| 181 | c = add c 1 |
| 182 | end |
| 183 | end |
| 184 | """ |
| 185 | FLAT_GRID = """for y ulong ny |
| 186 | for g ulong groups |
| 187 | wave g y |
| 188 | end |
| 189 | end |
| 190 | """ |
| 191 | |
| 192 | |
| 193 | def flat_grid_mutant(source, target): |
| 194 | # The dispatch loops before the fix: a variable-count for, which the pinned compiler stops after 1000000 passes (trap 104). |
| 195 | text = pathlib.Path(source).read_text() |
| 196 | assert text.count(NESTED_GRID) == 1 |
| 197 | pathlib.Path(target).write_text(text.replace(NESTED_GRID, FLAT_GRID)) |
| 198 | |
| 199 | |
| 200 | def tall_grid(exe, flat_exe, text, out): |
| 201 | # vadd with count 0 (64 zero bytes of memory): every wave ends before a load, so GRID_Y=1000001 runs 1000001 workgroups. |
| 202 | memory = pathlib.Path(out)/'tall-grid-memory.bin' |
| 203 | memory.write_bytes(bytes(64)) |
| 204 | result = subprocess.run([exe, str(text), str(memory), '1', '1000001'], capture_output=True, timeout=1200) |
| 205 | assert result.returncode == 0, result.returncode |
| 206 | assert memory.read_bytes() == bytes(64) |
| 207 | print('PASS vadd count=0 GRID_Y=1000001 exit=0 memory-unchanged', flush=True) |
| 208 | result = subprocess.run([flat_exe, str(text), str(memory), '1', '1000001'], capture_output=True, timeout=1200) |
| 209 | assert result.returncode == 104, result.returncode |
| 210 | print('CONTROL for-loop dispatch executor CAUGHT trap exit=104 at GRID_Y=1000001', flush=True) |
| 211 | |
| 212 | |
| 213 | if __name__ == '__main__': |
| 214 | {'suite': suite, 'mutate': mutate, 'scale-mutant': scale_mutant, 'flat-mutant': flat_mutant, 'long-wave': long_wave, 'flat-grid-mutant': flat_grid_mutant, 'tall-grid': tall_grid}[sys.argv[1]](*sys.argv[2:]) |