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 / fp8block_fast.py
| 1 | #!/usr/bin/env python3 |
| 2 | # SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception |
| 3 | """Independent checkpoint oracle and private-output acceptance for fp8gemv_b128f. |
| 4 | Python is a measuring instrument only. Objects are emitted by seeded Omega hsaco.om. |
| 5 | Run under an externally held queen pool lock and nice; see fp8block_fast.md. |
| 6 | """ |
| 7 | import argparse |
| 8 | from fractions import Fraction |
| 9 | import hashlib |
| 10 | import json |
| 11 | from pathlib import Path |
| 12 | import runpy |
| 13 | import shutil |
| 14 | import struct |
| 15 | import subprocess |
| 16 | |
| 17 | PIN = '2c82480596bbdc50cda9626866209ef662d5834f278f839ff4ce0250c495029f' |
| 18 | NAME = 'fp8gemv_b128f' |
| 19 | SHAPES = ((17408, 5120), (5120, 17408), (12288, 5120), (1024, 5120), |
| 20 | (10240, 5120), (6144, 5120), (5120, 6144)) |
| 21 | |
| 22 | |
| 23 | def sha(path): |
| 24 | with Path(path).open('rb') as f: |
| 25 | return hashlib.file_digest(f, 'sha256').hexdigest() |
| 26 | |
| 27 | |
| 28 | def ocp(byte, sg): |
| 29 | """F8_E4M3: sign, exponent bias7, 3 fraction bits, signed zero, two NaNs. |
| 30 | No executor/native-FNUZ conversion routine is used to construct this table. |
| 31 | """ |
| 32 | sign, exponent, fraction = byte >> 7, (byte >> 3) & 15, byte & 7 |
| 33 | if exponent == 15 and fraction == 7: |
| 34 | return 0x7fc00000 |
| 35 | if exponent == 0: |
| 36 | value = Fraction(fraction, 512) |
| 37 | else: |
| 38 | value = Fraction(8 + fraction, 8) * Fraction(2) ** (exponent - 7) |
| 39 | return sg['round32'](-value if sign else value) | (sign << 31) |
| 40 | |
| 41 | |
| 42 | def result(weights, x, scales, table, sg): |
| 43 | # Independent exact RN-even oracle: four adjacent products, scale, lane acc; |
| 44 | # then one simultaneous XOR32,16,8,4,2,1 reduction for the complete row. |
| 45 | lanes = [0] * 64 |
| 46 | for base in range(0, len(weights), 256): |
| 47 | for lane in range(64): |
| 48 | start = base + lane * 4 |
| 49 | if start >= len(weights): |
| 50 | continue |
| 51 | partial = 0 |
| 52 | for col in range(start, min(start + 4, len(weights))): |
| 53 | partial = sg['fma'](table[weights[col]], x[col], partial) |
| 54 | lanes[lane] = sg['fma'](scales[start // 128] << 16, partial, lanes[lane]) |
| 55 | for xor in (32, 16, 8, 4, 2, 1): |
| 56 | lanes = [sg['fma'](a, 0x3f800000, lanes[i ^ xor]) for i, a in enumerate(lanes)] |
| 57 | return lanes[0] |
| 58 | |
| 59 | |
| 60 | def tolerance(data, actual, rows, table, sg, baseline): |
| 61 | # v11 policy unchanged. Exact rational evaluation is stronger than its f64 |
| 62 | # reference: the same f64-reference allowance remains in the bound. |
| 63 | wp, xp, sp, yp, m, k = struct.unpack_from('<QQQQII', data) |
| 64 | nb = (k + 127) // 128 |
| 65 | n = nb + 8 |
| 66 | gamma = lambda depth, u: depth * u / (1 - depth * u) |
| 67 | factor = gamma(n, Fraction(1, 2**24)) + gamma(2*k+n, Fraction(1, 2**53)) |
| 68 | x = list(struct.unpack_from('<' + 'I'*k, data, xp)) |
| 69 | different = [] |
| 70 | for row in rows: |
| 71 | weights = data[wp+row*k:wp+(row+1)*k] |
| 72 | scales = list(struct.unpack_from('<' + 'H'*nb, data, sp+2*(row//128)*nb)) |
| 73 | bits, = struct.unpack_from('<I', actual, yp+4*row) |
| 74 | old = baseline(weights, x, scales, table, sg) |
| 75 | if old != bits: |
| 76 | different.append({'row': row, 'baseline_bits': f'{old:08x}', 'fast_bits': f'{bits:08x}'}) |
| 77 | if any((w & 127) == 127 for w in weights): |
| 78 | assert bits & 0x7fffffff > 0x7f800000 |
| 79 | continue |
| 80 | products = [sg['finite'](table[w]) * sg['finite'](x[col]) * |
| 81 | sg['finite'](scales[col//128] << 16) for col, w in enumerate(weights)] |
| 82 | ideal, magnitude = sum(products, Fraction()), sum(map(abs, products), Fraction()) |
| 83 | bound = factor*magnitude + Fraction(1, 2**126) |
| 84 | assert bits & 0x7fffffff < 0x7f800000 |
| 85 | assert abs(sg['finite'](bits)-ideal) <= bound, (row, k, bits, ideal, bound) |
| 86 | return different |
| 87 | |
| 88 | |
| 89 | def fixture(m, k, rows, table, sg, real=None, all_bytes=False): |
| 90 | nb, mb = (k + 127) // 128, (m + 127) // 128 |
| 91 | wp = 64 |
| 92 | xp = (wp + m * k + 63) & ~3 |
| 93 | sp = xp + k * 4 + 64 |
| 94 | yp = (sp + mb * nb * 2 + 67) & ~3 |
| 95 | data = bytearray(b'\xa5') * (yp + m * 4 + 64) |
| 96 | struct.pack_into('<QQQQII', data, 0, wp, xp, sp, yp, m, k) |
| 97 | x = [sg['round32'](Fraction(((i * 13 + 5) % 31) - 15, 16)) for i in range(k)] |
| 98 | if all_bytes: |
| 99 | x = [0x3f800000] |
| 100 | for i, bits in enumerate(x): |
| 101 | struct.pack_into('<I', data, xp + i * 4, bits) |
| 102 | scales = [0x3f00 + ((i * 37 + 11) % 192) for i in range(mb * nb)] |
| 103 | if all_bytes: |
| 104 | scales = [0x3f80] * (mb * nb) |
| 105 | if real: |
| 106 | scales = list(struct.unpack('<' + 'H' * (mb * nb), real['scales'])) |
| 107 | for i, word in enumerate(scales): |
| 108 | struct.pack_into('<H', data, sp + i * 2, word) |
| 109 | expected_rows = {} |
| 110 | for row in rows: |
| 111 | weights = bytes((((i * 29 + row * 17 + i // 128) % 127) | ((i + row) % 2 << 7)) for i in range(k)) |
| 112 | if all_bytes: |
| 113 | weights = bytes([row]) |
| 114 | if real: |
| 115 | weights = real['rows'][row] |
| 116 | data[wp + row * k:wp + (row + 1) * k] = weights |
| 117 | expected_rows[row] = result(weights, x, scales[(row // 128) * nb:(row // 128 + 1) * nb], table, sg) |
| 118 | expected = bytearray(data) |
| 119 | for row, bits in expected_rows.items(): |
| 120 | struct.pack_into('<I', expected, yp + row * 4, bits) |
| 121 | spans = [('kernarg', 0, 40), ('W', wp, m * k), ('x', xp, k * 4), |
| 122 | ('scale_inv', sp, mb * nb * 2), ('y', yp, m * 4)] |
| 123 | return data, expected, spans |
| 124 | |
| 125 | |
| 126 | def mutate(source): |
| 127 | def replace(text, old, new): |
| 128 | assert text.count(old) == 1, old |
| 129 | return text.replace(old, new) |
| 130 | per_row = replace(source, 'I 5 135 1 1 16\n', 'I 8 257 1 1\n') |
| 131 | trans = replace(source, 'I 9 12 645 257 4\nI 9 13 646 257 4\n', |
| 132 | 'I 8 257 1 12\nI 8 128 1 13\n') |
| 133 | trans = replace(trans, 'I 8 132 1 45\nI 8 130 1 46\n', |
| 134 | 'I 2 12 129 4 1\nI 2 4 135 4 30\nI 2 4 129 4 0\n' |
| 135 | 'I 8 4 1 45\nI 8 4 1 46\nI 5 130 45 45 18\nI 5 129 46 46 18\n') |
| 136 | tail = replace(source, 'I 3 13 0 16\n', |
| 137 | 'I 3 13 0 16\nI 2 16 135 16 30\nI 2 16 135 16 28\n') |
| 138 | return {'per-row-scale': per_row, 'transposed-scale': trans, 'no-tail-block': tail} |
| 139 | |
| 140 | |
| 141 | def main(): |
| 142 | p = argparse.ArgumentParser() |
| 143 | p.add_argument('--omc', required=True, type=Path) |
| 144 | p.add_argument('--weights', required=True, type=Path) |
| 145 | p.add_argument('--out', required=True, type=Path) |
| 146 | args = p.parse_args() |
| 147 | if sha(args.omc) != PIN: |
| 148 | raise SystemExit(69) |
| 149 | root = Path(__file__).resolve().parents[2] |
| 150 | out = args.out.resolve() |
| 151 | out.mkdir(parents=True, exist_ok=False) |
| 152 | snapshot = out / 'source' |
| 153 | snapshot.mkdir() |
| 154 | sources = [root / 'backend/amd/gfx942' / f for f in |
| 155 | ('hsaco.om', NAME + '.isa', NAME + '-gfx942.s', 'exec/fp.om', 'exec/fma.om', 'exec/main.om')] |
| 156 | sources += [Path(__file__).with_name(f) for f in ('sgemm.py', 'row-probe.om', 'token_access.py', 'fp8block.py', 'fp8block_fast.py')] |
| 157 | for source in sources: |
| 158 | shutil.copyfile(source, snapshot / source.name) |
| 159 | source_hashes = {p.name: sha(p) for p in snapshot.iterdir()} |
| 160 | sg = runpy.run_path(str(snapshot / 'sgemm.py')) |
| 161 | instrument = runpy.run_path(str(snapshot / 'token_access.py'))['instrument'] |
| 162 | baseline = runpy.run_path(str(snapshot / 'fp8block.py'))['result'] |
| 163 | table = [ocp(i, sg) for i in range(256)] |
| 164 | (out / 'ocp-e4m3-f32.json').write_text(json.dumps(table) + '\n') |
| 165 | commands = [] |
| 166 | |
| 167 | def run(argv, *, stdout=None, input=None, expected=0): |
| 168 | proc = subprocess.run([str(a) for a in argv], input=input, capture_output=True, timeout=900) |
| 169 | commands.append({'argv': [str(a) for a in argv], 'exit': proc.returncode, |
| 170 | 'stdout_sha256': hashlib.sha256(proc.stdout).hexdigest(), |
| 171 | 'stderr': proc.stderr.decode(errors='replace')}) |
| 172 | (out / 'commands.json').write_text(json.dumps(commands, indent=2) + '\n') |
| 173 | assert proc.returncode == expected and not proc.stderr, commands[-1] |
| 174 | if stdout: |
| 175 | Path(stdout).write_bytes(proc.stdout) |
| 176 | return proc.stdout |
| 177 | |
| 178 | def compile_source(name, source): |
| 179 | src = out / (name + '.om') |
| 180 | src.write_text(source) |
| 181 | exe = out / name |
| 182 | run([args.omc], input=source.encode(), stdout=exe) |
| 183 | exe.chmod(0o755) |
| 184 | return exe |
| 185 | |
| 186 | producer_source = (snapshot / 'hsaco.om').read_text() |
| 187 | producer = compile_source('hsaco', producer_source) |
| 188 | second = run([args.omc], input=producer_source.encode()) |
| 189 | assert second == producer.read_bytes() |
| 190 | executor_source = ''.join((snapshot / f).read_text() for f in ('fp.om', 'fma.om')) |
| 191 | executor_source += (snapshot / 'main.om').read_text().split('fn main to int\n')[0] |
| 192 | executor_source += (snapshot / 'row-probe.om').read_text() |
| 193 | executor = compile_source('row-exec', executor_source) |
| 194 | assert run([args.omc], input=executor_source.encode()) == executor.read_bytes() |
| 195 | |
| 196 | def section(path, name): |
| 197 | # Independent minimal ELF64 section reader, not seeded producer internals. |
| 198 | blob = Path(path).read_bytes() |
| 199 | shoff = struct.unpack_from('<Q', blob, 40)[0] |
| 200 | entsize, count, stridx = struct.unpack_from('<HHH', blob, 58) |
| 201 | entries = [struct.unpack_from('<IIQQQQIIQQ', blob, shoff + i * entsize) for i in range(count)] |
| 202 | names = blob[entries[stridx][4]:entries[stridx][4] + entries[stridx][5]] |
| 203 | for entry in entries: |
| 204 | end = names.index(0, entry[0]) |
| 205 | if names[entry[0]:end].decode() == name: |
| 206 | return blob[entry[4]:entry[4] + entry[5]] |
| 207 | raise AssertionError(name) |
| 208 | |
| 209 | texts, objects = {}, {} |
| 210 | original = (snapshot / (NAME + '.isa')).read_text() |
| 211 | variants = {NAME: original, **{NAME + '-' + k: v for k, v in mutate(original).items()}} |
| 212 | for label, text in variants.items(): |
| 213 | isa = out / (label + '.isa') |
| 214 | isa.write_text(text) |
| 215 | obj = out / (label + '.hsaco') |
| 216 | run([producer, isa], stdout=obj) |
| 217 | assert run([producer, isa]) == obj.read_bytes() |
| 218 | raw = out / (label + '.text') |
| 219 | raw.write_bytes(section(obj, '.text')) |
| 220 | texts[label], objects[label] = raw, obj |
| 221 | llvm_obj = out / 'llvm-oracle.o' |
| 222 | run(['llvm-mc-18', '-triple=amdgcn-amd-amdhsa', '-mcpu=gfx942', '-filetype=obj', |
| 223 | snapshot / (NAME + '-gfx942.s'), '-o', llvm_obj]) |
| 224 | for name in ('.text', '.note'): |
| 225 | assert section(objects[NAME], name) == section(llvm_obj, name), name |
| 226 | a, b = section(objects[NAME], '.rodata'), section(llvm_obj, '.rodata') |
| 227 | assert len(a) == len(b) == 64 and a[:16] + a[24:] == b[:16] + b[24:], 'descriptor' |
| 228 | print('PASS seeded deterministic producer/executor; LLVM text, metadata, descriptor (entry relocation excluded)', flush=True) |
| 229 | cases, bounds, controls = [], [], [] |
| 230 | memory = out / 'memory.bin' |
| 231 | |
| 232 | def execute(exe, text, data, rows, m): |
| 233 | memory.write_bytes(data) |
| 234 | stdout = run([exe, text, memory, *rows, m]) |
| 235 | actual = memory.read_bytes() |
| 236 | return stdout, actual |
| 237 | |
| 238 | def check(label, m, k, rows, real=None, all_bytes=False, measure=False): |
| 239 | data, expected, spans = fixture(m, k, rows, table, sg, real, all_bytes) |
| 240 | exe = executor |
| 241 | if measure: |
| 242 | exe = compile_source('access-' + label, instrument(executor_source, [(p, n) for _, p, n in spans])) |
| 243 | stdout, actual = execute(exe, texts[NAME], data, rows, m) |
| 244 | if actual != expected: |
| 245 | first = next(i for i, (a, b) in enumerate(zip(actual, expected)) if a != b) |
| 246 | raise AssertionError(f'{label} byte {first}: actual={actual[first:first+4].hex()} expected={expected[first:first+4].hex()}') |
| 247 | differences = tolerance(data, actual, rows, table, sg, baseline) |
| 248 | if measure: |
| 249 | hits = struct.unpack('<' + 'Q' * (2 * len(spans)), stdout) |
| 250 | access = [{'name': name, 'bytes': n, 'max_read_offset': hits[i*2]-1 if hits[i*2] else None, |
| 251 | 'max_write_offset': hits[i*2+1]-1 if hits[i*2+1] else None} |
| 252 | for i, (name, _, n) in enumerate(spans)] |
| 253 | bounds.append({'case': label, 'M': m, 'K': k, 'sampled_rows': rows, 'buffers': access}) |
| 254 | else: |
| 255 | assert not stdout |
| 256 | cases.append({'case': label, 'M': m, 'K': k, 'rows': rows, 'overdispatch_row': m, |
| 257 | 'comparison': 'every memory byte; exact RN-even Fraction wave oracle', |
| 258 | 'checkpoint': real['evidence'] if real else None, |
| 259 | 'v11_tolerance': 'PASS unchanged gamma policy; exact rational reference', |
| 260 | 'baseline_bit_differences': differences}) |
| 261 | print(f'PASS {label} M={m} K={k} rows={rows} overdispatch={m} all-memory-byte-equal', flush=True) |
| 262 | return data, expected, spans |
| 263 | |
| 264 | check('all-ocp-bytes', 256, 1, list(range(256)), all_bytes=True) |
| 265 | for m, k in ((0, 1), (3, 0), (3, 1), (3, 63), (3, 64), (3, 65), (3, 127), |
| 266 | (3, 128), (3, 129), (3, 191), (3, 255), (3, 256), (257, 259), |
| 267 | (3, 511), (3, 512), (3, 1023), (3, 1024), (3, 1025), (3, 2049)): |
| 268 | rows = list(range(m)) if m < 4 else [0, 1, 127, 128, 255, 256] |
| 269 | check(f'tail-{m}-{k}', m, k, rows, measure=(m, k) == (257, 259)) |
| 270 | |
| 271 | manifest = Path(str(args.weights) + '.sha256') |
| 272 | pins = {line.split()[1]: line.split()[0] for line in manifest.read_text().splitlines()} |
| 273 | checkpoint_evidence = {'manifest_sha256': sha(manifest), 'shards': []} |
| 274 | found_shapes = set() |
| 275 | for layer in (0, 3): |
| 276 | shard = args.weights / f'layers-{layer}.safetensors' |
| 277 | digest = sha(shard) |
| 278 | assert digest == pins[shard.name], (shard.name, digest) |
| 279 | checkpoint_evidence['shards'].append({'file': shard.name, 'sha256': digest}) |
| 280 | with shard.open('rb') as f: |
| 281 | header_size, = struct.unpack('<Q', f.read(8)) |
| 282 | header = json.loads(f.read(header_size)) |
| 283 | start = header_size + 8 |
| 284 | for name, tensor in header.items(): |
| 285 | if not isinstance(tensor, dict) or tensor.get('dtype') != 'F8_E4M3': |
| 286 | continue |
| 287 | shape = tuple(tensor['shape']) |
| 288 | if shape not in SHAPES or shape in found_shapes: |
| 289 | continue |
| 290 | m, k = shape |
| 291 | rows = sorted({0, 1, 127, 128, m//2, m-1}) |
| 292 | scale_name = name + '_scale_inv' |
| 293 | scale = header[scale_name] |
| 294 | assert scale['dtype'] == 'BF16' and scale['shape'] == [(m+127)//128, (k+127)//128] |
| 295 | lo, hi = scale['data_offsets'] |
| 296 | f.seek(start + lo) |
| 297 | scales = f.read(hi-lo) |
| 298 | weights = {} |
| 299 | for row in rows: |
| 300 | f.seek(start + tensor['data_offsets'][0] + row * k) |
| 301 | weights[row] = f.read(k) |
| 302 | assert len(weights[row]) == k |
| 303 | evidence = {'shard': shard.name, 'shard_sha256': digest, 'weight': name, |
| 304 | 'weight_data_offsets': tensor['data_offsets'], 'scale': scale_name, |
| 305 | 'scale_sha256': hashlib.sha256(scales).hexdigest(), |
| 306 | 'row_sha256': {str(r): hashlib.sha256(w).hexdigest() for r, w in weights.items()}} |
| 307 | real = {'rows': weights, 'scales': scales, 'evidence': evidence} |
| 308 | check(f'checkpoint-{m}-{k}', m, k, rows, real=real, measure=True) |
| 309 | found_shapes.add(shape) |
| 310 | assert found_shapes == set(SHAPES), found_shapes |
| 311 | |
| 312 | # Non-square scale grid prevents a transposition from accidentally being the identity. |
| 313 | for mutant in mutate(original): |
| 314 | rows = [1] if mutant == 'per-row-scale' else [128, 256] |
| 315 | mutant_data, mutant_expected, spans = fixture(257, 389, rows, table, sg) |
| 316 | exe = compile_source('access-' + mutant, instrument(executor_source, [(p, n) for _, p, n in spans])) |
| 317 | stdout, actual = execute(exe, texts[NAME + '-' + mutant], mutant_data, rows, 257) |
| 318 | assert actual != mutant_expected, f'escaped {mutant}' |
| 319 | try: |
| 320 | tolerance(mutant_data, actual, rows, table, sg, baseline) |
| 321 | except AssertionError: |
| 322 | pass |
| 323 | else: |
| 324 | raise AssertionError(f'{mutant} escaped unchanged v11 tolerance') |
| 325 | hits = struct.unpack('<' + 'Q' * (2 * len(spans)), stdout) |
| 326 | access = [{'name': name, 'bytes': n, 'max_read_offset': hits[i*2]-1 if hits[i*2] else None, |
| 327 | 'max_write_offset': hits[i*2+1]-1 if hits[i*2+1] else None} |
| 328 | for i, (name, _, n) in enumerate(spans)] |
| 329 | bounds.append({'case': mutant, 'M': 257, 'K': 389, 'sampled_rows': rows, 'buffers': access}) |
| 330 | controls.append({'mutant': mutant, 'exit': 0, 'result': 'CAUGHT exact and unchanged v11 tolerance mismatch'}) |
| 331 | print(f'CONTROL {mutant} CAUGHT exact and v11 tolerance mismatch, executor exit=0', flush=True) |
| 332 | |
| 333 | # Each buffer's measured last byte is protected by a separate one-byte-short boundary. |
| 334 | data, expected, spans = fixture(257, 259, [0, 1, 127, 128, 255, 256], table, sg) |
| 335 | measured = next(b for b in bounds if b['case'] == 'tail-257-259')['buffers'] |
| 336 | for index, (name, base, length) in enumerate(spans): |
| 337 | last = max(x for x in (measured[index]['max_read_offset'], measured[index]['max_write_offset']) if x is not None) |
| 338 | short = [(p, n) for _, p, n in spans] |
| 339 | short[index] = (base, last) |
| 340 | exe = compile_source('short-' + name, instrument(executor_source, short)) |
| 341 | memory.write_bytes(data) |
| 342 | assert run([exe, texts[NAME], memory, 0, 1, 127, 128, 255, 256, 257], expected=68) == b'' |
| 343 | controls.append({'buffer': name, 'result': 'CAUGHT one-byte-short span', 'exit': 68}) |
| 344 | print(f'CONTROL short-{name} CAUGHT exit=68', flush=True) |
| 345 | memory.unlink() |
| 346 | report = {'schema': 'fp8block-fast-acceptance-v1', 'status': 'EXERCISED', 'hardware': 'NOT_RUN', |
| 347 | 'performance': 'NOT_RUN', 'compiler_sha256': PIN, 'source_sha256': source_hashes, |
| 348 | 'checkpoint': checkpoint_evidence, 'decode_table_sha256': sha(out / 'ocp-e4m3-f32.json'), |
| 349 | 'kernarg_size': 40, 'grid_workgroups': ['M', 1, 1], 'block': [64, 1, 1], |
| 350 | 'objects': {k: {'file': v.name, 'sha256': sha(v)} for k, v in objects.items()}, |
| 351 | 'cases': cases, 'bounds': bounds, 'controls': controls} |
| 352 | (out / 'report.json').write_text(json.dumps(report, indent=2) + '\n') |
| 353 | print(f'PASS fp8gemv_b128f cases={len(cases)} controls={len(controls)} hardware=NOT_RUN performance=NOT_RUN', flush=True) |
| 354 | |
| 355 | |
| 356 | if __name__ == '__main__': |
| 357 | main() |