interplane.Get Omega
Read in your language

CUDApp

CUDA++: AIEN’s GPU machine-code toolchain, runtime and driver client for NVIDIA GPUs without the CUDA toolkit. Hardware coverage and driver replacement limits are explicit.

Brought by drakestapleton

branch main Branches Tags History

CUDApp / tests / gpu_attention_test.c

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