Interplane page as plain text, for reading tools and agents. English is the reference text: translate it with your own tool. Text in backticks and in ``` blocks (commands, fingerprints, file names) and link targets in <...> are exact: copy them, never translate them. Page: /drakestapleton/omega-mv/blob/main/om/gpu/dsv41/check.py # omega-mv Omega: a language for verified programs, semantic identity and machine realization. Seed-born work and existing implementations have distinct provenance. Brought by drakestapleton Sign in to star 1 stars 0 watching About Files History Releases Proposed changes Issues For developers branch `main` Branches Tags History `omega-mv / om / gpu / dsv41 / check.py` 346 lines ยท 17497 bytes Raw Blame History 1 """GB10 component parity check. Run with spark-window run python3 check.py CUBIN_DIR.""" 2 import ctypes as ct 3 import os 4 import sys 5 from pathlib import Path 6 7 import numpy as np 8 9 10 class Device: 11 def __init__(self, directory): 12 self.directory = Path(directory) 13 self.lib = ct.CDLL("libcuda.so.1") 14 self.ctx = ct.c_void_p() 15 self.call("cuInit", 0) 16 dev = ct.c_int() 17 self.call("cuDeviceGet", ct.byref(dev), 0) 18 self.call("cuCtxCreate_v2", ct.byref(self.ctx), 0, dev) 19 20 def call(self, name, *args): 21 ret = getattr(self.lib, name)(*args) 22 if ret: 23 error = ct.c_char_p() 24 self.lib.cuGetErrorName(ret, ct.byref(error)) 25 raise RuntimeError(f"{name}: {error.value} ({ret})") 26 27 def run(self, name, grid, block, tensors, output_count, scalars=()): 28 module, fn = ct.c_void_p(), ct.c_void_p() 29 args, arrays = [], [] 30 self.call("cuModuleLoad", ct.byref(module), os.fsencode(self.directory / (name + ".cubin"))) 31 try: 32 self.call("cuModuleGetFunction", ct.byref(fn), module, name.encode()) 33 for array in tensors: 34 array = np.ascontiguousarray(array) 35 ptr = ct.c_uint64() 36 self.call("cuMemAlloc_v2", ct.byref(ptr), ct.c_size_t((array.nbytes + 3) & ~3)) 37 args.append(ptr) 38 arrays.append(array) 39 self.call("cuMemcpyHtoD_v2", ptr, ct.c_void_p(array.ctypes.data), ct.c_size_t(array.nbytes)) 40 params = args + [ct.c_uint32(i) for i in scalars] 41 argv = (ct.c_void_p * len(params))(*(ct.addressof(i) for i in params)) 42 self.call("cuLaunchKernel", fn, *grid, block, 1, 1, 0, None, argv, None) 43 self.call("cuCtxSynchronize") 44 for ptr, arr in zip(args[-output_count:], arrays[-output_count:]): 45 self.call("cuMemcpyDtoH_v2", ct.c_void_p(arr.ctypes.data), ptr, ct.c_size_t(arr.nbytes)) 46 return arrays[-output_count:] 47 finally: 48 for ptr in args: 49 self.call("cuMemFree_v2", ptr) 50 self.call("cuModuleUnload", module) 51 52 53 def bf16(x): 54 x = np.asarray(x, dtype=np.float32) 55 u = x.view(np.uint32) 56 return ((u + 32767 + ((u >> 16) & 1)) & 0xffff0000).view(np.float32) 57 58 59 def lookup(): 60 values = [] 61 for code in range(256): 62 exp, frac = (code >> 3) & 15, code & 7 63 mag = frac / 512 if exp == 0 else (1 + frac / 8) * 2**(exp - 7) 64 if exp == 15 and frac == 7: 65 mag = np.nan 66 values.append(-mag if code & 128 else mag) 67 fp4 = [0., .5, 1, 1.5, 2, 3, 4, 6] 68 return np.array(values + fp4 + [-v for v in fp4], np.float32) 69 70 71 def check(device): 72 rng = np.random.default_rng(411) 73 def normal(*shape): 74 return rng.standard_normal(shape).astype(np.float32) 75 76 def verify(name, grid, block, inputs, expected, scalars=(), atol=2e-5, rtol=2e-5): 77 outputs = [np.full_like(ref, np.nan if ref.dtype.kind == "f" else 0xa5) for ref in expected] 78 actual = device.run(name, grid, block, inputs + outputs, len(outputs), scalars) 79 for ref, got in zip(expected, actual): 80 np.testing.assert_allclose(got, ref, atol=atol, rtol=rtol, equal_nan=False) 81 print(f"PASS {name}", flush=True) 82 return actual 83 84 b, d = 3, 5120 85 x = normal(b, 4, d) 86 pre, post, mat = normal(b, 4), normal(b, 4), normal(b, 4, 4) 87 (mixed,) = verify("hc_pre", (40, b, 1), 128, [x, pre], [np.einsum("bid,bi->bd", x, pre)]) 88 cancellation = np.repeat(np.array([[[-1.], [129/128], [0.], [0.]]], np.float32), d, axis=2) 89 coefficients = np.array([[`8454145`/`16777216`, `8388609`/`16777216`, .5, .5]], np.float32) 90 verify("hc_pre", (40, 1, 1), 128, [cancellation, coefficients], 91 [np.zeros((1, d), np.float32)], atol=0, rtol=0) 92 verify("hc_post", (40, b, 1), 128, [mixed, x, post, mat], 93 [mixed[:, None, :] * post[:, :, None] + np.einsum("bid,bij->bjd", x, mat)]) 94 raw, scale, bias = normal(b, 24), normal(3), normal(24) 95 logits = raw * np.repeat(scale, [4, 4, 16]) + bias 96 sigmoid = 1 / (1 + np.exp(-logits[:, :8])) 97 mat = logits[:, 8:].reshape(b, 4, 4) 98 mat = np.exp(mat - mat.max(axis=2, keepdims=True)) 99 mat = mat / mat.sum(axis=2, keepdims=True) + 1e-6 100 mat /= mat.sum(axis=1, keepdims=True) + 1e-6 101 for _ in range(19): 102 mat /= mat.sum(axis=2, keepdims=True) + 1e-6 103 mat /= mat.sum(axis=1, keepdims=True) + 1e-6 104 verify("hc_sinkhorn", (b, 1, 1), 1, [raw, scale, bias], 105 [sigmoid[:, :4] + 1e-6, sigmoid[:, 4:] * 2, mat]) 106 gate, up, weight = normal(b, 2304) * 12, normal(b, 2304) * 12, normal(b) 107 limited = np.minimum(10, gate) 108 verify("expert_act", (18, b, 1), 128, [gate, up, weight], 109 [limited / (1 + np.exp(-limited)) * np.clip(up, -10, 10) * weight[:, None]]) 110 111 lut = np.fromfile(device.directory / "decode.f32le", dtype=">16).astype(np.uint16) 219 (packed_gpu,) = verify("bf16_pack",(2,1,1),128,[values],[packed],(129,),atol=0,rtol=0) 220 verify("bf16_unpack",(2,1,1),128,[packed_gpu],[rounded],(129,),atol=0,rtol=0) 221 b,h,t = 3,4,19 222 query, keys = bf16(normal(b,h,128)), bf16(normal(b,t,128)) 223 weights = bf16(normal(b,h) / np.sqrt(128*32)) 224 lens = np.array([19,10,0],np.uint32) 225 keep = np.ones((b,3),np.int32) 226 keep[0,1] = 0 227 dots = bf16(np.einsum("bhd,btd->bht",query,keys)) 228 score = bf16(bf16(np.maximum(dots,0) * weights[:,:,None]).sum(axis=1)) 229 mask = (np.arange(t) < lens[:,None]) & (keep[:,np.arange(t)//8] != 0) 230 score = np.where(mask,score,-np.inf) 231 verify("index_scores",(1,b,1),128,[query,keys,weights,lens,keep],[score],(h,t)) 232 blocks = np.full((b,3),-np.inf,np.float32) 233 for row in range(b): 234 for col in range(3): 235 blocks[row,col] = score[row,col*8:(col+1)*8].max() 236 if lens[row]: 237 blocks[row,(int(lens[row])-1)//8] = np.inf 238 verify("candidate_blocks",(3,b,1),1,[score,lens],[blocks],(t,)) 239 score[0,:5] = 8 # cutoff crosses a tie 240 score[1,:9] = -np.inf 241 for scores, k, offset in [(score,3,128),(blocks,2,0)]: 242 ids = np.full((b,k),-1,np.int32) 243 mask = np.zeros_like(scores,dtype=np.int32) 244 for row, entries in enumerate(scores): 245 ids_sorted = np.argsort(-entries,kind="stable")[:k] 246 chosen = np.sort(ids_sorted[entries[ids_sorted] > -np.inf]) 247 ids[row,:len(chosen)] = chosen+offset 248 mask[row,chosen] = 1 249 verify("top_positions",(b,1,1),1,[scores],[ids,mask],(scores.shape[1],k,offset)) 250 residual, keys, gain = bf16(normal(b,4,5120)), bf16(normal(b,4,5120)), normal(4,5120) 251 valid = np.array([1,0,1],np.int32) 252 rstd = 1/np.sqrt(np.mean(residual**2,axis=2)+1e-20) / np.sqrt(np.mean(keys**2,axis=2)+1e-20) 253 dot = np.sum(residual*gain*keys,axis=2) * rstd / np.sqrt(5120) 254 gate = np.where(valid[:,None],1/(1+np.exp(-np.copysign(np.sqrt(np.maximum(np.abs(dot),1e-6)),dot))),0).astype(np.float32) 255 (gate_gpu,) = verify("engram_gate",(4,b,1),1,[residual,keys,gain,valid],[gate]) 256 v = bf16(normal(b,5120)) 257 ref = bf16(residual + gate_gpu[:,:,None]*v[:,None,:]) 258 verify("engram_add",(40,4,b),128,[residual,v,gate_gpu],[ref],atol=1e-6,rtol=0.008) 259 260 table = bf16(normal(7,5120)) 261 ids = np.array([9,10,15,17],np.int32) 262 rows = np.zeros((4,4,5120),np.float32) 263 rows[1],rows[2] = table[0],table[5] 264 verify("token_embed",(40,len(ids),1),128,[ids,(table.view(np.uint32)>>16).astype(np.uint16)],[rows],(10,7),atol=0,rtol=0) 265 experts, shared = bf16(normal(3,6,5120)), bf16(normal(3,5120)) 266 verify("moe_sum",(40,3,1),128,[experts,shared],[bf16(experts.sum(axis=1)+shared)],atol=0,rtol=0) 267 pos = np.array([1,127,260],np.uint32) 268 kv, cache = normal(3,512), normal(3,128,512) 269 expected_cache = cache.copy() 270 expected_cache[np.arange(3),pos % 128] = kv 271 expected_slots = (pos[:,None]+1+np.arange(128)) % 128 272 expected_slots = np.where(expected_slots > pos[:,None], -1, expected_slots).astype(np.int32) 273 got_cache, got_slots = device.run("window_step",(4,3,1),128,[kv,pos,cache,np.full((3,128),-2,np.int32)],2) 274 np.testing.assert_array_equal(got_cache,expected_cache) 275 np.testing.assert_array_equal(got_slots,expected_slots) 276 print("PASS window_step",flush=True) 277 278 h, t, s = 3, 7, 71 279 q, kv = bf16(normal(b, h, 512)), bf16(normal(b, t, 512)) 280 idx = rng.integers(-1, t, (b, s), dtype=np.int32) 281 idx[0, :64] = -1 282 idx[1] = -1 283 sink = np.array([-1, .5, 2], np.float32) 284 values = kv[np.arange(b)[:, None], np.maximum(idx, 0)] 285 scores = np.einsum("bhd,bsd->bhs", q, values) / np.float32(np.sqrt(512)) 286 scores = np.where(idx[:, None, :] < 0, -np.inf, scores) 287 (scores_gpu,) = verify("sparse_scores", (s, h, b), 1, [q, kv, idx], [scores], (h, t, s)) 288 peak = np.full((b,h), -1e30, np.float32) 289 denom = np.zeros_like(peak) 290 numerator = np.zeros((b,h,512), np.float32) 291 for first in range(0, s, 64): 292 tile = scores[:, :, first:first+64] 293 new_peak = np.maximum(peak, tile.max(axis=2)) 294 correction = np.exp(peak - new_peak) 295 p = np.exp(tile - new_peak[:, :, None]) 296 denom = denom * correction + p.sum(axis=2) 297 numerator = numerator * correction[:, :, None] + np.einsum("bhs,bsd->bhd", bf16(p), values[:, first:first+64]) 298 peak = new_peak 299 with np.errstate(over="ignore"): 300 denom += np.exp(sink - peak) 301 ref = numerator / denom[:, :, None] 302 verify("sparse_mix", (4, h, b), 128, [scores_gpu, kv, idx, sink], [ref], (h, t, s)) 303 304 # One routed expert at checkpoint widths. Each independently packed W row has two 305 # nonzero weights, allowing exact expected projections without a second GPU stack. 306 def quantize_vector(x): 307 packed = np.empty(x.shape, np.uint8) 308 scales = np.empty((x.size//32,), np.uint8) 309 reconstructed = np.empty_like(x) 310 return device.run("quant_fp8", (scales.size,1,1), 16, 311 [x,lut,packed,scales,reconstructed],3) 312 313 def project_vector(packed, scales, recon, rows, offset): 314 cols = packed.size 315 idx = np.arange(rows,dtype=np.int32) 316 i = (idx*17+offset) % cols 317 j = (i+31) % cols 318 mat = np.zeros((rows,cols//2),np.uint8) 319 mat[idx,i//2] |= (np.uint8(2) << ((i%2)*4)).astype(np.uint8) # +1.0 320 mat[idx,j//2] |= (np.uint8(9) << ((j%2)*4)).astype(np.uint8) # -0.5 321 ws = np.full((rows,cols//32),127,np.uint8) 322 (got,) = device.run("fp4_gemm",((rows+127)//128,1,1),128, 323 [packed,mat,scales,ws,lut,np.full(rows,np.nan,np.float32)],1,(cols,rows)) 324 np.testing.assert_array_equal(got, recon[i] - .5*recon[j]) 325 return bf16(got) 326 327 packed, scales, recon = quantize_vector(bf16(normal(5120))) 328 gate = project_vector(packed,scales,recon,2304,9) 329 up = project_vector(packed,scales,recon,2304,42) 330 weight = np.array([.375],np.float32) 331 mid_ref = np.minimum(gate,10) / (1+np.exp(-np.minimum(gate,10))) * np.clip(up,-10,10) * weight 332 (mid,) = device.run("expert_act",(18,1,1),128,[gate,up,weight,np.full_like(gate,np.nan)],1) 333 np.testing.assert_allclose(mid,mid_ref,atol=2e-6,rtol=2e-6) 334 packed, scales, recon = quantize_vector(bf16(mid)) 335 project_vector(packed,scales,recon,5120,91) 336 print("PASS routed expert chain 5120 -> 2304 -> 5120 (synthetic weights)",flush=True) 337 338 339 if __name__ == "__main__": 340 if not os.environ.get("SPARK_WINDOW"): 341 sys.exit("Run inside the authorized GB10 correctness window") 342 device = Device(sys.argv[1]) 343 try: 344 check(device) 345 finally: 346 device.call("cuCtxDestroy_v2", device.ctx)