interplane.Get Omega
Read in your language

omega-kernel-smoke

Minimal Omega GPU kernel smoke verification harness

Brought by drakestapleton

branch main Branches Tags History

omega-kernel-smoke / tools / cases.py

418 lines · 18617 bytes Raw Blame History
1#!/usr/bin/env python3
2# SPDX-License-Identifier: Apache-2.0
3"""Case planner and verdict writer for tools/check.sh (verification side only).
4
5It never generates IR, SPIR-V or native code. It reads kernel.om signatures,
6cases.tsv and reference.py, plans the cases, and after the runs compares the
7AArch64 and SPIR-V results with reference.py, then writes the receipt.
8
9INTERIM host glue (Python). Successor: an Omega conductor unit; the reference
10oracle stays a separate language on purpose, so it is independent of omc.
11
12usage: cases.py expand BUILD_DIR | cases.py report BUILD_DIR
13"""
14import datetime
15import hashlib
16import json
17import os
18import platform
19import random
20import re
21import shutil
22import subprocess
23import sys
24
25MASK = (1 << 64) - 1
26WIDTH = {'uchar': 8, 'ushort': 16, 'uint': 32, 'ulong': 64,
27 'byte': 8, 'short': 16, 'int': 32, 'long': 64}
28SIGNED = {'byte', 'short', 'int', 'long'}
29RETURNS = set(WIDTH) | {'bool', 'void'}
30SIGNATURE = re.compile(r'^fn\s+(\w+)((?:\s+\w+\s+\w+)*)\s+to\s+(\w+)\s*$')
31RANDOM_CASES = int(os.environ.get('RANDOM_CASES', '32'))
32SEED = os.environ.get('CASE_SEED', 'omega-kernel-template')
33NOT_RUN = ['any GPU (no GPU is used by this check)', 'sm_121 SASS', 'CUDA++ runtime']
34
35
36class Trap(Exception):
37 """Raise Trap(n) in reference.py where the kernel executes `trap n`."""
38
39 def __init__(self, code):
40 super().__init__(code)
41 if not 1 <= int(code) <= 14:
42 raise ValueError(f'trap code {code} outside 1..14')
43 self.code = int(code)
44
45
46class Bad(Exception):
47 """An input or reference problem; reported as a FAIL with this message."""
48
49
50def span(kind):
51 if kind == 'bool':
52 return 0, 1
53 bits = WIDTH[kind]
54 if kind in SIGNED:
55 return -(1 << (bits - 1)), (1 << (bits - 1)) - 1
56 return 0, (1 << bits) - 1
57
58
59def signatures(path='kernel.om'):
60 funcs = {}
61 with open(path, encoding='utf-8') as handle:
62 for number, line in enumerate(handle, 1):
63 if not line.startswith('fn '):
64 continue
65 match = SIGNATURE.match(line.strip())
66 if not match:
67 raise Bad(f'kernel.om:{number}: cannot read the signature "{line.strip()}"')
68 name, raw, ret = match[1], match[2].split(), match[3]
69 params = list(zip(raw[0::2], raw[1::2]))
70 for pname, kind in params:
71 if kind not in WIDTH and kind != 'bool':
72 raise Bad(f'kernel.om:{number}: {name} parameter {pname} has type {kind}; '
73 'the SPIR-V path at this pin takes integer and bool scalars only')
74 if ret not in RETURNS:
75 raise Bad(f'kernel.om:{number}: {name} returns {ret}; '
76 'the SPIR-V path at this pin returns integer, bool or void only')
77 if len(params) > 6:
78 raise Bad(f'kernel.om:{number}: {name} has {len(params)} parameters; the OpenCL host passes at most 6')
79 if name in ('main', 'ir_dump'):
80 raise Bad(f'kernel.om:{number}: the name {name} is reserved by the check harness')
81 funcs[name] = (params, ret)
82 if not funcs:
83 raise Bad('kernel.om defines no fn')
84 return funcs
85
86
87def parse_value(kind, text, where):
88 if kind == 'bool':
89 if text not in ('true', 'false'):
90 raise Bad(f'{where}: bool argument must be true or false, got {text}')
91 return text == 'true'
92 if not re.fullmatch(r'-?[0-9]+', text):
93 raise Bad(f'{where}: {kind} argument must be a decimal integer, got {text}')
94 value = int(text)
95 low, high = span(kind)
96 if not low <= value <= high:
97 raise Bad(f'{where}: {value} is outside {kind} range {low}..{high}')
98 return value
99
100
101def edges(kind):
102 if kind == 'bool':
103 return [False, True]
104 low, high = span(kind)
105 return sorted({0, 1, high, high - 1, low, low + 1} | ({-1} if kind in SIGNED else set()))
106
107
108def load_reference(path='reference.py'):
109 space = {'Trap': Trap, '__name__': 'reference'}
110 with open(path, encoding='utf-8') as handle:
111 code = compile(handle.read(), path, 'exec')
112 exec(code, space) # noqa: S102 - the developer's own oracle, run on their own runner
113 return space
114
115
116def expect(reference, name, params, ret, args):
117 shown = f'{name}({", ".join(str(a).lower() if isinstance(a, bool) else str(a) for a in args)})'
118 try:
119 value = reference[name](*args)
120 except Trap as trap:
121 return 0, 100 + trap.code
122 except Exception as error: # noqa: BLE001 - every reference fault is a named FAIL
123 raise Bad(f'reference.py {shown} raised {type(error).__name__}: {error}')
124 if ret == 'void':
125 if value is not None:
126 raise Bad(f'reference.py {shown} returned {value!r}; {name} returns void, so return None')
127 return 0, 0
128 if ret == 'bool':
129 if not isinstance(value, bool):
130 raise Bad(f'reference.py {shown} returned {value!r}; {name} returns bool')
131 return int(value), 0
132 if isinstance(value, bool) or not isinstance(value, int):
133 raise Bad(f'reference.py {shown} returned {value!r}; {name} returns {ret}, an integer')
134 low, high = span(ret)
135 if not low <= value <= high:
136 raise Bad(f'reference.py {shown} returned {value}, outside {ret} range {low}..{high}; '
137 'reduce it the way the kernel should (for example % 2**32)')
138 return value & MASK, 0
139
140
141def expand(build):
142 funcs = signatures()
143 reference = load_reference()
144 missing = [name for name in funcs if not callable(reference.get(name))]
145 if missing:
146 raise Bad(f'reference.py has no function for {", ".join(missing)}; every kernel fn needs one')
147 planned = []
148 seen = set()
149
150 def add(name, args, source):
151 key = (name, tuple(args))
152 if key in seen:
153 return
154 seen.add(key)
155 planned.append((name, list(args), source))
156
157 if os.path.exists('cases.tsv'):
158 with open('cases.tsv', encoding='utf-8') as handle:
159 for number, line in enumerate(handle, 1):
160 words = line.split()
161 if not words or words[0].startswith('#'):
162 continue
163 where = f'cases.tsv:{number}'
164 name = words[0]
165 if name not in funcs:
166 raise Bad(f'{where}: kernel.om has no fn {name}')
167 params, _ = funcs[name]
168 if len(words) - 1 != len(params):
169 raise Bad(f'{where}: {name} takes {len(params)} arguments, got {len(words) - 1}')
170 add(name, [parse_value(k, w, where) for (_, k), w in zip(params, words[1:])], where)
171 for name, (params, _) in funcs.items():
172 rng = random.Random(f'{SEED}:{name}')
173 if params:
174 pools = [edges(kind) for _, kind in params]
175 for _ in range(16):
176 add(name, [rng.choice(pool) for pool in pools], 'edge')
177 else:
178 add(name, [], 'edge')
179 for _ in range(RANDOM_CASES):
180 args = []
181 for _, kind in params:
182 low, high = span(kind)
183 args.append(bool(rng.getrandbits(1)) if kind == 'bool' else rng.randint(low, high))
184 add(name, args, 'random')
185 rows = []
186 for index, (name, args, source) in enumerate(planned, 1):
187 params, ret = funcs[name]
188 bits, status = expect(reference, name, params, ret, args)
189 typed, omargs = [], []
190 for (_, kind), value in zip(params, args):
191 text = ('true' if value else 'false') if kind == 'bool' else str(value)
192 typed.append(f'{kind}:{text}')
193 omargs.append(text if kind == 'bool' else f'{kind} {text}')
194 rows.append('\t'.join([str(index), name, ret, ','.join(typed) or '-', ' '.join(omargs) or '-',
195 str(bits), str(status), source]))
196 with open(os.path.join(build, 'plan.tsv'), 'w', encoding='ascii') as handle:
197 handle.write('\n'.join(rows) + '\n')
198 counts = {}
199 for _, _, source in planned:
200 kind = 'cases.tsv' if source.startswith('cases.tsv') else source
201 counts[kind] = counts.get(kind, 0) + 1
202 print(f'PLAN cases={len(rows)} functions={len(funcs)} ' +
203 ' '.join(f'{k}={v}' for k, v in sorted(counts.items())))
204
205
206def sha256(path):
207 digest = hashlib.sha256()
208 with open(path, 'rb') as handle:
209 for block in iter(lambda: handle.read(1 << 20), b''):
210 digest.update(block)
211 return digest.hexdigest()
212
213
214def read_tsv(path):
215 if not os.path.exists(path):
216 return []
217 with open(path, encoding='ascii') as handle:
218 return [line.rstrip('\n').split('\t') for line in handle if line.strip()]
219
220
221def show(ret, bits, status):
222 if status is None:
223 return 'not run'
224 if status:
225 return f'trap {status - 100}' if 101 <= status <= 114 else f'exit {status}'
226 if ret == 'void':
227 return '-'
228 if ret == 'bool':
229 return 'true' if bits else 'false'
230 if ret in SIGNED:
231 return str(bits - (1 << 64) if bits >> 63 else bits)
232 return str(bits)
233
234
235def command_line(*argv):
236 try:
237 done = subprocess.run(argv, capture_output=True, text=True, timeout=30)
238 except (OSError, subprocess.TimeoutExpired):
239 return None
240 if done.returncode:
241 return None
242 text = (done.stdout or done.stderr).strip().splitlines()
243 return text[0] if text else None
244
245
246def versions():
247 found = {
248 'python': platform.python_version(),
249 'cc': command_line(os.environ.get('CC', 'cc'), '--version'),
250 'spirv-val': command_line(os.environ.get('SPIRV_VAL', 'spirv-val'), '--version'),
251 }
252 if shutil.which('dpkg-query'):
253 for package in ('clang-18', 'libllvm18', 'libllvmspirvlib18.1', 'ocl-icd-libopencl1',
254 'ocl-icd-opencl-dev', 'spirv-tools'):
255 found[f'deb:{package}'] = command_line('dpkg-query', '-W', '-f=${Version}', package)
256 return found
257
258
259def report(build):
260 receipt_dir = os.path.join(build, 'receipt')
261 lock = dict(line.strip().split('=', 1) for line in open('toolchain.lock', encoding='ascii')
262 if '=' in line and not line.startswith('#'))
263 stop = read_tsv(os.path.join(build, 'stop.tsv'))
264 plan = read_tsv(os.path.join(build, 'plan.tsv'))
265 parity = {row[0]: row for row in read_tsv(os.path.join(build, 'case-spirv-parity.tsv'))[1:]}
266 cases = []
267 for index, name, ret, typed, omargs, bits, status, source in plan:
268 native_status = native_bits = spirv_status = spirv_bits = None
269 if index in parity:
270 row = parity[index]
271 native_status, native_bits = int(row[4]), int(row[5])
272 spirv_status, spirv_bits = int(row[6]), int(row[7])
273 expected = (int(bits), int(status))
274 aarch64_ok = native_status is not None and (native_bits, native_status) == expected
275 spirv_ok = spirv_status is not None and (spirv_bits, spirv_status) == (native_bits, native_status)
276 cases.append({
277 'case': int(index), 'fn': name, 'returns': ret, 'args': omargs, 'source': source,
278 'reference': show(ret, *expected),
279 'aarch64': show(ret, native_bits, native_status),
280 'spirv_pocl_cpu': show(ret, spirv_bits, spirv_status),
281 'aarch64_matches_reference': aarch64_ok, 'spirv_matches_aarch64': spirv_ok,
282 'verdict': 'PASS' if aarch64_ok and spirv_ok else 'FAIL',
283 })
284 failed = [c for c in cases if c['verdict'] != 'PASS']
285 if stop:
286 verdict, stage, message = stop[0]
287 elif not cases:
288 verdict, stage, message = 'FAIL', 'cases', 'no cases were planned'
289 elif failed:
290 verdict, stage = 'FAIL', 'compare'
291 message = f'{len(failed)} of {len(cases)} cases differ'
292 else:
293 verdict, stage = 'PASS', 'compare'
294 message = f'all {len(cases)} cases match on AArch64 and SPIR-V (PoCL CPU)'
295
296 os.makedirs(receipt_dir, exist_ok=True)
297 copies = ['kernel.om', 'cases.tsv', 'reference.py', 'toolchain.lock',
298 os.path.join(build, 'kernel.ir'), os.path.join(build, 'kernel.spv'),
299 os.path.join(build, 'kernel.spvasm'), os.path.join(build, 'kernel-aarch64.s'),
300 os.path.join(build, 'check.log'), os.path.join(build, 'case-spirv-parity.tsv'),
301 os.path.join(build, 'kernel.compile.err'), os.path.join(build, 'kernel.translate.err')]
302 for path in copies:
303 if os.path.exists(path) and os.path.getsize(path):
304 shutil.copy(path, os.path.join(receipt_dir, os.path.basename(path)))
305 with open(os.path.join(receipt_dir, 'results.tsv'), 'w', encoding='utf-8') as handle:
306 handle.write('case\tfn\targs\tsource\treference\taarch64\tspirv_pocl_cpu\tverdict\n')
307 for c in cases:
308 handle.write(f"{c['case']}\t{c['fn']}\t{c['args']}\t{c['source']}\t{c['reference']}\t"
309 f"{c['aarch64']}\t{c['spirv_pocl_cpu']}\t{c['verdict']}\n")
310
311 def hashed(path):
312 return sha256(path) if os.path.exists(path) else None
313
314 runtime = None
315 err = os.path.join(build, 'case-1.spirv.err')
316 if os.path.exists(err):
317 runtime = ' '.join(open(err, encoding='utf-8', errors='replace').read().split())
318 env = os.environ.get
319 run_url = None
320 if env('GITHUB_RUN_ID'):
321 run_url = f"{env('GITHUB_SERVER_URL')}/{env('GITHUB_REPOSITORY')}/actions/runs/{env('GITHUB_RUN_ID')}"
322 receipt = {
323 'schema': 'omega-kernel-receipt/1',
324 'verdict': verdict, 'stage': stage, 'message': message,
325 'created_utc': datetime.datetime.now(datetime.timezone.utc).strftime('%Y-%m-%dT%H:%M:%SZ'),
326 'where': {
327 'repository': env('GITHUB_REPOSITORY', 'local'), 'commit': env('GITHUB_SHA'),
328 'ref': env('GITHUB_REF_NAME'), 'run_url': run_url,
329 'runner': f"{env('RUNNER_OS', '')} {env('RUNNER_ARCH', '')} {env('ImageOS', '')} {env('ImageVersion', '')}".strip() or None,
330 'platform': ' '.join(platform.uname()[:3] + platform.uname()[4:5]),
331 },
332 'what_ran': {
333 'aarch64': 'omc-compiled native AArch64 Linux programs, one per case, on this CPU',
334 'spirv': 'Omega irspirv.om translated OSC IR to a SPIR-V 1.0 OpenCL kernel; '
335 'spirv-val checked it; PoCL ran it on its CPU device (one work-item per case)',
336 'reference': 'reference.py in CPython on this CPU',
337 'not_run': NOT_RUN,
338 },
339 'pins': {k: v for k, v in lock.items()},
340 'built': {
341 'irspirv': hashed(os.path.join(build, 'irspirv')),
342 'opencl-host': hashed(os.path.join(build, 'opencl-host')),
343 'pocl-library': hashed(os.environ.get('POCL_LIBRARY', os.path.join('.okt', 'pocl', lock.get('POCL_LIB', '')))),
344 },
345 'inputs': {name: hashed(name) for name in ('kernel.om', 'cases.tsv', 'reference.py')},
346 'outputs': {name: hashed(os.path.join(build, name)) for name in ('kernel.ir', 'kernel.spv')},
347 'opencl_runtime': runtime,
348 'versions': versions(),
349 'counts': {
350 'cases': len(cases),
351 'aarch64_matches_reference': sum(c['aarch64_matches_reference'] for c in cases),
352 'spirv_matches_aarch64': sum(c['spirv_matches_aarch64'] for c in cases),
353 'failed': len(failed),
354 },
355 'failures': failed[:50],
356 }
357 receipt_path = os.path.join(receipt_dir, 'receipt.json')
358 with open(receipt_path, 'w', encoding='utf-8') as handle:
359 json.dump(receipt, handle, indent=2)
360 handle.write('\n')
361 sums = []
362 for name in sorted(os.listdir(receipt_dir)):
363 if name != 'SHA256SUMS':
364 sums.append(f'{sha256(os.path.join(receipt_dir, name))} {name}')
365 with open(os.path.join(receipt_dir, 'SHA256SUMS'), 'w', encoding='ascii') as handle:
366 handle.write('\n'.join(sums) + '\n')
367
368 n = len(cases)
369 lines = [f'## Omega kernel check: {verdict}', '', f'**{stage}**: {message}', '']
370 if cases:
371 lines += ['| check | result |', '|---|---|',
372 f"| AArch64 native == reference.py | {receipt['counts']['aarch64_matches_reference']}/{n} |",
373 f"| SPIR-V on PoCL CPU == AArch64, bit for bit | {receipt['counts']['spirv_matches_aarch64']}/{n} |", '']
374 if failed:
375 lines += ['### First differing cases', '',
376 '| case | call | reference.py | AArch64 | SPIR-V (PoCL CPU) |', '|---|---|---|---|---|']
377 for c in failed[:20]:
378 lines.append(f"| {c['case']} ({c['source']}) | `{c['fn']} {c['args']}` | {c['reference']} | "
379 f"{c['aarch64']} | {c['spirv_pocl_cpu']} |")
380 lines.append('')
381 lines += ['### What ran where', '',
382 '- AArch64: `omc` compiled each case to a native Linux program; it ran on this runner CPU.',
383 '- SPIR-V: the Omega translator `irspirv.om` emitted a SPIR-V OpenCL kernel, `spirv-val` checked it, '
384 'and PoCL ran it on its **CPU** device.',
385 '- Not run: ' + '; '.join(NOT_RUN) + '. This is CPU evidence, not GPU qualification.', '',
386 '### Pins', '', '| item | value |', '|---|---|',
387 f"| omega-mv | `{lock.get('OMEGA_MV_COMMIT')}` |",
388 f"| omc sha256 | `{lock.get('OMC_SHA256')}` |",
389 f"| irspirv.om sha256 | `{lock.get('IRSPIRV_OM_SHA256')}` |",
390 f"| PoCL asset sha256 | `{lock.get('POCL_SHA256')}` |",
391 f"| kernel.om sha256 | `{receipt['inputs']['kernel.om']}` |",
392 f"| kernel.spv sha256 | `{receipt['outputs']['kernel.spv']}` |",
393 f"| receipt.json sha256 | `{sha256(receipt_path)}` |", '',
394 'Receipt: the `omega-kernel-receipt` artifact of this run (receipt.json, results.tsv, '
395 'kernel.spv, kernel.spvasm, kernel-aarch64.s, SHA256SUMS).', '']
396 with open(os.path.join(build, 'summary.md'), 'w', encoding='utf-8') as handle:
397 handle.write('\n'.join(lines))
398 print(f'{verdict} {stage}: {message}')
399 print(f'receipt {receipt_path} sha256={sha256(receipt_path)}')
400 return 0 if verdict == 'PASS' else 1
401
402
403def main(argv):
404 if len(argv) != 3 or argv[1] not in ('expand', 'report'):
405 print(__doc__.strip().splitlines()[-1], file=sys.stderr)
406 return 2
407 try:
408 if argv[1] == 'expand':
409 expand(argv[2])
410 return 0
411 return report(argv[2])
412 except Bad as error:
413 print(f'FAIL {error}' if argv[1] == 'report' else str(error))
414 return 1
415
416
417if __name__ == '__main__':
418 sys.exit(main(sys.argv))