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 / loop-sites.py

174 lines · 8545 bytes Raw Blame History
1#!/usr/bin/env python3
2# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
3"""Host measuring instrument for compiler-fuel exposure, not a product input cap.
4
5Inventory every loop, including nested chunks. Constant-trip loops and explicitly
6wire/buffer-bounded loops are excluded with their reason. Every remaining source
7site has an alarm case. Parser alarms use a conservative input-byte upper bound,
8not a claim to have executed that many iterations. Executor instruction/work and
9ring argument demands have separate units. The execution gate additionally runs
10past-fuel wave/grid programs and their compiled restored-bound mutants.
11
12Changing loop structure requires updating its case/policy here: an unclassified
13loop or a policy with no source site is a failure, never silently skipped.
14"""
15import pathlib
16import re
17import sys
18import tempfile
19
20FILES = ('backend/amd/gfx942/exec/main.om', 'backend/amd/gfx942/hsaco.om',
21 'backend/amd/kfd/records.om', 'backend/amd/kfd/ring.om')
22# These are semantic policies, not a stored line-number/count inventory.
23POLICY = {
24 'main.om': {
25 ('rdword', 'while lt i 4 bound 999999'): 'fixed: four-byte word',
26 ('mwrite', 'while lt i 4 bound 999999'): 'fixed: four-byte word',
27 ('boundary', 'while lt pc targetpc bound 999999'): 'instructions',
28 ('boundary', 'while and lt pc targetpc lt c 999998 bound 999999'): 'instructions',
29 ('validate', 'while lt pc get st 1 bound 999999'): 'instructions',
30 ('validate', 'while and lt pc get st 1 lt c 999998 bound 999999'): 'instructions',
31 ('smexec', 'for i ulong n'): 'fixed: decoded scalar-memory opcode width',
32 ('fp8bits', 'while lt f 8 bound 3'): 'fixed: FP8 mantissa normalization',
33 ('wide', 'for i ulong n'): 'fixed: decoded vector-memory opcode width',
34 ('vexec', 'while eq and shr get st 14 first 1 0 bound 64'): 'fixed: wave64 lane mask',
35 ('wave', 'while true bound 999999'): 'iterations',
36 ('wave', 'while lt c 999998 bound 999999'): 'iterations',
37 ('gridarg', 'for i ulong ulong n'): 'fixed: argread buffer of 4096 bytes',
38 ('main', 'while lt y ny bound 999999'): 'iterations',
39 ('main', 'while and lt y ny lt c 999998 bound 999999'): 'iterations',
40 ('main', 'while lt g groups bound 999999'): 'iterations',
41 ('main', 'while and lt g groups lt d 999998 bound 999999'): 'iterations',
42 },
43 'hsaco.om': {
44 ('labfind', 'for i ulong get gs 4'): 'bytes',
45 ('token', 'while true bound 999999'): 'bytes',
46 ('token', 'while ne get gs 1 10 bound 999999'): 'bytes',
47 ('number', 'while true bound 999999'): 'bytes',
48 ('format', 'for i ulong get gs 31'): 'bytes',
49 ('inst', 'for k ulong fg f 2'): 'fixed: fieldidx checks the 64 instruction bits',
50 ('namespan', 'while and gt c 32 ne c 256 bound 999999'): 'bytes',
51 ('table', 'while true bound 999999'): 'bytes',
52 ('flush', 'while lt p n bound 999999'): 'fixed: 4096-byte output buffer, positive write progress',
53 ('wrle', 'for j ulong n'): 'fixed: ELF integer widths at call sites',
54 ('zeros', 'for j ulong n'): 'bytes',
55 ('bytes', 'for j ulong len v'): 'bytes',
56 ('wrbe', 'for j ulong n'): 'fixed: MessagePack integer widths at call sites',
57 ('span', 'while lt i n bound 999999'): 'bytes',
58 ('span', 'for j ulong ulong r'): 'fixed: pread into 4096-byte name buffer',
59 },
60 'records.om': {
61 ('tnum', 'while true bound 999999'): 'bytes',
62 ('tnum', 'while ne c 10 bound 999999'): 'bytes',
63 ('tnum', 'while and ge c 48 le c 57 bound 999999'): 'bytes',
64 ('store', 'for i ulong wid'): 'fixed: validated u32/u64 wire width',
65 ('fld', 'for j ulong cnt'): 'fixed: positive wire width and record extent checked per field',
66 ('record', 'for f ulong nf'): 'bytes',
67 ('main', 'for i ulong add idx 1'): 'bytes',
68 },
69 'ring.om': {('main', 'for i ulong sub ulong argcnt 1'): 'arguments'},
70}
71THRESHOLD = 500000
72
73
74def inventory(root, replacements=None):
75 sites = []
76 for name in FILES:
77 path = pathlib.Path(root) / name
78 text = (replacements or {}).get(name, path.read_text())
79 policy = POLICY[path.name]
80 seen = set()
81 function = None
82 for line, statement in enumerate(text.splitlines(), 1):
83 if statement.startswith('fn '):
84 function = statement.split()[1]
85 if not statement.startswith(('while ', 'for ')):
86 continue
87 if re.fullmatch(r'for \w+ ulong \d+', statement):
88 continue
89 key = function, statement
90 assert key in policy, f'UNCLASSIFIED LOOP {name}:{line} {function}: {statement}'
91 assert key not in seen, f'DUPLICATE LOOP needs a distinct case {name}:{line}'
92 seen.add(key)
93 if not policy[key].startswith('fixed:'):
94 sites.append((name, line, function, statement, policy[key]))
95 assert seen == policy.keys(), f'LOOP CASE WITHOUT SITE {name}: {policy.keys() - seen}'
96 return sites
97
98
99def pin(root):
100 text = (pathlib.Path(root) / 'tests/multitarget/run.sh').read_text()
101 return re.search(r'^omc_pin=(\w+)$', text, re.M).group(1)
102
103
104def alarm(site, demand, compiler, source):
105 name, line, function, statement, units = site
106 if demand > THRESHOLD:
107 print(f'LOOP-FUEL ALARM site={name}:{line} function={function} loop={statement!r} '
108 f'demand_upper_bound={demand} units={units} threshold={THRESHOLD} '
109 f'compiler={compiler} input={source}')
110 return True
111 return False
112
113
114def test(root):
115 sites = inventory(root)
116 compiler = pin(root)
117 cases = []
118 with tempfile.TemporaryDirectory(prefix='loop-site-cases.') as tmp:
119 # Materialized inputs, not a typed-in expected count. For parser sites the
120 # byte count intentionally overestimates trips and alarms before fuel loss.
121 payload = pathlib.Path(tmp) / 'past-fuel-input'
122 payload.write_bytes(b'0\n' * 1000001)
123 measured = {'bytes': payload.stat().st_size,
124 'instructions': len(payload.read_bytes().splitlines()),
125 'iterations': len(payload.read_bytes().splitlines()),
126 'arguments': len(payload.read_bytes().splitlines())}
127 for site in sites:
128 assert alarm(site, measured[site[4]], compiler, payload), ('missing alarm', site)
129 cases.append(site)
130 assert len(cases) == len(sites) and len(set(cases)) == len(sites)
131 name = FILES[0]
132 original = (pathlib.Path(root) / name).read_text()
133 # A new bare input-growing loop cannot borrow an existing case.
134 extra = original + '\nfn unmatched n ulong to void\nfor added ulong n\nend\nend\n'
135 try:
136 inventory(root, {name: extra})
137 except AssertionError as exc:
138 assert 'UNCLASSIFIED LOOP' in str(exc)
139 print('CONTROL unmatched-loop CAUGHT scanner_exit=1', exc)
140 else:
141 raise AssertionError('new bare loop escaped inventory')
142 # A restored flat dispatch loop also invalidates the source/case bijection.
143 old = 'while lt y ny bound 999999'
144 assert original.count(old) == 1
145 try:
146 inventory(root, {name: original.replace(old, 'for y ulong ny')})
147 except AssertionError as exc:
148 assert 'UNCLASSIFIED LOOP' in str(exc)
149 print('CONTROL restored-bare-for CAUGHT scanner_exit=1', exc)
150 else:
151 raise AssertionError('restored bare for escaped inventory')
152 print(f'LOOP-SITES PASS growing_sites={len(sites)} past_fuel_alarm_cases={len(cases)} compiler={compiler}')
153
154
155if __name__ == '__main__':
156 try:
157 mode, root, *paths = sys.argv[1:]
158 if mode == 'test':
159 test(root)
160 elif mode == 'files':
161 sites, compiler = inventory(root), pin(root)
162 failed = False
163 for path in paths:
164 n = pathlib.Path(path).stat().st_size
165 for site in sites:
166 if site[4] == 'bytes':
167 failed |= alarm(site, n, compiler, path)
168 print(f'LOOP-FUEL measured input={path} bytes={n} threshold={THRESHOLD}')
169 sys.exit(1 if failed else 0)
170 else:
171 raise ValueError('unknown mode ' + mode)
172 except (AssertionError, OSError, ValueError) as exc:
173 print('LOOP-SITES FAIL', exc, file=sys.stderr)
174 sys.exit(1)