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 / oracle.py
| 1 | #!/usr/bin/env python3 |
| 2 | # SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception |
| 3 | """Test only. Python binary64 addition + struct binary32 rounding is the independent oracle. |
| 4 | Binary32 operands add exactly in binary64 when their exponents are close enough to |
| 5 | matter to binary32 rounding. At wider separation the small operand cannot change |
| 6 | round-to-nearest binary32. Overflow is signed infinity. NaNs are canonicalized to |
| 7 | 0x7fc00000 (executor policy, not a claim about hardware NaN payload propagation). |
| 8 | No production code, LLVM disassembly, or .isa parsing implements the reference. |
| 9 | """ |
| 10 | import math |
| 11 | import pathlib |
| 12 | import random |
| 13 | import struct |
| 14 | import subprocess |
| 15 | import sys |
| 16 | |
| 17 | COUNTS = (0, 1, 63, 64, 65, 200) |
| 18 | # Raw encodings: subnormal boundaries, both zeros, infinities, qNaN/sNaN, |
| 19 | # cancellation, overflow, half-ULP ties (even/odd), large exponent gaps. |
| 20 | PAIRS = ( |
| 21 | (0x00000001, 0x00000001), (0x007fffff, 0x00000001), |
| 22 | (0x00800000, 0x807fffff), (0x80000001, 0x80000001), |
| 23 | (0x00000000, 0x80000000), (0x80000000, 0x80000000), |
| 24 | (0x00000000, 0x00000000), (0x7f800000, 0x3f800000), |
| 25 | (0xff800000, 0xbf800000), (0x7f800000, 0xff800000), |
| 26 | (0x7fc12345, 0x3f800000), (0x7f812345, 0xffc12345), |
| 27 | (0x7f7fffff, 0x7f7fffff), (0xff7fffff, 0xff7fffff), |
| 28 | (0x3f800000, 0xbf800000), (0x3f800000, 0x33800000), |
| 29 | (0x3f800001, 0x33800000), (0xbf800001, 0xb3800000), |
| 30 | (0x7f7fffff, 0x00000001), (0x00800001, 0x80000001), |
| 31 | (0x3f800000, 0x80000001), (0x80800000, 0x007fffff), |
| 32 | (0x00000001, 0x80000001), (0x7f800000, 0x7f800000), |
| 33 | ) |
| 34 | |
| 35 | |
| 36 | def addref(a, b): |
| 37 | x, = struct.unpack('<f', struct.pack('<I', a)) |
| 38 | y, = struct.unpack('<f', struct.pack('<I', b)) |
| 39 | z = x + y |
| 40 | if math.isnan(z): |
| 41 | return 0x7fc00000 |
| 42 | try: |
| 43 | return struct.unpack('<I', struct.pack('<f', z))[0] |
| 44 | except OverflowError: |
| 45 | return 0xff800000 if z < 0 else 0x7f800000 |
| 46 | |
| 47 | |
| 48 | def extract(source, target): |
| 49 | data = pathlib.Path(source).read_bytes() |
| 50 | assert data[:7] == b'\x7fELF\x02\x01\x01' |
| 51 | off, = struct.unpack_from('<Q', data, 40) |
| 52 | size, num, names = struct.unpack_from('<HHH', data, 58) |
| 53 | assert size == 64 and names < num and off + size * num <= len(data) |
| 54 | sections = [struct.unpack_from('<IIQQQQIIQQ', data, off + size * i) for i in range(num)] |
| 55 | shstr = sections[names] |
| 56 | strings = data[shstr[4]:shstr[4] + shstr[5]] |
| 57 | matches = [] |
| 58 | for sh in sections: |
| 59 | assert sh[0] < len(strings) |
| 60 | end = strings.index(0, sh[0]) |
| 61 | if strings[sh[0]:end] == b'.text': |
| 62 | assert sh[1] == 1 and sh[2] & 4 and sh[4] + sh[5] <= len(data) |
| 63 | matches.append(data[sh[4]:sh[4] + sh[5]]) |
| 64 | assert len(matches) == 1 and matches[0] and len(matches[0]) % 4 == 0 |
| 65 | pathlib.Path(target).write_bytes(matches[0]) |
| 66 | |
| 67 | |
| 68 | def fixture(n, pairs): |
| 69 | capacity = max(64, ((n + 63) // 64) * 64) + 64 |
| 70 | a = 32 |
| 71 | b = a + capacity * 4 |
| 72 | c = b + capacity * 4 |
| 73 | data = bytearray([0xa5] * (c + capacity * 4 + 32)) |
| 74 | struct.pack_into('<QQQI', data, 0, a, b, c, n) |
| 75 | expected = bytearray(data) |
| 76 | for i in range(capacity): |
| 77 | x, y = pairs[i % len(pairs)] |
| 78 | struct.pack_into('<I', data, a + 4 * i, x) |
| 79 | struct.pack_into('<I', data, b + 4 * i, y) |
| 80 | expected[:] = data |
| 81 | for i in range(n): |
| 82 | x, y = pairs[i % len(pairs)] |
| 83 | struct.pack_into('<I', expected, c + 4 * i, addref(x, y)) |
| 84 | return data, expected |
| 85 | |
| 86 | |
| 87 | def invoke(exe, text, mem, expected_rc=0, count_offset=24): |
| 88 | count, = struct.unpack_from('<I', mem.read_bytes(), count_offset) |
| 89 | result = subprocess.run([exe, str(text), str(mem), str(max(1, count)), '1'], |
| 90 | capture_output=True, timeout=60) |
| 91 | assert result.returncode == expected_rc, (text, result.returncode, expected_rc, result.stderr) |
| 92 | assert result.stdout == b'' and result.stderr == b'', (result.stdout, result.stderr) |
| 93 | |
| 94 | |
| 95 | def check(exe, text, mem, n, pairs): |
| 96 | data, expected = fixture(n, pairs) |
| 97 | mem.write_bytes(data) |
| 98 | invoke(exe, text, mem) |
| 99 | actual = mem.read_bytes() |
| 100 | if actual != expected: |
| 101 | offset = next((i for i, (x, y) in enumerate(zip(actual, expected)) if x != y), None) |
| 102 | raise AssertionError(f'bit mismatch count={n} byte={offset} length={len(actual)}/{len(expected)}') |
| 103 | # The whole-file comparison also enforces unchanged kernarg, inputs, past-count and guard bytes. |
| 104 | |
| 105 | |
| 106 | def suite(exe, text, flipped, out): |
| 107 | out = pathlib.Path(out) |
| 108 | mem = out / 'memory.bin' |
| 109 | for n in COUNTS: |
| 110 | check(exe, text, mem, n, PAIRS) |
| 111 | print(f'PASS count={n} every-output-bit and past-count guards', flush=True) |
| 112 | rng = random.Random(942) |
| 113 | pairs = [(rng.getrandbits(32), rng.getrandbits(32)) for _ in range(4096)] |
| 114 | check(exe, text, mem, len(pairs), pairs) |
| 115 | print(f'PASS random binary32 pairs={len(pairs)} seed=942', flush=True) |
| 116 | try: |
| 117 | check(exe, flipped, mem, 200, PAIRS) |
| 118 | except AssertionError as error: |
| 119 | assert str(error).startswith('bit mismatch'), error |
| 120 | print('CONTROL one-bit-vadd-operand CAUGHT bit mismatch', flush=True) |
| 121 | else: |
| 122 | raise AssertionError('one-bit mutant escaped') |
| 123 | original = pathlib.Path(text).read_bytes() |
| 124 | data, _ = fixture(0, PAIRS) |
| 125 | words = list(struct.unpack('<' + 'I' * (len(original) // 4), original)) |
| 126 | branch_index = next(i for i, word in enumerate(words) if word >> 16 == 0xbf88) |
| 127 | literal_index = next(i + 1 for i, word in enumerate(words) |
| 128 | if word >> 25 == 0x13 and word & 511 == 255) |
| 129 | words[branch_index] = 0xbf880000 | ((literal_index - branch_index - 1) & 65535) |
| 130 | bad_branch = struct.pack('<' + 'I' * len(words), *words) |
| 131 | # Valid but unsupported S_CBRANCH_VCCZ (CDNA3 p140). Reject even after endpgm. |
| 132 | for label, code, rc in ( |
| 133 | ('outside-subset', struct.pack('<I', 0xbf860000) + original, 66), |
| 134 | ('unreachable-outside-subset', original + struct.pack('<I', 0xbf860000), 66), |
| 135 | ('truncated-word', original[:-1], 65), |
| 136 | ('branch-inside-literal', bad_branch, 65), |
| 137 | ): |
| 138 | bad = out / (label + '.text') |
| 139 | bad.write_bytes(code) |
| 140 | mem.write_bytes(data) |
| 141 | invoke(exe, bad, mem, rc) |
| 142 | assert mem.read_bytes() == data |
| 143 | print(f'CONTROL {label} CAUGHT exit={rc} memory-unchanged', flush=True) |
| 144 | # Invalid guest pointer cannot become a host access, or silently extend the memory file. |
| 145 | data, _ = fixture(1, PAIRS) |
| 146 | struct.pack_into('<Q', data, 0, 0xffffffffffffffff) |
| 147 | mem.write_bytes(data) |
| 148 | invoke(exe, text, mem, 67) |
| 149 | assert mem.read_bytes() == data |
| 150 | print('CONTROL memory-range CAUGHT exit=67 memory-unchanged', flush=True) |
| 151 | |
| 152 | |
| 153 | def reduce_ref(row): |
| 154 | result = row[0] |
| 155 | for value in row[1:]: |
| 156 | result = addref(result, value) |
| 157 | return result |
| 158 | |
| 159 | |
| 160 | def fsum_fixture(n, rows): |
| 161 | capacity = max(64, ((n + 63) // 64) * 64) + 64 |
| 162 | x = 32 |
| 163 | o = x + capacity * 16 * 4 |
| 164 | data = bytearray([0xa5] * (o + capacity * 4 + 32)) |
| 165 | struct.pack_into('<QQI', data, 0, x, o, n) |
| 166 | for g in range(capacity): |
| 167 | row = rows[g % len(rows)] |
| 168 | assert len(row) == 16 |
| 169 | struct.pack_into('<16I', data, x + g * 64, *row) |
| 170 | expected = bytearray(data) |
| 171 | for g in range(n): |
| 172 | struct.pack_into('<I', expected, o + g * 4, reduce_ref(rows[g % len(rows)])) |
| 173 | return data, expected |
| 174 | |
| 175 | |
| 176 | def fsum_check(exe, text, mem, n, rows): |
| 177 | data, expected = fsum_fixture(n, rows) |
| 178 | mem.write_bytes(data) |
| 179 | invoke(exe, text, mem, count_offset=16) |
| 180 | actual = mem.read_bytes() |
| 181 | if actual != expected: |
| 182 | offset = next((i for i, (a, b) in enumerate(zip(actual, expected)) if a != b), None) |
| 183 | raise AssertionError(f'fsum bit mismatch rows={n} byte={offset} length={len(actual)}/{len(expected)}') |
| 184 | |
| 185 | |
| 186 | def reverse_table(source, target): |
| 187 | lines = pathlib.Path(source).read_text().splitlines() |
| 188 | changed = [] |
| 189 | offsets = [] |
| 190 | for line in lines: |
| 191 | fields = line.split('#', 1)[0].split() |
| 192 | if len(fields) == 14 and fields[:2] == ['I', '7'] and fields[7] == '0x14': |
| 193 | old = int(fields[2]) |
| 194 | offsets.append(old) |
| 195 | fields[2] = str(60 - old) |
| 196 | line = ' '.join(fields) |
| 197 | changed.append(line) |
| 198 | assert offsets == list(range(0, 64, 4)), offsets |
| 199 | pathlib.Path(target).write_text('\n'.join(changed) + '\n') |
| 200 | |
| 201 | |
| 202 | def fsum_suite(exe, text, reversed_text, out): |
| 203 | mem = pathlib.Path(out) / 'fsum-memory.bin' |
| 204 | sensitive = [0x4c000000, 0xcc000000, 0x3f800000] + [0] * 13 |
| 205 | rows = [sensitive, [0x80000000] * 16, [1] * 16, [0] * 16] |
| 206 | rows += [[a, b] * 8 for a, b in PAIRS] |
| 207 | for n in COUNTS: |
| 208 | fsum_check(exe, text, mem, n, rows) |
| 209 | print(f'PASS fsum16 rows={n} left-to-right every-output-bit and past-count guards', flush=True) |
| 210 | rng = random.Random(94216) |
| 211 | random_rows = [[rng.getrandbits(32) for _ in range(16)] for _ in range(200)] |
| 212 | fsum_check(exe, text, mem, len(random_rows), random_rows) |
| 213 | print('PASS fsum16 random rows=200 seed=94216 all 15 rounded additions', flush=True) |
| 214 | left = reduce_ref(sensitive) |
| 215 | right = reduce_ref(list(reversed(sensitive))) |
| 216 | assert left != right |
| 217 | try: |
| 218 | fsum_check(exe, reversed_text, mem, 1, [sensitive]) |
| 219 | except AssertionError as error: |
| 220 | assert str(error).startswith('fsum bit mismatch'), error |
| 221 | print(f'CONTROL fsum16-right-to-left CAUGHT bits left={left:08x} right={right:08x} ' |
| 222 | f'row={[f"{value:08x}" for value in sensitive]}', flush=True) |
| 223 | else: |
| 224 | raise AssertionError('fsum16 right-to-left mutant escaped') |
| 225 | |
| 226 | |
| 227 | if __name__ == '__main__': |
| 228 | if sys.argv[1] == 'extract': |
| 229 | extract(*sys.argv[2:]) |
| 230 | elif sys.argv[1] == 'suite': |
| 231 | suite(*sys.argv[2:]) |
| 232 | elif sys.argv[1] == 'reverse-table': |
| 233 | reverse_table(*sys.argv[2:]) |
| 234 | elif sys.argv[1] == 'fsum-suite': |
| 235 | fsum_suite(*sys.argv[2:]) |
| 236 | else: |
| 237 | raise SystemExit('unknown oracle action') |