interplane.Get Omega
Read in your language

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

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."""
2import ctypes as ct
3import os
4import sys
5from pathlib import Path
6
7import numpy as np
8
9
10class 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
53def 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
59def 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
71def 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="<f4")
112 np.testing.assert_array_equal(lut.view(np.uint32), lookup().view(np.uint32))
113 def encode(values, table):
114 mag = np.abs(values).astype(np.float64)
115 mids = (table[:-1] + table[1:]).astype(np.float64) / 2
116 code = np.searchsorted(mids, mag, side="left")
117 tie = (code < len(mids)) & (mag == mids[np.minimum(code, len(mids)-1)])
118 return (code + (tie & (code % 2 == 1)) + np.signbit(values) * (128 if len(table)==127 else 8)).astype(np.uint8)
119
120 for name, group in [("quant_fp8", 32), ("quant_fp4", 32), ("quant_kv", 16)]:
121 fp4 = name != "quant_fp8"
122 values = bf16(normal(13, group) * 3)
123 values[0] = 0
124 values[1, :8] = [-0., .25, .75, 1.25, 1.75, 2.5, 3.5, 5.]
125 values[1, 8:] = 6
126 values[2] *= 2**-14
127 if name == "quant_kv":
128 values[3] = bf16(np.linspace(-2688., 2688., group, dtype=np.float32))
129 maxval = 6 if fp4 else 448
130 floor = 6*2**-9 if name == "quant_kv" else (6*2**-126 if fp4 else 1e-4)
131 ratio = np.maximum(np.abs(values).max(axis=1), floor) / np.float32(maxval)
132 if name == "quant_kv":
133 scale_codes = encode(ratio, lut[:127])
134 scales = lut[scale_codes]
135 else:
136 exponents = np.ceil(np.log2(ratio.astype(np.float64)))
137 scale_codes = (exponents + 127).astype(np.uint8)
138 scales = np.exp2(exponents).astype(np.float32)
139 codes = encode(values / scales[:, None], lut[256:264] if fp4 else lut[:127])
140 dequant = bf16(lut[codes.astype(int) + (256 if fp4 else 0)] * scales[:, None])
141 packed = codes[:, ::2] | (codes[:, 1::2] << 4) if fp4 else codes
142 verify(name, (len(values), 1, 1), group//2, [values, lut],
143 [packed, scale_codes, dequant], atol=0, rtol=0)
144
145 m, n, k = 2, 133, 64
146 a = rng.integers(16, 80, (m, k), dtype=np.uint8) | (rng.integers(0, 2, (m, k), dtype=np.uint8) << 7)
147 sa = rng.integers(125, 131, (m, k//32), dtype=np.uint8)
148 for packed in (False, True):
149 sw = rng.integers(125, 131, (n if packed else (n+31)//32, k//32), dtype=np.uint8)
150 w = rng.integers(0, 16 if packed else 90, (n, k), dtype=np.uint8)
151 weights = lut[256 + w.astype(int)] if packed else lut[w]
152 storage = w[:, ::2] | (w[:, 1::2] << 4) if packed else w
153 asc = np.repeat(np.exp2(sa.astype(np.float32) - 127), 32, axis=1)
154 wsc = np.repeat(np.exp2(sw.astype(np.float32) - 127), 32, axis=1)
155 if not packed:
156 wsc = np.repeat(wsc, 32, axis=0)[:n]
157 ref = (lut[a] * asc) @ (weights * wsc).T
158 verify("fp4_gemm" if packed else "fp8_gemm", ((n+127)//128, m, 1), 128,
159 [a, storage, sa, sw, lut], [ref], (k, n), atol=5e-4)
160
161 # Dense projection, normalization and the compressed latent's two-token pooling.
162 a, w = bf16(normal(3, 129)), bf16(normal(131, 129))
163 verify("dense", (2, 3, 1), 128, [a, w], [a @ w.T], (129, 131), atol=3e-5)
164 a, gain = bf16(normal(3, 5120)), normal(5120)
165 a[2] = 0
166 inv = 1 / np.sqrt(np.mean(a*a, axis=1) + 1e-20)
167 (stat,) = verify("rms_stat", (3, 1, 1), 1, [a], [inv], (5120,))
168 verify("rms_apply", (40, 3, 1), 128, [a, gain, stat], [a * inv[:,None] * gain], (5120,))
169 # rotary_tail mutates its first parameter, whose untouched prefix also needs checking.
170 for sign in (1., -1.):
171 angles = normal(3, 32)
172 freq = np.stack([np.cos(angles),np.sin(angles)], axis=-1)
173 xs = normal(3, 2, 128)
174 expected = xs.copy()
175 tail = xs[..., -64:].reshape(3, 2, 32, 2)
176 out = expected[..., -64:].reshape(tail.shape)
177 cos, sin = freq[:,None,:,0], freq[:,None,:,1] * sign
178 out[...,0] = tail[...,0]*cos - tail[...,1]*sin
179 out[...,1] = tail[...,0]*sin + tail[...,1]*cos
180 got, _ = device.run("rotary_tail", (2,3,1), 32, [xs, freq], 2,
181 (128, 2, np.float32(sign).view(np.uint32)))
182 np.testing.assert_allclose(got, expected, atol=1e-6, rtol=1e-6)
183 narrow = normal(32)
184 got, _ = device.run("rotary_tail", (1,1,1), 32, [narrow.copy(), freq[0]], 2,
185 (32, 1, np.float32(1).view(np.uint32)))
186 np.testing.assert_array_equal(got, narrow)
187 print("PASS rotary_tail", flush=True)
188 vals, gates = normal(3,2,512), normal(3,2,512)*35
189 coeff = np.exp(gates - gates.max(axis=1, keepdims=True))
190 verify("compress_pair", (4,3,1), 128, [vals,gates],
191 [(vals * coeff / coeff.sum(axis=1,keepdims=True)).sum(axis=1)])
192 logits, bias = normal(3,384)*4, normal(384)*6
193 logits[0,:] = -15
194 raw = np.sqrt(np.logaddexp(0., logits))
195 selected = np.argsort(-(raw + bias), axis=1, kind="stable")[:,:6].astype(np.int32)
196 selected_w = np.take_along_axis(raw, selected, axis=1)
197 verify("route6", (3,1,1), 1, [logits,bias],
198 [selected, selected_w * 1.5 / (selected_w.sum(axis=1, keepdims=True)+1e-20)])
199 tie_logits = np.zeros((1,384),np.float32)
200 tie_bias = np.zeros(384,np.float32)
201 tie_bias[:6],tie_bias[6] = 1.,2.
202 verify("route6",(1,1,1),1,[tie_logits,tie_bias],
203 [np.array([[6,0,1,2,3,4]],np.int32),np.full((1,6),.25,np.float32)])
204 code = rng.integers(0, 110, (7,256),dtype=np.uint8)
205 scale = rng.integers(124,131,(7,8),dtype=np.uint8)
206 shard = 180000000
207 ids = np.array([shard-1,shard,shard+6,shard+7,shard+2],np.int32)
208 ref = np.zeros((len(ids),256),np.float32)
209 decoded = lut[code] * np.repeat(np.exp2(scale.astype(np.float32)-127),32,axis=1)
210 for i,j in enumerate(ids-shard):
211 if 0 <= j < len(code):
212 ref[i] = decoded[j]
213 verify("engram_rows",(len(ids),1,1),256,[ids,code,scale,lut],[ref],(shard,7))
214
215 values = normal(129)
216 values[:6] = np.array([0., -0., 1.00390625, 1.01171875, -1.00390625, -1.01171875])
217 rounded = bf16(values)
218 packed = (rounded.view(np.uint32)>>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
339if __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)