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 / evidence / amd-qwen38-native-20261113 / oracle / emit-plan.py
| 1 | # SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception |
| 2 | """Harness: write an OMPLAN01 plan (FORMAT.md) from real2's own Card.emit, then decode the file independently and |
| 3 | compare it with the recorded launch list. Python never touches weight bytes: buffers name (file, offset, length). |
| 4 | Usage: emit-plan.py DRIVER WEIGHTS OUT.plan [--controls] [--capacity=N] [--fixture-json=PATH] |
| 5 | --capacity=N sizes the KV cache, RoPE table and attention partitions for N positions (Card's own default is |
| 6 | prompt+generated = 48). Prompt, generation and golden ids are unchanged; the override is applied here, not in Card. |
| 7 | --fixture-json=PATH replaces the driver's prompt_ids/generated_ids with the fixture's before anything is recorded |
| 8 | (Card source untouched); its capacity applies unless --capacity is given. The sidecar records the fixture's identity. |
| 9 | """ |
| 10 | import ctypes,hashlib,importlib.util,json,lzma,base64,os,struct,sys,types |
| 11 | from pathlib import Path |
| 12 | import torch |
| 13 | |
| 14 | driver_path,weights,out=Path(sys.argv[1]),Path(sys.argv[2]),Path(sys.argv[3]);controls='--controls' in sys.argv |
| 15 | capacity=next((int(a.split('=',1)[1]) for a in sys.argv[4:] if a.startswith('--capacity=')),None) |
| 16 | fixture_path=next((Path(a.split('=',1)[1]) for a in sys.argv[4:] if a.startswith('--fixture-json=')),None) |
| 17 | fixture=None |
| 18 | if fixture_path is not None: |
| 19 | fixture_raw=fixture_path.read_bytes();fixture=json.loads(fixture_raw) |
| 20 | for k in ('prompt_ids','generated_ids'): |
| 21 | if not (isinstance(fixture.get(k),list) and fixture[k] and all(isinstance(t,int) and t>=0 for t in fixture[k])):raise SystemExit('fixture %s: %s must be a non-empty list of token ids'%(fixture_path,k)) |
| 22 | if capacity is None:capacity=fixture.get('capacity') |
| 23 | os.environ['AMDSERVE_WEIGHTS']=str(weights);os.environ['AMDSERVE_OUTPUT']=str(out)+'.log' |
| 24 | |
| 25 | # Card allocates on 'cuda'; build the same objects on CPU. Weights are zero-stride stand-ins carrying true shape/dtype. |
| 26 | _to,_zeros,_tensor=torch.Tensor.to,torch.zeros,torch.tensor |
| 27 | def cpu(kw): |
| 28 | if str(kw.get('device'))=='cuda':kw['device']='cpu' |
| 29 | return kw |
| 30 | torch.zeros=lambda *a,**k:_zeros(*a,**cpu(k));torch.tensor=lambda *a,**k:_tensor(*a,**cpu(k)) |
| 31 | torch.Tensor.to=lambda self,*a,**k:_to(self,*(('cpu',)+a[1:] if a and str(a[0])=='cuda' else a),**cpu(k)) |
| 32 | torch.cuda.init=lambda:None;torch.cuda.synchronize=lambda:None |
| 33 | |
| 34 | index=json.loads((weights/'model.safetensors.index.json').read_text())['weight_map'] |
| 35 | headers={} |
| 36 | def header(file): |
| 37 | if file not in headers: |
| 38 | with (weights/file).open('rb') as f: |
| 39 | n=struct.unpack('<Q',f.read(8))[0];headers[file]=(8+n,json.loads(f.read(n))) |
| 40 | return headers[file] |
| 41 | DT={'BF16':torch.bfloat16,'F8_E4M3':torch.float8_e4m3fn,'F32':torch.float32} |
| 42 | stand={} |
| 43 | class FakeOpen: |
| 44 | def __init__(self,path,**k):self.file=Path(path).name |
| 45 | def __enter__(self):return self |
| 46 | def __exit__(self,*a):pass |
| 47 | def get_tensor(self,name): |
| 48 | base,h=header(self.file);meta=h[name] |
| 49 | t=_zeros(1,dtype=DT[meta['dtype']]).expand(meta['shape']) |
| 50 | stand[name]=(self.file,base+meta['data_offsets'][0],meta['data_offsets'][1]-meta['data_offsets'][0],meta['dtype'],tuple(meta['shape'])) |
| 51 | return t |
| 52 | sys.modules['safetensors']=types.SimpleNamespace(safe_open=FakeOpen) |
| 53 | |
| 54 | spec=importlib.util.spec_from_file_location('real2driver',driver_path);drv=importlib.util.module_from_spec(spec);spec.loader.exec_module(drv) |
| 55 | |
| 56 | class Recorder: |
| 57 | def __init__(self):self.calls=[] |
| 58 | def launch(self,name,gx,gy,*args):drv.check_bounds(name,args);self.calls.append((name,gx,gy,args)) |
| 59 | rec=Recorder() |
| 60 | if fixture is not None: |
| 61 | # Only the ids change; the driver's top5 references belong to its own fixture and are not used by the emitter. |
| 62 | drv.GOLD=dict(drv.GOLD,prompt_ids=list(fixture['prompt_ids']),generated_ids=list(fixture['generated_ids'])) |
| 63 | if capacity is not None: |
| 64 | need=len(drv.GOLD['prompt_ids'])+len(drv.GOLD['generated_ids']) |
| 65 | if capacity<need:raise SystemExit('capacity %d is below the %d positions this run needs'%(capacity,need)) |
| 66 | # Card writes self.cap in __init__; this class property keeps the requested capacity instead. |
| 67 | drv.Card.cap=property(lambda self:capacity,lambda self,value:None) |
| 68 | card=drv.Card(torch,rec,'controls' if controls else 'omega') |
| 69 | |
| 70 | # Buffers: one per distinct storage. Weight storages come from the checkpoint; the rest are zero-filled device memory, |
| 71 | # except the RoPE table, which the harness computes exactly as Card does and ships as plan data. |
| 72 | bufs=[];by_ptr={};data_pool=bytearray() |
| 73 | def buffer_for(t): |
| 74 | ptr=t.untyped_storage().data_ptr() |
| 75 | if ptr in by_ptr:return by_ptr[ptr] |
| 76 | raise KeyError('tensor storage not registered') |
| 77 | def add(ptr,entry):by_ptr[ptr]=len(bufs);bufs.append(entry) |
| 78 | for name,t in card.weights.items(): |
| 79 | file,off,length,dtype,shape=stand[name] |
| 80 | if t.ndim==1 or t.dtype==torch.float32: |
| 81 | assert dtype=='BF16' and len(shape)==1,(name,dtype,shape) |
| 82 | mutated=controls and (name.endswith(('input_layernorm.weight','post_attention_layernorm.weight','q_norm.weight','k_norm.weight')) or name==drv.PFX+'norm.weight') |
| 83 | if mutated: |
| 84 | # CONTROLS plan only: the omitted norm +1 mutation Card applies in mode controls, shipped as plan data (kind 3). |
| 85 | with (weights/file).open('rb') as f:f.seek(off);raw=f.read(length) |
| 86 | vec=(torch.frombuffer(bytearray(raw),dtype=torch.bfloat16).float()-1).numpy().tobytes() |
| 87 | add(t.untyped_storage().data_ptr(),dict(name=name,bytes=len(vec),kind=3,file=None,off=len(data_pool),len=len(vec),src=[file,off,length]));data_pool+=vec |
| 88 | else: |
| 89 | add(t.untyped_storage().data_ptr(),dict(name=name,bytes=length*2,kind=2,file=file,off=off,len=length)) |
| 90 | else: |
| 91 | add(t.untyped_storage().data_ptr(),dict(name=name,bytes=length,kind=1,file=file,off=off,len=length)) |
| 92 | cs=card.cs.contiguous().numpy().tobytes();cs_off=len(data_pool);data_pool+=cs |
| 93 | add(card.cs.untyped_storage().data_ptr(),dict(name='rope_cs',bytes=len(cs),kind=3,file=None,off=cs_off,len=len(cs))) |
| 94 | |
| 95 | card.emit();calls=rec.calls |
| 96 | for name,gx,gy,args in calls: |
| 97 | for a in args: |
| 98 | if isinstance(a,torch.Tensor) and a.untyped_storage().data_ptr() not in by_ptr: |
| 99 | s=a.untyped_storage();add(s.data_ptr(),dict(name='act%d'%len(bufs),bytes=s.nbytes(),kind=0,file=None,off=0,len=0)) |
| 100 | tok_buf=buffer_for(card.tok) |
| 101 | |
| 102 | # Kernarg size from each code object's kernel descriptor (.kd symbol, kernarg_size u32 at descriptor offset 8). |
| 103 | def kernarg_size(raw,symbol): |
| 104 | shoff,=struct.unpack_from('<Q',raw,0x28);shentsize,shnum=struct.unpack_from('<HH',raw,0x3a) |
| 105 | secs=[struct.unpack_from('<IIQQQQIIQQ',raw,shoff+i*shentsize) for i in range(shnum)] |
| 106 | for s in secs: |
| 107 | if s[1]!=2:continue |
| 108 | strtab=secs[s[6]]; |
| 109 | for j in range(s[5]//24): |
| 110 | st_name,_,_,_,value,_=struct.unpack_from('<IBBHQQ',raw,s[4]+j*24) |
| 111 | end=raw.index(b'\0',strtab[4]+st_name) |
| 112 | if raw[strtab[4]+st_name:end]==(symbol+'.kd').encode(): |
| 113 | for p in secs: |
| 114 | if p[3]<=value<p[3]+p[5] and p[1]!=8:return struct.unpack_from('<I',raw,p[4]+value-p[3]+8)[0] |
| 115 | raise KeyError(symbol+'.kd') |
| 116 | names=sorted({c[0] for c in calls});code={} |
| 117 | for n in names: |
| 118 | sha,data,symbol=drv.OBJ[n];raw=lzma.decompress(base64.b85decode(data));assert hashlib.sha256(raw).hexdigest()==sha |
| 119 | code[n]=dict(index=len(code),sha256=sha,symbol=symbol,kernarg=kernarg_size(raw,symbol),raw=raw) |
| 120 | |
| 121 | def kernarg(name,args): |
| 122 | blob=bytearray();relocs=[] |
| 123 | for a in args: |
| 124 | if isinstance(a,int): |
| 125 | assert 0<=a<1<<32;blob+=struct.pack('<I',a) |
| 126 | else: |
| 127 | while len(blob)%8:blob+=b'\0' |
| 128 | s=a.untyped_storage();relocs.append((len(blob),by_ptr[s.data_ptr()],a.data_ptr()-s.data_ptr()));blob+=bytes(8) |
| 129 | size=code[name]['kernarg'];assert len(blob)<=size,(name,len(blob),size);blob+=bytes(size-len(blob)) |
| 130 | return bytes(blob),relocs |
| 131 | files=sorted({b['file'] for b in bufs if b['file']}) |
| 132 | strings=bytearray();code_rows=[] |
| 133 | for n in names:code_rows.append((len(strings),len(code[n]['symbol'])));strings+=code[n]['symbol'].encode() |
| 134 | plan=bytearray(b'OMPLAN01'+struct.pack('<7Q',len(names),len(files),len(bufs),len(calls),len(drv.GOLD['prompt_ids']),len(drv.GOLD['generated_ids']),tok_buf)) |
| 135 | for o,l in code_rows:plan+=struct.pack('<2Q',o,l) |
| 136 | for b in bufs:plan+=struct.pack('<6Q',b['bytes'],b['kind'],files.index(b['file']) if b['file'] else 0,b['off'],b['len'],2 if b is bufs[tok_buf] else 1) |
| 137 | plan+=b''.join(struct.pack('<i',t) for t in drv.GOLD['prompt_ids']) |
| 138 | while len(plan)%8:plan+=b'\0' |
| 139 | for name,gx,gy,args in calls: |
| 140 | blob,relocs=kernarg(name,args) |
| 141 | plan+=struct.pack('<8I',code[name]['index'],gx,gy,1,64,len(blob),len(relocs),0)+blob+b''.join(struct.pack('<IIQ',*r) for r in relocs) |
| 142 | while len(plan)%8:plan+=b'\0' |
| 143 | spool=len(plan);plan+=strings |
| 144 | dpool=len(plan);plan+=data_pool |
| 145 | plan+=struct.pack('<4Q',spool,len(strings),dpool,len(data_pool)) |
| 146 | out.write_bytes(plan) |
| 147 | |
| 148 | # Independent decode of the written bytes, compared with the recorder (name, grid, every argument). |
| 149 | def decode(p): |
| 150 | assert p[:8]==b'OMPLAN01';h=struct.unpack_from('<7Q',p,8);nc,nf,nb,nd,npm,ng,tb=h;q=64 |
| 151 | sp,sl,dp,dl=struct.unpack_from('<4Q',p,len(p)-32) |
| 152 | cnames=[] |
| 153 | for i in range(nc):o,l=struct.unpack_from('<2Q',p,q);q+=16;cnames.append(p[sp+o:sp+o+l].decode()) |
| 154 | btab=[struct.unpack_from('<6Q',p,q+48*i) for i in range(nb)];q+=48*nb |
| 155 | prompt=list(struct.unpack_from('<%di'%npm,p,q));q+=4*npm;q+=(-q)%8 |
| 156 | disp=[] |
| 157 | for i in range(nd): |
| 158 | ci,gx,gy,gz,bx,kb,nr,_=struct.unpack_from('<8I',p,q);q+=32;blob=p[q:q+kb];q+=kb |
| 159 | rel=[struct.unpack_from('<IIQ',p,q+16*j) for j in range(nr)];q+=16*nr;q+=(-q)%8 |
| 160 | for off,bi,bo in rel: |
| 161 | assert bi<nb and bo<btab[bi][0] and blob[off:off+8]==bytes(8) and off%8==0 |
| 162 | disp.append((cnames[ci],gx,gy,gz,bx,blob,rel)) |
| 163 | assert q==sp,(q,sp) |
| 164 | return dict(code=cnames,bufs=btab,prompt=prompt,disp=disp,n_gen=ng,tok=tb) |
| 165 | d=decode(bytes(out.read_bytes())) |
| 166 | assert len(d['disp'])==len(calls) |
| 167 | for (name,gx,gy,args),(dn,dgx,dgy,gz,bx,blob,rel) in zip(calls,d['disp']): |
| 168 | assert dn==code[name]['symbol'] and (gz,bx)==(1,64),(name,dn,gz,bx) |
| 169 | assert (gx,gy)==(dgx,dgy) |
| 170 | ri=iter(rel);pos=0 |
| 171 | for a in args: |
| 172 | if isinstance(a,int):assert struct.unpack_from('<I',blob,pos)[0]==a;pos+=4 |
| 173 | else: |
| 174 | pos+=(-pos)%8;off,bi,bo=next(ri);s=a.untyped_storage() |
| 175 | assert off==pos and bi==by_ptr[s.data_ptr()] and bo==a.data_ptr()-s.data_ptr();pos+=8 |
| 176 | total=sum(b[0] for b in d['bufs']) |
| 177 | summary=dict(plan=str(out),bytes=len(plan),sha256=hashlib.sha256(plan).hexdigest(),controls=controls,code_objects={n:dict(sha256=code[n]['sha256'],kernarg=code[n]['kernarg']) for n in names}, |
| 178 | files=files,buffers=len(bufs),device_bytes=total,dispatches_per_step=len(calls),prompt=len(d['prompt']),generate=d['n_gen'],tok_buffer=tok_buf, |
| 179 | by_kernel={n:sum(1 for c in calls if c[0]==n) for n in names}, |
| 180 | control_vectors=[[i,b['src'][0],b['src'][1],b['src'][2]] for i,b in enumerate(bufs) if 'src' in b], |
| 181 | capacity=card.cap,rope_buffer=by_ptr[card.cs.untyped_storage().data_ptr()], |
| 182 | kv_buffers=[by_ptr[s.untyped_storage().data_ptr()] for l in sorted(card.states) if len(card.states[l])==2 for s in card.states[l]], |
| 183 | fixture=None if fixture is None else dict(path=str(fixture_path),sha256=hashlib.sha256(fixture_raw).hexdigest(),name=fixture.get('name'), |
| 184 | prompt_ids=fixture['prompt_ids'],generated_ids=fixture['generated_ids'])) |
| 185 | Path(str(out)+'.json').write_text(json.dumps(summary,indent=1)+'\n') |
| 186 | print('PLAN_DECODE_MATCH',json.dumps({k:summary[k] for k in ('bytes','sha256','buffers','device_bytes','dispatches_per_step','prompt','generate')})) |
| 187 | cdir=out.parent/'code';cdir.mkdir(exist_ok=True) |
| 188 | for n in names:(cdir/(n+'.hsaco')).write_bytes(code[n]['raw']) |
| 189 | args=['omega-launch','plan',out.name]+['code/'+n+'.hsaco' for n in names]+['$AMDSERVE_WEIGHTS/'+f for f in files] |
| 190 | Path(str(out)+'.cmd').write_text(' '.join(args)+'\n') |