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 / notebook_section.py
| 1 | # SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception |
| 2 | """Test-only notebook instrument. token_ref.py exports this with generated fixtures. |
| 3 | No production dependency; the numerical intervals come from the host oracle. |
| 4 | """ |
| 5 | def run_section(ctx): |
| 6 | import base64 |
| 7 | import ctypes as C |
| 8 | import math |
| 9 | import struct |
| 10 | import time |
| 11 | from fractions import Fraction |
| 12 | |
| 13 | p = _make_payload() |
| 14 | name = p['name'] |
| 15 | say, put, get = (ctx[k] for k in ('say', 'put', 'get')) |
| 16 | load, Params, launch = (ctx[k] for k in ('load', 'Params', 'launch')) |
| 17 | objects, controls = ctx['objs'], ctx['controls'] |
| 18 | fn = load(objects[name], name) |
| 19 | owned = [] |
| 20 | |
| 21 | def alloc(data): |
| 22 | d = put(data) |
| 23 | owned.append(d) |
| 24 | return d |
| 25 | |
| 26 | def raw(case): |
| 27 | return base64.b64decode(case['memory']) |
| 28 | |
| 29 | def step(case, base, function=fn): |
| 30 | vals = [C.c_void_p(base.value+v) if kind == 'ptr' else C.c_uint32(v) |
| 31 | for kind, v in case['args']] |
| 32 | return function, case['gx'], case['gy'], Params(vals) |
| 33 | |
| 34 | def check(actual, case): |
| 35 | before = raw(case) |
| 36 | assert len(actual) == len(before), 'notebook memory size mismatch' |
| 37 | unchanged = bytearray(actual) |
| 38 | widest = Fraction(0) |
| 39 | for off in case.get('bf16_outputs',[]): |
| 40 | assert struct.unpack_from('<I',actual,off)[0]&0xffff==0, f'{name} BF16 rounding mismatch offset={off}' |
| 41 | for off, lo, hi in case['intervals']: |
| 42 | bits = struct.unpack_from('<I', actual, off)[0] |
| 43 | x = struct.unpack('<f', struct.pack('<I', bits))[0] |
| 44 | lo, hi = Fraction(lo), Fraction(hi) |
| 45 | assert math.isfinite(x) and lo <= Fraction(x) <= hi, f'{name} interval mismatch offset={off} bits={bits:08x}' |
| 46 | widest = max(widest, hi-lo) |
| 47 | unchanged[off:off+4] = before[off:off+4] |
| 48 | for off,lo,hi in case.get('half_intervals',[]): |
| 49 | bits=struct.unpack_from('<H',actual,off)[0]<<16 |
| 50 | x=struct.unpack('<f',struct.pack('<I',bits))[0] |
| 51 | lo,hi=Fraction(lo),Fraction(hi) |
| 52 | assert math.isfinite(x) and lo<=Fraction(x)<=hi, f'{name} BF16 interval mismatch offset={off}' |
| 53 | widest=max(widest,hi-lo) |
| 54 | unchanged[off:off+2]=before[off:off+2] |
| 55 | for off, bits, width in case.get('exact', []): |
| 56 | assert int.from_bytes(actual[off:off+width], 'little') == bits, f'{name} exact mismatch offset={off}' |
| 57 | unchanged[off:off+width] = before[off:off+width] |
| 58 | assert unchanged == before, f'{name} input/guard corruption' |
| 59 | return widest |
| 60 | |
| 61 | try: |
| 62 | for case in p['cases']: |
| 63 | d = alloc(raw(case)) |
| 64 | launch([step(case,d)]) |
| 65 | width = check(get(d,len(raw(case))),case) |
| 66 | say(f'PASS {name} {case["label"]} every-output interval/exact inputs/guards widest_interval={width}') |
| 67 | case = dict(p['cases'][p['timing']]) |
| 68 | case['gx'],case['gy'] = case['timing_grid'] |
| 69 | image = raw(case) |
| 70 | d = alloc(image) |
| 71 | steps = [step(case,d)] |
| 72 | ev = ctx['event_ms'](steps) |
| 73 | warm = ctx['wall_ms']([steps]) |
| 74 | expected = get(d,len(image)) |
| 75 | width = check(expected,case) |
| 76 | # Distinct input allocations/addresses exceed the requested cold working set. |
| 77 | # The output is a separate region; all inputs are immutable across launches. |
| 78 | # Each case is idempotent, including stateful operators with old/new buffers. |
| 79 | copies = int(ctx['COLD_BYTES']) // case['input_bytes'] + 1 |
| 80 | cold = alloc(image*copies) |
| 81 | rotation = [[step(case,C.c_void_p(cold.value+i*len(image)))] for i in range(copies)] |
| 82 | cold_ms = ctx['wall_ms'](rotation) |
| 83 | observed = memoryview(get(cold,len(image)*copies)) |
| 84 | for i in range(copies): |
| 85 | # Exact equality with the interval-checked warm run checks EVERY output, |
| 86 | # every guard and every input of EVERY timed cold copy, not a sample. |
| 87 | assert observed[i*len(image):(i+1)*len(image)] == expected, f'{name} cold output/guard mismatch copy={i}' |
| 88 | say(f'{name} {case["label"]} event_ms={ev:.6f} warm_wall_ms={warm:.6f} cold_wall_ms={cold_ms:.6f} copies={copies} input_bytes={copies*case["input_bytes"]} every-timed-output=PASS guards=PASS widest_interval={width}') |
| 89 | for control in p['controls']: |
| 90 | bad = load(objects[control],name) |
| 91 | d = alloc(image) |
| 92 | launch([step(case,d,bad)]) |
| 93 | try: |
| 94 | check(get(d,len(image)),case) |
| 95 | except AssertionError: |
| 96 | controls[control] = True |
| 97 | say(f'CONTROL {control} CAUGHT') |
| 98 | else: |
| 99 | controls[control] = False |
| 100 | raise AssertionError(f'{control} escaped') |
| 101 | finally: |
| 102 | for d in reversed(owned): |
| 103 | ctx['chk'](ctx['hip'].hipFree(d),f'free {name} section') |
| 104 | # Reference implementation is a measurement instrument, never an Omega kernel. |
| 105 | try: |
| 106 | import torch |
| 107 | import torch.nn.functional as F |
| 108 | case = p['cases'][p['timing']] |
| 109 | image = raw(case) |
| 110 | def tensor(off,n): |
| 111 | vals = struct.unpack_from('<'+str(n)+'f',image,off) |
| 112 | return torch.tensor(vals,device='cuda',dtype=torch.float32) |
| 113 | if name == 'mlpsilu': |
| 114 | n = case['args'][3][1] |
| 115 | g,u = (tensor(case['args'][j][1],n) for j in (0,1)) |
| 116 | operation = lambda: F.silu(g)*u |
| 117 | elif name == 'rmsnorm5120': |
| 118 | n = 5120 |
| 119 | x,w = (tensor(case['args'][j][1],n) for j in (0,1)) |
| 120 | operation = lambda: x*torch.rsqrt(x.square().mean()+1e-6)*(1+w) |
| 121 | elif name == 'gdnconv4': |
| 122 | n = 16*128*2+48*128 |
| 123 | x = tensor(case['args'][0][1],n).view(1,n,1) |
| 124 | def bfloat(off): |
| 125 | values=struct.unpack_from('<'+str(n*4)+'H',image,off) |
| 126 | words=struct.pack('<'+str(n*4)+'I',*(v<<16 for v in values)) |
| 127 | return torch.tensor(struct.unpack('<'+str(n*4)+'f',words),device='cuda',dtype=torch.bfloat16) |
| 128 | weight=bfloat(case['args'][1][1]).view(n,1,4) |
| 129 | old=bfloat(case['args'][2][1]).view(1,n,4) |
| 130 | def operation(): |
| 131 | state=torch.cat((old,x),dim=-1).to(weight.dtype) |
| 132 | new=state[:,:,-4:].clone() |
| 133 | out=F.silu(F.conv1d(state,weight,groups=n)[:,:,-1:]).float() |
| 134 | return out,new |
| 135 | elif name == 'gdnqknorm': |
| 136 | x=tensor(case['args'][0][1],4096).view(32,128).bfloat16() |
| 137 | def operation(): |
| 138 | value=(x*torch.rsqrt((x*x).sum(dim=-1,keepdim=True)+1e-6)).float() |
| 139 | return torch.cat((value[:16]*(128**-0.5),value[16:])) |
| 140 | elif name == 'gdnstate': |
| 141 | qk=tensor(case['args'][0][1],4096).view(2,16,128).repeat_interleave(3,dim=1) |
| 142 | values=tensor(case['args'][1][1],48*128).view(48,128) |
| 143 | old=tensor(case['args'][2][1],48*128*128).view(48,128,128) |
| 144 | decay=tensor(case['args'][5][1],48).view(48,1,1) |
| 145 | beta=tensor(case['args'][6][1],48).view(48,1) |
| 146 | def operation(): |
| 147 | state=old*decay |
| 148 | memory=(state*qk[1,:,:,None]).sum(dim=1) |
| 149 | delta=(values-memory)*beta |
| 150 | state=state+qk[1,:,:,None]*delta[:,None,:] |
| 151 | return (state*qk[0,:,:,None]).sum(dim=1).bfloat16().float(),state |
| 152 | elif name == 'residual5120': |
| 153 | a,b=(tensor(case['args'][j][1],5120).bfloat16() for j in (0,1)) |
| 154 | operation=lambda: (a+b).float() |
| 155 | elif name == 'embed5120': |
| 156 | words=struct.unpack_from('<5120H',image,case['args'][0][1]) |
| 157 | row=torch.tensor(words,device='cuda',dtype=torch.uint16).view(torch.bfloat16) |
| 158 | operation=lambda: row.float() |
| 159 | elif name == 'gdnparams': |
| 160 | a,b,A,dt=(tensor(case['args'][j][1],48) for j in range(4)) |
| 161 | a,b=a.bfloat16(),b.bfloat16() |
| 162 | operation=lambda: ((-A.exp()*F.softplus(a.float()+dt)).exp(),b.sigmoid().float()) |
| 163 | elif name == 'gdnrmsgate': |
| 164 | x=tensor(case['args'][0][1],6144).view(48,128).bfloat16() |
| 165 | w=tensor(case['args'][1][1],128).bfloat16() |
| 166 | z=tensor(case['args'][2][1],6144).view(48,128).bfloat16().float() |
| 167 | def operation(): |
| 168 | norm=(x.float()*torch.rsqrt(x.float().square().mean(-1,keepdim=True)+1e-6)).bfloat16() |
| 169 | return ((norm*w).float()*F.silu(z)).bfloat16().float() |
| 170 | elif name == 'argmax_part': |
| 171 | logits=tensor(case['args'][0][1],248320).view(-1,64) |
| 172 | operation=lambda: logits.argmax(dim=-1) |
| 173 | elif name == 'argmax_final': |
| 174 | pairs=struct.unpack_from('<7760I',image,case['args'][0][1]) |
| 175 | keys=torch.tensor(pairs[::2],device='cuda',dtype=torch.int64) |
| 176 | indices=torch.tensor(pairs[1::2],device='cuda',dtype=torch.int64) |
| 177 | operation=lambda: torch.where(keys==keys.max(),indices,248320).min() |
| 178 | elif name == 'attn256_prep': |
| 179 | q=tensor(case['args'][0][1],12288).view(24,512)[:,:256] |
| 180 | k=tensor(case['args'][1][1],1024).view(4,256) |
| 181 | v=tensor(case['args'][2][1],1024).view(4,256) |
| 182 | qw,kw=(tensor(case['args'][j][1],256) for j in (3,4)) |
| 183 | cs=tensor(case['args'][5][1],64) |
| 184 | def rotate(x,w): |
| 185 | x=x*torch.rsqrt(x.square().mean(-1,keepdim=True)+1e-6)*(1+w) |
| 186 | a,b=x[:,:32].clone(),x[:,32:64].clone() |
| 187 | x[:,:32]=a*cs[:32]-b*cs[32:] |
| 188 | x[:,32:64]=b*cs[:32]+a*cs[32:] |
| 189 | return x |
| 190 | operation=lambda: (rotate(q,qw),rotate(k,kw).bfloat16(),v.bfloat16()) |
| 191 | elif name == 'attn256_gate': |
| 192 | gate=tensor(case['args'][0][1],12288).view(24,512)[:,256:] |
| 193 | attention=tensor(case['args'][1][1],6144).view(24,256) |
| 194 | operation=lambda: attention*gate.sigmoid() |
| 195 | else: |
| 196 | raise ValueError('missing torch reference for '+name) |
| 197 | operation(); torch.cuda.synchronize() |
| 198 | repetitions = ctx.get('NWALL',200) |
| 199 | start = time.perf_counter() |
| 200 | for _ in range(repetitions): reference = operation() |
| 201 | torch.cuda.synchronize() |
| 202 | elapsed = (time.perf_counter()-start)*1000/repetitions |
| 203 | # Different reduction/exp implementations are deliberately not the Omega |
| 204 | # interval oracle. Print the reference clock without claiming bit parity. |
| 205 | for index,value in enumerate(reference if isinstance(reference,tuple) else (reference,)): |
| 206 | if name == 'attn256_prep': |
| 207 | if index==2: |
| 208 | assert torch.equal(torch.isnan(value),torch.isnan(v)) |
| 209 | assert torch.equal(torch.isinf(value),torch.isinf(v)) |
| 210 | continue |
| 211 | assert torch.isfinite(value).all().item() |
| 212 | dtype = 'BF16-conv/cache FP32-accum/output' if name == 'gdnconv4' else 'FP32' |
| 213 | say(f'torch {name} (AMD library, not Omega) warm_wall_ms={elapsed:.6f} dtype={dtype}') |
| 214 | except ImportError: |
| 215 | say(f'torch {name} (AMD library, not Omega) NOT_RUN unavailable') |
| 216 | return True |