interplane.Get Omega
Read in your language

omega-mv

Omega: a language for verified programs, semantic identity and machine realization. Seed-born work and existing implementations have distinct provenance.

Brought by drakestapleton

branch main Branches Tags History

omega-mv / evidence / OWN30B-REQUAL-MAIN-710d438c-20261015 / gates / cut4b / FB1-CUT4B-710d438c / gpu_attention_test.c

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