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

184 lines · 9294 bytes Raw Blame History
1#!/usr/bin/env python3
2# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
3"""Test-only LLVM decode of emitted objects; CDNA3 PDF pp28-29 Table11/12.
4Checks the one-wait-state transcendental -> consuming non-trans VALU hazard,
5and v_readlane/v_readfirstlane SGPR writes -> VALU constant read (2 wait
6states), v_readlane/v_writelane lane select (4) and VMEM read (5), following
7fall-through and branch paths. Other SGPR-writing VALU ops (v_cmp, carry-out)
8and the other Table11 rows are not audited. Not a hardware timing model.
9"""
10import pathlib
11import re
12import subprocess
13import sys
14
15TRANS = set('''v_exp_f32 v_log_f32 v_rcp_f32 v_rcp_iflag_f32 v_rsq_f32
16v_rcp_f64 v_rsq_f64 v_sqrt_f32 v_sqrt_f64 v_sin_f32 v_cos_f32 v_rcp_f16
17v_sqrt_f16 v_rsq_f16 v_log_f16 v_exp_f16 v_sin_f16 v_cos_f16
18v_exp_legacy_f32 v_log_legacy_f32'''.split())
19
20SGPR_WRITERS = ('v_readfirstlane_b32','v_readlane_b32')
21LANE_SELECT = {'v_readlane_b32':2,'v_writelane_b32':2}
22CARRY_IN = ('v_addc_co_u32','v_subb_co_u32','v_subbrev_co_u32')
23CARRY_OUT = ('v_addc_co_u32','v_subb_co_u32','v_subbrev_co_u32','v_div_scale_')
24VMEM = ('global_','buffer_','scratch_','flat_')
25
26def vgprs(operand):
27 result = {int(n) for n in re.findall(r'\bv(\d+)\b', operand)}
28 for first,last in re.findall(r'\bv\[(\d+):(\d+)\]',operand):
29 result.update(range(int(first),int(last)+1))
30 return result
31
32def sgprs(operand):
33 result = {int(n) for n in re.findall(r'\bs(\d+)\b',operand)}
34 for first,last in re.findall(r'\bs\[(\d+):(\d+)\]',operand):
35 result.update(range(int(first),int(last)+1))
36 if re.search(r'\bvcc\b',operand): result.update((106,107))
37 if re.search(r'\bvcc_lo\b',operand): result.add(106)
38 if re.search(r'\bvcc_hi\b',operand): result.add(107)
39 return result
40
41def instructions(obj):
42 result = subprocess.run(['llvm-objdump-18','--disassemble','--mcpu=gfx942',str(obj)],
43 capture_output=True,text=True,timeout=30)
44 assert result.returncode == 0 and not result.stderr,result
45 obj.with_suffix('.schedule.txt').write_text(result.stdout)
46 rows = []
47 for line in result.stdout.splitlines():
48 if '//' not in line: continue
49 text,encoded = line.split('//',1)
50 if not re.match(r'\s*[0-9a-fA-F]+:',encoded): continue
51 fields = text.strip().split(None,1)
52 assert fields and re.match(r'^(s|v|ds|global)_\w+$',fields[0]),f'undecoded instruction: {line}'
53 name = re.sub(r'_e(?:32|64)$','',fields[0])
54 operands = fields[1] if len(fields)==2 else ''
55 rows.append((name,operands,encoded.split(':',1)[0].strip()))
56 assert rows,f'empty instruction stream {obj}'
57 return rows
58
59def hazards(rows):
60 failures = []
61 for producer,consumer in zip(rows,rows[1:]):
62 op,operands,pc = producer
63 nextop,nextargs,nextpc = consumer
64 if op not in TRANS or not nextop.startswith('v_') or nextop in TRANS: continue
65 written = vgprs(operands.split(',',1)[0])
66 reads = nextargs.split(',',1)[1] if ',' in nextargs else ''
67 # FMAC reads its destination accumulator as well as its explicit sources.
68 if nextop.startswith(('v_fmac_','v_mac_')): reads = nextargs
69 if written & vgprs(reads): failures.append(f'{pc}:{op} -> {nextpc}:{nextop}')
70 return failures
71
72def sgpr_need(op,operands,written):
73 """Wait states CDNA3 p29 requires before this instruction reads `written`."""
74 args = [arg.strip() for arg in operands.split(',')] if operands else []
75 if op.startswith(VMEM): return 5 if written & sgprs(operands) else 0
76 if not op.startswith('v_'): return 0
77 need = 0
78 for i,arg in enumerate(args):
79 if i == 0 or not written & sgprs(arg): continue
80 if LANE_SELECT.get(op) == i: need = max(need,4)
81 elif i == 1 and ('_co_' in op or op.startswith(CARRY_OUT)): continue
82 elif op.startswith(CARRY_IN) and i == len(args)-1: continue
83 else: need = max(need,2)
84 return need
85
86def waits(row):
87 op,operands,_ = row
88 return int(operands,0)+1 if op == 's_nop' else 1
89
90def successors(rows,index,at):
91 op,operands,pc = rows[at]
92 if op == 's_endpgm': return []
93 if op == 's_branch' or op.startswith('s_cbranch_'):
94 assert re.fullmatch(r'-?\d+',operands.split()[0]),f'unknown branch target: {pc}:{op} {operands}'
95 simm = int(operands.split()[0])
96 if simm >= 0x8000: simm -= 0x10000
97 target = int(pc,16)+4+4*simm
98 assert target in index,f'branch target outside object: {pc}:{op} {operands}'
99 rest = [at+1] if op != 's_branch' and at+1 < len(rows) else []
100 return [index[target]]+rest
101 assert op not in ('s_setpc_b64','s_swappc_b64'),f'indirect branch in SGPR window: {pc}:{op}'
102 return [at+1] if at+1 < len(rows) else []
103
104def sgpr_hazards(rows):
105 index = {int(pc,16):i for i,(_,_,pc) in enumerate(rows)}
106 failures = []
107 for start,(op,operands,pc) in enumerate(rows):
108 if op not in SGPR_WRITERS: continue
109 written = sgprs(operands.split(',',1)[0])
110 assert written,f'no SGPR destination: {pc}:{op} {operands}'
111 pending,seen = [(start,0)],set()
112 while pending:
113 at,count = pending.pop()
114 if (at,count) in seen: continue
115 seen.add((at,count))
116 count += 0 if at == start else waits(rows[at])
117 for nxt in successors(rows,index,at):
118 name,args,where = rows[nxt]
119 need = sgpr_need(name,args,written)
120 if need > count: failures.append(f'{pc}:{op} -> {where}:{name} waits={count} need={need}')
121 if count < 5: pending.append((nxt,count))
122 return failures
123
124# Checker controls on hand-written decoded rows: each must report its hazard,
125# and the safe rows must not.
126SYNTHETIC = {
127 'constant': ([('v_readfirstlane_b32','s8, v1','0'),('s_nop','0','4'),('v_mov_b32','v2, s8','8')],'waits=1 need=2'),
128 'lane-select': ([('v_readfirstlane_b32','s8, v1','0'),('s_nop','1','4'),('v_readlane_b32','s9, v2, s8','8')],'waits=2 need=4'),
129 'vmem': ([('v_readlane_b32','s9, v1, s2','0'),('s_nop','2','4'),('global_load_dword','v2, v3, s[8:9]','8')],'waits=3 need=5'),
130 'branch-path': ([('v_readfirstlane_b32','s8, v1','0'),('s_cbranch_scc0','2','4'),('s_nop','4','8'),('s_nop','4','c'),('v_mov_b32','v2, s8','10')],'waits=1 need=2'),
131}
132SAFE = {
133 'constant-after-nop1': [('v_readfirstlane_b32','s8, v1','0'),('s_nop','1','4'),('v_mov_b32','v2, s8','8')],
134 'carry-in': [('v_readfirstlane_b32','s8, v1','0'),('v_addc_co_u32','v1, vcc, v2, v3, s[8:9]','4')],
135 'salu-read': [('v_readfirstlane_b32','s8, v1','0'),('s_sub_u32','s28, s8, s10','4')],
136}
137
138def checker_controls():
139 for name,(rows,expect) in SYNTHETIC.items():
140 failures = sgpr_hazards(rows)
141 assert len(failures) == 1 and failures[0].endswith(expect),(name,failures)
142 print(f'CONTROL scheduling-sgpr-{name} CAUGHT {failures[0]}',flush=True)
143 for name,rows in SAFE.items():
144 assert sgpr_hazards(rows) == [],(name,sgpr_hazards(rows))
145 print(f'PASS scheduling-sgpr-{name} no hazard',flush=True)
146 return len(SYNTHETIC)
147
148def check(obj):
149 rows = instructions(obj)
150 failures = hazards(rows)
151 assert not failures,f'missing transcendental wait: {obj.name}: {failures}'
152 failures = sgpr_hazards(rows)
153 assert not failures,f'missing VALU SGPR-write wait: {obj.name}: {failures}'
154 return sum(op in TRANS for op,_,_ in rows),sum(op in SGPR_WRITERS for op,_,_ in rows)
155
156def suite(src,out):
157 kernels = sorted(p.stem for p in src.glob('*.isa'))
158 assert {'vadd','fsum16','sgemm','fp8gemv','bf16gemv','fp8gemv2','bf16gemv2'} <= set(kernels)
159 for kernel in kernels:
160 obj = out/('hsaco.hsaco' if kernel=='vadd' else kernel+'-hsaco.hsaco')
161 count,writes = check(obj)
162 print(f'PASS scheduling {kernel} trans_instructions={count} sgpr_writes={writes} rule=CDNA3-p28-29-trans-consumer,valu-sgpr-write',flush=True)
163 mutants = (('attn256_merge','\nI 4 0 0\n','no-trans-wait','no-wait','missing transcendental wait:'),
164 ('attn256_gate','\nI 4 0 0\n','no-trans-wait','no-wait','missing transcendental wait:'),
165 ('readfirst_probe','\nI 4 1 0\n','no-sgpr-wait','no-sgpr-wait','missing VALU SGPR-write wait:'))
166 for kernel,site,label,shown,message in mutants:
167 source = (src/(kernel+'.isa')).read_text()
168 assert site in source,(kernel,site)
169 mutant = out/(kernel+'-'+label+'.isa')
170 mutant.write_text(source.replace(site,'\n'))
171 obj = mutant.with_suffix('.hsaco')
172 with obj.open('wb') as stream:
173 result = subprocess.run([str(out/'hsaco'),str(mutant)],stdout=stream,stderr=subprocess.PIPE,timeout=30)
174 assert result.returncode == 0 and not result.stderr,result
175 try: check(obj)
176 except AssertionError as error:
177 assert str(error).startswith(message),error
178 print(f'CONTROL scheduling-{kernel}-{shown} CAUGHT {error}',flush=True)
179 else: raise AssertionError(f'scheduling control escaped: {kernel} {label}')
180 controls = len(mutants)+checker_controls()
181 print(f'PASS scheduling objects={len(kernels)} controls={controls} hardware=NOT_RUN',flush=True)
182
183if __name__=='__main__':
184 suite(pathlib.Path(sys.argv[1]),pathlib.Path(sys.argv[2]))