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-dnn/blob/main/tests/test_gpu.py # omega-dnn aien-dev/omega-dnn Brought by drakestapleton Sign in to star 0 stars 0 watching About Files History Releases Proposed changes Issues For developers branch `main` Branches Tags History `omega-dnn / tests / test_gpu.py` 681 lines ยท 33496 bytes Raw Blame History 1 """GB10 tier: CUDApp native kernels against the omega-dnn host reference (docs/TOLERANCE.md, "GPU tier"). 2 3 Usage: 4 python tests/test_gpu.py --lib LIB --group ew|attn|gemm [--cases N] [--seed S] --out receipt.json [--hold] 5 6 LIB is a shared build of CUDApp's libomega_gpu.a (README, "GPU tier"). Every case is prepared on the host first 7 (the omega-dnn unit's output and a torch float64 reference); with --hold the chip calls then run under 8 flock /tmp/aien-gb10.lock with the BOARD and health-check discipline of the Spark. Without --hold nothing touches the 9 chip and the run stops after the preparation (a dry run). 10 11 Each chip output element y must satisfy 12 |y - host| <= T_chip + T_host (the gate: the omega-dnn unit is the reference) 13 |y - ref64| <= T_chip + T_ref64 (diagnostic against torch float64) 14 where T_host is the host contract of tests/test_ops.py, T_ref64 = 2 gamma64(n + 64) M + 2^-149, and T_chip is the 15 op's bound for the CUDApp kernel against exact arithmetic, derived in docs/TOLERANCE.md and frozen before the run. 16 Every op also runs CUDApp's own chip mutants, and each mutant must fail the gate (negative control). 17 Exit status 1 on any gate violation, chip error, or surviving mutant. 18 """ 19 import argparse 20 import ctypes as C 21 import fcntl 22 import hashlib 23 import json 24 import math 25 import os 26 import re 27 import subprocess 28 import sys 29 import time 30 31 import torch 32 import torch.nn.functional as F 33 34 sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "python")) 35 import omega_dnn as od # noqa: E402 36 37 U = 2.0 ** -24 # f32 unit roundoff 38 U64 = 2.0 ** -53 39 TINY = 2.0 ** -149 40 FLOOR = 2.0 ** -124 # absolute allowance: a few f32 products that may flush below 2^-126 on the chip 41 E_EX2 = 5 * U # PTX ISA 9.4 ex2.approx.f32: 2 ulp from the correctly rounded result -> 2.5 ulp <= 5u 42 E_RCP = 2 * U # PTX ISA 9.4 rcp.approx.f32: 1 ulp 43 NEWTON = 3.`0000007` * U # Wolfram Maximize over the rsqrt Newton step (docs/TOLERANCE.md) 44 E_HEXP = 25 * U # host_exp2 (Cephes polynomial in f32) relative error: 24.27u (Wolfram) 45 C_HMMA = (17 * 2.0 ** -25 + 2.0 ** -23) * (1 + 2.0 ** -20) # one HMMA.16816 step, chip-exact model {16,2,RZ,nominal} 46 BOARD = "/home/drakestapleton/handoffs/BOARD.md" 47 LOCK = "/tmp/aien-gb10.lock" 48 LANE = "DnnGpu" 49 50 51 def g32(n): 52 return n * U / (1 - n * U) 53 54 55 def g64(n): 56 return n * U64 / (1 - n * U64) 57 58 59 def host_tol(ref, n, mag): 60 return U * ref.abs() + 2 * g64(n + 64) * mag + TINY 61 62 63 def ref_tol(n, mag): 64 return 2 * g64(n + 64) * mag + TINY 65 66 67 def ri(g, lo, hi): 68 return int(torch.randint(lo, hi + 1, (1,), generator=g)) 69 70 71 def rn(g, *shape, scale=1.0): 72 return torch.randn(*shape, generator=g) * scale 73 74 75 def pick(g, xs): 76 return xs[ri(g, 0, len(xs) - 1)] 77 78 79 def ptr(t): 80 return C.c_void_p(t.data_ptr()) 81 82 83 # ------------------------------------------------------------------ CUDApp ABI (src/*.h at the pinned sha) 84 class EwInfo(C.Structure): 85 _fields_ = [("chip_calls", C.c_uint32), ("elapsed_ns", C.c_uint64), ("completion_marker", C.c_uint32), 86 ("unwritten_words", C.c_uint32), ("kernel_cache_hit", C.c_bool), ("gpr_count", C.c_uint32), 87 ("insn_count", C.c_uint32), ("threads_per_cta", C.c_uint32), ("ctas_last_launch", C.c_uint32), 88 ("target_chip", C.c_char * 64), ("sm_architecture", C.c_uint32), ("call_ns", C.c_uint64)] 89 90 91 class AttnInfo(C.Structure): 92 _fields_ = [("chip_calls", C.c_uint32), ("elapsed_ns", C.c_uint64), ("call_ns", C.c_uint64), 93 ("completion_marker", C.c_uint32), ("unwritten_words", C.c_uint32), ("gpr_count", C.c_uint32), 94 ("insn_count", C.c_uint32), ("kernel_cache_hit", C.c_bool), ("ctas_last_launch", C.c_uint32), 95 ("threads_per_cta", C.c_uint32), ("target_chip", C.c_char * 64), ("sm_architecture", C.c_uint32), 96 ("kv_bytes_staged", C.c_uint64), ("kv_bytes_naive", C.c_uint64), ("kv_blocks_logical", C.c_uint32), 97 ("kv_blocks_unique", C.c_uint32), ("q_bytes", C.c_uint64), ("tab_bytes", C.c_uint64), 98 ("out_bytes", C.c_uint64), ("kv_source", C.c_uint32)] 99 100 101 class KvLayout(C.Structure): 102 _fields_ = [("block_stride_bytes", C.c_uint64), ("layer_stride_bytes", C.c_uint64), 103 ("kv_plane_stride_bytes", C.c_uint64), ("token_stride_bytes", C.c_uint64), 104 ("head_stride_bytes", C.c_uint64), ("pool_bytes", C.c_uint64), ("num_blocks", C.c_uint32), 105 ("num_layers", C.c_uint32), ("block_size", C.c_uint32)] 106 107 108 class GemmExInfo(C.Structure): 109 _fields_ = [("route", C.c_uint32), ("core_type", C.c_uint32), ("core_calls", C.c_uint64), ("host_fixed", C.c_uint64)] 110 111 112 class GemmExArgs(C.Structure): 113 _fields_ = [("op_a", C.c_int), ("op_b", C.c_int), ("m", C.c_uint64), ("n", C.c_uint64), ("k", C.c_uint64), 114 ("batch", C.c_uint64), ("a_type", C.c_int), ("b_type", C.c_int), ("c_type", C.c_int), 115 ("a", C.c_void_p), ("lda", C.c_uint64), ("stride_a", C.c_uint64), 116 ("b", C.c_void_p), ("ldb", C.c_uint64), ("stride_b", C.c_uint64), 117 ("c", C.c_void_p), ("ldc", C.c_uint64), ("stride_c", C.c_uint64), 118 ("alpha", C.c_float), ("beta", C.c_float), ("compute", C.c_int), ("scale", C.c_int), 119 ("scale_a", C.c_void_p), ("scale_b", C.c_void_p), ("scale_stride_a", C.c_uint64), 120 ("scale_stride_b", C.c_uint64), ("block_m", C.c_uint32), ("block_n", C.c_uint32), 121 ("block_k", C.c_uint32), ("info", C.POINTER(GemmExInfo))] 122 123 124 EW_RMSNORM, EW_ROPE, EW_SWIGLU = 3, 4, 5 125 ATTN_NO_MAX, ATTN_KV_HEAD, ATTN_SLOT, ATTN_NO_RESCALE, ATTN_Q_ROW, ATTN_OUT_ROW = 1, 2, 3, 4, 5, 6 # attention_api.h:217-226 126 PRED_MIN = 4.0 # a mutant runs on a case only if the host predicts gate ratio >= this (NO_RESCALE) 127 GEMM_DT_F32, GEMM_DT_BF16 = 0, 1 128 LIB = None 129 130 131 def info_dict(info): 132 d = {} 133 for f, _ in info._fields_: 134 v = getattr(info, f) 135 d[f] = v.decode() if isinstance(v, bytes) else v 136 return d 137 138 139 # ------------------------------------------------------------------ chip error bounds (docs/TOLERANCE.md, GPU tier) 140 def bound_rms(dim): 141 gs = g32(dim // 128 + 11) 142 return (1 + gs / (2 * (1 - gs))) * (1 + NEWTON) * (1 + U) ** 2 - 1 143 144 145 def bound_silu(gabs): 146 e = torch.exp(gabs * g32(2)) * (1 + E_EX2) - 1 147 return (1 + U) ** 2 * (1 + E_RCP) * (1 + e / (1 - e)) / (1 - U) - 1 148 149 150 def bound_attn(ctx, hd, splits, lam): 151 """Relative bound (x A = p @ |v|) for one output row of the online-softmax kernels; ctx, lam tensors.""" 152 ctx = ctx.double() 153 nch = torch.ceil(ctx / hd) 154 ep = torch.exp(2 * lam * g32(hd + 3)) * (1 + E_EX2) - 1 155 ea = torch.exp(2 * lam * U) * (1 + E_EX2) - 1 156 ew = torch.exp(2 * lam * U) * (1 + E_HEXP) - 1 if splits > 1 else torch.zeros_like(lam) 157 eta = (1 + ep) * (1 + ea) ** (nch - 1) * (1 + ew) - 1 158 gs = g32(ctx + 2 * nch + 2 * splits + 8) 159 alpha = (1 + eta) * (1 + gs) - 1 160 phi = (1 + E_RCP) * (1 + U) - 1 161 return (phi + alpha * (2 + phi)) / (1 - alpha) 162 163 164 def own_log2split(ctx, hd): 165 x, l = (ctx + hd - 1) // hd, 0 166 while l < 4 and (2 << l) <= x: 167 l += 1 168 return l 169 170 171 def gemm_steps(k): 172 parts = -(-k // 1808) + -(-k // 16384) 173 return 9 * (-(-k // 16) + parts) + parts 174 175 176 # ------------------------------------------------------------------ cases: each returns a dict with the chip call 177 def case_rmsnorm(g): 178 rows, dim = ri(g, 1, 8), pick(g, [128, 256, 384, 640, 1024, 2048, 4096, 128 * ri(g, 1, 128), 16384]) 179 x, w, eps = rn(g, rows, dim, scale=float(torch.rand(1, generator=g)) * 8 + 0.1), rn(g, dim), 2.0 ** -20 180 xd = x.double() 181 ref = xd / torch.sqrt((xd * xd).mean(-1, keepdim=True) + eps) * w.double() 182 183 def chip(): 184 out, info = torch.empty_like(x), EwInfo() 185 rc = LIB.omega_gpu_rmsnorm_f32(rows, dim, ptr(x), ptr(w), C.c_float(eps), ptr(out), C.byref(info)) 186 return rc, out, info 187 return dict(op="rmsnorm", shape=[rows, dim], host=od.rms_norm(x, w, eps), ref=ref, chip=chip, 188 t_chip=bound_rms(dim) * ref.abs() + FLOOR, t_host=host_tol(ref, dim, ref.abs()), 189 t_ref=ref_tol(dim, ref.abs()), mutants=[("ew", EW_RMSNORM, {})]) 190 191 192 def case_rope(g): 193 heads, hd = ri(g, 1, 8), pick(g, [2, 64, 128, 2 * ri(g, 1, 64), 2 * ri(g, 1, 1024), 2048]) 194 maxp = ri(g, 1, 64) 195 x, cos, sin = rn(g, heads, hd), rn(g, maxp, hd // 2), rn(g, maxp, hd // 2) 196 p = ri(g, 0, maxp - 1) 197 xd, c, s = x.double(), cos.double()[p], sin.double()[p] 198 x1, x2 = xd[:, : hd // 2], xd[:, hd // 2:] 199 ref = torch.cat([x1 * c - x2 * s, x2 * c + x1 * s], -1) 200 mag = torch.cat([x1.abs() * c.abs() + x2.abs() * s.abs(), x2.abs() * c.abs() + x1.abs() * s.abs()], -1) 201 ch, sh = cos[p].contiguous(), sin[p].contiguous() 202 host = od.rope(x.view(1, heads, 1, hd), cos, sin, torch.tensor([[p]]), rot=hd, interleaved=False).view(heads, hd) 203 204 def chip(): 205 out, info = torch.empty_like(x), EwInfo() 206 rc = LIB.omega_gpu_rope_f32(heads, hd, ptr(x), ptr(ch), ptr(sh), ptr(out), C.byref(info)) 207 return rc, out, info 208 return dict(op="rope", shape=[heads, hd, p], host=host, ref=ref, chip=chip, t_chip=g32(2) * mag + FLOOR, 209 t_host=host_tol(ref, 2, mag), t_ref=ref_tol(2, mag), mutants=[("ew", EW_ROPE, {})]) 210 211 212 def case_swiglu(g, silu=False): 213 n = pick(g, [1, 127, 128, 129, ri(g, 1, 5000), ri(g, 1, 200000)]) 214 gate = rn(g, n, scale=pick(g, [1.0, 4.0, 16.0])).clamp(-80, 80) 215 up = torch.ones(n) if silu else rn(g, n, scale=4) 216 gd, ud = gate.double(), up.double() 217 ref = F.silu(gd) * ud 218 if silu: 219 host, n_h, mag = od.elementwise(od.SILU, gate), 1, ref.abs() + gd.abs() 220 else: 221 host, n_h, mag = od.elementwise(od.SWIGLU, gate, up), 1, ref.abs() + gd.abs() * (1 + ud.abs()) 222 223 def chip(): 224 out, info = torch.empty_like(gate), EwInfo() 225 rc = LIB.omega_gpu_swiglu_f32(n, ptr(gate), ptr(up), ptr(out), C.byref(info)) 226 return rc, out, info 227 return dict(op="silu" if silu else "swiglu", shape=[n], host=host, ref=ref, chip=chip, 228 t_chip=bound_silu(gd.abs()) * ref.abs() + FLOOR, t_host=host_tol(ref, n_h, mag), t_ref=ref_tol(n_h, mag), 229 mutants=[("ew", EW_SWIGLU, {})]) 230 231 232 def attn_stats(qd, kd, vd, scale, mask=None): 233 """qd [H,Sq,D], kd/vd [H,Skv,D] float64 (kv heads already repeated). Returns ref, A = p@|v|, lam [H,Sq,1].""" 234 lg = qd @ kd.transpose(-1, -2) * scale 235 lam = qd.abs() @ kd.abs().transpose(-1, -2) * scale 236 if mask is not None: 237 lg = lg.masked_fill(mask, float("-inf")) 238 lam = lam.masked_fill(mask, 0.0) 239 p = torch.softmax(lg, -1) 240 return p @ vd, p @ vd.abs(), lam.amax(-1, keepdim=True) 241 242 243 def nores_output(qd, kd, vd, scale, hd, mask=None): 244 """Host model of CUDApp's NO_RESCALE mutant with one CTA per head (split 1): the chunk loop walks HD tokens at a 245 time from token 0, rescales L by alpha = exp(M_old - M_new) but leaves the accumulator unscaled 246 (src/omega_gpu_attention_api.c:571-572). Same shapes as attn_stats; returns the mutant's output.""" 247 lg = qd @ kd.transpose(-1, -2) * scale 248 if mask is not None: 249 lg = lg.masked_fill(mask, float("-inf")) 250 m = torch.full(lg.shape[:-1] + (1,), float("-inf"), dtype=lg.dtype) 251 L = torch.zeros_like(m) 252 acc = torch.zeros(lg.shape[:-1] + (vd.shape[-1],), dtype=lg.dtype) 253 for c0 in range(0, lg.shape[-1], hd): 254 lc = lg[..., c0:c0 + hd] 255 mn = torch.maximum(m, lc.amax(-1, keepdim=True)) 256 safe = torch.where(torch.isinf(mn), torch.zeros_like(mn), mn) # a row with every key masked so far 257 L = L * torch.exp(m - safe) + torch.exp(lc - safe).sum(-1, keepdim=True) 258 acc = acc + torch.exp(lc - safe) @ vd[..., c0:c0 + hd, :] 259 m = mn 260 return acc / L 261 262 263 def gate_pred(mut, host, t_chip, t_host): 264 """max |mutant - host| / (T_chip + T_host): the gate ratio the mutant is predicted to reach.""" 265 return float(((mut - host.double()).abs() / (t_chip + t_host)).max()) 266 267 268 def row_mutants(nq, nkv): 269 """Head-wiring mutants, on the shapes CUDApp's own tests run them (tests/gpu_attention_test.c:379,524).""" 270 m = [("attn", ATTN_KV_HEAD, {})] if nkv >= 2 else [] 271 if nq >= 2: # both swap rows h and h ^ 1: num_q_heads even (omega_gpu_attention_api.h:222-224) 272 m += [("attn", ATTN_Q_ROW, {}), ("attn", ATTN_OUT_ROW, {})] 273 return m 274 275 276 def visible(pred): 277 """A mutant joins a case only if the host predicts it leaves the gate by PRED_MIN (no equivalent mutants).""" 278 return pred >= PRED_MIN 279 280 281 def case_softmax(g): 282 """softmax over c <= 64 logits through the attention kernel: D = 64, K = V = I[:c], q = 8 x (scale 1/8 exact).""" 283 c = ri(g, 1, 64) 284 x = rn(g, c, scale=float(torch.rand(1, generator=g)) * 8 + 0.1) 285 if ri(g, 0, 1): 286 x = x * 300 # far past exp overflow: only a max-subtracted softmax survives (the NO_MAX mutant overflows) 287 q = torch.zeros(64) 288 q[:c] = 8 * x 289 eye = torch.zeros(c, 1, 64) 290 eye[:, 0, :c] = torch.eye(c) 291 xd = x.double() 292 r = torch.softmax(xd, -1) 293 ref = torch.zeros(64, dtype=torch.float64) 294 ref[:c] = r 295 span = (xd - xd.amax()).abs() 296 host = torch.zeros(64) 297 host[:c] = od.softmax(x.view(1, c)).view(c) 298 mag = torch.zeros(64, dtype=torch.float64) 299 mag[:c] = r * (1 + span) + r.amax() * span.amax() 300 lam = xd.abs().amax().view(1) 301 tc = bound_attn(torch.tensor([c]), 64, 1, lam) * ref.abs() + FLOOR # A = p @ |e_d| = p_d = |ref| 302 303 def chip(): 304 out, info = torch.empty(64), AttnInfo() 305 rc = LIB.omega_gpu_gqa_attention_f32(ptr(q), ptr(eye), ptr(eye), c, 1, 1, 64, ptr(out), C.byref(info)) 306 return rc, out, info 307 # NO_MAX is exact softmax unless 2^(x log2 e) leaves the f32 range (CUDApp tests/gpu_attention_test.c:523) 308 lo2 = float(xd.amax()) * math.log2(math.e) 309 muts = [("attn", ATTN_NO_MAX, dict(pred=math.inf))] if lo2 > 128 or lo2 < -126 else [] 310 return dict(op="softmax_via_attn", shape=[c, round(float(x.abs().max()), 1)], host=host, ref=ref, chip=chip, 311 t_chip=tc, t_host=host_tol(ref, c, mag), t_ref=ref_tol(c, mag), mutants=muts) 312 313 314 def heads(g, max_q): 315 while True: 316 nkv, rep = pick(g, [1, 2, 4, 8]), pick(g, [1, 2, 4, 8]) 317 if nkv * rep <= max_q: 318 return nkv, rep 319 320 321 def case_gqa(g): 322 hd = pick(g, [64, 128]) 323 nkv, rep = heads(g, 64) 324 nq = nkv * rep 325 ctx = pick(g, [1, 2, hd - 1, hd, hd + 1, ri(g, 1, 512), ri(g, 1, 512), ri(g, 1, 4096), 4096]) 326 q = rn(g, nq, hd, scale=float(torch.rand(1, generator=g)) * 2 + 0.1) 327 k, v = rn(g, ctx, nkv, hd), rn(g, ctx, nkv, hd) 328 sc = hd ** -0.5 329 kd, vd = (t.double().permute(1, 0, 2).repeat_interleave(rep, 0) for t in (k, v)) 330 ref, A, lam = attn_stats(q.double()[:, None], kd, vd, sc) 331 ref, A, lam = ref[:, 0], A[:, 0], lam[:, 0] 332 host = od.attention(q.view(1, nq, 1, hd), k.permute(1, 0, 2)[None].contiguous(), v.permute(1, 0, 2)[None].contiguous(), 333 causal=False).view(nq, hd) 334 mag = A * (1 + 2 * lam) + ref.abs() 335 tc = bound_attn(torch.full((nq, 1), ctx), hd, 1, lam) * A + FLOOR 336 337 def chip(): 338 out, info = torch.empty(nq, hd), AttnInfo() 339 rc = LIB.omega_gpu_gqa_attention_f32(ptr(q), ptr(k), ptr(v), ctx, nq, nkv, hd, ptr(out), C.byref(info)) 340 return rc, out, info 341 t_host = host_tol(ref, hd + ctx, mag) 342 muts = row_mutants(nq, nkv) 343 pred = gate_pred(nores_output(q.double()[:, None], kd, vd, sc, hd)[:, 0], host, tc, t_host) 344 if visible(pred): 345 muts.append(("attn", ATTN_NO_RESCALE, dict(pred=pred))) 346 return dict(op="attention_decode", shape=[nq, nkv, hd, ctx], host=host, ref=ref, chip=chip, t_chip=tc, 347 t_host=t_host, t_ref=ref_tol(hd + ctx, mag), mutants=muts) 348 349 350 def case_rows(g): 351 hd = pick(g, [64, 128]) 352 nkv, rep = heads(g, 16) 353 nq, rows = nkv * rep, pick(g, [1, 2, ri(g, 1, 64), ri(g, 64, 200)]) 354 q = rn(g, rows, nq, hd, scale=float(torch.rand(1, generator=g)) * 2 + 0.1) 355 k, v = rn(g, rows, nkv, hd), rn(g, rows, nkv, hd) 356 kd, vd = (t.double().permute(1, 0, 2).repeat_interleave(rep, 0) for t in (k, v)) 357 mask = torch.ones(rows, rows, dtype=torch.bool).triu(1) 358 ref, A, lam = attn_stats(q.double().permute(1, 0, 2), kd, vd, hd ** -0.5, mask) # [nq, rows, hd] 359 host = od.attention(q.permute(1, 0, 2)[None].contiguous(), k.permute(1, 0, 2)[None].contiguous(), 360 v.permute(1, 0, 2)[None].contiguous(), causal=True)[0] 361 ctx = torch.arange(1, rows + 1).view(1, rows, 1).expand(nq, rows, 1) 362 tc = bound_attn(ctx, hd, 1, lam) * A + FLOOR 363 mag = A * (1 + 2 * lam) + ref.abs() 364 perm = (1, 0, 2) 365 366 def chip(): 367 out, info = torch.empty(rows, nq, hd), AttnInfo() 368 rc = LIB.omega_gpu_gqa_attention_rows_f32(ptr(q), ptr(k), ptr(v), 0, rows, nq, nkv, hd, ptr(out), C.byref(info)) 369 return rc, out.permute(*perm), info 370 t_host = host_tol(ref, hd + rows, mag) 371 muts = row_mutants(nq, nkv) 372 pred = gate_pred(nores_output(q.double().permute(1, 0, 2), kd, vd, hd ** -0.5, hd, mask), host, tc, t_host) 373 if visible(pred): 374 muts.append(("attn", ATTN_NO_RESCALE, dict(pred=pred))) 375 return dict(op="attention_prefill_causal", shape=[nq, nkv, hd, rows], host=host, ref=ref, chip=chip, t_chip=tc, 376 t_host=t_host, t_ref=ref_tol(hd + rows, mag), mutants=muts) 377 378 379 def case_paged(g, single=False): 380 hd = pick(g, [64, 128]) 381 nkv, rep = heads(g, 32) 382 nq, B, bs = nkv * rep, 1 if single else ri(g, 1, 4), pick(g, [8, 16, 32, 64]) 383 maxb = ri(g, 1, 2048 // bs) 384 nblk = B * maxb + ri(g, 0, 4) 385 lens = torch.randint(1, maxb * bs + 1, (B,), generator=g) 386 table = torch.stack([torch.randperm(nblk, generator=g)[:maxb] for _ in range(B)]) 387 q = rn(g, B, nq, hd, scale=float(torch.rand(1, generator=g)) * 2 + 0.1) 388 kc, vc = (rn(g, nblk, bs, nkv, hd).bfloat16().float() for _ in range(2)) 389 host = od.paged_decode(q, kc, vc, table, lens) 390 refs, As, lams, nores = [], [], [], [] 391 for i in range(B): 392 kb, vb = (t[table[i]].reshape(-1, nkv, hd)[: lens[i]].double().permute(1, 0, 2).repeat_interleave(rep, 0) 393 for t in (kc, vc)) 394 r, a, lm = attn_stats(q[i].double()[:, None], kb, vb, hd ** -0.5) 395 refs.append(r[:, 0]), As.append(a[:, 0]), lams.append(lm[:, 0]) 396 nores.append(nores_output(q[i].double()[:, None], kb, vb, hd ** -0.5, hd)[:, 0]) 397 ref, A, lam = torch.stack(refs), torch.stack(As), torch.stack(lams) 398 splits = 1 << max(own_log2split(int(n), hd) for n in lens) 399 tc = bound_attn(lens.view(B, 1, 1).expand(B, nq, 1), hd, splits, lam) * A + FLOOR 400 mag = A * (1 + 2 * lam) + ref.abs() 401 pool = torch.stack([kc, vc], 1).bfloat16().contiguous() # [block][plane][token][head][d], one layer 402 lay = KvLayout() 403 lay.head_stride_bytes, lay.token_stride_bytes = hd * 2, nkv * hd * 2 404 lay.kv_plane_stride_bytes = bs * lay.token_stride_bytes 405 lay.layer_stride_bytes = lay.block_stride_bytes = 2 * lay.kv_plane_stride_bytes 406 lay.pool_bytes, lay.num_blocks, lay.num_layers, lay.block_size = nblk * lay.block_stride_bytes, nblk, 1, bs 407 tab32, len32 = table.to(torch.int32).contiguous(), lens.to(torch.int32).contiguous() 408 ids = table[0, : -(-int(lens[0]) // bs)].to(torch.int32).contiguous() # single call: uint32 block ids 409 410 def chip(): 411 out, info = torch.empty(B, nq, hd), AttnInfo() 412 if single: 413 rc = LIB.omega_gpu_paged_attention_bf16(ptr(q), ptr(pool), C.byref(lay), ptr(ids), ids.numel(), int(lens[0]), 414 0, nq, nkv, hd, ptr(out), C.byref(info)) 415 else: 416 rc = LIB.omega_gpu_paged_attention_batch_bf16(ptr(q), ptr(pool), C.byref(lay), ptr(tab32), ptr(len32), maxb, 417 B, 0, nq, nkv, hd, ptr(out), C.byref(info)) 418 return rc, out, info 419 n_h = hd + maxb * bs 420 t_host = host_tol(ref, n_h, mag) 421 muts = row_mutants(nq, nkv) 422 if int(lens.min()) >= 2: # one token: softmax weight 1 whatever K says, so a K/V slot mismatch is invisible 423 muts.append(("attn", ATTN_SLOT, {})) 424 # NO_RESCALE runs with one CTA per head as CUDApp's own test does (cut J gives each split one chunk otherwise) 425 pred = gate_pred(torch.stack(nores), host, tc, t_host) 426 if visible(pred): 427 muts.append(("attn", ATTN_NO_RESCALE, dict(pred=pred, split0=True))) 428 return dict(op="paged_decode_single" if single else "paged_decode_batch", 429 shape=[B, nq, nkv, hd, bs, maxb, int(lens.max()), splits], host=host, ref=ref, 430 chip=chip, t_chip=tc, t_host=t_host, t_ref=ref_tol(n_h, mag), mutants=muts) 431 432 433 def gemm_call(a, a_t, b, b_t, m, n, k, op_b, ldb, c, beta): 434 info = GemmExInfo() 435 args = GemmExArgs(op_a=0, op_b=op_b, m=m, n=n, k=k, batch=1, a_type=a_t, b_type=b_t, c_type=GEMM_DT_F32, 436 a=a.data_ptr(), lda=0, b=b.data_ptr(), ldb=ldb, c=c.data_ptr(), ldc=0, alpha=1.0, beta=beta, 437 compute=0, scale=0, info=C.pointer(info)) 438 return LIB.omega_gpu_gemm_ex(C.byref(args)), info 439 440 441 def case_matmul(g): 442 M, N = pick(g, [1, 16, ri(g, 1, 70)]), pick(g, [1, 8, ri(g, 1, 300)]) 443 K = pick(g, [1, 15, 16, 17, ri(g, 1, 300), ri(g, 1, 2048), 1808, 1809]) 444 A, Bm = rn(g, M, K), rn(g, K, N) 445 tb, has_bias = bool(ri(g, 0, 1)), ri(g, 0, 3) > 0 446 bv = rn(g, N) if has_bias else torch.zeros(N) 447 Bs = Bm.t().contiguous() if tb else Bm 448 host = od.matmul(A, Bs, bv if has_bias else None, trans_b=tb) 449 ref = A.double() @ Bm.double() + bv.double() 450 sab = A.double().abs() @ Bm.double().abs() 451 sapb = A.double().abs().sum(1, keepdim=True) + Bm.double().abs().sum(0, keepdim=True) 452 acc = ((1 + C_HMMA) ** gemm_steps(K) - 1) * sab + 2.0 ** -124 * sapb + K * 2.0 ** -140 453 tc = acc + 2.0 ** -52 * (sab + bv.double().abs()) + U * (ref.abs() + acc) + TINY 454 mag = sab + bv.double().abs() 455 456 def chip(): 457 c = bv.expand(M, N).contiguous() 458 rc, info = gemm_call(A, GEMM_DT_F32, Bs, GEMM_DT_F32, M, N, K, 1 if tb else 0, K if tb else N, c, 459 1.0 if has_bias else 0.0) 460 return rc, c, info 461 mut = 2 if tb and N > 1 and K > 1 else (1 if K <= 256 else None) 462 return dict(op="matmul", shape=[M, N, K, int(tb), int(has_bias)], host=host, ref=ref, chip=chip, t_chip=tc, 463 t_host=host_tol(ref, K, mag), t_ref=ref_tol(K, mag), mutants=[("gemm", mut, {})] if mut else []) 464 465 466 GROUPS = {"ew": [case_rmsnorm, case_rope, case_swiglu, lambda g: case_swiglu(g, silu=True)], 467 "attn": [case_softmax, case_gqa, case_rows, case_paged, lambda g: case_paged(g, single=True)], 468 "gemm": [case_matmul]} 469 470 471 # ------------------------------------------------------------------ the CUDApp#139 per-step bound probe (host model: scratch) 472 def probe_hmma(): 473 """bf16 native gemm_ex, k = 1808 (one k part): a = [1, t x 1807], b = 1, t = 0x1.fcp-26. The chip-exact HMMA 474 model {16,2,RZ,nominal} truncates every t at alignment to the running 1.0, so the result is 1.0 and the error is 475 1807 t = 5.343e-5, above the old stated bound (steps+4) 2^-22 sab = 2.843e-5 and below ((1+c)^steps - 1) sab.""" 476 k, t = 1808, float.fromhex("0x1.fcp-26") 477 a = torch.full((1, k), t) 478 a[0, 0] = 1.0 479 a16, b16 = a.bfloat16().contiguous(), torch.ones(k, 1).bfloat16().contiguous() 480 assert torch.equal(a16.float(), a) 481 c = torch.zeros(1, 1) 482 rc, info = gemm_call(a16, GEMM_DT_BF16, b16, GEMM_DT_BF16, 1, 1, k, 0, 1, c, 0.0) 483 ref = 1.0 + (k - 1) * t 484 parts = 2 485 steps = -(-k // 16) + parts 486 err = abs(ref - float(c[0, 0])) 487 return dict(rc=rc, got=float(c[0, 0]).hex(), ref=ref, err=err, old_bound=(steps + 4) * 2.0 ** -22 * ref + U * ref, 488 new_bound=((1 + C_HMMA) ** steps - 1) * ref + U * ref, model_prediction="0x1.0000000000000p+0", 489 info=info_dict(info)) 490 491 492 class GemmInfo(C.Structure): # OmegaGpuGemmInfo, src/omega_gpu_gemm.h:93-98 493 _fields_ = [("pack_ns", C.c_uint64), ("main_ns", C.c_uint64), ("call_ns", C.c_uint64), ("gpr", C.c_uint32 * 3)] 494 495 496 def gemm_chip_witness(): 497 """OmegaGemmExInfo carries no device field, so the receipt also runs the core gemm_ex calls by default (chip_core -> 498 omega_gpu_gemm_ld, src/omega_gpu_gemm_ex.c:20-22; this harness never calls omega_gpu_gemm_ex_set_backend) directly, 499 with its kernel timings and register counts, and checks the product bit-for-bit against gemm_ex native bf16.""" 500 g = torch.Generator().manual_seed(1) 501 a = torch.randn(32, 64, generator=g).bfloat16().contiguous() 502 b = torch.randn(64, 16, generator=g).bfloat16().contiguous() 503 c1, c2, info = torch.zeros(32, 16), torch.zeros(32, 16), GemmInfo() 504 rc1 = LIB.omega_gpu_gemm_ld(0, 0, 32, 16, 64, ptr(a), C.c_uint64(0), ptr(b), C.c_uint64(0), ptr(c1), C.byref(info)) 505 rc2, xinfo = gemm_call(a, GEMM_DT_BF16, b, GEMM_DT_BF16, 32, 16, 64, 0, 16, c2, 0.0) 506 ok = rc1 == 0 and rc2 == 0 and info.main_ns > 0 and torch.equal(c1, c2) 507 return dict(ok=ok, rc_core=rc1, rc_ex=rc2, pack_ns=info.pack_ns, main_ns=info.main_ns, call_ns=info.call_ns, 508 gpr=list(info.gpr), bit_identical=bool(torch.equal(c1, c2)), ex_info=info_dict(xinfo)) 509 510 # ------------------------------------------------------------------ chip session discipline 511 def window_open(): 512 try: 513 lines = [ln for ln in open(BOARD) if re.match(r"^[0-9TZ:.-]+ Main: WINDOW-(START|END|ABORTED)", ln)] 514 except OSError: 515 return True 516 return bool(lines) and "WINDOW-START" in lines[-1] 517 518 519 def board(msg): 520 with open(BOARD, "a") as f: 521 f.write(f"{time.strftime('%Y-%m-%dT%H:%M:%SZ', time.gmtime())} {LANE}: {msg}\n") 522 523 524 def health(): 525 r = subprocess.run(["curl", "-s", "-m", "5", "127.0.0.1:18091/health"], capture_output=True, text=True) 526 return r.stdout.strip() or f"rc={r.returncode}" 527 528 529 def judge(case, rc, y): 530 if rc != 0: 531 return dict(rc=rc, gate_viol=-1, exact_viol=-1, gate_ratio=float("inf"), exact_ratio=float("inf")) 532 y = y.double().reshape(case["ref"].shape) 533 out = {"rc": 0} 534 for key, base, tol in (("gate", case["host"].double().reshape(case["ref"].shape), case["t_chip"] + case["t_host"]), 535 ("exact", case["ref"], case["t_chip"] + case["t_ref"])): 536 err = (y - base).abs() 537 out[f"{key}_viol"] = int((~(err <= tol)).sum()) 538 out[f"{key}_ratio"] = float((err / tol).nan_to_num(float("inf")).max()) 539 return out 540 541 542 MUTANT_SETTER = {"ew": "omega_gpu_elementwise_test_set_mutant", "attn": "omega_gpu_attention_test_set_mutant", 543 "gemm": "omega_gpu_gemm_ex_test_set_mutant"} 544 545 546 def set_mutant(kind, m): 547 getattr(LIB, MUTANT_SETTER[kind])(m) 548 549 550 def main(): 551 global LIB 552 ap = argparse.ArgumentParser() 553 ap.add_argument("--lib", required=True) 554 ap.add_argument("--group", required=True, choices=sorted(GROUPS)) 555 ap.add_argument("--cases", type=int, default=24) 556 ap.add_argument("--mutant-cases", type=int, default=4) 557 ap.add_argument("--seed", type=int, default=7) 558 ap.add_argument("--cudapp-sha", required=True) 559 ap.add_argument("--out", required=True) 560 ap.add_argument("--hold", action="store_true") 561 a = ap.parse_args() 562 LIB = C.CDLL(os.path.abspath(a.lib)) 563 g = torch.Generator().manual_seed(a.seed) 564 t0 = time.time() 565 cases = [mk(g) for _ in range(a.cases) for mk in GROUPS[a.group]] 566 print(f"prepared {len(cases)} cases on the host in {time.time() - t0:.1f}s", flush=True) 567 for kind in {m[0] for cs in cases for m in cs["mutants"]}: 568 getattr(LIB, MUTANT_SETTER[kind]) # an absent hook fails here, before any hold 569 rec = dict(lane=LANE, group=a.group, seed=a.seed, cases_per_op=a.cases, cudapp_sha=a.cudapp_sha, 570 lib=os.path.abspath(a.lib), lib_sha256=hashlib.sha256(open(a.lib, "rb").read()).hexdigest(), 571 harness_sha256=hashlib.sha256(open(os.path.abspath(__file__), "rb").read()).hexdigest(), 572 torch=torch.__version__, host=os.uname().nodename, kernel=os.uname().release, 573 driver=open("/proc/driver/nvidia/version").readline().strip(), ops={}, mutants={}, cases=[]) 574 if not a.hold: 575 print("dry run: no --hold, chip not touched") 576 return 0 577 if window_open(): 578 print("REFUSED: Main WINDOW-START without END/ABORTED on BOARD; no hold taken") 579 return 2 580 fd = os.open(LOCK, os.O_RDWR | os.O_CREAT, 0o600) 581 deadline = time.time() + 900 582 while True: 583 try: 584 fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB) 585 break 586 except BlockingIOError: 587 if time.time() > deadline: 588 print("REFUSED: lock not free within 900 s") 589 return 2 590 time.sleep(2) 591 if window_open(): 592 os.close(fd) 593 print("REFUSED: window opened while waiting") 594 return 2 595 rec["health_before"] = health() 596 rec["utc_start"] = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()) 597 board(f"GPU-START omega-dnn GPU tier group={a.group} (CUDApp kernels, no model) health={rec['health_before'][:60]}") 598 t_hold = time.time() 599 bad = 0 600 try: 601 for cs in cases: 602 rc, y, info = cs["chip"]() 603 j = judge(cs, rc, y) 604 row = rec["ops"].setdefault(cs["op"], dict(cases=0, gate_viol=0, exact_viol=0, rc_fail=0, gate_worst=0.0, 605 exact_worst=0.0, chip_calls=0, elapsed_ns=0)) 606 row["cases"] += 1 607 row["rc_fail"] += rc != 0 608 row["gate_viol"] += max(j["gate_viol"], 0) 609 row["exact_viol"] += max(j["exact_viol"], 0) 610 row["gate_worst"] = max(row["gate_worst"], j["gate_ratio"]) 611 row["exact_worst"] = max(row["exact_worst"], j["exact_ratio"]) 612 inf = info_dict(info) 613 row["chip_calls"] += inf.get("chip_calls", inf.get("core_calls", 0)) 614 row["elapsed_ns"] += inf.get("elapsed_ns", 0) 615 for f in ("target_chip", "sm_architecture", "route", "core_type"): 616 if f in inf: 617 row[f] = inf[f] 618 rec["cases"].append(dict(op=cs["op"], shape=cs["shape"], **j)) 619 bad += (rc != 0) + (j["gate_viol"] != 0) 620 # negative controls: CUDApp's own mutants must fail the gate. A case only carries a mutant the host 621 # predicts to be visible on it (attention: nores_output; docs/TOLERANCE.md, GPU tier). 622 done = {} 623 for cs in cases: 624 for kind, m, opt in cs["mutants"]: 625 key = f"{cs['op']}:{kind}:{m}" 626 if done.get(key, 0) >= a.mutant_cases: 627 continue 628 done[key] = done.get(key, 0) + 1 629 if opt.get("split0"): 630 LIB.omega_gpu_attention_test_set_split(0) 631 set_mutant(kind, m) 632 try: 633 rc, y, _ = cs["chip"]() 634 finally: 635 set_mutant(kind, 0) 636 if opt.get("split0"): 637 LIB.omega_gpu_attention_test_set_split(-1) 638 j = judge(cs, rc, y) 639 killed = rc == 0 and j["gate_viol"] > 0 640 row = rec["mutants"].setdefault(key, dict(runs=0, killed=0, refused=0, survived=0, runs_detail=[])) 641 row["runs"] += 1 642 row["killed"] += killed 643 row["refused"] += rc != 0 644 row["survived"] += rc == 0 and not killed 645 row["runs_detail"].append(dict(shape=cs["shape"], rc=rc, gate_viol=j["gate_viol"], 646 gate_ratio=j["gate_ratio"], predicted_ratio=opt.get("pred"), 647 split0=bool(opt.get("split0")))) 648 bad += rc == 0 and not killed 649 if a.group == "gemm": 650 rec["probe_cudapp139_hmma_bound"] = probe_hmma() 651 rec["gemm_chip_witness"] = gemm_chip_witness() 652 bad += not rec["gemm_chip_witness"]["ok"] 653 except Exception as e: # recorded in the receipt as a failure; the hold is still released below 654 rec["error"] = repr(e) 655 bad += 1 656 finally: 657 rec["hold_s"] = round(time.time() - t_hold, 1) 658 rec["utc_end"] = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()) 659 rec["health_after"] = health() 660 board(f"GPU-END group={a.group} hold={rec['hold_s']}s health={rec['health_after'][:60]}") 661 fcntl.flock(fd, fcntl.LOCK_UN) 662 os.close(fd) 663 rec["result"] = "PASS" if bad == 0 else "FAIL" 664 with open(a.out, "w") as f: 665 json.dump(rec, f, indent=1) 666 for name, r in rec["ops"].items(): 667 print(f"{name:26s} cases={r['cases']:3d} gate_worst={r['gate_worst']:.3g} gate_viol={r['gate_viol']} " 668 f"exact_worst={r['exact_worst']:.3g} exact_viol={r['exact_viol']} rc_fail={r['rc_fail']} " 669 f"chip={r.get('target_chip', '')} sm={r.get('sm_architecture', '')}") 670 for key, r in rec["mutants"].items(): 671 print(f"MUTANT {key:34s} runs={r['runs']} killed={r['killed']} refused={r['refused']} survived={r['survived']}") 672 if "probe_cudapp139_hmma_bound" in rec: 673 print("PROBE", json.dumps(rec["probe_cudapp139_hmma_bound"])) 674 if "gemm_chip_witness" in rec: 675 print("WITNESS", json.dumps(rec["gemm_chip_witness"])) 676 print(f"RESULT {rec['result']} hold={rec['hold_s']}s") 677 return 0 if bad == 0 else 1 678 679 680 if __name__ == "__main__": 681 sys.exit(main())