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
CUDApp / tests / amd-exec / replay.py
| 1 | #!/usr/bin/env python3 |
| 2 | # SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception |
| 3 | """External test instrument: exact replay parity, independent scalar controls, buffer bounds.""" |
| 4 | import base64 |
| 5 | import hashlib |
| 6 | import json |
| 7 | import pathlib |
| 8 | import runpy |
| 9 | import struct |
| 10 | import subprocess |
| 11 | import sys |
| 12 | |
| 13 | HERE = pathlib.Path(__file__).parent |
| 14 | ROOT = HERE.parent.parent |
| 15 | SRC = ROOT/'backend/amd/gfx942' |
| 16 | PIN = '2c82480596bbdc50cda9626866209ef662d5834f278f839ff4ce0250c495029f' |
| 17 | NAMES = ('embed5120_step','attn256_prep_step','attn256_part_step','attn256_merge_step', |
| 18 | 'gdnconv4_step','gdnstate_step','step_advance','readfirst_probe') |
| 19 | BASELINES = ('embed5120','attn256_prep','attn256_part','attn256_merge','gdnconv4','gdnstate') |
| 20 | MUTANTS = { |
| 21 | 'embed5120_step-stale': ('embed5120_step','I 7 0 0 2 0 0 20 0 30 0 127 0 29','I 8 128 1 29'), |
| 22 | 'attn256_prep_step-row0': ('attn256_prep_step','I 8 22 1 45','I 8 128 1 45'), |
| 23 | 'attn256_part_step-length1': ('attn256_part_step','I 2 14 129 14 0','I 3 129 0 14'), |
| 24 | 'attn256_merge_step-length1': ('attn256_merge_step','I 2 14 129 14 0','I 3 129 0 14'), |
| 25 | 'gdnconv4_step-bank': ('gdnconv4_step','I 4 @901 5','I 4 @901 4'), |
| 26 | 'gdnstate_step-bank': ('gdnstate_step','I 4 @901 5','I 4 @901 4'), |
| 27 | 'step_advance-noinc': ('step_advance','I 5 129 8 8 52','I 8 264 1 8'), |
| 28 | 'readfirst_probe-zero': ('readfirst_probe','I 8 264 2 10','I 3 128 0 10'), |
| 29 | } |
| 30 | |
| 31 | class Gate: |
| 32 | def __init__(self, omc, out): |
| 33 | self.omc, self.out = str(omc), out |
| 34 | self.commands, self.results, self.access = [], [], [] |
| 35 | self.source = ''.join((SRC/'exec'/n).read_text() for n in ('fp.om','fma.om','main.om')) |
| 36 | self.instrument = runpy.run_path(str(HERE/'token_access.py'))['instrument'] |
| 37 | self.extract = runpy.run_path(str(HERE/'oracle.py'))['extract'] |
| 38 | self.executors = {} |
| 39 | self.arg_controls = set() |
| 40 | self.spans = None |
| 41 | self.argbytes = {n:int(next(x.split()[2] for x in (SRC/(n+'.isa')).read_text().splitlines() |
| 42 | if x.startswith('K '))) for n in (*NAMES,*BASELINES)} |
| 43 | paths = [SRC/'exec'/n for n in ('fp.om','fma.om','main.om')] |
| 44 | paths += [SRC/(n+suffix) for n in NAMES for suffix in ('.isa','-gfx942.s')] |
| 45 | paths += [SRC/(n+'.isa') for n in BASELINES] |
| 46 | paths += [SRC/'hsaco.om',SRC/'rope.om'] |
| 47 | paths += [HERE/n for n in ('replay.py','semantics.py','semantics-probe.om','token_access.py', |
| 48 | 'oracle.py','gdn.py','gdnconv.py','token_ref.py','attention.py','prep.py')] |
| 49 | self.pins = {str(p.relative_to(ROOT)):hashlib.sha256(p.read_bytes()).hexdigest() for p in paths} |
| 50 | def call(self, argv, data=None, rc=0): |
| 51 | p = subprocess.run(list(map(str,argv)), input=data, capture_output=True, timeout=900) |
| 52 | stdout_path = self.out/('command-'+str(len(self.commands))+'.stdout') |
| 53 | stdout_path.write_bytes(p.stdout) |
| 54 | self.commands.append(dict(argv=list(map(str,argv)),exit=p.returncode, |
| 55 | stdout_path=str(stdout_path),stdout_sha256=hashlib.sha256(p.stdout).hexdigest(),stderr=p.stderr.decode(errors='replace'))) |
| 56 | (self.out/'commands.json').write_text(json.dumps(self.commands,indent=2)+'\n') |
| 57 | assert p.returncode == rc, (argv,p.returncode,p.stderr.decode(errors='replace')) |
| 58 | assert not p.stderr, (argv,p.stderr) |
| 59 | return p.stdout |
| 60 | def compile(self, name, source): |
| 61 | (self.out/(name+'.om')).write_text(source) |
| 62 | binary = self.call([self.omc],source.encode()) |
| 63 | path = self.out/name |
| 64 | path.write_bytes(binary); path.chmod(0o700) |
| 65 | return path |
| 66 | def build(self): |
| 67 | producer = self.compile('hsaco', (SRC/'hsaco.om').read_text()) |
| 68 | self.compile('exec',self.source) |
| 69 | self.compile('rope',(SRC/'rope.om').read_text()) |
| 70 | sem = runpy.run_path(str(HERE/'semantics.py')) |
| 71 | source = self.source[:self.source.index('fn main to int\n')] + (HERE/'semantics-probe.om').read_text() |
| 72 | exe = self.compile('semantics',source) |
| 73 | self.call([sys.executable,'-I',HERE/'semantics.py','suite',exe,self.out]) |
| 74 | old,new = sem['MUTATIONS']['readfirst-lane-zero'] |
| 75 | assert source.count(old)==1 |
| 76 | mutant = self.compile('readfirst-lane-zero',source.replace(old,new)) |
| 77 | self.call([sys.executable,'-I',HERE/'semantics.py','control',mutant,self.out,'readfirst-lane-zero']) |
| 78 | for name in (*NAMES,*BASELINES): |
| 79 | blob = self.call([producer,SRC/(name+'.isa')]) |
| 80 | path = self.out/(name+'.hsaco'); path.write_bytes(blob) |
| 81 | self.extract(path,self.out/(name+'.text')) |
| 82 | assert blob == self.call([producer,SRC/(name+'.isa')]) |
| 83 | if name in NAMES: |
| 84 | oracle = self.out/(name+'.o') |
| 85 | self.call(['llvm-mc-18','-triple=amdgcn-amd-amdhsa','-mcpu=gfx942','-filetype=obj',SRC/(name+'-gfx942.s'),'-o',oracle]) |
| 86 | self.extract(oracle,self.out/(name+'.llvm.text')) |
| 87 | assert (self.out/(name+'.text')).read_bytes()==(self.out/(name+'.llvm.text')).read_bytes(), name+' encoding mismatch' |
| 88 | for name,(base,old,new) in MUTANTS.items(): |
| 89 | source = (SRC/(base+'.isa')).read_text(); assert source.count(old)==1,(name,source.count(old)) |
| 90 | table = self.out/(name+'.isa'); table.write_text(source.replace(old,new)) |
| 91 | path = self.out/(name+'.hsaco'); path.write_bytes(self.call([producer,table])) |
| 92 | self.extract(path,self.out/(name+'.text')) |
| 93 | print('PASS build, independent LLVM code bytes, semantic oracle/control',flush=True) |
| 94 | def layout(self, name, spans): |
| 95 | self.layout_name, self.spans, self.executors = name, spans, {} |
| 96 | def bounded(self, argbytes): |
| 97 | spans=[(0,argbytes),*self.spans[1:]] |
| 98 | if argbytes not in self.executors: |
| 99 | self.executors[argbytes]=self.compile(self.layout_name+'-args'+str(argbytes), |
| 100 | self.instrument(self.source,spans)) |
| 101 | return self.executors[argbytes],spans |
| 102 | def run(self, name, memory, gx, gy, rc=0): |
| 103 | argbytes=self.argbytes[MUTANTS[name][0] if name in MUTANTS else name] |
| 104 | exe,spans=self.bounded(argbytes) |
| 105 | path = self.out/'replay.memory' |
| 106 | if name in NAMES and name not in self.arg_controls and rc==0: |
| 107 | short,_=self.bounded(argbytes-1) |
| 108 | path.write_bytes(memory) |
| 109 | self.call([short,self.out/(name+'.text'),path,gx*64,gy],rc=68) |
| 110 | self.results.append(dict(case=name+' truncated kernargs',result='CAUGHT',exit=68)) |
| 111 | self.arg_controls.add(name) |
| 112 | print('CAUGHT',name,'truncated kernargs',flush=True) |
| 113 | path.write_bytes(memory) |
| 114 | raw = self.call([exe,self.out/(name+'.text'),path,gx*64,gy],rc=rc) |
| 115 | if rc: return None |
| 116 | assert len(raw)==16*len(spans) |
| 117 | hits=struct.unpack('<'+str(len(spans)*2)+'Q',raw) |
| 118 | self.access.append(dict(kernel=name,buffers=[dict(start=p,bytes=n, |
| 119 | max_read_byte=hits[2*i]-1 if hits[2*i] else None, |
| 120 | max_write_byte=hits[2*i+1]-1 if hits[2*i+1] else None) for i,(p,n) in enumerate(spans)])) |
| 121 | return bytearray(path.read_bytes()) |
| 122 | def equal(self, name, actual, expected, start): |
| 123 | assert actual[start:]==expected[start:], name+' byte mismatch' |
| 124 | self.results.append(dict(case=name,result='PASS',mismatched_bytes=0)) |
| 125 | print('PASS',name,flush=True) |
| 126 | def caught(self, name, actual, expected, start): |
| 127 | assert actual[start:]!=expected[start:], name+' ESCAPED' |
| 128 | self.results.append(dict(case=name,result='CAUGHT')) |
| 129 | print('CAUGHT',name,flush=True) |
| 130 | |
| 131 | |
| 132 | def append(memory, payload): |
| 133 | memory.extend(bytes(64)); p=len(memory); memory.extend(payload); memory.extend(bytes(64)); return p |
| 134 | |
| 135 | |
| 136 | def advance(g,memory,pos,cap,variant='step_advance'): |
| 137 | struct.pack_into('<QI',memory,0,pos,cap) |
| 138 | return g.run(variant,memory,2,2) |
| 139 | |
| 140 | |
| 141 | def recurrence(g,base): |
| 142 | ref = runpy.run_path(str(HERE/('gdn.py' if base=='gdnstate' else 'gdnconv.py'))) |
| 143 | fixture = ref['state_fixture'](16,'dense') if base=='gdnstate' else ref['fixture'](10240,'history') |
| 144 | original = bytearray(base64.b64decode(fixture['memory'])) |
| 145 | ptr=[p for _,p in fixture['args']] |
| 146 | sizes=([16384,24576,3145728,3145728,24576,192,192] if base=='gdnstate' |
| 147 | else [40960,81920,81920,81920,40960]) |
| 148 | oldargs=8*len(ptr); position=append(original,bytes(4)) |
| 149 | spans=[(0,64),*zip(ptr,sizes),(position,4)] |
| 150 | g.layout(base,spans) |
| 151 | actual, expected = original[:],original[:] |
| 152 | gx,gy=fixture['timing_grid'] |
| 153 | for step in range(3): |
| 154 | args=ptr[:] |
| 155 | if step&1: args[2],args[3]=args[3],args[2] |
| 156 | struct.pack_into('<'+str(len(args))+'Q',expected,0,*args) |
| 157 | baseline=g.run(base,expected,gx,gy) |
| 158 | struct.pack_into('<'+str(len(ptr)+1)+'Q',actual,0,*ptr,position) |
| 159 | observed=g.run(base+'_step',actual,gx,gy) |
| 160 | if step==0: |
| 161 | # The baseline's original interval/exact oracle also applies to the first step. |
| 162 | check=runpy.run_path(str(HERE/'token_ref.py'))['check'] |
| 163 | width=check(baseline[:len(base64.b64decode(fixture['memory']))],fixture) |
| 164 | g.results.append(dict(case=base+' initial original oracle',result='PASS', |
| 165 | interval_escapes=0,widest_interval=str(width))) |
| 166 | wrong=g.run(base+'_step-bank',actual,gx,gy) |
| 167 | g.caught(base+' wrong state bank',wrong,baseline,64) |
| 168 | g.equal(base+f' consecutive step{step}',observed,baseline,64) |
| 169 | expected=baseline; struct.pack_into('<I',expected,position,step+1) |
| 170 | actual=advance(g,observed,position,3) |
| 171 | g.equal(base+f' counter step{step}',actual,expected,64) |
| 172 | # Shorten an actually accessed state buffer by one word: must refuse, not silently pad. |
| 173 | spans[3]=(ptr[2],sizes[2]-4) |
| 174 | g.layout(base+'-short',spans) |
| 175 | struct.pack_into('<'+str(len(ptr)+1)+'Q',original,0,*ptr,position) |
| 176 | g.run(base+'_step',original,gx,gy,rc=68) |
| 177 | g.results.append(dict(case=base+' truncated old state',result='CAUGHT',exit=68)) |
| 178 | |
| 179 | |
| 180 | def embedding(g): |
| 181 | p,o,t=64,64+4*10240+64,64+4*10240+64+20480+64 |
| 182 | memory=bytearray(t+4+64) |
| 183 | for row in range(4): |
| 184 | struct.pack_into('<5120H',memory,p+row*10240,*[0x3f00+row*32+i%31 for i in range(5120)]) |
| 185 | position=append(memory,bytes(4)) |
| 186 | g.layout('embedding',[(0,64),(p,40960),(o,20480),(t,4),(position,4)]) |
| 187 | for step,token in enumerate((2,1,3)): |
| 188 | struct.pack_into('<I',memory,t,token) |
| 189 | expected=memory[:]; struct.pack_into('<2Q',expected,0,p+token*10240,o) |
| 190 | expected=g.run('embed5120',expected,80,1) |
| 191 | struct.pack_into('<3QI',memory,0,p,o,t,4) |
| 192 | observed=g.run('embed5120_step',memory,81,2) |
| 193 | g.equal('embedding device token '+str(token),observed,expected,64) |
| 194 | for i in range(5120): |
| 195 | assert struct.unpack_from('<I',observed,o+i*4)[0] == (0x3f00+token*32+i%31)<<16 |
| 196 | if step==0: |
| 197 | g.caught('stale token',g.run('embed5120_step-stale',memory,80,1),expected,64) |
| 198 | stale=advance(g,observed[:],position,3,'step_advance-noinc') |
| 199 | good=advance(g,observed[:],position,3) |
| 200 | g.caught('no increment',stale,good,64) |
| 201 | memory=advance(g,observed,position,3) |
| 202 | assert struct.unpack_from('<I',memory,position)[0]==step+1 |
| 203 | before=memory[:]; memory=advance(g,memory,position,3) |
| 204 | g.equal('capacity exhausted no wrap',memory,before,64) |
| 205 | struct.pack_into('<3QI',memory,0,p,o,t,4); struct.pack_into('<I',memory,t,4) |
| 206 | g.equal('invalid token untouched',g.run('embed5120_step',memory,80,1),memory,64) |
| 207 | |
| 208 | |
| 209 | def attention(g,start): |
| 210 | ref=runpy.run_path(str(HERE/'attention.py')) |
| 211 | memory,*_=ref['fixture'](65 if start else 3) |
| 212 | ptr=list(struct.unpack_from('<5Q',memory)); cap=struct.unpack_from('<I',memory,44)[0] |
| 213 | tiles=(cap+63)//64 |
| 214 | sizes=[24576,4*cap*512,4*cap*512,24*tiles*1040,24576] |
| 215 | position=append(memory,struct.pack('<I',start)) |
| 216 | g.layout('attention'+str(start),[(0,64),*zip(ptr,sizes),(position,4)]) |
| 217 | for step in range(start,start+3): |
| 218 | expected=memory[:]; struct.pack_into('<5QII',expected,0,*ptr,step+1,cap) |
| 219 | expected=g.run('attn256_part',expected,(step+64)//64,24) |
| 220 | part=expected[:] |
| 221 | expected=g.run('attn256_merge',expected,1,24) |
| 222 | struct.pack_into('<6QI',memory,0,*ptr,position,cap) |
| 223 | observed=g.run('attn256_part_step',memory,tiles+1,24) |
| 224 | g.equal(f'attention part pos{step}',observed,part,64) |
| 225 | premerge=observed[:] |
| 226 | observed=g.run('attn256_merge_step',observed,1,24) |
| 227 | g.equal(f'attention merge pos{step}',observed,expected,64) |
| 228 | if step>0: |
| 229 | g.caught(f'attention part stale length pos{step}',g.run('attn256_part_step-length1',memory,tiles,24),part,64) |
| 230 | if step>=64: |
| 231 | g.caught('attention merge stale tile stride',g.run('attn256_merge_step-length1',premerge,1,24),expected,64) |
| 232 | memory=advance(g,observed,position,cap) |
| 233 | assert struct.unpack_from('<I',memory,position)[0]==step+1 |
| 234 | |
| 235 | |
| 236 | def preparation(g): |
| 237 | ref=runpy.run_path(str(HERE/'prep.py')) |
| 238 | rows=[g.call([g.out/'rope'],struct.pack('<I',p)) for p in range(5)] |
| 239 | memory,ptr,*rest=ref['fixture'](2,struct.unpack('<64I',rows[2])); cap=rest[-1] |
| 240 | table=append(memory,b''.join(rows)); position=append(memory,bytes(4)) |
| 241 | sizes=[49152,4096,4096,1024,1024,256,24576,4*cap*512,4*cap*512] |
| 242 | g.layout('preparation',[(0,128),*zip(ptr,sizes),(table,cap*256),(position,4)]) |
| 243 | for step in range(3): |
| 244 | expected=memory[:]; expected[ptr[5]:ptr[5]+256]=rows[step] |
| 245 | struct.pack_into('<9QII',expected,0,*ptr,step,cap) |
| 246 | expected=g.run('attn256_prep',expected,24,1) |
| 247 | # The original row is immutable scratch from the caller's perspective, not a step output. |
| 248 | memory[ptr[5]:ptr[5]+256]=rows[step] |
| 249 | args=list(ptr); args[5]=table |
| 250 | struct.pack_into('<10QI',memory,0,*args,position,cap) |
| 251 | observed=g.run('attn256_prep_step',memory,25,2) |
| 252 | g.equal('prep RoPE row pos'+str(step),observed,expected,128) |
| 253 | if step: |
| 254 | g.caught('stale RoPE row '+str(step),g.run('attn256_prep_step-row0',memory,24,1),expected,128) |
| 255 | memory=advance(g,observed,position,cap) |
| 256 | struct.pack_into('<I',memory,position,cap) |
| 257 | struct.pack_into('<10QI',memory,0,*args,position,cap) |
| 258 | g.equal('prep full cache untouched',g.run('attn256_prep_step',memory,24,1),memory,128) |
| 259 | |
| 260 | |
| 261 | def firstlane(g): |
| 262 | memory=bytearray(448); struct.pack_into('<64I',memory,64,*[0xabc00000+i for i in range(64)]) |
| 263 | g.layout('firstlane',[(0,24),(64,256),(384,4)]) |
| 264 | rows=[] |
| 265 | for mask,lane in ((0,0),(1,0),(2,1),(1<<63,63),((1<<63)|8,3),((1<<64)-1,0)): |
| 266 | struct.pack_into('<3Q',memory,0,64,384,mask) |
| 267 | expected=memory[:]; struct.pack_into('<I',expected,384,0xabc00000+lane) |
| 268 | actual=g.run('readfirst_probe',memory,1,1) |
| 269 | g.equal('readfirst mask '+str(mask),actual,expected,24) |
| 270 | g.caught('readfirst no-read '+str(mask),g.run('readfirst_probe-zero',memory,1,1),expected,24) |
| 271 | rows.append(dict(mask=mask,expected=0xabc00000+lane)) |
| 272 | (g.out/'readfirst-probe.json').write_text(json.dumps(dict(input=[0xabc00000+i for i in range(64)],rows=rows, |
| 273 | positive='readfirst_probe.hsaco',negative='readfirst_probe-zero.hsaco',args=['input_ptr','output_ptr','mask_u64'],grid=[1,1],block=[64,1,1],buffers=[256,4]),indent=2)+'\n') |
| 274 | |
| 275 | |
| 276 | def main(): |
| 277 | omc,out=pathlib.Path(sys.argv[1]),pathlib.Path(sys.argv[2]) |
| 278 | assert hashlib.sha256(omc.read_bytes()).hexdigest()==PIN |
| 279 | out.mkdir(parents=True,exist_ok=False) |
| 280 | gate=Gate(omc,out) |
| 281 | gate.build() |
| 282 | firstlane(gate); embedding(gate); preparation(gate); attention(gate,0); attention(gate,62) |
| 283 | recurrence(gate,'gdnconv4'); recurrence(gate,'gdnstate') |
| 284 | objects=[] |
| 285 | for name in NAMES: |
| 286 | table=(SRC/(name+'.isa')).read_text().splitlines() |
| 287 | k=next(x.split() for x in table if x.startswith('K ')) |
| 288 | args=[dict(name=x.split()[1],offset=int(x.split()[2]),bytes=int(x.split()[3]),kind='ptr' if x.split()[4]=='0' else 'scalar') for x in table if x.startswith('A ')] |
| 289 | path=out/(name+'.hsaco') |
| 290 | objects.append(dict(name=name,path=str(path),sha256=hashlib.sha256(path.read_bytes()).hexdigest(),kernarg_bytes=int(k[2]),args=args,block=[64,1,1])) |
| 291 | report=dict(result='PASS',hardware='NOT_RUN',compiler_sha256=PIN,source_sha256=gate.pins, |
| 292 | objects=objects,cases=gate.results,access=gate.access) |
| 293 | (out/'report.json').write_text(json.dumps(report,indent=2)+'\n') |
| 294 | print('PASS replay exact parity, controls, every-access bounds; hardware NOT_RUN',flush=True) |
| 295 | |
| 296 | if __name__=='__main__': main() |