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

105 lines · 6376 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 v11 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):
18 run, dest = Path(run_dir).resolve(), Path(destination).resolve()
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_b128.isa': 'backend/amd/gfx942/fp8gemv_b128.isa',
24 'fp8gemv_b128-gfx942.s': 'backend/amd/gfx942/fp8gemv_b128-gfx942.s',
25 'fp8block.py': 'tests/amd-exec/fp8block.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 dest.mkdir(parents=True, exist_ok=False)
33 shutil.copytree(run / 'source', dest / 'source')
34 for file in ('report.json', 'commands.json', 'ocp-e4m3-f32.json'):
35 shutil.copyfile(run / file, dest / file)
36 source = (run / 'source/fp8gemv_b128.isa').read_text()
37 args, kernarg = [], None
38 for line in source.splitlines():
39 words = line.split()
40 if words and words[0] == 'K':
41 kernarg = int(words[2])
42 if words and words[0] == 'A':
43 args.append({'name': words[1], 'offset': int(words[2]), 'size': int(words[3]),
44 'kind': 'global_buffer' if words[4] == '0' else 'by_value'})
45 assert kernarg == report['kernarg_size']
46 objects = []
47 for name, entry in report['objects'].items():
48 shutil.copyfile(run / entry['file'], dest / entry['file'])
49 shutil.copyfile(run / (name + '.isa'), dest / (name + '.isa'))
50 suffix = name.removeprefix('fp8gemv_b128-')
51 access = [b for b in report['bounds'] if b['case'] == suffix] if name != 'fp8gemv_b128' else [
52 b for b in report['bounds'] if b['case'].startswith(('checkpoint-', 'tail-'))]
53 assert access
54 objects.append({**entry, 'entry': 'fp8gemv_b128', 'bytes': (dest / entry['file']).stat().st_size,
55 'role': 'kernel' if name == 'fp8gemv_b128' else 'deliberately_wrong_control',
56 'table_sha256': sha(dest / (name + '.isa')), 'access': access})
57 manifest = {'schema': 'gfx942-notebook-bundle-v11', 'source_head': head,
58 'compiler_sha256': report['compiler_sha256'], 'hardware': 'NOT_RUN',
59 'performance': 'NOT_RUN', 'evidence': {
60 file: {'file': file, 'sha256': sha(dest / file)}
61 for file in ('report.json', 'commands.json', 'ocp-e4m3-f32.json')},
62 'kernels': [{'name': 'fp8gemv_b128', 'kernarg_size': kernarg, 'kernarg': args,
63 'grid_workgroups': report['grid_workgroups'], 'block': report['block'],
64 'scale_layout': 'BF16 [ceil(M/128)][ceil(K/128)] row-major',
65 'weight_encoding': 'OCP F8_E4M3, unmodified checkpoint bytes',
66 'cases': report['cases'], 'controls_caught': report['controls'],
67 'objects': objects}]}
68 (dest / 'list.json').write_text(json.dumps(manifest, indent=2) + '\n')
69 lines = ['# gfx942 checkpoint block-FP8 kernel bundle', '', f'Source head: `{head}`.',
70 f"Seeded compiler SHA256: `{report['compiler_sha256']}`.",
71 'Hardware: **NOT_RUN**. Performance: **NOT_RUN**.', '',
72 'Objects are emitted by seeded Omega `hsaco.om`; LLVM is an independent encoding oracle.',
73 'Real-shape tests retain full dimensions/strides but execute the listed sampled rows.',
74 'The full acceptance report, executed commands and exact input source snapshots are included.', '',
75 '| Object | Role | Bytes | SHA256 |', '|---|---|---:|---|']
76 for obj in objects:
77 lines.append(f"| {obj['file']} | {obj['role']} | {obj['bytes']} | `{obj['sha256']}` |")
78 lines += ['', '## fp8gemv_b128 ABI', '', f'Kernarg bytes: **{kernarg}**.',
79 f"Workgroup grid: `{report['grid_workgroups']}`. Threads per workgroup: `{report['block']}`.",
80 'W: raw OCP E4M3; x/y: FP32; scale_inv: packed BF16 row-major block grid.', '',
81 '| Argument | Offset | Bytes | Kind |', '|---|---:|---:|---|']
82 for arg in args:
83 lines.append(f"| {arg['name']} | {arg['offset']} | {arg['size']} | {arg['kind']} |")
84 lines += ['', '## Measured per-buffer bounds', '',
85 'Offsets are inclusive bytes from each buffer base; `None` means no access.',
86 'Every measurement is executor evidence, not a device memory trace.', '']
87 for obj in objects:
88 lines += [f"### {obj['file']}", '']
89 for bound in obj['access']:
90 lines += [f"Case `{bound['case']}`: M={bound['M']}, K={bound['K']}; rows={bound['sampled_rows']}.", '',
91 '| Buffer | Allocated bytes | Last read | Last write |', '|---|---:|---:|---:|']
92 for buf in bound['buffers']:
93 lines.append(f"| {buf['name']} | {buf['bytes']} | {buf['max_read_offset']} | {buf['max_write_offset']} |")
94 lines.append('')
95 lines += ['## Negative controls', '']
96 for control in report['controls']:
97 lines.append(f"- {control.get('mutant', control.get('buffer'))}: {control['result']}; exit {control['exit']}.")
98 (dest / 'list.md').write_text('\n'.join(lines) + '\n')
99 files = sorted(p for p in dest.rglob('*') if p.is_file())
100 (dest / 'SHA256SUMS').write_text(''.join(f'{sha(p)} {p.relative_to(dest)}\n' for p in files))
101 print(json.dumps({'bundle': str(dest), 'source_head': head, 'objects': report['objects']}, indent=2))
102
103
104if __name__ == '__main__':
105 main(*sys.argv[1:])