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 / sgemm.py
| 1 | #!/usr/bin/env python3 |
| 2 | # SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception |
| 3 | """Test oracle only: arbitrary rational arithmetic, one RN-even binary32 rounding. |
| 4 | No host float operation implements FMA. Independent of the executor's fixed limbs. |
| 5 | """ |
| 6 | from fractions import Fraction |
| 7 | import itertools |
| 8 | import pathlib |
| 9 | import random |
| 10 | import struct |
| 11 | import subprocess |
| 12 | import sys |
| 13 | |
| 14 | SHAPES = ((1, 1, 1), (1, 3, 3), (3, 1, 65), (3, 65, 3), |
| 15 | (64, 3, 1), (65, 1, 64), (1, 64, 65), (3, 65, 64), |
| 16 | (65, 65, 3), (65, 65, 65), (1, 1, 0), (3, 65, 0), |
| 17 | (0, 65, 3), (3, 0, 65)) |
| 18 | VALUES = (0, 0x80000000, 1, 0x80000001, 0x007fffff, 0x00800000, |
| 19 | 0x3f800000, 0xbf800000, 0x3f800001, 0x3f7ffffe, 0x7f7fffff, |
| 20 | 0xff7fffff, 0x7f800000, 0xff800000, 0x7fc12345, 0x7f812345, |
| 21 | 0x00800001, 0x33000000, 0x4c000000, 0xcc000000) |
| 22 | FINITE = (0x3f800001, 0xbf800001, 0x3f7ffffe, 0x3eaaaaab, 0xbe4ccccd, |
| 23 | 0x33000000, 1, 0x80000001, 0x4c000000, 0xcc000000, 0x3f000000) |
| 24 | |
| 25 | |
| 26 | def finite(bits): |
| 27 | exponent = (bits >> 23) & 255 |
| 28 | significand = (bits & 0x7fffff) | (0x800000 if exponent else 0) |
| 29 | power = max(1, exponent) - 150 |
| 30 | value = Fraction(significand) * Fraction(2) ** power |
| 31 | return -value if bits >> 31 else value |
| 32 | |
| 33 | |
| 34 | def round32(value): |
| 35 | if not value: |
| 36 | return 0 |
| 37 | sign = 0x80000000 if value < 0 else 0 |
| 38 | value = abs(value) |
| 39 | e = value.numerator.bit_length() - value.denominator.bit_length() |
| 40 | if value < Fraction(2) ** e: |
| 41 | e -= 1 |
| 42 | quantum = max(-149, e - 23) |
| 43 | scaled = value / (Fraction(2) ** quantum) |
| 44 | q, r = divmod(scaled.numerator, scaled.denominator) |
| 45 | if 2 * r > scaled.denominator or (2 * r == scaled.denominator and q & 1): |
| 46 | q += 1 |
| 47 | if q == 1 << 24: |
| 48 | q >>= 1 |
| 49 | quantum += 1 |
| 50 | if quantum > 104: |
| 51 | return sign | 0x7f800000 |
| 52 | exponent = quantum + 150 if q >= 1 << 23 else 0 |
| 53 | return sign | exponent << 23 | (q & 0x7fffff) |
| 54 | |
| 55 | |
| 56 | def fma(a, b, c): |
| 57 | ax, bx, cx = (x & 0x7fffffff for x in (a, b, c)) |
| 58 | if max(ax, bx, cx) > 0x7f800000: |
| 59 | return 0x7fc00000 |
| 60 | product_sign = (a ^ b) & 0x80000000 |
| 61 | if ax == 0x7f800000 or bx == 0x7f800000: |
| 62 | if not ax or not bx or (cx == 0x7f800000 and product_sign != c & 0x80000000): |
| 63 | return 0x7fc00000 |
| 64 | return product_sign | 0x7f800000 |
| 65 | if cx == 0x7f800000: |
| 66 | return c |
| 67 | if (not ax or not bx) and not cx: |
| 68 | return product_sign & c & 0x80000000 |
| 69 | return round32(finite(a) * finite(b) + finite(c)) |
| 70 | |
| 71 | |
| 72 | def probe(exe): |
| 73 | triples = list(itertools.product(VALUES, repeat=3)) |
| 74 | rng = random.Random(94232) |
| 75 | triples += [tuple(rng.getrandbits(32) for _ in range(3)) for _ in range(10000)] |
| 76 | # Deep product cancellation, overflow canceled before rounding, and subnormal halfway ties. |
| 77 | triples += [(0x3f800001, 0x3f7ffffe, 0xbf800000), |
| 78 | (0x7f7fffff, 0x40000000, 0xff7fffff), |
| 79 | (1, 0x3f000000, 0), (3, 0x3f000000, 0), |
| 80 | (0x80000001, 0x3f000000, 0x80000000)] |
| 81 | data = b''.join(struct.pack('<III', *row) for row in triples) |
| 82 | result = subprocess.run([exe], input=data, capture_output=True, timeout=60) |
| 83 | assert result.returncode == 0 and result.stderr == b'', (result.returncode, result.stderr) |
| 84 | expected = b''.join(struct.pack('<I', fma(*row)) for row in triples) |
| 85 | if result.stdout != expected: |
| 86 | index = next(i for i, (x, y) in enumerate(zip(result.stdout, expected)) if x != y) // 4 |
| 87 | actual, = struct.unpack_from('<I', result.stdout, index * 4) |
| 88 | raise AssertionError(f'fma triple={triples[index]} observed={actual:08x} expected={fma(*triples[index]):08x}') |
| 89 | print(f'PASS exact FMA rational-reference triples={len(triples)} seed=94232 RN-even denormals signed-zeros infinities NaNs', flush=True) |
| 90 | |
| 91 | |
| 92 | def fixture(m, n, k, sensitive=False, values=FINITE): |
| 93 | # Guards immediately before and after every array; check the ENTIRE memory file. |
| 94 | ap = 64 |
| 95 | bp = ap + 4 * m * k + 32 |
| 96 | cp = bp + 4 * k * n + 32 |
| 97 | data = bytearray([0xa5] * (cp + 4 * m * n + 64)) |
| 98 | struct.pack_into('<QQQIII', data, 0, ap, bp, cp, m, n, k) |
| 99 | av = [values[(i * 7 + i // max(1, k)) % len(values)] for i in range(m * k)] |
| 100 | bv = [values[(i * 13 + i // max(1, n) + 3) % len(values)] for i in range(k * n)] |
| 101 | if sensitive: |
| 102 | assert (m, n, k) == (1, 1, 2) |
| 103 | av, bv = [0xbf800000, 0x3f800001], [0x3f800000, 0x3f7ffffe] |
| 104 | for i, bits in enumerate(av): |
| 105 | struct.pack_into('<I', data, ap + i * 4, bits) |
| 106 | for i, bits in enumerate(bv): |
| 107 | struct.pack_into('<I', data, bp + i * 4, bits) |
| 108 | expected = bytearray(data) |
| 109 | for row in range(m): |
| 110 | for col in range(n): |
| 111 | acc = 0 |
| 112 | for inner in range(k): |
| 113 | acc = fma(av[row * k + inner], bv[inner * n + col], acc) |
| 114 | struct.pack_into('<I', expected, cp + 4 * (row * n + col), acc) |
| 115 | return data, expected |
| 116 | |
| 117 | |
| 118 | def check(exe, text, mem, m, n, k, sensitive=False, values=FINITE): |
| 119 | data, expected = fixture(m, n, k, sensitive, values) |
| 120 | mem.write_bytes(data) |
| 121 | # Deliberate extra workgroup in BOTH dimensions checks masked columns and the s3 row guard. |
| 122 | result = subprocess.run([exe, str(text), str(mem), str(n + 64), str(m + 1)], |
| 123 | capture_output=True, timeout=180) |
| 124 | assert result.returncode == 0 and result.stdout == b'' and result.stderr == b'', result |
| 125 | actual = mem.read_bytes() |
| 126 | if actual != expected: |
| 127 | offset = next((i for i, (a, b) in enumerate(zip(actual, expected)) if a != b), None) |
| 128 | raise AssertionError(f'sgemm bit mismatch shape={(m,n,k)} byte={offset}') |
| 129 | |
| 130 | |
| 131 | def suite(exe, text, mutant_text, out): |
| 132 | mem = pathlib.Path(out) / 'sgemm-memory.bin' |
| 133 | for values, mode in ((FINITE, 'finite'), (VALUES, 'special')): |
| 134 | for shape in SHAPES: |
| 135 | check(exe, text, mem, *shape, values=values) |
| 136 | print(f'PASS sgemm M={shape[0]} N={shape[1]} K={shape[2]} inputs={mode} ordered-fma every-output-bit and all guards', flush=True) |
| 137 | check(exe, text, mem, 1, 1, 2, True) |
| 138 | fused = fma(0x3f800001, 0x3f7ffffe, 0xbf800000) |
| 139 | separate = fma(fma(0x3f800001, 0x3f7ffffe, 0), 0x3f800000, 0xbf800000) |
| 140 | assert fused != separate |
| 141 | try: |
| 142 | check(exe, mutant_text, mem, 1, 1, 2, True) |
| 143 | except AssertionError as error: |
| 144 | assert str(error).startswith('sgemm bit mismatch'), error |
| 145 | print(f'CONTROL sgemm-separate-mul-add CAUGHT fused={fused:08x} separate={separate:08x}', flush=True) |
| 146 | else: |
| 147 | raise AssertionError('unfused mutant escaped') |
| 148 | data, _ = fixture(1, 1, 1) |
| 149 | mem.write_bytes(data) |
| 150 | code = bytearray(pathlib.Path(text).read_bytes()) |
| 151 | needle = struct.pack('<I', (28 << 25) | (11 << 17) | (11 << 9) | 263) |
| 152 | assert code.count(needle) == 1 |
| 153 | index = code.index(needle) |
| 154 | struct.pack_into('<I', code, index, (28 << 25) | (11 << 17) | (11 << 9) | 19) |
| 155 | invalid = pathlib.Path(out) / 'constant-bus.text' |
| 156 | invalid.write_bytes(code) |
| 157 | result = subprocess.run([exe, str(invalid), str(mem), '1', '1'], capture_output=True, timeout=60) |
| 158 | assert result.returncode == 66 and result.stdout == b'' and result.stderr == b'', result |
| 159 | assert mem.read_bytes() == data |
| 160 | print('CONTROL addc-second-scalar-constant-bus CAUGHT exit=66 memory-unchanged', flush=True) |
| 161 | print(f'PASS sgemm shapes={len(SHAPES)} patterns=finite,special plus fused-sensitive shape and overdispatch X/Y guard groups hardware=NOT_RUN', flush=True) |
| 162 | |
| 163 | |
| 164 | def mutant(source, target): |
| 165 | original = pathlib.Path(source).read_text() |
| 166 | needle = 'I 5 270 6 4 0x3b' |
| 167 | assert original.count(needle) == 1 |
| 168 | changed = original.replace(needle, 'I 5 270 6 14 0x05\nI 5 270 4 4 0x01') |
| 169 | pathlib.Path(target).write_text(changed) |
| 170 | |
| 171 | |
| 172 | def summary(kernels): |
| 173 | import runpy |
| 174 | counts = runpy.run_path(str(pathlib.Path(__file__).with_name('oracle.py')))['COUNTS'] |
| 175 | semantics = runpy.run_path(str(pathlib.Path(__file__).with_name('semantics.py')))['CASES'] |
| 176 | fp8 = runpy.run_path(str(pathlib.Path(__file__).with_name('fp8gemv.py'))) |
| 177 | bf16 = runpy.run_path(str(pathlib.Path(__file__).with_name('bf16gemv.py'))) |
| 178 | gemv2 = runpy.run_path(str(pathlib.Path(__file__).with_name('gemv2.py'))) |
| 179 | attention = runpy.run_path(str(pathlib.Path(__file__).with_name('attention.py'))) |
| 180 | prep = runpy.run_path(str(pathlib.Path(__file__).with_name('prep.py'))) |
| 181 | token = runpy.run_path(str(pathlib.Path(__file__).with_name('token_ref.py'))) |
| 182 | norm = runpy.run_path(str(pathlib.Path(__file__).with_name('norm.py'))) |
| 183 | conv = runpy.run_path(str(pathlib.Path(__file__).with_name('gdnconv.py'))) |
| 184 | gdn = runpy.run_path(str(pathlib.Path(__file__).with_name('gdn.py'))) |
| 185 | decode = runpy.run_path(str(pathlib.Path(__file__).with_name('decode.py')))['SPECS'] |
| 186 | prep_sections = runpy.run_path(str(pathlib.Path(__file__).with_name('prep_section.py')))['SPECS'] |
| 187 | print(f'AMD-GFX942-EXEC PASS kernels={kernels.replace(" ", ",")} ' |
| 188 | f'counts={",".join(map(str, counts))} sgemm_shapes={len(SHAPES)} ' |
| 189 | f'sgemm_cases={2*len(SHAPES)+1} semantics_cases={len(semantics)} ' |
| 190 | f'fp8gemv_shapes={len(fp8["SHAPES"])} fp8gemv_cases={2*len(fp8["SHAPES"])+1} ' |
| 191 | f'fp8_conversion_bytes={len(range(256))} ' |
| 192 | f'bf16gemv_shapes={len(bf16["SHAPES"])} bf16gemv_cases={2*len(bf16["SHAPES"])+1} ' |
| 193 | f'gemv2_shapes={len(gemv2["SHAPES"])} gemv2_cases_per_kernel={2*len(gemv2["SHAPES"])+1} ' |
| 194 | f'gemv2_sampled_shapes={len(gemv2["LARGE"])} ' |
| 195 | f'attention_T={",".join(map(str, attention["SHAPES"]))} ' |
| 196 | f'attention_cases={len(attention["SHAPES"])+1} ' |
| 197 | f'prep_positions={",".join(map(str, prep["POSITIONS"]))} ' |
| 198 | f'prep_cases={len(prep["POSITIONS"])+1} gate_cases=1 ' |
| 199 | f'rope_cases={len(prep["ROPE_POSITIONS"])} ' |
| 200 | f'mlpsilu_counts={",".join(map(str, token["COUNTS"]))} ' |
| 201 | f'mlpsilu_cases={len(token["COUNTS"])} ' |
| 202 | f'rmsnorm5120_rows={",".join(map(str, sorted(set(r for r,_ in norm["CASES"]))))} ' |
| 203 | f'rmsnorm5120_cases={len(norm["CASES"])} ' |
| 204 | f'gdnconv_channels={conv["CHANNELS"]} gdnconv_cases={len(conv["CASES"])} ' |
| 205 | f'gdnqknorm_cases={len(gdn["QK_CASES"])} gdnstate_cases={len(gdn["STATE_CASES"])} ' |
| 206 | f'decode_cases={sum(len(s[2]) for s in decode)} prep_section_cases={sum(len(s[2]) for s in prep_sections)} ' |
| 207 | f'per_buffer_access_kernels={2+len(decode)+len(prep_sections)} hardware=NOT_RUN') |
| 208 | |
| 209 | |
| 210 | if __name__ == '__main__': |
| 211 | {'probe': probe, 'suite': suite, 'mutant': mutant, 'summary': summary}[sys.argv[1]](*sys.argv[2:]) |