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/tests/gpu_attention_test.c # 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 / tests / gpu_attention_test.c` 1250 lines ยท 98853 bytes Raw Blame History 1 /* SPDX-License-Identifier: Apache-2.0 2 * Copyright 2026 Drake Stapleton (AIEN / aien-dev) 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 /* gpu_attention_test: FB-1 cut 5 gate for omega_gpu_attention_api. 18 * 19 * ./gpu_attention_test --host-only refusals, codegen (both kernel families and every 20 * mutant), register budget, sm121dis listing check 21 * ./gpu_attention_test --split-timing [--hd 128] [--spin-us N] [--out r.json] paged bf16 32q/8kv at ATTN_SPLIT_CTX 22 * (default 1268): 100 calls per forced split 1,2,4,8 + auto, parity 23 * ./gpu_attention_test --timing [--out r.json] cut 4b gate: 1 query x 32 heads x 2048 ctx, 100 calls 24 * through the persistent session, median under 3 ms 25 * ./gpu_attention_test --sweep [--out s.json] head-scaling sweep: paged bf16 at head_dim 64 over q heads 26 * 1..64 x every kv-head divisor x ctx 256/2048, parity + timings 27 * (receipt OMEGA_GPU_ATTENTION_SWEEP_V1; --sim marks host timings) 28 * ./gpu_attention_test --out receipt.json chip gate: every shape against the host oracle, the 29 * mutants (deliberately wrong kernels, all of 30 * 1 .. OMEGA_GPU_ATTN_MUTANT_COUNT-1) which the same 31 * check must catch, a negative control, timings 32 * 33 * Oracles re-state aien-sovereign-core crates/aien-inference-abi/src/backend.rs (main `8b5caed`) in C: 34 * ReferenceCpuBackend::gqa_attention (f64 scores, max, exp, sum, 1/max(sum,1e-12), f64 weighted sum), 35 * TensorBackend::paged_attention (f64 online softmax token by token over the paged bf16 pool, tokens 36 * past the block table dropped, zeros for empty context) and paged_attention_batch (ctx <= 0 -> 0, 37 * table rows past the array -> empty, negative entries removed). Compiled with -ffp-contract=off. 38 * 39 * Tolerance (why): the chip accumulates the 64-term dot products, the per-chunk sums and the 40 * rescaled running sums in f32 (worst case about n * 2^-24 relative over n = 2048 terms, 1.2e-4), 41 * uses MUFU.EX2 (PTX ex2.approx: 2^-22.5 relative) for every weight and for the 32 chunk rescale 42 * factors, and MUFU.RCP for the final normalisation. Every output is a convex combination of V 43 * values of unit scale, so |error| <= 2e-4 * |want| + 2e-5 covers these with margin; the mutants 44 * move results by 1e-2 or more (wrong head, wrong token) or produce NaN (overflow without the max). 45 * The large-score case (scores up to ~300) carries the f32 rounding of the score itself into the 46 * exponent (3e-5 absolute per score), so it uses 1e-3 relative + 1e-4 absolute. 47 */ 48 #include "omega_gpu_attention_api.h" 49 #include "omega_gpu_session.h" 50 #include "omega_blackwell_codegen.h" 51 #include "omega_sm121_disasm.h" /* C6 (L386): Omega's own disassembler replaces nvdisasm here */ 52 #include "bw_warp_sim.h" /* omega #308: SIMT warp simulator for --divergent */ 53 #include 54 #include 55 #include 56 #include 57 #include 58 #include 59 #include 60 #include 61 62 /* 0644, not fopen's 0666 & ~umask: a receipt is never world-writable */ 63 static FILE *create_0644(const char *path) { 64 int fd = open(path, O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC, 0644); 65 FILE *f = fd >= 0 ? fdopen(fd, "w") : NULL; 66 if (fd >= 0 && !f) close(fd); 67 return f; 68 } 69 70 static int g_checks, g_failed; 71 static int g_sim_mode; /* --sim: the host simulator never opens the device */ 72 static int g_divergent; /* --divergent (omega #308 R2): the j >= ctx branch inside a BSSY/BSYNC region */ 73 static uint32_t g_hd = 64; /* --hd 128: the whole battery at head_dim 128 (Qwen3-4B shapes); both simulators size the CTA from it */ 74 /* Host-only register bound (omega#470). hd 64 kernels are the program from before cut K (#417 keeps them byte-identical, 75 * see the hd64 digest pins) and stay under 64. hd 128 follows AT_GPR_BUDGET in src/omega_gpu_attention_api.c (96 since 76 * cut K, chip battery 225/225): the codegen refuses any kernel above it and every launch declares exactly that many 77 * registers, so a peak under it changes nothing on the chip. The pinned-digest check further down uses the same 96. */ 78 #define ATTN_GPR_BOUND (g_hd == 64 ? 64u : 96u) 79 #define CHECK(cond, ...) do { g_checks++; if (!(cond)) { g_failed++; printf("FAIL: "); printf(__VA_ARGS__); printf("\n"); } } while (0) 80 81 static uint32_t lcg(uint32_t *s) { *s = *s * 1664525u + 1013904223u; return *s; } 82 static float frand(uint32_t *s, float lo, float hi) { return lo + (hi - lo) * ((float)(lcg(s) >> 8) / `16777216`.0f); } 83 static uint16_t f2bf(float f) { uint32_t u; memcpy(&u, &f, 4); uint32_t r = ((u >> 16) & 1u) + 0x7fffu; return (uint16_t)((u + r) >> 16); } 84 static float bf2f(uint16_t b) { uint32_t u = (uint32_t)b << 16; float f; memcpy(&f, &u, 4); return f; } 85 86 /* ----------------------------------------------------------------- oracles */ 87 static void oracle_gqa(const float *q, const float *kc, const float *vc, size_t seq_len, size_t nqh, size_t nkv, size_t hd, float *out) { 88 if (seq_len == 0) { memset(out, 0, nqh * hd * 4); return; } 89 size_t ratio = nqh / nkv; double inv_sqrt_d = 1.0 / sqrt((double)hd); 90 double *scores = malloc(seq_len * sizeof *scores); 91 for (size_t h = 0; h < nqh; h++) { 92 size_t kvh = h / ratio; const float *qh = q + h * hd; 93 for (size_t t = 0; t < seq_len; t++) { 94 const float *kt = kc + (t * nkv + kvh) * hd; double dot = 0.0; 95 for (size_t d = 0; d < hd; d++) dot += (double)qh[d] * (double)kt[d]; 96 scores[t] = dot * inv_sqrt_d; 97 } 98 double mx = -INFINITY; for (size_t t = 0; t < seq_len; t++) if (scores[t] > mx) mx = scores[t]; 99 double sum = 0.0; for (size_t t = 0; t < seq_len; t++) { scores[t] = exp(scores[t] - mx); sum += scores[t]; } 100 double inv = 1.0 / (sum > 1e-12 ? sum : 1e-12); 101 for (size_t t = 0; t < seq_len; t++) scores[t] *= inv; 102 for (size_t d = 0; d < hd; d++) { 103 double s = 0.0; 104 for (size_t t = 0; t < seq_len; t++) s += scores[t] * (double)vc[(t * nkv + kvh) * hd + d]; 105 out[h * hd + d] = (float)s; 106 } 107 } 108 free(scores); 109 } 110 /* bf16 pool in the canonical layout; the oracle's read_kv_head: element_offset(block, layer, is_value, token) + kv_head*head_dim*2 */ 111 static const uint16_t *kv_head(const uint8_t *pool, const OmegaGpuKvLayout *ly, size_t blk, size_t layer, int is_v, size_t tok, size_t kvh, size_t hd) { 112 size_t off = blk * ly->block_stride_bytes + layer * ly->layer_stride_bytes + (is_v ? ly->kv_plane_stride_bytes : 0) + tok * ly->token_stride_bytes + kvh * hd * 2; 113 return (const uint16_t *)(pool + off); 114 } 115 static void oracle_paged(const float *q, const uint8_t *pool, const OmegaGpuKvLayout *ly, const uint32_t *ids, size_t nids, size_t ctx, size_t layer, 116 size_t nqh, size_t nkv, size_t hd, float *out) { 117 if (ctx == 0 || nids == 0) { memset(out, 0, nqh * hd * 4); return; } 118 size_t ratio = nqh / nkv; double inv_sqrt_d = 1.0 / sqrt((double)hd); size_t bs = ly->block_size; 119 double *acc = malloc(hd * sizeof *acc); 120 for (size_t h = 0; h < nqh; h++) { 121 size_t kvh = h / ratio; const float *qh = q + h * hd; 122 double m = -INFINITY, l = 0.0; for (size_t d = 0; d < hd; d++) acc[d] = 0.0; 123 for (size_t t = 0; t < ctx; t++) { 124 size_t bi = t / bs; if (bi >= nids) break; 125 const uint16_t *kh = kv_head(pool, ly, ids[bi], layer, 0, t % bs, kvh, hd); 126 const uint16_t *vh = kv_head(pool, ly, ids[bi], layer, 1, t % bs, kvh, hd); 127 double dot = 0.0; for (size_t d = 0; d < hd; d++) dot += (double)qh[d] * (double)bf2f(kh[d]); 128 double score = dot * inv_sqrt_d, mn = m > score ? m : score, alpha = exp(m - mn), beta = exp(score - mn); 129 l = l * alpha + beta; 130 for (size_t d = 0; d < hd; d++) acc[d] = acc[d] * alpha + beta * (double)bf2f(vh[d]); 131 m = mn; 132 } 133 double inv = l > 0.0 ? 1.0 / l : 0.0; 134 for (size_t d = 0; d < hd; d++) out[h * hd + d] = (float)(acc[d] * inv); 135 } 136 free(acc); 137 } 138 static void oracle_batch(const float *q, const uint8_t *pool, const OmegaGpuKvLayout *ly, const int32_t *tables, const int32_t *ctxs, size_t maxb, size_t nseq, 139 size_t layer, size_t nqh, size_t nkv, size_t hd, float *out) { 140 size_t stride = nqh * hd; 141 uint32_t *ids = malloc((maxb ? maxb : 1) * sizeof *ids); 142 for (size_t s = 0; s < nseq; s++) { 143 size_t ctx = ctxs[s] > 0 ? (size_t)ctxs[s] : 0, n = 0; 144 size_t total = nseq * maxb; /* the table array length as the trait sees it */ 145 if ((s + 1) * maxb <= total) for (size_t b = 0; b < maxb; b++) if (tables[s * maxb + b] >= 0) ids[n++] = (uint32_t)tables[s * maxb + b]; 146 oracle_paged(q + s * stride, pool, ly, ids, n, ctx, layer, nqh, nkv, hd, out + s * stride); 147 } 148 free(ids); 149 } 150 151 static size_t compare(const float *got, const float *want, size_t n, double rel, double abs_tol, double *worst) { 152 size_t bad = 0; *worst = 0.0; 153 for (size_t i = 0; i < n; i++) { 154 double d = fabs((double)got[i] - (double)want[i]); 155 double lim = rel * fabs((double)want[i]) + abs_tol; 156 double scaled = lim > 0 ? d / lim : (d > 0 ? INFINITY : 0.0); 157 if (scaled > *worst) *worst = scaled; 158 if (!(d <= lim)) bad++; /* NaN counts as bad */ 159 } 160 return bad; 161 } 162 163 /* ------------------------------------------------------------- host only */ 164 /* One instruction line of a SASS listing (sm121dis prints the nvdisasm layout): leading blanks, then the byte offset as a hex comment, "/" "*" hex "*" "/". 165 * omega#470: the old test matched the text "/" "*" "0", which stops at offset 0x1000, so every listing looked cut off at 166 * 256 instructions and any opcode first emitted past 4 KiB (the hd 128 kernels are 512 and 624 instructions) was missed. */ 167 static bool is_sass_insn_line(const char *line) { 168 while (*line == ' ' || *line == '\t') line++; 169 if (line[0] != '/' || line[1] != '*') return false; 170 const char *p = line + 2; 171 int digits = 0; 172 while ((*p >= '0' && *p <= '9') || (*p >= 'a' && *p <= 'f') || (*p >= 'A' && *p <= 'F')) { p++; digits++; } 173 return digits >= 4 && p[0] == '*' && p[1] == '/'; 174 } 175 176 static int sm121dis_check(bool f32, const char *name, const char *const *must, int n_must) { 177 OmegaBlackwellKernel k; memset(&k, 0, sizeof k); 178 if (omega_gpu_attention_codegen_hd(f32, f32 ? 12 : 4, 3, g_hd, &k) != OMEGA_GPU_ATTN_OK) return -1; 179 char lst[64]; 180 snprintf(lst, sizeof lst, "/tmp/omega_attn_%s_%d.sass.XXXXXX", name, (int)getpid()); 181 int fd = mkstemp(lst); /* private, unique listing; read back the same descriptor */ 182 FILE *f = fd >= 0 ? fdopen(fd, "w+") : NULL; 183 if (!f) { if (fd >= 0) close(fd); free(k.code); return -1; } 184 int rc = omega_sm121_listing(k.code, k.code_size, f); 185 const int want_insns = (int)(k.code_size / 16); /* every 16-byte slot, padding included, is one listing line */ 186 free(k.code); 187 if (fflush(f) != 0 || fseek(f, 0, SEEK_SET) != 0) { fclose(f); return -1; } 188 FILE *l = f; 189 char line[512]; int seen[16] = {0}; int bad = 0, insns = 0; 190 while (fgets(line, sizeof line, l)) { 191 if (!is_sass_insn_line(line)) continue; /* every address line, 0x1000 and up too (omega#470) */ 192 insns++; 193 if (strstr(line, "?") || strstr(line, "error")) bad++; 194 for (int i = 0; i < n_must; i++) if (strstr(line, must[i])) seen[i] = 1; 195 } 196 if (ferror(l)) rc = -1; 197 if (fclose(l) != 0) rc = -1; 198 int miss = 0; 199 for (int i = 0; i < n_must; i++) if (!seen[i]) { printf(" %s: sm121dis listing lacks %s\n", name, must[i]); miss++; } 200 printf("sm121dis %s: rc=%d insns=%d of %d undecodable=%d missing=%d (%s)\n", name, rc, insns, want_insns, bad, miss, lst); 201 return (rc == 0 && insns == want_insns && bad == 0 && miss == 0) ? 0 : -1; 202 } 203 204 static OmegaGpuKvLayout layout_for(uint32_t num_blocks, uint32_t bs, uint32_t layers, uint32_t nkv, uint32_t hd) { 205 OmegaGpuKvLayout ly; 206 ly.head_stride_bytes = (uint64_t)hd * 2; ly.token_stride_bytes = ly.head_stride_bytes * nkv; 207 ly.kv_plane_stride_bytes = ly.token_stride_bytes * bs; ly.layer_stride_bytes = 2 * ly.kv_plane_stride_bytes; 208 ly.block_stride_bytes = ly.layer_stride_bytes * layers; ly.pool_bytes = ly.block_stride_bytes * num_blocks; 209 ly.num_blocks = num_blocks; ly.num_layers = layers; ly.block_size = bs; 210 return ly; 211 } 212 213 static void host_only(void) { 214 float q[64 * 64], kv[64 * 64], out[64 * 64]; memset(q, 0, sizeof q); memset(kv, 0, sizeof kv); 215 CHECK(omega_gpu_gqa_attention_f32(NULL, kv, kv, 1, 32, 4, 64, out, NULL) == OMEGA_GPU_ATTN_BAD_ARGS, "NULL q refused"); 216 CHECK(omega_gpu_gqa_attention_f32(q, kv, kv, 1, 32, 4, 96, out, NULL) == OMEGA_GPU_ATTN_TOO_LARGE, "head_dim 96 refused (TOO_LARGE)"); 217 CHECK(omega_gpu_gqa_attention_f32(q, kv, kv, 1, 32, 4, 256, out, NULL) == OMEGA_GPU_ATTN_TOO_LARGE, "head_dim 256 refused (TOO_LARGE)"); 218 CHECK(omega_gpu_gqa_attention_f32(q, kv, kv, 1, 6, 2, 64, out, NULL) == OMEGA_GPU_ATTN_BAD_ARGS, "gqa ratio 3 refused"); 219 CHECK(omega_gpu_gqa_attention_f32(q, kv, kv, 1, 32, 5, 64, out, NULL) == OMEGA_GPU_ATTN_BAD_ARGS, "32 q heads / 5 kv heads refused"); 220 CHECK(omega_gpu_gqa_attention_f32(q, kv, kv, OMEGA_GPU_ATTN_MAX_GQA_CTX + 1, 32, 4, 64, out, NULL) == OMEGA_GPU_ATTN_TOO_LARGE, "context past the envelope refused"); 221 for (int i = 0; i < 64; i++) out[i] = 1.0f; 222 OmegaGpuAttnInfo info; 223 CHECK(omega_gpu_gqa_attention_f32(q, kv, kv, 0, 1, 1, 64, out, &info) == OMEGA_GPU_ATTN_OK && out[0] == 0.0f && out[63] == 0.0f && info.chip_calls == 0, "seq_len 0 writes zeros without a launch"); 224 OmegaGpuKvLayout ly = layout_for(8, 16, 2, 4, 64); 225 uint8_t *pool = calloc(ly.pool_bytes, 1); 226 uint32_t ids[2] = { 1, 9 }; 227 CHECK(omega_gpu_paged_attention_bf16(q, pool, &ly, ids, 2, 20, 0, 32, 4, 64, out, NULL) == OMEGA_GPU_ATTN_BAD_ARGS, "block id past the pool refused"); 228 CHECK(omega_gpu_paged_attention_bf16(q, pool, &ly, ids, 1, 20, 2, 32, 4, 64, out, NULL) == OMEGA_GPU_ATTN_BAD_ARGS, "layer past the pool refused"); 229 OmegaGpuKvLayout bad = ly; bad.block_size = 12; 230 CHECK(omega_gpu_paged_attention_bf16(q, pool, &bad, ids, 1, 10, 0, 32, 4, 64, out, NULL) == OMEGA_GPU_ATTN_BAD_ARGS, "block size 12 (not a power of two) refused"); 231 bad = ly; bad.head_stride_bytes = 256; 232 CHECK(omega_gpu_paged_attention_bf16(q, pool, &bad, ids, 1, 10, 0, 32, 4, 64, out, NULL) == OMEGA_GPU_ATTN_BAD_ARGS, "layout whose head stride is not head_dim*2 refused"); 233 free(pool); 234 CHECK(strcmp(omega_gpu_attention_rc_name(OMEGA_GPU_ATTN_UNWRITTEN), "UNWRITTEN") == 0, "rc name"); 235 236 /* with --divergent the listing must also show the region ops (last two entries) */ 237 static const char *const must_bf16[] = { "MUFU.EX2", "MUFU.RCP", "FMNMX", "BAR.SYNC", "SHFL.DOWN", "@P0 BRA", "@!P0 BRA", "LDG.E.U16", "LDG.E ", "LDG.E.128", "LDS.128", "LDS R", "STS [R", "STG.E", "LOP3.LUT", "SHF.R.U32.HI", "BSSY", "BSYNC" }; 238 static const char *const must_f32[] = { "MUFU.EX2", "MUFU.RCP", "FMNMX", "BAR.SYNC", "SHFL.DOWN", "@P0 BRA", "@!P0 BRA", "LDG.E ", "LDG.E.128", "LDS.128", "LDS R", "STS [R", "STG.E", "BSSY", "BSYNC" }; 239 for (int f32 = 0; f32 < 2; f32++) { 240 const char *name = f32 ? "gqa_f32" : "paged_bf16"; 241 OmegaBlackwellKernel k; memset(&k, 0, sizeof k); 242 int rc = omega_gpu_attention_codegen_hd(f32 != 0, f32 ? 12 : 4, 3, g_hd, &k); 243 CHECK(rc == OMEGA_GPU_ATTN_OK && k.code_size > 0 && k.gpr_count <= ATTN_GPR_BOUND, "%s kernel generated (rc %s, %zu insns, %u gprs)", name, omega_gpu_attention_rc_name(rc), k.insn_count, k.gpr_count); 244 printf("codegen %s: %zu insns, %u gprs, %u ugprs\n", name, k.insn_count, k.gpr_count, k.uniform_gpr_count); 245 /* every mutant (1 .. COUNT-1) is a distinct kernel: different from the baseline and from 246 * every other mutant, named, and inside the register budget */ 247 uint8_t digests[OMEGA_GPU_ATTN_MUTANT_COUNT][32]; memcpy(digests[0], k.code_digest, 32); 248 free(k.code); 249 for (int m = 1; m < OMEGA_GPU_ATTN_MUTANT_COUNT; m++) { 250 omega_gpu_attention_test_set_mutant((OmegaGpuAttnMutant)m); 251 memset(&k, 0, sizeof k); 252 int mrc = omega_gpu_attention_codegen_hd(f32 != 0, f32 ? 12 : 4, 3, g_hd, &k); 253 CHECK(mrc == OMEGA_GPU_ATTN_OK && k.gpr_count <= ATTN_GPR_BOUND, "%s mutant %s generated (rc %s, %u gprs)", name, omega_gpu_attention_mutant_name((OmegaGpuAttnMutant)m), omega_gpu_attention_rc_name(mrc), k.gpr_count); 254 CHECK(strcmp(omega_gpu_attention_mutant_name((OmegaGpuAttnMutant)m), "?") != 0, "mutant %d has a name", m); 255 memcpy(digests[m], k.code_digest, 32); 256 free(k.code); 257 omega_gpu_attention_test_set_mutant(OMEGA_GPU_ATTN_MUTANT_NONE); 258 for (int o = 0; o < m; o++) 259 CHECK(memcmp(digests[o], digests[m], 32) != 0, "%s mutant %s kernel differs from %s", name, omega_gpu_attention_mutant_name((OmegaGpuAttnMutant)m), omega_gpu_attention_mutant_name((OmegaGpuAttnMutant)o)); 260 } 261 CHECK(strcmp(omega_gpu_attention_mutant_name(OMEGA_GPU_ATTN_MUTANT_COUNT), "?") == 0, "COUNT has no name"); 262 /* a different shape key is a different kernel */ 263 memset(&k, 0, sizeof k); 264 CHECK(omega_gpu_attention_codegen_hd(f32 != 0, f32 ? 12 : 4, 2, g_hd, &k) == OMEGA_GPU_ATTN_OK && memcmp(digests[0], k.code_digest, 32) != 0, "%s log2gqa 2 kernel differs from log2gqa 3", name); 265 free(k.code); 266 CHECK(sm121dis_check(f32 != 0, name, f32 ? must_f32 : must_bf16, (f32 ? 11 : 14) + (g_divergent ? 2 : 0)) == 0, "%s sm121dis listing decodes and shows the expected instructions", name); 267 } 268 } 269 270 /* ------------------------------------------------------------- chip gate */ 271 typedef struct { const char *name; size_t n; int rc; size_t bad; double worst; int pass; uint64_t chip_ns, call_ns; uint32_t calls, unwritten; 272 int mutants_run, mutants_caught; char mutant_note[400]; 273 uint64_t kv_staged, kv_naive; uint32_t blk_logical, blk_unique; } Case; 274 static void case_info(Case *c, const OmegaGpuAttnInfo *i) { 275 c->chip_ns = i->elapsed_ns; c->call_ns = i->call_ns; c->calls = i->chip_calls; c->unwritten = i->unwritten_words; 276 c->kv_staged = i->kv_bytes_staged; c->kv_naive = i->kv_bytes_naive; c->blk_logical = i->kv_blocks_logical; c->blk_unique = i->kv_blocks_unique; 277 } 278 static Case g_cases[64]; static int g_ncases; 279 static int g_mutant_caught[OMEGA_GPU_ATTN_MUTANT_COUNT], g_mutant_run[OMEGA_GPU_ATTN_MUTANT_COUNT]; 280 281 static void record(Case c, FILE *out) { 282 g_cases[g_ncases++] = c; 283 CHECK(c.pass, "%s rc=%s violations=%zu worst=%g", c.name, omega_gpu_attention_rc_name(c.rc), c.bad, c.worst); 284 CHECK(c.mutants_caught == c.mutants_run, "%s mutants caught %d of %d (%s)", c.name, c.mutants_caught, c.mutants_run, c.mutant_note); 285 printf("%s %s n=%zu rc=%s violations=%zu worst_scaled_err=%g chip_ns=%" PRIu64 " call_ns=%" PRIu64 " calls=%u unwritten=%u kv_staged=%" PRIu64 "/%" PRIu64 " blocks=%u/%u | mutants %d/%d %s\n", 286 c.pass && c.mutants_caught == c.mutants_run ? "PASS" : "FAIL", c.name, c.n, omega_gpu_attention_rc_name(c.rc), c.bad, c.worst, c.chip_ns, c.call_ns, c.calls, c.unwritten, 287 c.kv_staged, c.kv_naive, c.blk_unique, c.blk_logical, c.mutants_caught, c.mutants_run, c.mutant_note); 288 if (out) fprintf(out, "%s{\"case\":\"%s\",\"n\":%zu,\"rc\":\"%s\",\"violations\":%zu,\"worst_scaled_err\":%g,\"pass\":%s,\"chip_elapsed_ns\":%" PRIu64 ",\"call_ns\":%" PRIu64 ",\"chip_calls\":%u,\"unwritten_words\":%u," 289 "\"kv_bytes_staged\":%" PRIu64 ",\"kv_bytes_naive\":%" PRIu64 ",\"kv_blocks_unique\":%u,\"kv_blocks_logical\":%u,\"mutants_run\":%d,\"mutants_caught\":%d,\"mutant_note\":\"%s\"}", 290 g_ncases > 1 ? "," : "", c.name, c.n, omega_gpu_attention_rc_name(c.rc), c.bad, c.worst, c.pass ? "true" : "false", c.chip_ns, c.call_ns, c.calls, c.unwritten, 291 c.kv_staged, c.kv_naive, c.blk_unique, c.blk_logical, c.mutants_run, c.mutants_caught, c.mutant_note); 292 } 293 294 static const char *mutant_name(int m) { return omega_gpu_attention_mutant_name((OmegaGpuAttnMutant)m); } 295 296 /* Runs the mutants listed in `ms` (terminated by 0) through `run` and counts the catches. */ 297 typedef int (*RunFn)(void *ctx, float *got, OmegaGpuAttnInfo *info); 298 /* The forced launch split the battery currently holds (the engine hook has no getter); -1 = automatic. */ 299 static int g_forced_split = -1; 300 static void set_split(int log2split) { g_forced_split = log2split; omega_gpu_attention_test_set_split(log2split); } 301 302 static void run_mutants(Case *c, const int *ms, RunFn run, void *ctx, float *got, const float *want, size_t n, double rel, double abs_tol) { 303 size_t pos = strlen(c->mutant_note); /* appends: a case may call this more than once */ 304 for (int i = 0; ms[i]; i++) { 305 OmegaGpuAttnInfo info; double w; 306 omega_gpu_attention_test_set_mutant((OmegaGpuAttnMutant)ms[i]); 307 /* cut J (one chunk per split): a paged call at up to 16 chunks gives every CTA one chunk, so the in-kernel 308 * rescale between chunks never runs and the NO_RESCALE mutant would be invisible. That mutant runs with the 309 * whole context in one CTA per head (forced split 1), where the rescale happens on every chunk after the first. */ 310 const int one_cta = ms[i] == OMEGA_GPU_ATTN_MUTANT_NO_RESCALE; 311 if (one_cta) omega_gpu_attention_test_set_split(0); 312 int rc = run(ctx, got, &info); 313 if (one_cta) omega_gpu_attention_test_set_split(g_forced_split); 314 size_t bad = compare(got, want, n, rel, abs_tol, &w); 315 int caught = rc != OMEGA_GPU_ATTN_OK || bad > 0; 316 omega_gpu_attention_test_set_mutant(OMEGA_GPU_ATTN_MUTANT_NONE); 317 c->mutants_run++; c->mutants_caught += caught; g_mutant_run[ms[i]]++; g_mutant_caught[ms[i]] += caught; 318 pos += (size_t)snprintf(c->mutant_note + pos, sizeof c->mutant_note - pos, "%s%s:%s(rc=%s,bad=%zu)", pos ? " " : "", mutant_name(ms[i]), caught ? "CAUGHT" : "MISSED", omega_gpu_attention_rc_name(rc), bad); 319 if (pos >= sizeof c->mutant_note) break; 320 } 321 } 322 323 typedef struct { const float *q, *kc, *vc; uint32_t seq, nqh, nkv; } GqaCtx; 324 static int run_gqa(void *p, float *got, OmegaGpuAttnInfo *info) { GqaCtx *c = p; return omega_gpu_gqa_attention_f32(c->q, c->kc, c->vc, c->seq, c->nqh, c->nkv, g_hd, got, info); } 325 typedef struct { const float *q, *kc, *vc; uint32_t base, nr, nqh, nkv; } RowsCtx; 326 static int run_rows(void *p, float *got, OmegaGpuAttnInfo *info) { RowsCtx *c = p; return omega_gpu_gqa_attention_rows_f32(c->q, c->kc, c->vc, c->base, c->nr, c->nqh, c->nkv, g_hd, got, info); } 327 typedef struct { const float *q; const uint8_t *pool; const OmegaGpuKvLayout *ly; const uint32_t *ids; uint32_t nids, ctx, layer, nqh, nkv; } PagedCtx; 328 static int run_paged(void *p, float *got, OmegaGpuAttnInfo *info) { PagedCtx *c = p; return omega_gpu_paged_attention_bf16(c->q, c->pool, c->ly, c->ids, c->nids, c->ctx, c->layer, c->nqh, c->nkv, g_hd, got, info); } 329 typedef struct { const float *q; const uint8_t *pool; const OmegaGpuKvLayout *ly; const int32_t *tables, *ctxs; uint32_t maxb, nseq, layer, nqh, nkv; } BatchCtx; 330 static int run_batch(void *p, float *got, OmegaGpuAttnInfo *info) { BatchCtx *c = p; return omega_gpu_paged_attention_batch_bf16(c->q, c->pool, c->ly, c->tables, c->ctxs, c->maxb, c->nseq, c->layer, c->nqh, c->nkv, g_hd, got, info); } 331 /* single vs batched parity and repeat (L6-KV, CAND-0 coverage): each sequence of a batch, run 332 * alone through the single-sequence entry point with the batch's own rules applied by hand 333 * (negative table entries removed, ctx <= 0 -> 0), must equal its row of the batched output bit 334 * for bit (same kernel, same per-CTA inputs; the batch only shares staging). Then the batch is 335 * called again with the same inputs: kernel cache hit, bit-identical output, identical staging 336 * counters. `got` must hold the batched output of `bc`. */ 337 static void batch_single_repeat_checks(const char *name, const BatchCtx *bc, const float *got, const Case *c) { 338 size_t row = (size_t)bc->nqh * g_hd, n = (size_t)bc->nseq * row; 339 float *one = malloc(row * 4), *again = malloc(n * 4); 340 uint32_t *ids = malloc((bc->maxb ? bc->maxb : 1) * 4); 341 for (uint32_t s = 0; s < bc->nseq; s++) { 342 uint32_t nb = 0; 343 for (uint32_t b = 0; b < bc->maxb; b++) { int32_t v = bc->tables[(size_t)s * bc->maxb + b]; if (v >= 0) ids[nb++] = (uint32_t)v; } 344 uint32_t ctx = bc->ctxs[s] > 0 ? (uint32_t)bc->ctxs[s] : 0; 345 for (size_t i = 0; i < row; i++) one[i] = -7.0f; /* poison: an unwritten row cannot match */ 346 OmegaGpuAttnInfo si; 347 int src = omega_gpu_paged_attention_bf16(bc->q + (size_t)s * row, bc->pool, bc->ly, ids, nb, ctx, bc->layer, bc->nqh, bc->nkv, g_hd, one, &si); 348 CHECK(src == OMEGA_GPU_ATTN_OK && memcmp(one, got + (size_t)s * row, row * 4) == 0, 349 "%s: sequence %u alone (single entry point, %u blocks, ctx %u) is bit-identical to its batched row (rc=%s)", name, s, nb, ctx, omega_gpu_attention_rc_name(src)); 350 } 351 OmegaGpuAttnInfo ri; 352 int rrc = omega_gpu_paged_attention_batch_bf16(bc->q, bc->pool, bc->ly, bc->tables, bc->ctxs, bc->maxb, bc->nseq, bc->layer, bc->nqh, bc->nkv, g_hd, again, &ri); 353 CHECK(rrc == OMEGA_GPU_ATTN_OK && ri.kernel_cache_hit && memcmp(again, got, n * 4) == 0 && ri.kv_bytes_staged == c->kv_staged && ri.kv_bytes_naive == c->kv_naive 354 && ri.kv_blocks_unique == c->blk_unique && ri.kv_blocks_logical == c->blk_logical, 355 "%s: repeated batch call is a cache hit, bit-identical, same staging counters (rc=%s hit=%d staged %" PRIu64 "/%" PRIu64 ")", 356 name, omega_gpu_attention_rc_name(rrc), (int)ri.kernel_cache_hit, ri.kv_bytes_staged, c->kv_staged); 357 free(one); free(again); free(ids); 358 } 359 360 361 static int chip(const char *out_path) { 362 FILE *out = out_path ? create_0644(out_path) : NULL; 363 if (out_path && !out) { printf("cannot open %s\n", out_path); return 2; } 364 if (out) fprintf(out, "{\"schema\":\"OMEGA_GPU_ATTENTION_V1\",\"tolerances\":{\"rel\":2e-4,\"abs\":2e-5,\"large_scores_rel\":1e-3,\"large_scores_abs\":1e-4},\"cases\":["); 365 uint32_t seed = 0xfb1c0005u; 366 const uint32_t hd = g_hd; 367 typedef struct { uint32_t nqh, nkv; const char *model; } Shape; 368 const Shape shapes64[2] = { { 32, 4, "tinyllama" }, { 32, 8, "llama32_1b" } }; 369 /* head_dim 128: Qwen3-4B (32 q heads, 8 kv heads, GQA 4:1) and a ratio-8 shape */ 370 const Shape shapes128[2] = { { 32, 8, "qwen3_4b" }, { 32, 4, "gqa8" } }; 371 const Shape *shapes = hd == 128 ? shapes128 : shapes64; 372 /* 65, 129, 300 and 1000 end in a partial 64-token chunk after whole ones: the case that 373 * caught the diverged-warp shuffle on the chip (2026-10-04); 1, 17, 128, 256, 2048 did not. */ 374 /* head_dim 128 chunks are 128 tokens: 127, 128, 129 straddle a chunk, 300 and 1000 end in a partial one */ 375 const uint32_t ctxs64[9] = { 1, 17, 256, 2048, 65, 128, 129, 300, 1000 }, ctxs128[9] = { 1, 17, 256, 2048, 127, 128, 129, 300, 1000 }; 376 const uint32_t *ctxs = hd == 128 ? ctxs128 : ctxs64; 377 const int no_mutants[1] = { 0 }; 378 379 /* 1. contiguous f32 KV (gqa_attention) */ 380 for (int sh = 0; sh < 2; sh++) for (int ci = 0; ci < 9; ci++) { 381 uint32_t nqh = shapes[sh].nqh, nkv = shapes[sh].nkv, seq = ctxs[ci]; 382 size_t n = (size_t)nqh * hd, nkvs = (size_t)seq * nkv * hd; 383 float *q = malloc(n * 4), *kc = malloc(nkvs * 4), *vc = malloc(nkvs * 4), *got = malloc(n * 4), *want = malloc(n * 4), *again = malloc(n * 4); 384 for (size_t i = 0; i < n; i++) q[i] = frand(&seed, -1.0f, 1.0f); 385 for (size_t i = 0; i < nkvs; i++) { kc[i] = frand(&seed, -1.0f, 1.0f); vc[i] = frand(&seed, -1.0f, 1.0f); } 386 oracle_gqa(q, kc, vc, seq, nqh, nkv, hd, want); 387 char name[96]; snprintf(name, sizeof name, "gqa_f32_%s_%uq%ukv_ctx%u", shapes[sh].model, nqh, nkv, seq); 388 Case c = { .name = strdup(name), .n = n }; 389 OmegaGpuAttnInfo info; 390 GqaCtx gc = { q, kc, vc, seq, nqh, nkv }; 391 c.rc = run_gqa(&gc, got, &info); 392 c.bad = compare(got, want, n, 2e-4, 2e-5, &c.worst); 393 c.pass = c.rc == OMEGA_GPU_ATTN_OK && c.bad == 0; case_info(&c, &info); 394 if (ci == 3) { 395 OmegaGpuAttnInfo i2; int rc2 = run_gqa(&gc, again, &i2); 396 CHECK(rc2 == OMEGA_GPU_ATTN_OK && i2.kernel_cache_hit && memcmp(got, again, n * 4) == 0, "%s repeat run (cache hit) is bit-identical", name); 397 /* negative control: the comparison must reject a wrong expectation (kv heads swapped) */ 398 float *wrong = malloc(n * 4); double w2; 399 for (uint32_t h = 0; h < nqh; h++) memcpy(wrong + (size_t)h * hd, want + (size_t)((h + nqh / nkv) % nqh) * hd, hd * 4); 400 size_t neg = compare(got, wrong, n, 2e-4, 2e-5, &w2); 401 CHECK(neg > n / 2, "%s negative control: wrong expectation flagged (%zu of %zu)", name, neg, n); 402 free(wrong); 403 static const int ms[5] = { OMEGA_GPU_ATTN_MUTANT_SLOT, OMEGA_GPU_ATTN_MUTANT_NO_RESCALE, OMEGA_GPU_ATTN_MUTANT_Q_ROW, OMEGA_GPU_ATTN_MUTANT_OUT_ROW, 0 }; 404 run_mutants(&c, ms, run_gqa, &gc, got, want, n, 2e-4, 2e-5); 405 } else if (ci == 1 && sh == 1) { 406 static const int ms[2] = { OMEGA_GPU_ATTN_MUTANT_KV_HEAD, 0 }; 407 run_mutants(&c, ms, run_gqa, &gc, got, want, n, 2e-4, 2e-5); 408 } else run_mutants(&c, no_mutants, run_gqa, &gc, got, want, n, 2e-4, 2e-5); 409 record(c, out); free(q); free(kc); free(vc); free(got); free(want); free(again); 410 } 411 /* 1b. rows path (prompt read, 2026-10-12): base_len tokens already in the KV, then num_rows 412 * query rows in one call; row i attends over base_len + i + 1 tokens. Expected per row from 413 * oracle_gqa on that prefix. 40 rows at 32 q heads exceed the 1024-CTA launch bound: 2 launches. */ 414 for (int sh = 0; sh < 2; sh++) for (int ri = 0; ri < 3; ri++) { 415 static const uint32_t bases[3] = { 0, 17, 300 }, nrows[3] = { 1, 5, 40 }; 416 uint32_t nqh = shapes[sh].nqh, nkv = shapes[sh].nkv, base = bases[ri], nr = nrows[ri], total = base + nr; 417 size_t row = (size_t)nqh * hd, n = row * nr, nkvs = (size_t)total * nkv * hd; 418 float *q = malloc(n * 4), *kc = malloc(nkvs * 4), *vc = malloc(nkvs * 4), *got = malloc(n * 4), *want = malloc(n * 4); 419 for (size_t i = 0; i < n; i++) q[i] = frand(&seed, -1.0f, 1.0f); 420 for (size_t i = 0; i < nkvs; i++) { kc[i] = frand(&seed, -1.0f, 1.0f); vc[i] = frand(&seed, -1.0f, 1.0f); } 421 for (uint32_t i = 0; i < nr; i++) oracle_gqa(q + i * row, kc, vc, base + i + 1, nqh, nkv, hd, want + i * row); 422 char name[96]; snprintf(name, sizeof name, "gqa_rows_f32_%s_%uq%ukv_base%u_rows%u", shapes[sh].model, nqh, nkv, base, nr); 423 Case c = { .name = strdup(name), .n = n }; 424 OmegaGpuAttnInfo info; 425 RowsCtx rx = { q, kc, vc, base, nr, nqh, nkv }; 426 c.rc = run_rows(&rx, got, &info); 427 c.bad = compare(got, want, n, 2e-4, 2e-5, &c.worst); 428 c.pass = c.rc == OMEGA_GPU_ATTN_OK && c.bad == 0; case_info(&c, &info); 429 if (nr == 1) { 430 /* one row is the single-row call, bit for bit */ 431 float *one = malloc(row * 4); OmegaGpuAttnInfo i1; 432 int rc1 = omega_gpu_gqa_attention_f32(q, kc, vc, total, nqh, nkv, hd, one, &i1); 433 CHECK(rc1 == OMEGA_GPU_ATTN_OK && memcmp(got, one, row * 4) == 0, "%s equals omega_gpu_gqa_attention_f32 bit for bit", name); 434 free(one); 435 } 436 if (nr == 40) { 437 CHECK(info.chip_calls == 2, "%s 40 rows x %u heads go in 2 launches (got %u)", name, nqh, info.chip_calls); 438 CHECK(info.kv_bytes_staged == 2 * nkvs * 4, "%s KV staged once (%" PRIu64 " bytes, expected %zu)", name, info.kv_bytes_staged, 2 * nkvs * 4); 439 /* negative control: every row scored over the whole context (no causal cut) must be flagged */ 440 float *wrong = malloc(n * 4); double w2; 441 for (uint32_t i = 0; i < nr; i++) oracle_gqa(q + i * row, kc, vc, total, nqh, nkv, hd, wrong + i * row); 442 size_t neg = compare(got, wrong, n, 2e-4, 2e-5, &w2); 443 CHECK(neg > n / 4, "%s negative control: non-causal expectation flagged (%zu of %zu)", name, neg, n); 444 free(wrong); 445 static const int ms[5] = { OMEGA_GPU_ATTN_MUTANT_SLOT, OMEGA_GPU_ATTN_MUTANT_NO_RESCALE, OMEGA_GPU_ATTN_MUTANT_Q_ROW, OMEGA_GPU_ATTN_MUTANT_OUT_ROW, 0 }; 446 run_mutants(&c, ms, run_rows, &rx, got, want, n, 2e-4, 2e-5); 447 } else run_mutants(&c, no_mutants, run_rows, &rx, got, want, n, 2e-4, 2e-5); 448 record(c, out); free(q); free(kc); free(vc); free(got); free(want); 449 } 450 { /* rows path refusals */ 451 float d[1]; OmegaGpuAttnInfo i0; 452 CHECK(omega_gpu_gqa_attention_rows_f32(d, d, d, 0, 0, 32, 4, hd, d, &i0) == OMEGA_GPU_ATTN_BAD_ARGS, "rows: zero rows refused"); 453 CHECK(omega_gpu_gqa_attention_rows_f32(d, d, d, OMEGA_GPU_ATTN_MAX_GQA_CTX, 1, 32, 4, hd, d, &i0) == OMEGA_GPU_ATTN_TOO_LARGE, "rows: base + rows past the context bound refused"); 454 } 455 /* 2. large scores (q scaled by 200): the softmax without the running max overflows */ 456 { 457 uint32_t nqh = 32, nkv = 4, seq = 256; size_t n = (size_t)nqh * hd, nkvs = (size_t)seq * nkv * hd; 458 float *q = malloc(n * 4), *kc = malloc(nkvs * 4), *vc = malloc(nkvs * 4), *got = malloc(n * 4), *want = malloc(n * 4); 459 for (size_t i = 0; i < n; i++) q[i] = frand(&seed, -200.0f, 200.0f); /* scores ~ +-200 natural: EX2 without the max subtraction overflows f32 (2^128) */ 460 for (size_t i = 0; i < nkvs; i++) { kc[i] = frand(&seed, -1.0f, 1.0f); vc[i] = frand(&seed, -1.0f, 1.0f); } 461 oracle_gqa(q, kc, vc, seq, nqh, nkv, hd, want); 462 Case c = { .name = "gqa_f32_large_scores_32q4kv_ctx256", .n = n }; 463 OmegaGpuAttnInfo info; GqaCtx gc = { q, kc, vc, seq, nqh, nkv }; 464 c.rc = run_gqa(&gc, got, &info); 465 c.bad = compare(got, want, n, 1e-3, 1e-4, &c.worst); 466 c.pass = c.rc == OMEGA_GPU_ATTN_OK && c.bad == 0; case_info(&c, &info); 467 static const int ms[2] = { OMEGA_GPU_ATTN_MUTANT_NO_MAX, 0 }; 468 run_mutants(&c, ms, run_gqa, &gc, got, want, n, 1e-3, 1e-4); 469 record(c, out); free(q); free(kc); free(vc); free(got); free(want); 470 } 471 /* 2b. MHA (16q/16kv, ratio 1, ctx 300 = 4 full chunks + a partial one): the head-wiring 472 * mutants Q_ROW and OUT_ROW are observably different here (Q_ROW keeps kv head h, OUT_ROW 473 * lands on kv head h^1), unlike GQA where both swap the same pair of outputs. */ 474 { 475 uint32_t nqh = 16, nkv = 16, seq = 300; size_t n = (size_t)nqh * hd, nkvs = (size_t)seq * nkv * hd; 476 float *q = malloc(n * 4), *kc = malloc(nkvs * 4), *vc = malloc(nkvs * 4), *got = malloc(n * 4), *want = malloc(n * 4), *got_q = malloc(n * 4); 477 for (size_t i = 0; i < n; i++) q[i] = frand(&seed, -1.0f, 1.0f); 478 for (size_t i = 0; i < nkvs; i++) { kc[i] = frand(&seed, -1.0f, 1.0f); vc[i] = frand(&seed, -1.0f, 1.0f); } 479 oracle_gqa(q, kc, vc, seq, nqh, nkv, hd, want); 480 Case c = { .name = "gqa_f32_mha_16q16kv_ctx300", .n = n }; 481 OmegaGpuAttnInfo info; GqaCtx gc = { q, kc, vc, seq, nqh, nkv }; 482 c.rc = run_gqa(&gc, got, &info); 483 c.bad = compare(got, want, n, 2e-4, 2e-5, &c.worst); 484 c.pass = c.rc == OMEGA_GPU_ATTN_OK && c.bad == 0; case_info(&c, &info); 485 static const int ms_q[2] = { OMEGA_GPU_ATTN_MUTANT_Q_ROW, 0 }; 486 static const int ms_o[3] = { OMEGA_GPU_ATTN_MUTANT_OUT_ROW, OMEGA_GPU_ATTN_MUTANT_KV_HEAD, 0 }; 487 run_mutants(&c, ms_q, run_gqa, &gc, got, want, n, 2e-4, 2e-5); 488 memcpy(got_q, got, n * 4); /* Q_ROW output */ 489 run_mutants(&c, ms_o, run_gqa, &gc, got, want, n, 2e-4, 2e-5); 490 /* `got` now holds the KV_HEAD output; rerun OUT_ROW alone to compare it with Q_ROW */ 491 omega_gpu_attention_test_set_mutant(OMEGA_GPU_ATTN_MUTANT_OUT_ROW); 492 OmegaGpuAttnInfo i3; int rc3 = run_gqa(&gc, got, &i3); 493 omega_gpu_attention_test_set_mutant(OMEGA_GPU_ATTN_MUTANT_NONE); 494 double wq; size_t differ = compare(got, got_q, n, 2e-4, 2e-5, &wq); 495 CHECK(rc3 == OMEGA_GPU_ATTN_OK && differ > n / 2, "mha: Q_ROW and OUT_ROW outputs are distinct wrong answers (%zu of %zu differ)", differ, n); 496 record(c, out); free(q); free(kc); free(vc); free(got); free(want); free(got_q); 497 } 498 /* resident fit rule at the 32-bit edge (Qwen3-8B geometry: 36 layers, 8 kv heads x 128, block 16), no allocation */ 499 { 500 OmegaGpuKvLayout big = layout_for(4096, 16, 36, 8, 128); 501 uint32_t id_ok = (uint32_t)((0xffffffffull - big.layer_stride_bytes) / big.block_stride_bytes); 502 CHECK(omega_gpu_attention_test_resident_fits(&big, id_ok) && !omega_gpu_attention_test_resident_fits(&big, id_ok + 1), 503 "resident fit rule at the 4 GiB edge: block %u fits, %u does not (block stride %llu)", id_ok, id_ok + 1, 504 (unsigned long long)big.block_stride_bytes); 505 } 506 /* 3. paged bf16 KV, block size 16, 2 layers (layer 1 under test), scattered block ids */ 507 for (int sh = 0; sh < 2; sh++) for (int ci = 0; ci < 9; ci++) { 508 uint32_t nqh = shapes[sh].nqh, nkv = shapes[sh].nkv, ctx = ctxs[ci], bs = 16, layers = 2, layer = 1; 509 uint32_t nblk = (ctx + bs - 1) / bs, pool_blocks = nblk + 7; 510 OmegaGpuKvLayout ly = layout_for(pool_blocks, bs, layers, nkv, hd); 511 uint8_t *pool = malloc(ly.pool_bytes); uint16_t *pw = (uint16_t *)pool; 512 for (size_t i = 0; i < ly.pool_bytes / 2; i++) pw[i] = f2bf(frand(&seed, -1.0f, 1.0f)); 513 uint32_t *ids = malloc(nblk * 4); /* a scattered permutation of the pool blocks */ 514 for (uint32_t b = 0; b < nblk; b++) ids[b] = (b * 7 + 3) % pool_blocks; 515 size_t n = (size_t)nqh * hd; 516 float *q = malloc(n * 4), *got = malloc(n * 4), *want = malloc(n * 4); 517 for (size_t i = 0; i < n; i++) q[i] = frand(&seed, -1.0f, 1.0f); 518 oracle_paged(q, pool, &ly, ids, nblk, ctx, layer, nqh, nkv, hd, want); 519 char name[96]; snprintf(name, sizeof name, "paged_bf16_%s_%uq%ukv_bs%u_ctx%u", shapes[sh].model, nqh, nkv, bs, ctx); 520 Case c = { .name = strdup(name), .n = n }; 521 OmegaGpuAttnInfo info; PagedCtx pc = { q, pool, &ly, ids, nblk, ctx, layer, nqh, nkv }; 522 c.rc = run_paged(&pc, got, &info); 523 c.bad = compare(got, want, n, 2e-4, 2e-5, &c.worst); 524 /* Resident pool (2026-10-12): the same bytes in omega's own allocation, read in place. Same kernel, 525 * same data, only the addressing differs: bit-identical to the staged result just computed (which is 526 * the negative control: a plain host pool reports STAGED), nothing staged, info says RESIDENT. */ 527 if (c.rc == OMEGA_GPU_ATTN_OK) { 528 void *rp = NULL; 529 int arc = omega_gpu_attention_pool_alloc(ly.pool_bytes, &rp); 530 CHECK(arc == OMEGA_GPU_ATTN_OK && rp, "%s: resident pool alloc rc=%d (%s)", name, arc, omega_gpu_attention_last_error()); 531 if (arc == OMEGA_GPU_ATTN_OK) { 532 memcpy(rp, pool, ly.pool_bytes); 533 float *got_r = malloc(n * 4); OmegaGpuAttnInfo ri; 534 PagedCtx rpc = { q, rp, &ly, ids, nblk, ctx, layer, nqh, nkv }; 535 int rrc = run_paged(&rpc, got_r, &ri); 536 int same = memcmp(got_r, got, n * 4) == 0; 537 CHECK(rrc == OMEGA_GPU_ATTN_OK && ri.kv_source == OMEGA_GPU_ATTN_KV_RESIDENT && ri.kv_bytes_staged == 0 && 538 info.kv_source == OMEGA_GPU_ATTN_KV_STAGED && same, 539 "%s: resident pool rc=%d source=%u staged=%llu (control source=%u) bit-identical=%d", name, rrc, ri.kv_source, 540 (unsigned long long)ri.kv_bytes_staged, info.kv_source, same); 541 free(got_r); 542 } 543 omega_gpu_attention_pool_free(); 544 } 545 c.pass = c.rc == OMEGA_GPU_ATTN_OK && c.bad == 0; case_info(&c, &info); 546 if (ci == 3) { 547 /* NO_MAX cannot overflow on unit-scale scores (softmax is shift invariant); it is caught by the large-score gqa case */ 548 static const int ms3[6] = { OMEGA_GPU_ATTN_MUTANT_KV_HEAD, OMEGA_GPU_ATTN_MUTANT_SLOT, OMEGA_GPU_ATTN_MUTANT_NO_RESCALE, OMEGA_GPU_ATTN_MUTANT_Q_ROW, OMEGA_GPU_ATTN_MUTANT_OUT_ROW, 0 }; 549 run_mutants(&c, ms3, run_paged, &pc, got, want, n, 2e-4, 2e-5); 550 } else if (ci == 1) { 551 static const int ms[3] = { OMEGA_GPU_ATTN_MUTANT_KV_HEAD, OMEGA_GPU_ATTN_MUTANT_SLOT, 0 }; 552 run_mutants(&c, ms, run_paged, &pc, got, want, n, 2e-4, 2e-5); 553 } else if (ci == 0) { 554 /* one token: its softmax weight is 1 whatever K says, so a K-only slot shift is invisible; KV_HEAD still shows */ 555 static const int ms[2] = { OMEGA_GPU_ATTN_MUTANT_KV_HEAD, 0 }; 556 run_mutants(&c, ms, run_paged, &pc, got, want, n, 2e-4, 2e-5); 557 } else run_mutants(&c, no_mutants, run_paged, &pc, got, want, n, 2e-4, 2e-5); 558 record(c, out); free(pool); free(ids); free(q); free(got); free(want); 559 } 560 /* 3b. context split (cut F): the 32q/8kv shape at ctx 1000 under every forced split against the oracle, the 561 * CTA count per launch grows with the split, the automatic choice at this context is 8 (hd 128: 8 chunks) or 562 * 16 (hd 64: 16 chunks; cut J, one chunk per split), and a short context (ctx 100, one chunk) stays unsplit. A forced launch split at or above 563 * the sequence's own count gives the same bits (the extra CTAs write empty partials that add exact zeros). */ 564 { 565 uint32_t nqh = 32, nkv = 8, bs = 16, layers = 2, layer = 1; 566 const uint32_t cx[2] = { 1000, 100 }; 567 for (int ci = 0; ci < 2; ci++) { 568 uint32_t ctx = cx[ci], nblk = (ctx + bs - 1) / bs, pool_blocks = nblk + 3; 569 OmegaGpuKvLayout ly = layout_for(pool_blocks, bs, layers, nkv, hd); 570 uint8_t *pool = malloc(ly.pool_bytes); uint16_t *pw = (uint16_t *)pool; 571 for (size_t i = 0; i < ly.pool_bytes / 2; i++) pw[i] = f2bf(frand(&seed, -1.0f, 1.0f)); 572 uint32_t *ids = malloc(nblk * 4); 573 for (uint32_t b = 0; b < nblk; b++) ids[b] = (b * 5 + 1) % pool_blocks; 574 size_t n = (size_t)nqh * hd; 575 float *q = malloc(n * 4), *got = malloc(n * 4), *want = malloc(n * 4), *auto_got = malloc(n * 4); 576 for (size_t i = 0; i < n; i++) q[i] = frand(&seed, -1.0f, 1.0f); 577 oracle_paged(q, pool, &ly, ids, nblk, ctx, layer, nqh, nkv, hd, want); 578 PagedCtx pc = { q, pool, &ly, ids, nblk, ctx, layer, nqh, nkv }; 579 OmegaGpuAttnInfo ai; 580 int arc = run_paged(&pc, auto_got, &ai); 581 uint32_t chunks = (ctx + hd - 1) / hd, want_log2 = 0; 582 const uint32_t gcta = nqh / omega_gpu_attention_heads_per_cta(hd, 2); /* CTAs per split: cut K groups 4 heads per CTA at hd 128 */ 583 while (want_log2 < OMEGA_GPU_ATTN_MAX_LOG2SPLIT && (2u << want_log2) <= chunks) want_log2++; 584 CHECK(arc == OMEGA_GPU_ATTN_OK && ai.ctas_last_launch == (gcta << want_log2), 585 "split auto ctx %u: rc=%s ctas=%u (expected %u)", ctx, omega_gpu_attention_rc_name(arc), ai.ctas_last_launch, gcta << want_log2); 586 for (int ls = 0; ls <= (int)OMEGA_GPU_ATTN_MAX_LOG2SPLIT; ls++) { 587 set_split(ls); 588 OmegaGpuAttnInfo fi; 589 char name[96]; snprintf(name, sizeof name, "paged_bf16_split%d_32q8kv_ctx%u", 1 << ls, ctx); 590 Case c = { .name = strdup(name), .n = n }; 591 c.rc = run_paged(&pc, got, &fi); 592 c.bad = compare(got, want, n, 2e-4, 2e-5, &c.worst); 593 c.pass = c.rc == OMEGA_GPU_ATTN_OK && c.bad == 0; case_info(&c, &fi); 594 CHECK(fi.ctas_last_launch == (gcta << ls) && fi.out_bytes == (uint64_t)nqh * (1u << ls) * (hd + 2) * 4, 595 "%s: ctas=%u out_bytes=%llu", name, fi.ctas_last_launch, (unsigned long long)fi.out_bytes); 596 if ((uint32_t)ls >= want_log2) CHECK(memcmp(got, auto_got, n * 4) == 0, "%s equals the automatic choice bit for bit (a larger launch split only adds empty partials)", name); 597 if (ls == 1 && ci == 0) { 598 static const int ms[3] = { OMEGA_GPU_ATTN_MUTANT_KV_HEAD, OMEGA_GPU_ATTN_MUTANT_SLOT, 0 }; 599 run_mutants(&c, ms, run_paged, &pc, got, want, n, 2e-4, 2e-5); 600 } else run_mutants(&c, no_mutants, run_paged, &pc, got, want, n, 2e-4, 2e-5); 601 record(c, out); 602 } 603 set_split(-1); 604 if (ci == 1 && chunks == 1) CHECK(ai.ctas_last_launch == gcta, "ctx %u: one chunk stays unsplit (%u CTAs)", ctx, ai.ctas_last_launch); 605 else if (ci == 1) CHECK(ai.ctas_last_launch == (gcta << want_log2), "ctx %u: %u chunks -> %u splits (%u CTAs)", ctx, chunks, 1u << want_log2, ai.ctas_last_launch); 606 free(pool); free(ids); free(q); free(got); free(want); free(auto_got); 607 } 608 } 609 /* 4. batch: three sequences (short, empty, truncated by its table), a negative table entry, table rows of 16 */ 610 { 611 uint32_t nqh = 32, nkv = 8, bs = 16, layers = 3, layer = 2, maxb = 16, nseq = 3, pool_blocks = 40; 612 OmegaGpuKvLayout ly = layout_for(pool_blocks, bs, layers, nkv, hd); 613 uint8_t *pool = malloc(ly.pool_bytes); uint16_t *pw = (uint16_t *)pool; 614 for (size_t i = 0; i < ly.pool_bytes / 2; i++) pw[i] = f2bf(frand(&seed, -1.0f, 1.0f)); 615 int32_t *tables = malloc((size_t)nseq * maxb * 4); 616 for (size_t i = 0; i < (size_t)nseq * maxb; i++) tables[i] = -1; 617 /* seq 0: ctx 40 over blocks 5, 17 (-1 in the middle closes up), 29 */ 618 tables[0] = 5; tables[1] = -1; tables[2] = 17; tables[3] = 29; 619 /* seq 1: ctx 0 with a table */ 620 tables[maxb + 0] = 1; 621 /* seq 2: ctx 100 but only 4 blocks (64 tokens used) */ 622 tables[2 * maxb + 0] = 30; tables[2 * maxb + 1] = 2; tables[2 * maxb + 2] = 33; tables[2 * maxb + 3] = 11; 623 int32_t ctxs2[3] = { 40, 0, 100 }; 624 size_t n = (size_t)nseq * nqh * hd; 625 float *q = malloc(n * 4), *got = malloc(n * 4), *want = malloc(n * 4); 626 for (size_t i = 0; i < n; i++) q[i] = frand(&seed, -1.0f, 1.0f); 627 oracle_batch(q, pool, &ly, tables, ctxs2, maxb, nseq, layer, nqh, nkv, hd, want); 628 Case c = { .name = "paged_bf16_batch_3seq_32q8kv_ctx40_0_100", .n = n }; 629 OmegaGpuAttnInfo info; BatchCtx bc = { q, pool, &ly, tables, ctxs2, maxb, nseq, layer, nqh, nkv }; 630 c.rc = run_batch(&bc, got, &info); 631 c.bad = compare(got, want, n, 2e-4, 2e-5, &c.worst); 632 c.pass = c.rc == OMEGA_GPU_ATTN_OK && c.bad == 0; case_info(&c, &info); 633 int zeros = 1; for (size_t i = 0; i < (size_t)nqh * hd; i++) if (got[(size_t)nqh * hd + i] != 0.0f) zeros = 0; 634 CHECK(zeros, "batch: the empty sequence is all zeros"); 635 batch_single_repeat_checks(c.name, &bc, got, &c); 636 static const int ms[5] = { OMEGA_GPU_ATTN_MUTANT_KV_HEAD, OMEGA_GPU_ATTN_MUTANT_SLOT, OMEGA_GPU_ATTN_MUTANT_Q_ROW, OMEGA_GPU_ATTN_MUTANT_OUT_ROW, 0 }; 637 run_mutants(&c, ms, run_batch, &bc, got, want, n, 2e-4, 2e-5); 638 /* all 7 referenced blocks are distinct here, so dedupe stages exactly the naive figure */ 639 CHECK(c.blk_logical == 7 && c.blk_unique == 7 && c.kv_staged == c.kv_naive && c.kv_staged == 7ull * ly.layer_stride_bytes, "batch: 7 distinct blocks staged once each (%u/%u, %" PRIu64 " bytes)", c.blk_unique, c.blk_logical, c.kv_staged); 640 record(c, out); free(pool); free(tables); free(q); free(got); free(want); 641 } 642 /* 5. branch-heavy batch (attention hardening cut): four sequences share the same 10 physical 643 * prefix blocks (160 tokens, scattered ids) and own private tails of 1..3 blocks ending in a 644 * partial 64-token chunk. The shared prefix must be staged once per launch, keyed by the 645 * physical block id. Two head shapes: 8q/2kv puts all four sequences in one launch 646 * (unique = 10 + 9 tails), 32q/8kv splits them two per launch (unique = 2*10 + 9). 647 * Negative control: the legacy per-sequence staging (test hook) copies the prefix four 648 * times and the byte-reduction check must flag it. */ 649 for (int sh = 0; sh < 2; sh++) { 650 uint32_t nqh = sh ? 32 : 8, nkv = sh ? 8 : 2, bs = 16, layers = 2, layer = 1, nseq = 4, prefix_blocks = 10, pool_blocks = 64; 651 uint32_t expect_unique = sh ? 2 * prefix_blocks + 9 : prefix_blocks + 9; 652 uint32_t maxb = prefix_blocks + 3; 653 OmegaGpuKvLayout ly = layout_for(pool_blocks, bs, layers, nkv, hd); 654 uint8_t *pool = malloc(ly.pool_bytes); uint16_t *pw = (uint16_t *)pool; 655 for (size_t i = 0; i < ly.pool_bytes / 2; i++) pw[i] = f2bf(frand(&seed, -1.0f, 1.0f)); 656 int32_t *tables = malloc((size_t)nseq * maxb * 4); 657 for (size_t i = 0; i < (size_t)nseq * maxb; i++) tables[i] = -1; 658 const uint32_t tails[4] = { 1, 2, 3, 3 }; /* private blocks per sequence: 9 in all */ 659 const int32_t ctxs5[4] = { 165, 180, 193, 207 }; /* 160 + 5, 20, 33, 47: every last chunk partial */ 660 for (uint32_t s = 0; s < nseq; s++) { 661 for (uint32_t b = 0; b < prefix_blocks; b++) tables[s * maxb + b] = (int32_t)((b * 5 + 7) % pool_blocks); /* same scattered physical prefix */ 662 for (uint32_t b = 0; b < tails[s]; b++) tables[s * maxb + prefix_blocks + b] = (int32_t)(50 + s * 3 + b); /* private, distinct */ 663 } 664 size_t n = (size_t)nseq * nqh * hd; 665 float *q = malloc(n * 4), *got = malloc(n * 4), *want = malloc(n * 4), *legacy = malloc(n * 4); 666 for (size_t i = 0; i < n; i++) q[i] = frand(&seed, -1.0f, 1.0f); 667 oracle_batch(q, pool, &ly, tables, ctxs5, maxb, nseq, layer, nqh, nkv, hd, want); 668 char name[96]; snprintf(name, sizeof name, "paged_bf16_shared_prefix_4seq_%uq%ukv_10pre", nqh, nkv); 669 Case c = { .name = strdup(name), .n = n }; 670 OmegaGpuAttnInfo info; BatchCtx bc = { q, pool, &ly, tables, ctxs5, maxb, nseq, layer, nqh, nkv }; 671 c.rc = run_batch(&bc, got, &info); 672 c.bad = compare(got, want, n, 2e-4, 2e-5, &c.worst); 673 c.pass = c.rc == OMEGA_GPU_ATTN_OK && c.bad == 0; case_info(&c, &info); 674 uint32_t logical = 4 * prefix_blocks + 9; 675 CHECK(c.blk_logical == logical && c.blk_unique == expect_unique, "%s: %u logical references, %u unique staged (expected %u/%u)", name, c.blk_logical, c.blk_unique, logical, expect_unique); 676 CHECK(c.kv_naive == (uint64_t)logical * ly.layer_stride_bytes && c.kv_staged == (uint64_t)expect_unique * ly.layer_stride_bytes && c.kv_staged < c.kv_naive, 677 "%s: staged %" PRIu64 " < naive %" PRIu64 " bytes (saved %" PRIu64 ")", name, c.kv_staged, c.kv_naive, c.kv_naive - c.kv_staged); 678 /* cut F: the output traffic is the partials, launch split = the largest own split in the call (cut J: hd 64: ctx 193 and 207 are 4 chunks, 4 splits; hd 128: 2 chunks, 2 splits) */ 679 uint32_t ls_max = 0; 680 for (uint32_t s = 0; s < nseq; s++) { uint32_t x = ((uint32_t)ctxs5[s] + hd - 1) / hd, l = 0; while (l < OMEGA_GPU_ATTN_MAX_LOG2SPLIT && (2u << l) <= x) l++; if (l > ls_max) ls_max = l; } 681 const uint64_t out_expect = (uint64_t)nseq * nqh * (1u << ls_max) * (hd + 2) * 4; 682 CHECK(info.kv_source == OMEGA_GPU_ATTN_KV_STAGED && info.q_bytes == n * 4 && info.out_bytes == out_expect && info.tab_bytes > 0, "%s: q/out/table traffic accounted (q=%" PRIu64 " out=%" PRIu64 " tab=%" PRIu64 ")", name, info.q_bytes, info.out_bytes, info.tab_bytes); 683 /* negative control: legacy per-sequence staging duplicates the shared prefix; same answer, more bytes */ 684 omega_gpu_attention_test_set_dedupe(false); 685 OmegaGpuAttnInfo li; int lrc = run_batch(&bc, legacy, &li); 686 omega_gpu_attention_test_set_dedupe(true); 687 double lw; size_t lbad = compare(legacy, want, n, 2e-4, 2e-5, &lw); 688 CHECK(lrc == OMEGA_GPU_ATTN_OK && lbad == 0, "%s legacy staging: parity (rc=%s bad=%zu)", name, omega_gpu_attention_rc_name(lrc), lbad); 689 CHECK(li.kv_blocks_unique == logical && li.kv_bytes_staged == li.kv_bytes_naive && li.kv_bytes_staged > c.kv_staged, 690 "%s negative control: duplicated prefix staging is flagged (legacy staged %" PRIu64 " == naive %" PRIu64 ", dedupe %" PRIu64 ")", name, li.kv_bytes_staged, li.kv_bytes_naive, c.kv_staged); 691 CHECK(memcmp(got, legacy, n * 4) == 0, "%s: dedupe and legacy staging are bit-identical", name); 692 batch_single_repeat_checks(name, &bc, got, &c); 693 static const int ms5[3] = { OMEGA_GPU_ATTN_MUTANT_KV_HEAD, OMEGA_GPU_ATTN_MUTANT_SLOT, 0 }; 694 run_mutants(&c, ms5, run_batch, &bc, got, want, n, 2e-4, 2e-5); 695 record(c, out); free(pool); free(tables); free(q); free(got); free(want); free(legacy); 696 } 697 /* every mutant the API knows (1 .. COUNT-1) ran at least once and was caught every time; 698 * a mutant added to the enum without a battery entry fails here */ 699 for (int m = 1; m < OMEGA_GPU_ATTN_MUTANT_COUNT; m++) { 700 CHECK(g_mutant_run[m] > 0 && g_mutant_caught[m] == g_mutant_run[m], "mutant %s caught %d of %d runs", mutant_name(m), g_mutant_caught[m], g_mutant_run[m]); 701 printf("mutant %s: caught %d of %d\n", mutant_name(m), g_mutant_caught[m], g_mutant_run[m]); 702 } 703 CHECK(omega_gpu_session_open_count() == (g_sim_mode ? 0u : 1u), "device opened %s for the battery (opens=%u)", g_sim_mode ? "never (simulator)" : "once", omega_gpu_session_open_count()); 704 printf("device_opens=%u\n", omega_gpu_session_open_count()); 705 if (out) { 706 fprintf(out, "],\"mutant_count\":%d,\"mutants\":{", OMEGA_GPU_ATTN_MUTANT_COUNT - 1); 707 for (int m = 1; m < OMEGA_GPU_ATTN_MUTANT_COUNT; m++) fprintf(out, "%s\"%s\":{\"run\":%d,\"caught\":%d}", m > 1 ? "," : "", mutant_name(m), g_mutant_run[m], g_mutant_caught[m]); 708 fprintf(out, "},\"device_opens\":%u,\"checks\":%d,\"failed\":%d,\"verdict\":\"%s\"}\n", omega_gpu_session_open_count(), g_checks, g_failed, g_failed == 0 ? "OMEGA_GPU_ATTENTION_PASS" : "OMEGA_GPU_ATTENTION_FAIL"); 709 fclose(out); 710 } 711 return 0; 712 } 713 714 /* ------------------------------------------------------------ host simulator 715 * Executes the allocated IR program (physical registers, so the register allocator's 716 * loop handling is under test too) for every CTA of a launch: 64 threads, 1 KB shared, 717 * host pointers as addresses, SHFL and BAR as lockstep points (all threads of the CTA 718 * must sit at the same instruction). EX2 and RCP are exact here; the chip's are approximate. */ 719 /* path: hash of every branch decision so far. The attention kernels use no reconvergence 720 * region (the IR has BSSY/BSYNC since omega #310, omega_bw_reconv.h; the --divergent mode 721 * below covers them), so once a warp splits it may stay split on the chip, and a 722 * SHFL reading an inactive lane is undefined (CUDA guide, warp shuffle functions). Every 723 * SHFL therefore requires one path across the warp, or the simulator stops with error 7. */ 724 typedef struct { uint32_t r[256]; int pc; int p0; int done; uint64_t path; } SimThr; 725 static uint32_t sim_cbank[256]; 726 static uint8_t sim_shared[8192]; 727 #define SIM_TMAX 128 728 #define SIM_T ((int)g_hd) /* threads per CTA = head_dim */ 729 static uint32_t g_smem_cap; /* negative control: pretend the QMD declared this many bytes (0 = the real 16 * head_dim) */ 730 #define SIM_SMEM (g_smem_cap ? g_smem_cap : omega_gpu_attention_test_shared_bytes()) /* the shared memory the QMD declares for this kernel (launcher: shared_bytes_for) */ 731 static int g_sim_err; 732 static int g_trace, g_trace_launch; static uint32_t g_trace_cx; 733 static uint32_t rd(const SimThr *t, int v, const BlackwellIRProgram *p) { if (v < 0) return 0; int ph = p->regalloc.vreg_to_phys[v]; return ph < 0 ? 0 : t->r[ph & 0xff]; } 734 static uint64_t rd64(const SimThr *t, int v, const BlackwellIRProgram *p) { if (v < 0) return 0; int ph = p->regalloc.vreg_to_phys[v] & 0xff; return (uint64_t)t->r[ph] | ((uint64_t)t->r[ph + 1] << 32); } 735 static void wr(SimThr *t, int v, uint32_t x, const BlackwellIRProgram *p) { if (v < 0) return; int ph = p->regalloc.vreg_to_phys[v]; if (ph >= 0) t->r[ph & 0xff] = x; } 736 static void wr64(SimThr *t, int v, uint64_t x, const BlackwellIRProgram *p) { if (v < 0) return; int ph = p->regalloc.vreg_to_phys[v] & 0xff; t->r[ph] = (uint32_t)x; t->r[ph + 1] = (uint32_t)(x >> 32); } 737 static uint32_t rds(const SimThr *t, int v, unsigned sub, const BlackwellIRProgram *p) { if (v < 0) return 0; int ph = p->regalloc.vreg_to_phys[v]; return ph < 0 ? 0 : t->r[(ph + sub) & 0xff]; } 738 static void wrs(SimThr *t, int v, unsigned sub, uint32_t x, const BlackwellIRProgram *p) { if (v < 0) return; int ph = p->regalloc.vreg_to_phys[v]; if (ph >= 0) t->r[(ph + sub) & 0xff] = x; } 739 static float u2f(uint32_t u) { float f; memcpy(&f, &u, 4); return f; } 740 static uint32_t f2u_(float f) { uint32_t u; memcpy(&u, &f, 4); return u; } 741 /* run one thread until it reaches a SHFL or BAR (not executed) or EXIT; returns 1 if parked at a sync op */ 742 static int sim_step(SimThr *t, const BlackwellIRProgram *p, uint32_t tid, uint32_t cx, uint32_t cy) { 743 for (int guard = 0; guard < `50000000`; guard++) { 744 if (t->done) return 0; 745 if (t->pc < 0 || (size_t)t->pc >= p->count) { g_sim_err = 1; t->done = 1; return 0; } 746 const BlackwellIRInsn *in = &p->insns[t->pc]; 747 uint32_t a = rds(t, in->src1_vreg, in->src1_subreg, p), b = rds(t, in->src2_vreg, in->src2_subreg, p), c = rds(t, in->src3_vreg, in->src3_subreg, p); 748 switch (in->op) { 749 case BW_IR_SHFL_DOWN: case BW_IR_BAR_SYNC: return 1; 750 case BW_IR_EXIT: if (!in->predicate_p0 || t->p0) { t->done = 1; return 0; } break; 751 case BW_IR_BRA: { 752 int take = !in->predicate_p0 || (in->predicate_not ? !t->p0 : t->p0); 753 t->path = t->path * 1000003u + (((uint64_t)t->pc << 1) | (uint64_t)take); 754 if (take) { if ((int32_t)in->imm == 0) { g_sim_err = 2; t->done = 1; return 0; } t->pc += (int32_t)in->imm; continue; } 755 break; } 756 case BW_IR_MOV_IMM: wrs(t, in->dst_vreg, in->dst_subreg, in->imm, p); break; 757 case BW_IR_MOV_RZ: wrs(t, in->dst_vreg, in->dst_subreg, 0, p); break; 758 case BW_IR_S2R: wrs(t, in->dst_vreg, in->dst_subreg, in->imm == BW_SR_TID_X ? tid : in->imm == BW_SR_CTAID_X ? cx : in->imm == BW_SR_CTAID_Y ? cy : 0, p); break; 759 case BW_IR_LDC: wrs(t, in->dst_vreg, in->dst_subreg, sim_cbank[in->imm / 4], p); break; 760 case BW_IR_LDC64: wr64(t, in->dst_vreg, (uint64_t)sim_cbank[in->imm / 4] | ((uint64_t)sim_cbank[in->imm / 4 + 1] << 32), p); break; 761 case BW_IR_LDCU64: break; /* memory descriptor: not modelled */ 762 case BW_IR_IMAD: wrs(t, in->dst_vreg, in->dst_subreg, in->src2_vreg >= 0 ? a * b + c : a * in->imm + c, p); break; 763 case BW_IR_IMAD_WIDE: wr64(t, in->dst_vreg, (uint64_t)a * in->imm + rd64(t, in->src3_vreg, p), p); break; 764 case BW_IR_IADD3: wrs(t, in->dst_vreg, in->dst_subreg, a + b, p); break; 765 case BW_IR_SHF_R: wrs(t, in->dst_vreg, in->dst_subreg, a >> (in->imm & 31), p); break; 766 case BW_IR_LOP3_AND: wrs(t, in->dst_vreg, in->dst_subreg, a & in->imm, p); break; 767 case BW_IR_LOP3_XOR: wrs(t, in->dst_vreg, in->dst_subreg, a ^ b, p); break; 768 case BW_IR_ISETP_GE_U32: t->p0 = a >= b; break; 769 case BW_IR_LDG_E: { uint32_t x; memcpy(&x, (const void *)(uintptr_t)(rd64(t, in->src1_vreg, p) + (uint64_t)(int64_t)(int32_t)in->imm), 4); wrs(t, in->dst_vreg, in->dst_subreg, x, p); break; } 770 case BW_IR_LDG_E_U16: { uint16_t x; memcpy(&x, (const void *)(uintptr_t)rd64(t, in->src1_vreg, p), 2); wrs(t, in->dst_vreg, in->dst_subreg, x, p); break; } 771 case BW_IR_STG_E: memcpy((void *)(uintptr_t)rd64(t, in->src1_vreg, p), &b, 4); break; 772 case BW_IR_LDG_E_64: case BW_IR_LDG_E_128: { unsigned n = in->op == BW_IR_LDG_E_64 ? 8u : 16u; uint64_t ad = rd64(t, in->src1_vreg, p) + (uint64_t)(int64_t)(int32_t)in->imm; if (ad & (n - 1)) { g_sim_err = 5; t->done = 1; return 0; } uint32_t x[4]; memcpy(x, (const void *)(uintptr_t)ad, n); for (unsigned i = 0; i < n / 4; i++) wrs(t, in->dst_vreg, i, x[i], p); break; } 773 case BW_IR_LDS128: { uint32_t ad = a + in->imm; if ((ad & 15u) || ad + 16 > SIM_SMEM) { g_sim_err = 3; t->done = 1; return 0; } for (unsigned i = 0; i < 4; i++) { uint32_t x; memcpy(&x, sim_shared + ad + 4u * i, 4); wrs(t, in->dst_vreg, i, x, p); } break; } 774 case BW_IR_LDS32: { uint32_t x; if (a + 4 > SIM_SMEM) { g_sim_err = 3; t->done = 1; return 0; } memcpy(&x, sim_shared + a, 4); wrs(t, in->dst_vreg, in->dst_subreg, x, p); break; } 775 case BW_IR_STS32: if (a + 4 > SIM_SMEM) { g_sim_err = 3; t->done = 1; return 0; } memcpy(sim_shared + a, &b, 4); break; 776 case BW_IR_FADD: wrs(t, in->dst_vreg, in->dst_subreg, f2u_(u2f(a) + u2f(b)), p); break; 777 case BW_IR_FSUB: wrs(t, in->dst_vreg, in->dst_subreg, f2u_(u2f(a) - u2f(b)), p); break; 778 case BW_IR_FMUL: wrs(t, in->dst_vreg, in->dst_subreg, f2u_(u2f(a) * u2f(b)), p); break; 779 case BW_IR_FFMA: wrs(t, in->dst_vreg, in->dst_subreg, f2u_(fmaf(u2f(a), u2f(b), u2f(c))), p); break; 780 case BW_IR_FMNMX_MAX: wrs(t, in->dst_vreg, in->dst_subreg, f2u_(fmaxf(u2f(a), u2f(b))), p); break; 781 case BW_IR_MUFU_EX2: wrs(t, in->dst_vreg, in->dst_subreg, f2u_(ws_mufu_ex2(u2f(a))), p); break; /* bw_mufu_ftz.h (#462) */ 782 case BW_IR_MUFU_RCP: wrs(t, in->dst_vreg, in->dst_subreg, f2u_(ws_mufu_rcp(u2f(a))), p); break; 783 default: g_sim_err = 100 + (int)in->op; t->done = 1; return 0; 784 } 785 if (g_trace && tid == 0 && cx == g_trace_cx && cy == 0 && g_trace_launch == 1) { uint32_t dv = rd(t, in->dst_vreg, p); printf("T pc=%d op=%d dst=v%d(r%d)=%08x f=%g p0=%d a=%08x b=%08x c=%08x\n", t->pc, (int)in->op, in->dst_vreg, in->dst_vreg >= 0 ? p->regalloc.vreg_to_phys[in->dst_vreg] : -1, dv, u2f(dv), t->p0, a, b, c); } 786 t->pc++; 787 } 788 g_sim_err = 4; t->done = 1; return 0; 789 } 790 /* omega #462: this per-thread simulator's MUFU cases follow the chip's flush rule (tests/bw_mufu_ftz.h). One MUFU then 791 * EXIT through sim_step: a subnormal EX2 / RCP result is a zero of the same sign, a subnormal RCP input is a zero (so the 792 * result is an infinity), normals unchanged. Reachable in the kernel: softmax EX2 of a score more than 126 below the 793 * running max (log2 units) is subnormal in IEEE and 0 on the chip. */ 794 static void mufu_ftz_sim_check(void) { 795 static BlackwellIRProgram p; 796 static const struct { BlackwellIROpcode op; uint32_t in, want; } c[] = { 797 { BW_IR_MUFU_EX2, 0xc3020000u /* -130 */, 0x00000000u }, { BW_IR_MUFU_EX2, 0xc2fc0000u /* -126 */, 0x00800000u }, 798 { BW_IR_MUFU_RCP, 0x7f400000u /* 1.5 * 2^127 */, 0x00000000u }, { BW_IR_MUFU_RCP, 0xff400000u, 0x80000000u }, 799 { BW_IR_MUFU_RCP, 0x00400000u /* 2^-127 */, 0x7f800000u }, { BW_IR_MUFU_RCP, 0x7e800000u /* 2^126 */, 0x00800000u }, 800 }; 801 memset(&p, 0, sizeof p); 802 p.count = 2; p.regalloc.vreg_to_phys[0] = 0; p.regalloc.vreg_to_phys[1] = 1; 803 for (int i = 0; i < 2; i++) { p.insns[i].dst_vreg = p.insns[i].src1_vreg = p.insns[i].src2_vreg = p.insns[i].src3_vreg = p.insns[i].ureg = -1; } 804 p.insns[1].op = BW_IR_EXIT; 805 for (size_t i = 0; i < sizeof c / sizeof c[0]; i++) { 806 SimThr t; memset(&t, 0, sizeof t); 807 p.insns[0].op = c[i].op; p.insns[0].dst_vreg = 0; p.insns[0].src1_vreg = 1; 808 t.r[1] = c[i].in; t.r[0] = 0xdeadbeefu; g_sim_err = 0; 809 sim_step(&t, &p, 0, 0, 0); 810 CHECK(g_sim_err == 0 && t.r[0] == c[i].want, "attention sim MUFU %s(0x%08x) = 0x%08x, chip rule 0x%08x (omega #462)", 811 c[i].op == BW_IR_MUFU_EX2 ? "EX2" : "RCP", c[i].in, t.r[0], c[i].want); 812 } 813 } 814 static int sim_launch(const void *progv, const OmegaGpuAttnLaunch *L, OmegaGpuAttnInfo *info) { 815 const BlackwellIRProgram *p = progv; 816 memset(sim_cbank, 0, sizeof sim_cbank); 817 uint64_t qa = (uintptr_t)L->q, pa = (uintptr_t)L->pool, oa = (uintptr_t)L->out, ta = (uintptr_t)L->tab; 818 sim_cbank[0x380 / 4] = (uint32_t)qa; sim_cbank[0x380 / 4 + 1] = (uint32_t)(qa >> 32); 819 sim_cbank[0x388 / 4] = (uint32_t)pa; sim_cbank[0x388 / 4 + 1] = (uint32_t)(pa >> 32); 820 sim_cbank[0x390 / 4] = (uint32_t)oa; sim_cbank[0x390 / 4 + 1] = (uint32_t)(oa >> 32); 821 sim_cbank[0x398 / 4] = (uint32_t)ta; sim_cbank[0x398 / 4 + 1] = (uint32_t)(ta >> 32); 822 memcpy(&sim_cbank[0x3a0 / 4], L->params, sizeof L->params); 823 uint32_t *outw = L->out; for (size_t i = 0; i < L->out_bytes / 4; i++) outw[i] = 0xffbadbadu; 824 g_sim_err = 0; 825 static SimThr th[SIM_TMAX]; 826 g_trace_launch++; if (getenv("ATTN_SIM_TRACE")) { g_trace = 1; g_trace_cx = (uint32_t)atoi(getenv("ATTN_SIM_TRACE")); } 827 for (uint32_t cy = 0; cy < L->grid_y && !g_sim_err; cy++) for (uint32_t cx = 0; cx < L->grid_x && !g_sim_err; cx++) { 828 memset(th, 0, sizeof th); memset(sim_shared, 0, sizeof sim_shared); 829 for (;;) { 830 int parked = 0, alive = 0; 831 for (int i = 0; i < SIM_T; i++) { if (th[i].done) continue; alive++; parked += sim_step(&th[i], p, (uint32_t)i, cx, cy); } 832 if (g_sim_err) break; 833 if (alive == 0) break; 834 if (parked == 0) continue; /* every live thread exited this round */ 835 if (parked != alive) { g_sim_err = 5; break; } /* a thread exited while others wait at a barrier */ 836 int pc = -1; 837 for (int i = 0; i < SIM_T; i++) if (!th[i].done) { if (pc < 0) pc = th[i].pc; else if (th[i].pc != pc) g_sim_err = 6; } 838 if (g_sim_err) break; 839 const BlackwellIRInsn *in = &p->insns[pc]; 840 if (in->op == BW_IR_SHFL_DOWN) { 841 for (int i = 0; i < SIM_T; i++) if (!th[i].done && !th[i & ~31].done && th[i].path != th[i & ~31].path) g_sim_err = 7; 842 if (g_sim_err) break; 843 uint32_t src[SIM_TMAX]; 844 for (int i = 0; i < SIM_T; i++) src[i] = rd(&th[i], in->src1_vreg, p); 845 for (int i = 0; i < SIM_T; i++) { int lane = i & 31, from = lane + (int)(in->imm & 31); wr(&th[i], in->dst_vreg, from < 32 ? src[(i & ~31) + from] : src[i], p); } 846 } 847 for (int i = 0; i < SIM_T; i++) th[i].pc++; 848 } 849 } 850 uint32_t unwritten = 0; for (size_t i = 0; i < L->out_bytes / 4; i++) if (outw[i] == 0xffbadbadu) unwritten++; 851 if (info) { info->chip_calls++; info->unwritten_words += unwritten; info->ctas_last_launch = L->grid_x * L->grid_y; info->threads_per_cta = SIM_T; } 852 if (g_sim_err) { printf("simulator error %d\n", g_sim_err); return OMEGA_GPU_ATTN_CHIP_FAIL; } 853 return unwritten ? OMEGA_GPU_ATTN_UNWRITTEN : OMEGA_GPU_ATTN_OK; 854 } 855 856 857 /* ---------------------------------------------------- timing (cut 4b) */ 858 /* One query step of TinyLlama attention at context 2048 (32 q heads, 4 kv heads, 859 * f32 KV) 100 times through the persistent session, every call checked against the 860 * oracle; gate: median wall time per call under 3 ms, one device open per process. */ 861 static double now_ms(void) { struct timespec t; clock_gettime(CLOCK_MONOTONIC, &t); return t.tv_sec * 1e3 + t.tv_nsec / 1e6; } 862 static int cmp_d(const void *a, const void *b) { double x = *(const double *)a, y = *(const double *)b; return x < y ? -1 : x > y; } 863 /* --split-timing: the paged bf16 decode shape (32 q / 8 kv heads at the current head_dim, one sequence, context 864 * ATTN_SPLIT_CTX, default 1268: the campaign's document tasks) through the persistent session, 100 calls per 865 * forced launch split 1, 2, 4, 8 and the automatic choice; median wall and mean chip time per call, every call 866 * against the oracle. A measurement for the decode-speed work (2026-10-12): whether the kernel's time at this 867 * context falls with more CTAs per (sequence, head) or stays flat (bandwidth bound: the four query heads of a 868 * kv head each read its slice). */ 869 static int split_timing(const char *out_path) { 870 FILE *out = out_path ? create_0644(out_path) : NULL; 871 if (out_path && !out) { printf("cannot open %s\n", out_path); return 2; } 872 enum { N = 100 }; 873 const uint32_t hd = g_hd, nqh = 32, nkv = 8, bs = 16, layers = 2, layer = 1; 874 const char *ce = getenv("ATTN_SPLIT_CTX"); 875 const uint32_t ctx = ce && atoi(ce) > 0 ? (uint32_t)atoi(ce) : 1268u; 876 const uint32_t nblk = (ctx + bs - 1) / bs, pool_blocks = nblk + 3; 877 uint32_t seed = 0x5b17c0deu; 878 OmegaGpuKvLayout ly = layout_for(pool_blocks, bs, layers, nkv, hd); 879 uint8_t *pool = malloc(ly.pool_bytes); uint16_t *pw = (uint16_t *)pool; 880 for (size_t i = 0; i < ly.pool_bytes / 2; i++) pw[i] = f2bf(frand(&seed, -1.0f, 1.0f)); 881 uint32_t *ids = malloc(nblk * 4); 882 for (uint32_t b = 0; b < nblk; b++) ids[b] = (b * 5 + 1) % pool_blocks; 883 const size_t n = (size_t)nqh * hd; 884 float *q = malloc(n * 4), *got = malloc(n * 4), *want = malloc(n * 4); 885 for (size_t i = 0; i < n; i++) q[i] = frand(&seed, -1.0f, 1.0f); 886 oracle_paged(q, pool, &ly, ids, nblk, ctx, layer, nqh, nkv, hd, want); 887 PagedCtx pc = { q, pool, &ly, ids, nblk, ctx, layer, nqh, nkv }; 888 if (out) fprintf(out, "{\"schema\":\"OMEGA_GPU_ATTENTION_SPLIT_TIMING_V1\",\"hd\":%u,\"ctx\":%u,\"calls\":%d,\"spin_us\":%u,\"cases\":[", 889 hd, ctx, N, omega_gpu_session_spin_us()); 890 int first = 1; 891 for (int ls = -1; ls <= (int)OMEGA_GPU_ATTN_MAX_LOG2SPLIT; ls++) { 892 set_split(ls); 893 OmegaGpuAttnInfo info; 894 int rc0 = run_paged(&pc, got, &info); /* warm-up: opens the device, generates this split's kernel */ 895 CHECK(rc0 == OMEGA_GPU_ATTN_OK, "split-timing split=%d first call rc=%s err=\"%s\"", ls, omega_gpu_attention_rc_name(rc0), omega_gpu_attention_last_error()); 896 double samples[N]; int ok_calls = 0; size_t bad_total = 0; double worst = 0; uint64_t chip_sum = 0; 897 for (int i = 0; i < N; i++) { 898 double t0 = now_ms(); 899 int rc = run_paged(&pc, got, &info); 900 samples[i] = now_ms() - t0; 901 double w; size_t bad = compare(got, want, n, 2e-4, 2e-5, &w); 902 if (w > worst) worst = w; 903 bad_total += bad; chip_sum += info.elapsed_ns; 904 if (rc == OMEGA_GPU_ATTN_OK && bad == 0) ok_calls++; 905 } 906 qsort(samples, N, sizeof samples[0], cmp_d); 907 const double median = samples[N / 2], p90 = samples[N * 9 / 10], mn = samples[0], mx = samples[N - 1]; 908 const int pass = ok_calls == N && bad_total == 0; 909 CHECK(pass, "split-timing split=%d ctx=%u ok_calls=%d/%d violations=%zu", ls, ctx, ok_calls, N, bad_total); 910 printf("%s split-timing split=%s ctas=%u ctx=%u ok_calls=%d/%d worst_scaled_err=%g median_ms=%.3f p90_ms=%.3f min_ms=%.3f max_ms=%.3f chip_us_mean=%.1f\n", 911 pass ? "PASS" : "FAIL", ls < 0 ? "auto" : (const char *[]){ "1", "2", "4", "8", "16" }[ls], info.ctas_last_launch, ctx, ok_calls, N, worst, 912 median, p90, mn, mx, chip_sum / 1e3 / N); 913 if (out) fprintf(out, "%s{\"split\":%d,\"ctas\":%u,\"ok_calls\":%d,\"violations\":%zu,\"worst_scaled_err\":%g,\"median_ms\":%.4f,\"p90_ms\":%.4f,\"min_ms\":%.4f,\"max_ms\":%.4f,\"chip_us_mean\":%.1f,\"pass\":%s}", 914 first ? "" : ",", ls, info.ctas_last_launch, ok_calls, bad_total, worst, median, p90, mn, mx, chip_sum / 1e3 / N, pass ? "true" : "false"); 915 first = 0; 916 } 917 set_split(-1); 918 free(pool); free(ids); free(q); free(got); free(want); 919 if (out) { fprintf(out, "],\"checks\":%d,\"failed\":%d,\"verdict\":\"%s\"}\n", g_checks, g_failed, g_failed == 0 ? "OMEGA_GPU_ATTENTION_SPLIT_TIMING_PASS" : "OMEGA_GPU_ATTENTION_SPLIT_TIMING_FAIL"); fclose(out); } 920 return 0; 921 } 922 923 static int timing(const char *out_path) { 924 FILE *out = out_path ? create_0644(out_path) : NULL; 925 if (out_path && !out) { printf("cannot open %s\n", out_path); return 2; } 926 enum { N = 100 }; 927 const uint32_t hd = 64, nqh = 32, nkv = 4, seq = 2048; 928 const char *name = "gqa_f32_tinyllama_32q4kv_ctx2048"; 929 if (out) fprintf(out, "{\"schema\":\"OMEGA_GPU_ATTENTION_TIMING_V1\",\"gate_median_ms\":3.0,\"calls\":%d,\"cases\":[", N); 930 uint32_t seed = 0xfb1c004bu; 931 size_t n = (size_t)nqh * hd, nkvs = (size_t)seq * nkv * hd; 932 float *q = malloc(n * 4), *kc = malloc(nkvs * 4), *vc = malloc(nkvs * 4), *got = malloc(n * 4), *want = malloc(n * 4); 933 for (size_t i = 0; i < n; i++) q[i] = frand(&seed, -1.0f, 1.0f); 934 for (size_t i = 0; i < nkvs; i++) { kc[i] = frand(&seed, -1.0f, 1.0f); vc[i] = frand(&seed, -1.0f, 1.0f); } 935 oracle_gqa(q, kc, vc, seq, nqh, nkv, hd, want); 936 double samples[N]; int ok_calls = 0; size_t bad_total = 0; double worst = 0; uint64_t chip_sum = 0; int rc_last = 0; 937 OmegaGpuAttnInfo info; 938 /* warm-up: the first call opens the device and generates the kernel (not timed) */ 939 int rc0 = omega_gpu_gqa_attention_f32(q, kc, vc, seq, nqh, nkv, hd, got, &info); 940 double first_ms = info.call_ns / 1e6; 941 CHECK(rc0 == OMEGA_GPU_ATTN_OK, "%s first call rc=%s err=\"%s\"", name, omega_gpu_attention_rc_name(rc0), omega_gpu_attention_last_error()); 942 for (int i = 0; i < N; i++) { 943 double t0 = now_ms(); 944 int rc = omega_gpu_gqa_attention_f32(q, kc, vc, seq, nqh, nkv, hd, got, &info); 945 samples[i] = now_ms() - t0; 946 double w; size_t bad = compare(got, want, n, 2e-4, 2e-5, &w); 947 if (w > worst) worst = w; 948 bad_total += bad; chip_sum += info.elapsed_ns; rc_last = rc; 949 if (rc == OMEGA_GPU_ATTN_OK && bad == 0) ok_calls++; 950 } 951 qsort(samples, N, sizeof samples[0], cmp_d); 952 double median = samples[N / 2], p90 = samples[N * 9 / 10], mn = samples[0], mx = samples[N - 1]; 953 uint32_t opens = omega_gpu_session_open_count(); 954 int pass = ok_calls == N && bad_total == 0 && median < 3.0 && opens == 1; 955 CHECK(pass, "timing %s ok_calls=%d/%d violations=%zu median_ms=%.3f opens=%u last_rc=%s err=\"%s\"", name, ok_calls, N, bad_total, median, opens, omega_gpu_attention_rc_name(rc_last), omega_gpu_attention_last_error()); 956 printf("%s timing %s first_call_ms=%.3f ok_calls=%d/%d violations=%zu worst_scaled_err=%g median_ms=%.3f p90_ms=%.3f min_ms=%.3f max_ms=%.3f chip_us_mean=%.1f device_opens=%u\n", 957 pass ? "PASS" : "FAIL", name, first_ms, ok_calls, N, bad_total, worst, median, p90, mn, mx, chip_sum / 1e3 / N, opens); 958 if (out) fprintf(out, "{\"case\":\"%s\",\"first_call_ms\":%.3f,\"ok_calls\":%d,\"violations\":%zu,\"worst_scaled_err\":%g,\"median_ms\":%.4f,\"p90_ms\":%.4f,\"min_ms\":%.4f,\"max_ms\":%.4f,\"chip_us_mean\":%.1f,\"device_opens\":%u,\"pass\":%s}", 959 name, first_ms, ok_calls, bad_total, worst, median, p90, mn, mx, chip_sum / 1e3 / N, opens, pass ? "true" : "false"); 960 free(q); free(kc); free(vc); free(got); free(want); 961 if (out) { fprintf(out, "],\"checks\":%d,\"failed\":%d,\"verdict\":\"%s\"}\n", g_checks, g_failed, g_failed == 0 ? "OMEGA_GPU_ATTENTION_TIMING_PASS" : "OMEGA_GPU_ATTENTION_TIMING_FAIL"); fclose(out); } 962 return 0; 963 } 964 965 /* ------------------------------------------------ head-scaling sweep (attention hardening cut) 966 * `--sweep [--out sweep.json]`: the production paged bf16 path at head_dim 64 over query-head 967 * counts 1, 2, 4, 8, 16, 24, 32, 64 and every divisor as the kv-head count, at context 256 968 * (latency) and 2048 (bandwidth), block size 16, scattered block ids. Points whose GQA ratio 969 * is not a power of two are mathematically legal (the generic contract allows them) but 970 * outside the current kernel envelope (codegen selects the kv head with a shift): they are 971 * called anyway, must be refused with BAD_ARGS, and are recorded as 972 * "unsupported_by_kernel_envelope" (no chip time). Every supported point is checked against 973 * the host oracle on its first call, then warmed and timed over N calls (median / p90 of the 974 * whole call and of the chip kernel time). Gates: parity, no unwritten word, one device open, 975 * every call OK; the timings are evidence, not a threshold. Only quantities the stack measures 976 * are recorded; SM occupancy, bandwidth utilisation and cache hit rates are not observable 977 * through this path and are reported as unavailable. Under --sim the timings are host-simulator 978 * timings and the receipt says so. */ 979 static int sweep(const char *out_path) { 980 FILE *out = out_path ? create_0644(out_path) : NULL; 981 if (out_path && !out) { printf("cannot open %s\n", out_path); return 2; } 982 const int N = g_sim_mode ? 1 : 20; 983 const uint32_t hd = 64, bs = 16, layers = 1, layer = 0; 984 static const uint32_t qheads[8] = { 1, 2, 4, 8, 16, 24, 32, 64 }; 985 static const uint32_t ctxs[2] = { 256, 2048 }; 986 uint32_t seed = 0xfb1c05eeu; 987 if (out) fprintf(out, "{\"schema\":\"OMEGA_GPU_ATTENTION_SWEEP_V1\",\"path\":\"paged_bf16\",\"head_dim\":%u,\"block_size\":%u,\"timed_calls\":%d,\"host_simulator\":%s," 988 "\"tolerances\":{\"rel\":2e-4,\"abs\":2e-5},\"hardware_counters\":\"unavailable (SM occupancy, bandwidth utilisation, cache hit rates are not observable through this path)\",\"points\":[", 989 hd, bs, N, g_sim_mode ? "true" : "false"); 990 int npoints = 0, supported = 0, unsupported = 0; 991 double *samples = malloc((size_t)N * sizeof *samples), *ksamples = malloc((size_t)N * sizeof *ksamples); 992 for (int qi = 0; qi < 8; qi++) for (uint32_t nkv = 1; nkv <= qheads[qi]; nkv++) { 993 uint32_t nqh = qheads[qi]; 994 if (nqh % nkv) continue; 995 uint32_t ratio = nqh / nkv; int pow2 = (ratio & (ratio - 1)) == 0; 996 for (int ci = 0; ci < 2; ci++) { 997 uint32_t ctx = ctxs[ci], nblk = (ctx + bs - 1) / bs, pool_blocks = nblk + 5; 998 OmegaGpuKvLayout ly = layout_for(pool_blocks, bs, layers, nkv, hd); 999 uint8_t *pool = malloc(ly.pool_bytes); uint16_t *pw = (uint16_t *)pool; 1000 for (size_t i = 0; i < ly.pool_bytes / 2; i++) pw[i] = f2bf(frand(&seed, -1.0f, 1.0f)); 1001 uint32_t *ids = malloc(nblk * 4); 1002 for (uint32_t b = 0; b < nblk; b++) ids[b] = (b * 7 + 3) % pool_blocks; 1003 size_t n = (size_t)nqh * hd; 1004 float *q = malloc(n * 4), *got = malloc(n * 4), *want = malloc(n * 4); 1005 for (size_t i = 0; i < n; i++) q[i] = frand(&seed, -1.0f, 1.0f); 1006 OmegaGpuAttnInfo info; memset(&info, 0, sizeof info); 1007 int rc = omega_gpu_paged_attention_bf16(q, pool, &ly, ids, nblk, ctx, layer, nqh, nkv, hd, got, &info); 1008 const char *klass; int pass; size_t bad = 0; double worst = 0; int ok_calls = 0; uint32_t unwritten = 0, cache_hits = 0; double med = 0, p90 = 0, kmed = 0, kp90 = 0; 1009 if (!pow2) { 1010 klass = "unsupported_by_kernel_envelope"; 1011 pass = rc == OMEGA_GPU_ATTN_BAD_ARGS; unsupported++; 1012 CHECK(pass, "sweep %uq/%ukv ctx %u: ratio %u (not a power of two) refused with BAD_ARGS (got %s)", nqh, nkv, ctx, ratio, omega_gpu_attention_rc_name(rc)); 1013 } else { 1014 klass = "supported"; supported++; 1015 oracle_paged(q, pool, &ly, ids, nblk, ctx, layer, nqh, nkv, hd, want); 1016 bad = compare(got, want, n, 2e-4, 2e-5, &worst); 1017 unwritten = info.unwritten_words; 1018 uint64_t kv_staged = info.kv_bytes_staged, kv_naive = info.kv_bytes_naive, qb = info.q_bytes, tb = info.tab_bytes, ob = info.out_bytes; 1019 uint32_t launches = info.chip_calls, ctas = info.ctas_last_launch, blk_l = info.kv_blocks_logical, blk_u = info.kv_blocks_unique, kv_src = info.kv_source; 1020 for (int i = 0; i < N; i++) { 1021 OmegaGpuAttnInfo ti; 1022 int trc = omega_gpu_paged_attention_bf16(q, pool, &ly, ids, nblk, ctx, layer, nqh, nkv, hd, got, &ti); 1023 samples[i] = ti.call_ns / 1e6; ksamples[i] = ti.elapsed_ns / 1e6; 1024 double w; size_t b2 = compare(got, want, n, 2e-4, 2e-5, &w); 1025 if (w > worst) worst = w; 1026 bad += b2; unwritten += ti.unwritten_words; cache_hits += ti.kernel_cache_hit; 1027 if (trc == OMEGA_GPU_ATTN_OK && b2 == 0) ok_calls++; 1028 } 1029 qsort(samples, (size_t)N, sizeof samples[0], cmp_d); qsort(ksamples, (size_t)N, sizeof ksamples[0], cmp_d); 1030 med = samples[N / 2]; p90 = samples[N * 9 / 10]; kmed = ksamples[N / 2]; kp90 = ksamples[N * 9 / 10]; 1031 pass = rc == OMEGA_GPU_ATTN_OK && bad == 0 && ok_calls == N && unwritten == 0 && cache_hits == (uint32_t)N; 1032 CHECK(pass, "sweep %uq/%ukv ctx %u: rc=%s violations=%zu ok_calls=%d/%d unwritten=%u cache_hits=%u", nqh, nkv, ctx, omega_gpu_attention_rc_name(rc), bad, ok_calls, N, unwritten, cache_hits); 1033 printf("%s sweep %2uq/%2ukv ratio %2u ctx %4u: launches=%u ctas=%u call_ms med=%.3f p90=%.3f kernel_ms med=%.3f p90=%.3f kv_staged=%" PRIu64 " (naive %" PRIu64 ") blocks=%u/%u q=%" PRIu64 " tab=%" PRIu64 " out=%" PRIu64 " worst=%g\n", 1034 pass ? "PASS" : "FAIL", nqh, nkv, ratio, ctx, launches, ctas, med, p90, kmed, kp90, kv_staged, kv_naive, blk_u, blk_l, qb, tb, ob, worst); 1035 if (out) fprintf(out, "%s{\"q_heads\":%u,\"kv_heads\":%u,\"gqa_ratio\":%u,\"head_dim\":%u,\"context\":%u,\"q_width\":%zu,\"out_width\":%zu,\"class\":\"%s\",\"rc\":\"%s\",\"pass\":%s," 1036 "\"violations\":%zu,\"worst_scaled_err\":%g,\"unwritten_words\":%u,\"launches_per_call\":%u,\"ctas_last_launch\":%u,\"threads_per_cta\":%u," 1037 "\"call_ms_median\":%.4f,\"call_ms_p90\":%.4f,\"kernel_ms_median\":%.4f,\"kernel_ms_p90\":%.4f,\"kernel_cache_hits\":%u,\"first_call_cache_hit\":%s," 1038 "\"kv_bytes_staged\":%" PRIu64 ",\"kv_bytes_naive\":%" PRIu64 ",\"kv_blocks_logical\":%u,\"kv_blocks_unique\":%u,\"q_bytes\":%" PRIu64 ",\"tab_bytes\":%" PRIu64 ",\"out_bytes\":%" PRIu64 ",\"kv_source\":\"%s\"}", 1039 npoints ? "," : "", nqh, nkv, ratio, hd, ctx, n, n, klass, omega_gpu_attention_rc_name(rc), pass ? "true" : "false", bad, worst, unwritten, launches, ctas, info.threads_per_cta, 1040 med, p90, kmed, kp90, cache_hits, info.kernel_cache_hit ? "true" : "false", kv_staged, kv_naive, blk_l, blk_u, qb, tb, ob, kv_src == OMEGA_GPU_ATTN_KV_STAGED ? "staged" : "resident"); 1041 npoints++; 1042 } 1043 if (!pow2) { 1044 printf("%s sweep %2uq/%2ukv ratio %2u ctx %4u: %s (rc=%s)\n", pass ? "PASS" : "FAIL", nqh, nkv, ratio, ctx, klass, omega_gpu_attention_rc_name(rc)); 1045 if (out) fprintf(out, "%s{\"q_heads\":%u,\"kv_heads\":%u,\"gqa_ratio\":%u,\"head_dim\":%u,\"context\":%u,\"q_width\":%zu,\"out_width\":%zu,\"class\":\"%s\",\"rc\":\"%s\",\"pass\":%s}", 1046 npoints ? "," : "", nqh, nkv, ratio, hd, ctx, n, n, klass, omega_gpu_attention_rc_name(rc), pass ? "true" : "false"); 1047 npoints++; 1048 } 1049 free(pool); free(ids); free(q); free(got); free(want); 1050 } 1051 } 1052 free(samples); free(ksamples); 1053 uint32_t opens = omega_gpu_session_open_count(); 1054 CHECK(opens == (g_sim_mode ? 0u : 1u), "sweep: device opened %s (opens=%u)", g_sim_mode ? "never (simulator)" : "once", opens); 1055 printf("sweep: %d points (%d supported, %d unsupported by the kernel envelope), device_opens=%u\n", npoints, supported, unsupported, opens); 1056 if (out) { fprintf(out, "],\"points_total\":%d,\"points_supported\":%d,\"points_unsupported\":%d,\"device_opens\":%u,\"checks\":%d,\"failed\":%d,\"verdict\":\"%s\"}\n", npoints, supported, unsupported, opens, g_checks, g_failed, g_failed == 0 ? "OMEGA_GPU_ATTENTION_SWEEP_PASS" : "OMEGA_GPU_ATTENTION_SWEEP_FAIL"); fclose(out); } 1057 return 0; 1058 } 1059 1060 /* ------------------------------------------------------------ warp simulator (omega #308) 1061 * The per-thread simulator above has no model of a warp (its SHFL rule is "one path across the 1062 * warp or error 7"). With --divergent the kernel carries a real lane-dependent branch inside a 1063 * BSSY/BSYNC region, and every launch runs through tests/bw_warp_sim.h instead: 32-lane 1064 * fragments, barrier registers, SHFL/BAR participation. Each launch runs in both fragment 1065 * orders and the two outputs must be bit-identical. */ 1066 static uint64_t g_ws_issues, g_ws_launches; 1067 static int ws_attn_launch(const void *progv, const OmegaGpuAttnLaunch *L, OmegaGpuAttnInfo *info) { 1068 const BlackwellIRProgram *p = progv; 1069 uint32_t *outw = L->out; size_t nw = L->out_bytes / 4; 1070 uint32_t *copy = malloc(L->out_bytes); 1071 int err = 0; char msg[240] = ""; 1072 for (int order = 0; order < 2 && !err && copy; order++) { 1073 WsSim s; memset(&s, 0, sizeof s); 1074 s.p = p; s.threads = SIM_T; s.smem = sim_shared; s.smem_bytes = SIM_SMEM; s.order = order; 1075 uint64_t qa = (uintptr_t)L->q, pa = (uintptr_t)L->pool, oa = (uintptr_t)L->out, ta = (uintptr_t)L->tab; 1076 s.cbank[0x380 / 4] = (uint32_t)qa; s.cbank[0x380 / 4 + 1] = (uint32_t)(qa >> 32); 1077 s.cbank[0x388 / 4] = (uint32_t)pa; s.cbank[0x388 / 4 + 1] = (uint32_t)(pa >> 32); 1078 s.cbank[0x390 / 4] = (uint32_t)oa; s.cbank[0x390 / 4 + 1] = (uint32_t)(oa >> 32); 1079 s.cbank[0x398 / 4] = (uint32_t)ta; s.cbank[0x398 / 4 + 1] = (uint32_t)(ta >> 32); 1080 memcpy(&s.cbank[0x3a0 / 4], L->params, sizeof L->params); 1081 for (size_t i = 0; i < nw; i++) outw[i] = 0xffbadbadu; 1082 err = ws_run(&s, L->grid_x, L->grid_y); 1083 if (err) { snprintf(msg, sizeof msg, "order %d: %s", order, s.msg); break; } 1084 g_ws_issues += s.warp_issues; 1085 if (order == 0) memcpy(copy, outw, L->out_bytes); 1086 else if (memcmp(copy, outw, L->out_bytes) != 0) { err = -1; snprintf(msg, sizeof msg, "the fragment order changed the result"); } 1087 } 1088 free(copy); 1089 g_ws_launches++; 1090 uint32_t unwritten = 0; for (size_t i = 0; i < nw; i++) if (outw[i] == 0xffbadbadu) unwritten++; 1091 if (info) { info->chip_calls++; info->unwritten_words += unwritten; info->ctas_last_launch = L->grid_x * L->grid_y; info->threads_per_cta = SIM_T; } 1092 if (err) { printf("warp simulator error: %s\n", msg); return OMEGA_GPU_ATTN_CHIP_FAIL; } 1093 return unwritten ? OMEGA_GPU_ATTN_UNWRITTEN : OMEGA_GPU_ATTN_OK; 1094 } 1095 /* Negative control for --divergent --sim: mode 2 builds the same kernel with the BSYNC dropped; 1096 * the warp simulator must reject it (the whole point of the simulator: the old one could not). */ 1097 static void divergent_negative_control(void) { 1098 enum { SEQ = 65, NQH = 8, NKV = 2 }; 1099 const uint32_t HD = g_hd; 1100 float *q = malloc(NQH * HD * 4), *kv = malloc((size_t)SEQ * NKV * HD * 4), *out = malloc(NQH * HD * 4); 1101 uint32_t seed = 0x308u; 1102 for (uint32_t i = 0; i < NQH * HD; i++) q[i] = frand(&seed, -1.0f, 1.0f); 1103 for (size_t i = 0; i < (size_t)SEQ * NKV * HD; i++) kv[i] = frand(&seed, -1.0f, 1.0f); 1104 omega_gpu_attention_test_set_divergent(2); 1105 int rc = omega_gpu_gqa_attention_f32(q, kv, kv, SEQ, NQH, NKV, HD, out, NULL); 1106 omega_gpu_attention_test_set_divergent(1); 1107 CHECK(rc == OMEGA_GPU_ATTN_CHIP_FAIL, "divergent mode 2 (BSYNC dropped) rejected by the warp simulator (rc %s)", omega_gpu_attention_rc_name(rc)); 1108 int rc1 = omega_gpu_gqa_attention_f32(q, kv, kv, SEQ, NQH, NKV, HD, out, NULL); 1109 CHECK(rc1 == OMEGA_GPU_ATTN_OK, "divergent mode 1 (regioned branch) runs clean on the same input (rc %s)", omega_gpu_attention_rc_name(rc1)); 1110 free(q); free(kv); free(out); 1111 } 1112 1113 /* ------------------------------------------------------------ head_dim 128 (CPU phase) 1114 * Checks that need the public API only, so the same code runs on the host simulators now and on 1115 * the chip in the coordinated window. Run with --hd 128 (--sim for the host simulators). 1116 * They target what head_dim 128 changed: four warps per CTA, so the chunk max and the chunk sum 1117 * each combine FOUR warp partials (lane 0 of warps 0..3), and 128-token chunks. 1118 * (a) uniform scores (K = 0): every weight is 1, the output is the mean of V over the context; 1119 * a sum that drops the partial of warp 2 or 3 gives about twice the mean; 1120 * (b) one dominant token with a score above the f32 exponent range (EX2 overflows without the 1121 * right running max): the token sits in each of the four warps of chunk 0 and in the later, 1122 * partial chunks; a max that ignores warp 2 or 3 overflows to inf / NaN. 1123 * Negative controls: the comparison rejects the answer of a different token, and a shared-memory 1124 * declaration of 1024 bytes (the head_dim 64 size) is refused by the simulators. */ 1125 static void hd128_checks(void) { 1126 const uint32_t hd = 128, nqh = 8, nkv = 2, seq = 300; 1127 uint32_t seed = 0x128u; 1128 size_t n = (size_t)nqh * hd, nkvs = (size_t)seq * nkv * hd; 1129 float *q = malloc(n * 4), *kc = malloc(nkvs * 4), *vc = malloc(nkvs * 4), *got = malloc(n * 4), *want = malloc(n * 4); 1130 for (size_t i = 0; i < n; i++) q[i] = 1.0f; 1131 for (size_t i = 0; i < nkvs; i++) vc[i] = frand(&seed, -1.0f, 1.0f); 1132 OmegaGpuAttnInfo info; 1133 /* (a) uniform */ 1134 memset(kc, 0, nkvs * 4); 1135 oracle_gqa(q, kc, vc, seq, nqh, nkv, hd, want); 1136 int rc = omega_gpu_gqa_attention_f32(q, kc, vc, seq, nqh, nkv, hd, got, &info); 1137 double w; size_t bad = compare(got, want, n, 2e-4, 2e-5, &w); 1138 CHECK(rc == OMEGA_GPU_ATTN_OK && bad == 0 && info.threads_per_cta == 128, "hd128 uniform scores: mean of V over 300 tokens (rc %s, %zu bad, worst %g, %u threads)", omega_gpu_attention_rc_name(rc), bad, w, info.threads_per_cta); 1139 float *half = malloc(n * 4); for (size_t i = 0; i < n; i++) half[i] = want[i] * 0.5f; 1140 size_t neg = compare(got, half, n, 2e-4, 2e-5, &w); 1141 CHECK(neg > n / 2, "hd128 uniform negative control: a result with the sum of two warps dropped (half the mean) is flagged (%zu of %zu)", neg, n); 1142 free(half); 1143 /* (b) one dominant token */ 1144 static const uint32_t pos[] = { 5, 40, 70, 100, 127, 128 + 3, 256 + 43 }; 1145 int all_ok = 1; size_t worst_bad = 0; 1146 for (size_t pi = 0; pi < sizeof pos / sizeof pos[0]; pi++) { 1147 memset(kc, 0, nkvs * 4); 1148 for (uint32_t kvh = 0; kvh < nkv; kvh++) for (uint32_t d = 0; d < hd; d++) kc[((size_t)pos[pi] * nkv + kvh) * hd + d] = 12.0f; /* dot 1536, scaled by log2e / sqrt(128): about 2^196 */ 1149 oracle_gqa(q, kc, vc, seq, nqh, nkv, hd, want); 1150 rc = omega_gpu_gqa_attention_f32(q, kc, vc, seq, nqh, nkv, hd, got, &info); 1151 bad = compare(got, want, n, 2e-4, 2e-5, &w); 1152 if (rc != OMEGA_GPU_ATTN_OK || bad) { all_ok = 0; if (bad > worst_bad) worst_bad = bad; } 1153 printf(" hd128 dominant token %u (warp %u of chunk %u): rc %s, %zu bad, worst %g\n", pos[pi], (pos[pi] % 128) / 32, pos[pi] / 128, omega_gpu_attention_rc_name(rc), bad, w); 1154 if (pi == 0) { 1155 /* negative control: the answer of token 6 instead of token 5 must be flagged */ 1156 float *other = malloc(n * 4); 1157 for (uint32_t h = 0; h < nqh; h++) for (uint32_t d = 0; d < hd; d++) other[h * hd + d] = vc[((size_t)6 * nkv + h / (nqh / nkv)) * hd + d]; 1158 size_t negb = compare(got, other, n, 2e-4, 2e-5, &w); 1159 CHECK(negb > n / 2, "hd128 dominant-token negative control: the neighbouring token's V is flagged (%zu of %zu)", negb, n); 1160 free(other); 1161 } 1162 } 1163 CHECK(all_ok, "hd128 dominant token in every warp and chunk: exact max/sum over four warp partials (worst bad %zu)", worst_bad); 1164 /* a kernel that needs 2048 bytes of shared memory must not run in a 1024-byte declaration (simulators only: they bound shared accesses) */ 1165 if (g_sim_mode) { 1166 g_smem_cap = 1024; 1167 rc = omega_gpu_gqa_attention_f32(q, kc, vc, seq, nqh, nkv, hd, got, NULL); 1168 g_smem_cap = 0; 1169 CHECK(rc == OMEGA_GPU_ATTN_CHIP_FAIL, "hd128 kernel refused under a 1024-byte shared-memory declaration (rc %s)", omega_gpu_attention_rc_name(rc)); 1170 rc = omega_gpu_gqa_attention_f32(q, kc, vc, seq, nqh, nkv, hd, got, NULL); 1171 CHECK(rc == OMEGA_GPU_ATTN_OK, "hd128 kernel runs under the 2048-byte declaration (rc %s)", omega_gpu_attention_rc_name(rc)); 1172 } 1173 free(q); free(kc); free(vc); free(got); free(want); 1174 } 1175 1176 /* head_dim 64 byte-identity pin and head_dim 128 codegen facts (CPU only, no device, no simulator). 1177 * The digests are SHA-256 of the encoded kernel bytes as emitted by the batched-load program of 2026-10-12 1178 * (speed/attention-batched-loads; before it, main `c0369e6` was pinned at 160 instructions), re-pinned 2026-10-18 for the encoder 1179 * control-word fix (omega-mv#545: 8 IADD3 and 1 EXIT word 3 per kernel carry the scheduled waits; reverting only those 1180 * words reproduces the previous digests); any change to the head_dim 64 program changes a digest and fails here. */ 1181 typedef struct { bool f32; uint32_t log2bs, log2gqa; size_t insns; const char *sha256; } Pin; 1182 static const Pin k_pins64[] = { 1183 { false, 4, 3, 216, "`5e183059327a4b3f188d749f296385ec43e718bbbf98de4f2697b5b553e7ccb1`" }, 1184 { false, 4, 2, 216, "`6656927ae80d3677c8444e5ccbb696b50850e21b3ff52bf14dd79d6f83232243`" }, 1185 { false, 4, 0, 216, "`b3d40b99628c4bb9bdb25c503766aca5c904456e63301b5338963071ab9b28e0`" }, 1186 { true, 12, 3, 184, "`61eab0c548f36364ee4d7547fa8f32fffcc20096182112d5fef12fe381712e31`" }, 1187 { true, 12, 2, 184, "`0095f8fb408efad952f0cad4f0e9d6d99f950d4aa8bbd14ee71a5347297fcbc9`" }, 1188 { true, 12, 0, 184, "`e0c44b49246198765f0eb60a6cc065d59c98f41fadc10b1d4e3fbc18587d855d`" }, 1189 }; 1190 static void hex_digest(const uint8_t d[32], char out[65]) { for (int i = 0; i < 32; i++) snprintf(out + 2 * i, 3, "%02x", d[i]); } 1191 static void hd_codegen_checks(void) { 1192 char hex[65]; 1193 for (size_t i = 0; i < sizeof k_pins64 / sizeof k_pins64[0]; i++) { 1194 const Pin *p = &k_pins64[i]; 1195 OmegaBlackwellKernel k; memset(&k, 0, sizeof k); 1196 int rc = omega_gpu_attention_codegen_hd(p->f32, p->log2bs, p->log2gqa, 64, &k); 1197 hex_digest(k.code_digest, hex); 1198 CHECK(rc == OMEGA_GPU_ATTN_OK && k.insn_count == p->insns && strcmp(hex, p->sha256) == 0, "hd64 %s log2bs %u log2gqa %u: encoded kernel is byte-identical to the pinned program (%zu insns, sha256 %s)", p->f32 ? "f32 " : "bf16", p->log2bs, p->log2gqa, k.insn_count, hex); 1199 free(k.code); 1200 /* the 4-argument entry point is the same kernel */ 1201 OmegaBlackwellKernel k4; memset(&k4, 0, sizeof k4); 1202 CHECK(omega_gpu_attention_codegen(p->f32, p->log2bs, p->log2gqa, &k4) == OMEGA_GPU_ATTN_OK && memcmp(k4.code_digest, k.code_digest, 32) == 0, "hd64 4-argument codegen entry is the same kernel"); 1203 free(k4.code); 1204 /* head_dim 128: encodes, inside the register budget, a different (longer) program */ 1205 OmegaBlackwellKernel k2; memset(&k2, 0, sizeof k2); 1206 int rc2 = omega_gpu_attention_codegen_hd(p->f32, p->log2bs, p->log2gqa, 128, &k2); 1207 CHECK(rc2 == OMEGA_GPU_ATTN_OK && k2.code_size > 0 && k2.gpr_count <= 96 /* AT_GPR_BUDGET; cut K: the four-head kernel peaks at 84 */ && k2.insn_count > p->insns && memcmp(k2.code_digest, k.code_digest, 32) != 0, 1208 "hd128 %s log2bs %u log2gqa %u: kernel encodes (%zu insns vs %zu, %u gprs)", p->f32 ? "f32 " : "bf16", p->log2bs, p->log2gqa, k2.insn_count, p->insns, k2.gpr_count); 1209 free(k2.code); 1210 } 1211 OmegaBlackwellKernel kx; memset(&kx, 0, sizeof kx); 1212 CHECK(omega_gpu_attention_codegen_hd(false, 4, 3, 96, &kx) == OMEGA_GPU_ATTN_TOO_LARGE, "codegen refuses head_dim 96"); 1213 CHECK(omega_gpu_attention_codegen_hd(false, 4, 3, 256, &kx) == OMEGA_GPU_ATTN_TOO_LARGE, "codegen refuses head_dim 256"); 1214 /* negative control for the pin itself: a one-bit change to a pinned digest must not match */ 1215 OmegaBlackwellKernel kn; memset(&kn, 0, sizeof kn); 1216 (void)omega_gpu_attention_codegen_hd(k_pins64[0].f32, k_pins64[0].log2bs, k_pins64[0].log2gqa, 64, &kn); 1217 kn.code_digest[0] ^= 1u; hex_digest(kn.code_digest, hex); 1218 CHECK(strcmp(hex, k_pins64[0].sha256) != 0, "pin negative control: a flipped digest bit does not match the pin"); 1219 free(kn.code); 1220 } 1221 1222 1223 int main(int argc, char **argv) { 1224 const char *out_path = NULL; int host = 0, sim = 0, timing_mode = 0, sweep_mode = 0, split_timing_mode = 0; 1225 uint32_t spin_us = 0; 1226 for (int i = 1; i < argc; i++) { 1227 if (strcmp(argv[i], "--host-only") == 0) host = 1; 1228 else if (strcmp(argv[i], "--sim") == 0) sim = 1; 1229 else if (strcmp(argv[i], "--divergent") == 0) g_divergent = 1; 1230 else if (strcmp(argv[i], "--timing") == 0) timing_mode = 1; 1231 else if (strcmp(argv[i], "--split-timing") == 0) split_timing_mode = 1; 1232 else if (strcmp(argv[i], "--sweep") == 0) sweep_mode = 1; 1233 else if (strcmp(argv[i], "--hd") == 0 && i + 1 < argc) g_hd = (uint32_t)atoi(argv[++i]); 1234 else if (strcmp(argv[i], "--spin-us") == 0 && i + 1 < argc) spin_us = (uint32_t)atoi(argv[++i]); 1235 else if (strcmp(argv[i], "--out") == 0 && i + 1 < argc) out_path = argv[++i]; 1236 } 1237 if (g_hd != 64 && g_hd != 128) { printf("--hd must be 64 or 128\n"); return 2; } 1238 if (g_hd == 128 && (timing_mode || sweep_mode)) { printf("--hd 128 supports the battery, --split-timing and --host-only (timing and sweep are head_dim 64 only)\n"); return 2; } 1239 if (spin_us && omega_gpu_session_set_spin_us(spin_us) != 0) { printf("--spin-us %u refused\n", spin_us); return 2; } 1240 if (g_divergent) omega_gpu_attention_test_set_divergent(1); 1241 if (sim) { g_sim_mode = 1; omega_gpu_attention_test_set_simulator(g_divergent ? ws_attn_launch : sim_launch); } 1242 if (sim && g_divergent && !host) divergent_negative_control(); 1243 if (host) { host_only(); hd_codegen_checks(); mufu_ftz_sim_check(); } 1244 else if (split_timing_mode) { if (split_timing(out_path) != 0) return 2; } 1245 else if (timing_mode) { if (timing(out_path) != 0) return 2; } 1246 else if (sweep_mode) { if (sweep(out_path) != 0) return 2; } 1247 else { if (chip(out_path) != 0) return 2; if (g_hd == 128) hd128_checks(); } 1248 printf("%s: %d checks, %d failed\n", g_failed ? "FAIL" : "PASS", g_checks, g_failed); 1249 return g_failed ? 1 : 0; 1250 }