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 / attn_views_check.py

139 lines · 7081 bytes Raw Blame History
1#!/usr/bin/env python3
2# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
3"""Host-only typed-view differential, mutation gate, coverage and loop benchmark.
4Run through the mandatory device-hiding bwrap command in the evidence README.
5"""
6import argparse
7import json
8import os
9from pathlib import Path
10import re
11import subprocess
12import tempfile
13
14ROOT = Path(__file__).resolve().parents[1]
15p = argparse.ArgumentParser()
16p.add_argument('--mutants', action='store_true')
17p.add_argument('--coverage', action='store_true')
18p.add_argument('--bench', action='store_true')
19p.add_argument('--api', action='store_true')
20p.add_argument('--out')
21a = p.parse_args()
22tmp = None if a.out else tempfile.TemporaryDirectory(prefix='attn-views-')
23out = Path(a.out if a.out else tmp.name).resolve()
24out.mkdir(parents=True, exist_ok=True)
25os.chdir(ROOT)
26commands = []
27def run(cmd, *, expect=0, stdout=None):
28 r = subprocess.run([str(x) for x in cmd], text=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
29 commands.append({'command': [str(x) for x in cmd], 'rc': r.returncode, 'output': r.stdout})
30 (out / 'commands.json').write_text(json.dumps(commands, indent=2)+'\n')
31 if stdout is not None:
32 Path(stdout).write_text(r.stdout)
33 elif r.stdout:
34 print(r.stdout, end='', flush=True)
35 if expect is not None and r.returncode != expect:
36 raise SystemExit('FAIL command rc '+str(r.returncode)+': '+str(cmd))
37 return r
38cc = os.environ.get('CC', 'cc')
39flags = ['-std=gnu11', '-O2', '-ffp-contract=off', '-Isrc', '-Itests']
40units = dict(re.findall(r'^UNITS="\$UNITS (attn_\w+)=([^"\n]+)"$', (ROOT/'om/units.sh').read_text(), re.M))
41objects = {}
42for name in units:
43 obj = out/(name+'.o')
44 providers = sorted((ROOT/'src').glob('cudapp_*_'+name+'.c'))
45 if len(providers) != 1:
46 raise SystemExit('FAIL expected exactly one checked provider for '+name+': '+str(providers))
47 run([cc, *flags, '-c', providers[0], '-o', obj])
48 objects[name] = obj
49for name in ['api_mm_plan','api_at_plan','api_ew_plan','api_bf_plan','api_da_plan','api_rt_plan','core_hostmath']:
50 obj = out/(name+'.o')
51 run([cc, *flags, '-c', 'src/cudapp_om_'+name+'.c', '-o', obj])
52 objects[name] = obj
53hostmath = out/'hostmath.o'
54run([cc, *flags, '-c', 'src/omega_gpu_hostmath.c', '-o', hostmath])
55omega = out/'cases-omega.o'
56oracle = out/'cases-oracle.o'
57run([cc, *flags, '-DAV_ENTRY=attn_omega', '-c', 'tests/attn_views_cases.c', '-o', omega])
58oracle_flags = ['-O0', '--coverage'] if a.coverage else []
59run([cc, *flags, *oracle_flags, '-DCUDAPP_MIGRATION_PENDING_ATTN_VIEWS=1', '-DAV_ENTRY=attn_oracle', '-c', 'tests/attn_views_cases.c', '-o', oracle])
60main = out/'diff.o'
61run([cc, *flags, '-c', 'tests/attn_views_diff.c', '-o', main])
62def link(dest, replacements=None):
63 objs = dict(objects)
64 objs.update(replacements or {})
65 run([cc, *flags, *(['--coverage'] if a.coverage else []), main, omega, oracle, hostmath, *objs.values(), '-lm', '-o', dest])
66link(out/'diff')
67run([out/'diff'])
68if a.mutants:
69 bridge = Path(os.environ['OMEGA_BRIDGE']).resolve()
70 env = os.environ.copy()
71 env['OMEGA_SEEDED_OMC'] = os.environ['OMEGA_OMC']
72 mutants = [
73 ('attn_args', 'shr v 32', 'shr v 31'),
74 ('attn_lay', 'shr v 32', 'shr v 31'),
75 ('attn_buf', 'get s i', 'get s 0'),
76 ('attn_bfexp', 'shl uint get s i 16', 'shl uint get s i 15'),
77 ('attn_rows', 'v = and add add base i 1', 'v = and add add base i 2'),
78 ('attn_gtab', 'put tab add mul i 4 3 uint 0', 'put tab add mul i 4 3 uint 1'),
79 ('attn_comp', 'if lt v 2147483648', 'if ge v 2147483648'),
80 ('attn_math', 'put dest 1 bitcast ulong pc', 'put dest 1 bitcast ulong neg pc'),
81 ('attn_tables', 'ret mul a get w 16', 'ret a'),
82 ]
83 killed = 0
84 for num, (name, site, replacement) in enumerate(mutants):
85 source = '\n'.join((ROOT/x).read_text() for x in units[name].split(','))+'\n'
86 if source.count(site) != 1:
87 raise SystemExit('FAIL mutant site '+name+' count '+str(source.count(site)))
88 om = out/('mutant-'+str(num)+'.om')
89 om.write_text(source.replace(site,replacement))
90 c = out/('mutant-'+str(num)+'.c')
91 providers = sorted((ROOT/'src').glob('cudapp_*_'+name+'.c'))
92 if len(providers) != 1:
93 raise SystemExit('FAIL expected exactly one checked provider for '+name)
94 freestanding = providers[0].name.startswith('cudapp_freest_')
95 cmd = ['sh', bridge/('tools/bridge-freest' if freestanding else 'tools/bridge-seeded')]
96 if not freestanding and name not in ['attn_args','attn_lay']:
97 cmd.append('--runtime-views')
98 cmd += ['c', om]
99 r = subprocess.run([str(x) for x in cmd], env=env, text=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
100 commands.append({'command':[str(x) for x in cmd], 'rc':r.returncode, 'output':r.stderr})
101 if r.returncode:
102 raise SystemExit('FAIL mutant did not generate '+name+': '+r.stderr)
103 c.write_text(r.stdout)
104 obj = out/('mutant-'+str(num)+'.o')
105 run([cc, *flags, '-c', c, '-o', obj])
106 exe = out/('mutant-'+str(num))
107 link(exe, {name:obj})
108 r = run([exe], expect=None)
109 if r.returncode == 0:
110 raise SystemExit('FAIL surviving mutant '+name)
111 killed += 1
112 print('KILLED '+name+' rc='+str(r.returncode), flush=True)
113 print('PASS attention host typed views mutants killed='+str(killed), flush=True)
114if a.coverage:
115 run(['gcov', '-b', '-c', '-o', out, oracle], stdout=out/'gcov.txt')
116 # gcov writes source listings in cwd; retain only this lane's fresh files.
117 for path in ROOT.glob('*.gcov'):
118 if path.name in ['attn_views_cases.c.gcov','omega_attn_views.h.gcov','omega_attn_tables.h.gcov','omega_api_plan.h.gcov']:
119 path.replace(out/path.name)
120 print('PASS attention C oracle coverage captured in '+str(out/'gcov.txt'), flush=True)
121if a.bench:
122 benchobjs = []
123 for label, extra in [('omega', []), ('oracle', ['-DCUDAPP_MIGRATION_PENDING_ATTN_VIEWS=1'])]:
124 obj = out/('bench-'+label+'.o')
125 run([cc, *flags, *extra, '-DAV_BENCH=attn_bench_'+label, '-c', 'tests/attn_views_bench.c', '-o', obj])
126 benchobjs.append(obj)
127 exe = out/'bench'
128 run([cc, *flags, 'tests/attn_views_bench_main.c', *benchobjs, hostmath, *objects.values(), '-lm', '-o', exe])
129 run([exe], stdout=out/'bench.tsv')
130 print('PASS attention loop benchmark raw samples '+str(out/'bench.tsv'), flush=True)
131if a.api:
132 for target in ['test-gpu-attention','test-gpu-decode-attn','test-gpu-decode-attn256','test-gpu-router','test-gpu-bf16-gemv']:
133 run(['make', '-j3', target])
134 run(['make', '-j3', 'build/gpu_prefill_attn_test', 'build/gpu_prefill_attn256_test'])
135 for exe in ['build/gpu_prefill_attn_test','build/gpu_prefill_attn256_test']:
136 run([exe, '--host-only'])
137 run([exe, '--sim'])
138 print('PASS seven attention-family API host/sim gates', flush=True)
139print('PASS attention typed-view host gate', flush=True)