interplane.Get Omega
Read in your language

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

branch main Branches Tags History

CUDApp / tests / amd-exec / fp8block.py

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