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 / fp8block_fast_notebook / simulated_device.py
| 1 | # SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception |
| 2 | # TEST INJECTION ONLY. No hardware, driver, GPU, or AMD library is exercised. |
| 3 | import signal, resource, types |
| 4 | resource.setrlimit(resource.RLIMIT_CORE,(0,0)) |
| 5 | SIMULATED=True |
| 6 | _original_run=subprocess.run |
| 7 | |
| 8 | def _simulation_run(argv,*args,**kwargs): |
| 9 | if isinstance(argv,str) and argv.startswith('rocminfo '): |
| 10 | return subprocess.CompletedProcess(argv,0,'SIMULATED host; no device query\n','') |
| 11 | return _original_run(argv,*args,**kwargs) |
| 12 | subprocess.run=_simulation_run |
| 13 | |
| 14 | |
| 15 | def _simulation_result(case,mode): |
| 16 | m,k=case['m'],case['k']; tab=fp8_table(); x=case['x'].astype(np.float64) |
| 17 | flat=(case['scales'].astype(np.uint32)<<16).view(np.float32).ravel().astype(np.float64) |
| 18 | nb=(k+127)//128; mb=(m+127)//128; out=np.zeros(m,dtype=np.float64) |
| 19 | stop=k//128*128 if mode=='no-tail-block' else k |
| 20 | for row in range(m): |
| 21 | columns=np.arange(stop)//128 |
| 22 | indices=(row*nb+columns if mode=='per-row-scale' else columns*mb+row//128 if mode=='transposed-scale' else (row//128)*nb+columns) |
| 23 | scales=np.zeros(stop,dtype=np.float64) |
| 24 | valid=indices<len(flat); scales[valid]=flat[indices[valid]] |
| 25 | out[row]=np.dot(tab[case['w'][row,:stop]]*scales,x[:stop]) |
| 26 | return out.astype(np.float32).tobytes() |
| 27 | |
| 28 | |
| 29 | class Fake: |
| 30 | def __init__(self): |
| 31 | self.mem={}; self.next=1<<20; self.modules={}; self.functions={}; self.cache={} |
| 32 | def hipInit(self,n): return 0 |
| 33 | def locate(self,p,n): |
| 34 | address=p.value if hasattr(p,'value') else p |
| 35 | for base,record in self.mem.items(): |
| 36 | if base<=address and address+n<=base+record['size']: return record,address-base |
| 37 | raise AssertionError('simulated allocation overrun') |
| 38 | def read(self,p,n): |
| 39 | record,off=self.locate(p,n); data=record['data'] |
| 40 | return data[off:off+n]+bytes(max(0,off+n-max(off,len(data)))) |
| 41 | def hipMalloc(self,pp,n): |
| 42 | pp._obj.value=self.next; self.mem[self.next]=dict(size=n.value,data=b'') |
| 43 | self.next+=n.value+4096; return 0 |
| 44 | def hipMemset(self,p,value,n): |
| 45 | record,off=self.locate(p,n.value) |
| 46 | assert value==0 and off==len(record['data']) and n.value==SLACK |
| 47 | return 0 |
| 48 | def hipMemcpy(self,dst,src,n,kind): |
| 49 | if kind==1: |
| 50 | record,off=self.locate(dst,n.value); assert off==0 |
| 51 | record['data']=src if isinstance(src,bytes) else ctypes.string_at(src,n.value) |
| 52 | assert len(record['data'])==n.value |
| 53 | else: ctypes.memmove(dst,self.read(src,n.value),n.value) |
| 54 | return 0 |
| 55 | def hipFree(self,p): del self.mem[p.value]; return 0 |
| 56 | def hipModuleLoadData(self,pm,data): |
| 57 | digest=hashlib.sha256(data.raw).hexdigest() |
| 58 | names=[name for name,item in DATA['objects'].items() if item['sha256']==digest] |
| 59 | assert len(names)==1 |
| 60 | handle=len(self.modules)+1; self.modules[handle]=names[0]; pm._obj.value=handle; return 0 |
| 61 | def hipModuleGetFunction(self,pf,module,name): |
| 62 | assert name==DATA['objects'][self.modules[module.value]]['entry'].encode() |
| 63 | handle=len(self.functions)+1; self.functions[handle]=self.modules[module.value]; pf._obj.value=handle; return 0 |
| 64 | def hipModuleUnload(self,module): return 0 |
| 65 | def hipDeviceSynchronize(self): return 0 |
| 66 | def hipModuleLaunchKernel(self,fn,gx,gy,gz,bx,by,bz,shared,stream,params,extra): |
| 67 | case=CURRENT_CASE; bufs=CURRENT_BUFFERS |
| 68 | assert (gy,gz,bx,by,bz)==(1,1,64,1,1) |
| 69 | assert gx in (max(1,case['m']),case['m']+1) |
| 70 | for i,value in enumerate(bufs.values[CURRENT_INDEX]): |
| 71 | if i<4: |
| 72 | p=ctypes.cast(params[i],ctypes.POINTER(ctypes.c_void_p)).contents.value |
| 73 | assert p==value.value |
| 74 | record=self.mem[p]; expected=case['buffers'][i] |
| 75 | assert record['size']==len(expected)+SLACK |
| 76 | assert self.read(p+len(expected),SLACK)==bytes(SLACK) |
| 77 | if i<3: assert record['data']==expected |
| 78 | else: assert ctypes.cast(params[i],ctypes.POINTER(ctypes.c_uint32)).contents.value==value.value |
| 79 | if GROUP==os.environ.get('SELFCHECK_FAULT_GROUP'): os.kill(os.getpid(),signal.SIGSEGV) |
| 80 | name=self.functions[fn.value]; mode=name.removeprefix('fp8gemv_b128f-') if name.startswith('fp8gemv_b128f-') else '' |
| 81 | group=next(g for g in DATA['groups'] if g['id']==GROUP) |
| 82 | if group['kind']=='timing': assert name==group['kernel'],'timing dispatched the wrong kernel' |
| 83 | if GROUP==os.environ.get('SELFCHECK_ESCAPE_GROUP'): mode='' |
| 84 | key=(case['digest'],mode) |
| 85 | if key not in self.cache: self.cache[key]=_simulation_result(case,mode) |
| 86 | output=self.cache[key] |
| 87 | if GROUP==os.environ.get('SELFCHECK_CORRUPT_GROUP'): |
| 88 | output=bytearray(output); index=max(0,case['m']-2) |
| 89 | struct.pack_into('<f',output,index*4,1e30); output=bytes(output) |
| 90 | self.mem[bufs.outputs[CURRENT_INDEX].value]['data']=output |
| 91 | return 0 |
| 92 | |
| 93 | setup_hip=lambda: Fake() |
| 94 | |
| 95 | |
| 96 | class Storage: |
| 97 | def __init__(self,size,dtype,data=None): self.size=size; self.dtype=dtype; self.data=data |
| 98 | |
| 99 | |
| 100 | class Tensor: |
| 101 | def __init__(self,storage,shape=None,start=0,count=None): |
| 102 | self.storage=storage; self.start=start |
| 103 | self.count=storage.size-start if count is None else count |
| 104 | self.shape=(self.count,) if shape is None else tuple(shape) |
| 105 | def array(self): |
| 106 | data=self.storage.data |
| 107 | if data is None or self.start>=len(data): return np.zeros(self.shape,dtype=self.storage.dtype) |
| 108 | assert self.start+self.count<=len(data) |
| 109 | return data[self.start:self.start+self.count].reshape(self.shape) |
| 110 | def __getitem__(self,item): |
| 111 | assert isinstance(item,slice) and item.step is None |
| 112 | start=0 if item.start is None else item.start; end=self.count if item.stop is None else item.stop |
| 113 | return Tensor(self.storage,start=self.start+start,count=end-start) |
| 114 | def reshape(self,*shape): |
| 115 | assert math.prod(shape)==self.count |
| 116 | return Tensor(self.storage,shape,self.start,self.count) |
| 117 | def copy_(self,other): |
| 118 | assert self.start==0 and self.count==other.count and self.storage.dtype==other.storage.dtype |
| 119 | self.storage.data=other.array().reshape(-1) |
| 120 | return self |
| 121 | def view(self,dtype): |
| 122 | assert dtype=='bf16' and self.storage.dtype==np.uint16 |
| 123 | return self |
| 124 | def to(self,dtype): |
| 125 | assert dtype=='bf16' |
| 126 | value=self.array().astype(np.float32); bits=value.view(np.uint32) |
| 127 | data=((bits+0x7fff+((bits>>16)&1))>>16).astype(np.uint16) |
| 128 | data[np.isnan(value)]=0x7fc0 |
| 129 | return Tensor(Storage(data.size,np.uint16,data.ravel()),data.shape) |
| 130 | def float(self): |
| 131 | assert self.storage.dtype==np.uint16 |
| 132 | data=(self.array().astype(np.uint32)<<16).view(np.float32) |
| 133 | return Tensor(Storage(data.size,np.float32,data.ravel()),data.shape) |
| 134 | def cpu(self): return self |
| 135 | def numpy(self): return self.array() |
| 136 | |
| 137 | |
| 138 | class Torch: |
| 139 | bfloat16='bf16'; __version__='SIMULATED'; version=types.SimpleNamespace(hip='SIMULATED') |
| 140 | cuda=types.SimpleNamespace(is_available=lambda:True,synchronize=lambda:None,get_device_name=lambda:'SIMULATED_gfx942') |
| 141 | def __init__(self): self.cache={} |
| 142 | def zeros(self,n,dtype,device): |
| 143 | assert dtype=='bf16' and device=='cuda' and n>=SLACK//2 |
| 144 | return Tensor(Storage(n,np.uint16)) |
| 145 | def from_numpy(self,data): return Tensor(Storage(data.size,data.dtype,data.ravel()),data.shape) |
| 146 | def count_nonzero(self,t): return types.SimpleNamespace(item=lambda:int(np.count_nonzero(t.array()))) |
| 147 | def matmul(self,a,x,out): |
| 148 | # All matrix copies alias immutable simulation storage, not real device allocations. |
| 149 | base=a.storage.data |
| 150 | while getattr(base,'base',None) is not None: base=base.base |
| 151 | key=(id(base),id(x.storage.data),a.shape) |
| 152 | if key not in self.cache: |
| 153 | w=a.array(); xf=x.float().array().astype(np.float64); result=np.zeros(a.shape[0],dtype=np.float32) |
| 154 | for r in range(0,a.shape[0],128): |
| 155 | wf=(w[r:r+128].astype(np.uint32)<<16).view(np.float32).astype(np.float64) |
| 156 | result[r:r+128]=wf@xf |
| 157 | bits=result.view(np.uint32) |
| 158 | words=((bits+0x7fff+((bits>>16)&1))>>16).astype(np.uint16); words[np.isnan(result)]=0x7fc0 |
| 159 | self.cache[key]=words |
| 160 | out.storage.data=self.cache[key] |
| 161 | return out |
| 162 | |
| 163 | sys.modules['torch']=Torch() |