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 / bf16gemv.py
| 1 | #!/usr/bin/env python3 |
| 2 | # SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception |
| 3 | """Test only: BF16 sign/exponent/fraction -> exact Fraction -> FP32 FMA. |
| 4 | No production code, host floating arithmetic, or FP16 rounding implements the oracle. |
| 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((0, 1, 63, 64, 65), (0, 1, 3, 64, 65, 130))) |
| 16 | FINITE = (0x3f80, 0xbf80, 0x3f81, 0xbf81, 0x3f7f, 0x3eab, 0xbe4d, |
| 17 | 1, 0x8001, 0x007f, 0x807f, 0x0080, 0x8080, 0x7f7f, 0xff7f, |
| 18 | 0, 0x8000, 0x3380, 0x4c80, 0xcc80) |
| 19 | VALUES = FINITE + (0x7f80, 0xff80, 0x7fc1, 0x7f81, 0xffc1, 0xff81) |
| 20 | |
| 21 | |
| 22 | def decode(bits): |
| 23 | # BF16 S1E8M7, bias127; same exponent/sign position as FP32 after exact widening. |
| 24 | exponent, fraction = (bits >> 7) & 255, bits & 127 |
| 25 | sign = (bits >> 15) << 31 |
| 26 | if exponent == 255: |
| 27 | return sign | 0x7f800000 | fraction << 16 |
| 28 | if not exponent and not fraction: |
| 29 | return sign |
| 30 | value = Fraction(fraction if not exponent else 128 + fraction, 128) |
| 31 | value *= Fraction(2) ** ((exponent if exponent else 1) - 127) |
| 32 | if sign: value = -value |
| 33 | return SG['round32'](value) |
| 34 | |
| 35 | |
| 36 | def fixture(m, k, special=False, isolated=False): |
| 37 | # A two-byte-aligned, non-dword-aligned base and odd K exercise both row-end alignments. |
| 38 | wp = 66 |
| 39 | xp = (wp + 2*m*k + 19) & ~3 |
| 40 | yp = xp + 4*k + 16 |
| 41 | data = bytearray([0xa5] * (yp + 4*m + 64)) |
| 42 | struct.pack_into('<QQQII', data, 0, wp, xp, yp, m, k) |
| 43 | values = VALUES if special else FINITE |
| 44 | weights = [values[(row*7+col*11) % len(values)] for row in range(m) for col in range(k)] |
| 45 | inputs = SG['VALUES'] if special else SG['FINITE'] |
| 46 | xs = [inputs[(i*3) % len(inputs)] for i in range(k)] |
| 47 | if isolated: |
| 48 | assert (m, k) == (len(VALUES), 1) |
| 49 | weights, xs = list(VALUES), [0x3f800000] |
| 50 | for i, bits in enumerate(weights): struct.pack_into('<H', data, wp+2*i, bits) |
| 51 | for i, bits in enumerate(xs): struct.pack_into('<I', data, xp+4*i, bits) |
| 52 | expected = bytearray(data) |
| 53 | for row in range(m): |
| 54 | acc = 0 |
| 55 | for inner in range(k): |
| 56 | acc = SG['fma'](decode(weights[row*k+inner]), xs[inner], acc) |
| 57 | struct.pack_into('<I', expected, yp+4*row, acc) |
| 58 | return data, expected |
| 59 | |
| 60 | |
| 61 | def check(exe, text, out, m, k, special=False, isolated=False): |
| 62 | memory = pathlib.Path(out)/'bf16gemv-memory.bin' |
| 63 | data, expected = fixture(m, k, special, isolated) |
| 64 | memory.write_bytes(data) |
| 65 | result = subprocess.run([exe, str(text), str(memory), str(m+64), '1'], capture_output=True, timeout=180) |
| 66 | assert result.returncode == 0 and not result.stdout and not result.stderr, result |
| 67 | actual = memory.read_bytes() |
| 68 | if actual != expected: |
| 69 | offset = next((i for i, (a,b) in enumerate(zip(actual, expected)) if a != b), min(len(actual), len(expected))) |
| 70 | raise AssertionError(f'bf16gemv bit mismatch M={m} K={k} byte={offset}') |
| 71 | |
| 72 | |
| 73 | def suite(exe, text, swapped_exe, truncated_text, out): |
| 74 | for special in (False, True): |
| 75 | for m, k in SHAPES: |
| 76 | check(exe, text, out, m, k, special) |
| 77 | print(f'PASS bf16gemv M={m} K={k} inputs={"special" if special else "finite"} ordered-FMA exact-BF16 every-bit all-guards', flush=True) |
| 78 | check(exe, text, out, len(VALUES), 1, isolated=True) |
| 79 | pathlib.Path(out, 'bf16-values.tsv').write_text('BF16_bits\tFP32_bits\n' + ''.join(f'{b:04x}\t{decode(b):08x}\n' for b in VALUES)) |
| 80 | print('PASS bf16gemv isolated BF16 signed-zeros subnormals normals extremes infinities quiet/signaling-NaNs', flush=True) |
| 81 | for label, binary, code in [('big-endian-weight', swapped_exe, text), ('truncated-FP32-x', exe, truncated_text)]: |
| 82 | try: |
| 83 | check(binary, code, out, 1, 1) |
| 84 | except AssertionError as error: |
| 85 | assert str(error).startswith('bf16gemv bit mismatch'), error |
| 86 | print(f'CONTROL bf16gemv-{label} CAUGHT {error}', flush=True) |
| 87 | else: |
| 88 | raise AssertionError(f'escaped {label}') |
| 89 | |
| 90 | |
| 91 | def swap_mutant(source, target): |
| 92 | text = pathlib.Path(source).read_text() |
| 93 | needle = 'ret or ulong get io 0 shl ulong get io 1 8\n' |
| 94 | assert text.count(needle) == 1 |
| 95 | pathlib.Path(target).write_text(text.replace(needle, 'ret or ulong get io 1 shl ulong get io 0 8\n')) |
| 96 | |
| 97 | |
| 98 | def truncate_mutant(source, target): |
| 99 | text = pathlib.Path(source).read_text() |
| 100 | needle = 'I 5 263 6 4 59\n' |
| 101 | assert text.count(needle) == 1 |
| 102 | pathlib.Path(target).write_text(text.replace(needle, 'I 5 255 6 6 19\nL 0xffff0000\n' + needle)) |
| 103 | |
| 104 | |
| 105 | if __name__ == '__main__': |
| 106 | {'suite': suite, 'swap-mutant': swap_mutant, 'truncate-mutant': truncate_mutant}[sys.argv[1]](*sys.argv[2:]) |