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_fast_bundle.py

138 lines · 8464 bytes Raw Blame History
1#!/usr/bin/env python3
2# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
3"""Notebook-glue only: derive the immutable v13 ABI/evidence bundle from a run."""
4import hashlib
5import json
6from pathlib import Path
7import shutil
8import subprocess
9import sys
10
11
12def sha(path):
13 with Path(path).open('rb') as f:
14 return hashlib.file_digest(f, 'sha256').hexdigest()
15
16
17def main(run_dir, destination, baseline_dir):
18 run, dest, base = map(lambda p: Path(p).resolve(), (run_dir, destination, baseline_dir))
19 report = json.loads((run / 'report.json').read_text())
20 assert report['status'] == 'EXERCISED'
21 root = Path(__file__).resolve().parents[2]
22 head = subprocess.check_output(['git', '-C', str(root), 'rev-parse', 'HEAD'], text=True).strip()
23 own_paths = {'fp8gemv_b128f.isa': 'backend/amd/gfx942/fp8gemv_b128f.isa',
24 'fp8gemv_b128f-gfx942.s': 'backend/amd/gfx942/fp8gemv_b128f-gfx942.s',
25 'fp8block_fast.py': 'tests/amd-exec/fp8block_fast.py'}
26 for name, path in own_paths.items():
27 committed = subprocess.check_output(['git', '-C', str(root), 'show', head + ':' + path])
28 assert hashlib.sha256(committed).hexdigest() == report['source_sha256'][name], path
29 # Input validation happens before creating the destination. Never overwrite a bundle.
30 for entry in report['objects'].values():
31 assert sha(run / entry['file']) == entry['sha256'], entry
32 baseline = json.loads((base / 'list.json').read_text())
33 assert baseline['compiler_sha256'] == report['compiler_sha256']
34 previous = next(k for k in baseline['kernels'] if k['name'] == 'fp8gemv_b128')
35 previous['objects'] = [o for o in previous['objects'] if o['role'] == 'kernel']
36 assert len(previous['objects']) == 1
37 for obj in previous['objects']:
38 assert sha(base / obj['file']) == obj['sha256']
39 table = Path(obj['file']).with_suffix('.isa')
40 assert sha(base / table) == obj['table_sha256']
41 committed = subprocess.check_output(['git', '-C', str(root), 'show',
42 baseline['source_head'] + ':backend/amd/gfx942/' + str(table)])
43 assert hashlib.sha256(committed).hexdigest() == obj['table_sha256']
44 notebook = Path(__file__).with_name('fp8block_fast_notebook')
45 for p in notebook.iterdir():
46 if p.is_file():
47 committed = subprocess.check_output(['git', '-C', str(root), 'show', head + ':' + str(p.relative_to(root))])
48 assert hashlib.sha256(committed).hexdigest() == sha(p)
49 dest.mkdir(parents=True, exist_ok=False)
50 shutil.copytree(run / 'source', dest / 'source')
51 shutil.copytree(base / 'source', dest / 'baseline/source')
52 for file in ('list.json', 'report.json', 'commands.json'):
53 shutil.copyfile(base / file, dest / 'baseline' / file)
54 for obj in previous['objects']:
55 shutil.copyfile(base / obj['file'], dest / 'baseline' / obj['file'])
56 table = Path(obj['file']).with_suffix('.isa')
57 shutil.copyfile(base / table, dest / 'baseline' / table)
58 obj['file'] = 'baseline/' + obj['file']
59 for p in notebook.iterdir():
60 if p.is_file():
61 shutil.copyfile(p, dest / p.name)
62 for file in ('report.json', 'commands.json', 'ocp-e4m3-f32.json'):
63 shutil.copyfile(run / file, dest / file)
64 source = (run / 'source/fp8gemv_b128f.isa').read_text()
65 args, kernarg = [], None
66 for line in source.splitlines():
67 words = line.split()
68 if words and words[0] == 'K':
69 kernarg = int(words[2])
70 if words and words[0] == 'A':
71 args.append({'name': words[1], 'offset': int(words[2]), 'size': int(words[3]),
72 'kind': 'global_buffer' if words[4] == '0' else 'by_value'})
73 assert kernarg == report['kernarg_size']
74 objects = []
75 for name, entry in report['objects'].items():
76 shutil.copyfile(run / entry['file'], dest / entry['file'])
77 shutil.copyfile(run / (name + '.isa'), dest / (name + '.isa'))
78 suffix = name.removeprefix('fp8gemv_b128f-')
79 access = [b for b in report['bounds'] if b['case'] == suffix] if name != 'fp8gemv_b128f' else [
80 b for b in report['bounds'] if b['case'].startswith(('checkpoint-', 'tail-'))]
81 assert access
82 objects.append({**entry, 'entry': 'fp8gemv_b128f', 'bytes': (dest / entry['file']).stat().st_size,
83 'role': 'kernel' if name == 'fp8gemv_b128f' else 'deliberately_wrong_control',
84 'table_sha256': sha(dest / (name + '.isa')), 'access': access})
85 manifest = {'schema': 'gfx942-notebook-bundle-v13', 'source_head': head,
86 'compiler_sha256': report['compiler_sha256'], 'hardware': 'NOT_RUN',
87 'performance': 'NOT_RUN', 'evidence': {
88 file: {'file': file, 'sha256': sha(dest / file)}
89 for file in ('report.json', 'commands.json', 'ocp-e4m3-f32.json')},
90 'kernels': [{'name': 'fp8gemv_b128f', 'kernarg_size': kernarg, 'kernarg': args,
91 'grid_workgroups': report['grid_workgroups'], 'block': report['block'],
92 'scale_layout': 'BF16 [ceil(M/128)][ceil(K/128)] row-major',
93 'weight_encoding': 'OCP F8_E4M3, unmodified checkpoint bytes',
94 'cases': report['cases'], 'controls_caught': report['controls'],
95 'objects': objects}]}
96 manifest['baseline_source_head'] = baseline['source_head']
97 manifest['kernels'].append(previous)
98 (dest / 'list.json').write_text(json.dumps(manifest, indent=2) + '\n')
99 lines = ['# gfx942 checkpoint block-FP8 kernel bundle', '', f'Source head: `{head}`.',
100 f"Seeded compiler SHA256: `{report['compiler_sha256']}`.",
101 'Hardware: **NOT_RUN**. Performance: **NOT_RUN**.', '',
102 'Objects are emitted by seeded Omega `hsaco.om`; LLVM is an independent encoding oracle.',
103 'Real-shape tests retain full dimensions/strides but execute the listed sampled rows.',
104 'The full acceptance report, executed commands and exact input source snapshots are included.', '',
105 '| Object | Role | Bytes | SHA256 |', '|---|---|---:|---|']
106 for obj in objects:
107 lines.append(f"| {obj['file']} | {obj['role']} | {obj['bytes']} | `{obj['sha256']}` |")
108 for obj in previous['objects']:
109 lines.append(f"| {obj['file']} | baseline kernel | {obj['bytes']} | `{obj['sha256']}` |")
110 lines += ['', f"Baseline source head: `{baseline['source_head']}`; original acceptance in `baseline/`."]
111 lines += ['', '## fp8gemv_b128f ABI', '', f'Kernarg bytes: **{kernarg}**.',
112 f"Workgroup grid: `{report['grid_workgroups']}`. Threads per workgroup: `{report['block']}`.",
113 'W: raw OCP E4M3; x/y: FP32; scale_inv: packed BF16 row-major block grid.', '',
114 '| Argument | Offset | Bytes | Kind |', '|---|---:|---:|---|']
115 for arg in args:
116 lines.append(f"| {arg['name']} | {arg['offset']} | {arg['size']} | {arg['kind']} |")
117 lines += ['', '## Measured per-buffer bounds', '',
118 'Offsets are inclusive bytes from each buffer base; `None` means no access.',
119 'Every measurement is executor evidence, not a device memory trace.', '']
120 for obj in objects:
121 lines += [f"### {obj['file']}", '']
122 for bound in obj['access']:
123 lines += [f"Case `{bound['case']}`: M={bound['M']}, K={bound['K']}; rows={bound['sampled_rows']}.", '',
124 '| Buffer | Allocated bytes | Last read | Last write |', '|---|---:|---:|---:|']
125 for buf in bound['buffers']:
126 lines.append(f"| {buf['name']} | {buf['bytes']} | {buf['max_read_offset']} | {buf['max_write_offset']} |")
127 lines.append('')
128 lines += ['## Negative controls', '']
129 for control in report['controls']:
130 lines.append(f"- {control.get('mutant', control.get('buffer'))}: {control['result']}; exit {control['exit']}.")
131 (dest / 'list.md').write_text('\n'.join(lines) + '\n')
132 files = sorted(p for p in dest.rglob('*') if p.is_file())
133 (dest / 'SHA256SUMS').write_text(''.join(f'{sha(p)} {p.relative_to(dest)}\n' for p in files))
134 print(json.dumps({'bundle': str(dest), 'source_head': head, 'objects': report['objects']}, indent=2))
135
136
137if __name__ == '__main__':
138 main(*sys.argv[1:])