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 / CODEPAD-PREFETCH-f1d57c5 / hd64-regression / gpu_attention_test.c

849 lines · 66702 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 --timing [--out r.json] cut 4b gate: 1 query x 32 heads x 2048 ctx, 100 calls
6 * through the persistent session, median under 3 ms
7 * ./gpu_attention_test --sweep [--out s.json] head-scaling sweep: paged bf16 at head_dim 64 over q heads
8 * 1..64 x every kv-head divisor x ctx 256/2048, parity + timings
9 * (receipt OMEGA_GPU_ATTENTION_SWEEP_V1; --sim marks host timings)
10 * ./gpu_attention_test --out receipt.json chip gate: every shape against the host oracle, the
11 * mutants (deliberately wrong kernels, all of
12 * 1 .. OMEGA_GPU_ATTN_MUTANT_COUNT-1) which the same
13 * check must catch, a negative control, timings
14 *
15 * Oracles re-state aien-sovereign-core crates/aien-inference-abi/src/backend.rs (main 8b5caed) in C:
16 * ReferenceCpuBackend::gqa_attention (f64 scores, max, exp, sum, 1/max(sum,1e-12), f64 weighted sum),
17 * TensorBackend::paged_attention (f64 online softmax token by token over the paged bf16 pool, tokens
18 * past the block table dropped, zeros for empty context) and paged_attention_batch (ctx <= 0 -> 0,
19 * table rows past the array -> empty, negative entries removed). Compiled with -ffp-contract=off.
20 *
21 * Tolerance (why): the chip accumulates the 64-term dot products, the per-chunk sums and the
22 * rescaled running sums in f32 (worst case about n * 2^-24 relative over n = 2048 terms, 1.2e-4),
23 * uses MUFU.EX2 (PTX ex2.approx: 2^-22.5 relative) for every weight and for the 32 chunk rescale
24 * factors, and MUFU.RCP for the final normalisation. Every output is a convex combination of V
25 * values of unit scale, so |error| <= 2e-4 * |want| + 2e-5 covers these with margin; the mutants
26 * move results by 1e-2 or more (wrong head, wrong token) or produce NaN (overflow without the max).
27 * The large-score case (scores up to ~300) carries the f32 rounding of the score itself into the
28 * exponent (3e-5 absolute per score), so it uses 1e-3 relative + 1e-4 absolute.
29 */
30#include "omega_gpu_attention_api.h"
31#include "omega_gpu_session.h"
32#include "omega_blackwell_codegen.h"
33#include "bw_warp_sim.h" /* omega #308: SIMT warp simulator for --divergent */
34#include <inttypes.h>
35#include <math.h>
36#include <stdio.h>
37#include <stdlib.h>
38#include <string.h>
39#include <time.h>
40#include <unistd.h>
41
42static int g_checks, g_failed;
43static int g_sim_mode; /* --sim: the host simulator never opens the device */
44static int g_divergent; /* --divergent (omega #308 R2): the j >= ctx branch inside a BSSY/BSYNC region */
45#define CHECK(cond, ...) do { g_checks++; if (!(cond)) { g_failed++; printf("FAIL: "); printf(__VA_ARGS__); printf("\n"); } } while (0)
46
47static uint32_t lcg(uint32_t *s) { *s = *s * 1664525u + 1013904223u; return *s; }
48static float frand(uint32_t *s, float lo, float hi) { return lo + (hi - lo) * ((float)(lcg(s) >> 8) / 16777216.0f); }
49static 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); }
50static float bf2f(uint16_t b) { uint32_t u = (uint32_t)b << 16; float f; memcpy(&f, &u, 4); return f; }
51
52/* ----------------------------------------------------------------- oracles */
53static 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) {
54 if (seq_len == 0) { memset(out, 0, nqh * hd * 4); return; }
55 size_t ratio = nqh / nkv; double inv_sqrt_d = 1.0 / sqrt((double)hd);
56 double *scores = malloc(seq_len * sizeof *scores);
57 for (size_t h = 0; h < nqh; h++) {
58 size_t kvh = h / ratio; const float *qh = q + h * hd;
59 for (size_t t = 0; t < seq_len; t++) {
60 const float *kt = kc + (t * nkv + kvh) * hd; double dot = 0.0;
61 for (size_t d = 0; d < hd; d++) dot += (double)qh[d] * (double)kt[d];
62 scores[t] = dot * inv_sqrt_d;
63 }
64 double mx = -INFINITY; for (size_t t = 0; t < seq_len; t++) if (scores[t] > mx) mx = scores[t];
65 double sum = 0.0; for (size_t t = 0; t < seq_len; t++) { scores[t] = exp(scores[t] - mx); sum += scores[t]; }
66 double inv = 1.0 / (sum > 1e-12 ? sum : 1e-12);
67 for (size_t t = 0; t < seq_len; t++) scores[t] *= inv;
68 for (size_t d = 0; d < hd; d++) {
69 double s = 0.0;
70 for (size_t t = 0; t < seq_len; t++) s += scores[t] * (double)vc[(t * nkv + kvh) * hd + d];
71 out[h * hd + d] = (float)s;
72 }
73 }
74 free(scores);
75}
76/* bf16 pool in the canonical layout; the oracle's read_kv_head: element_offset(block, layer, is_value, token) + kv_head*head_dim*2 */
77static 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) {
78 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;
79 return (const uint16_t *)(pool + off);
80}
81static 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,
82 size_t nqh, size_t nkv, size_t hd, float *out) {
83 if (ctx == 0 || nids == 0) { memset(out, 0, nqh * hd * 4); return; }
84 size_t ratio = nqh / nkv; double inv_sqrt_d = 1.0 / sqrt((double)hd); size_t bs = ly->block_size;
85 double *acc = malloc(hd * sizeof *acc);
86 for (size_t h = 0; h < nqh; h++) {
87 size_t kvh = h / ratio; const float *qh = q + h * hd;
88 double m = -INFINITY, l = 0.0; for (size_t d = 0; d < hd; d++) acc[d] = 0.0;
89 for (size_t t = 0; t < ctx; t++) {
90 size_t bi = t / bs; if (bi >= nids) break;
91 const uint16_t *kh = kv_head(pool, ly, ids[bi], layer, 0, t % bs, kvh, hd);
92 const uint16_t *vh = kv_head(pool, ly, ids[bi], layer, 1, t % bs, kvh, hd);
93 double dot = 0.0; for (size_t d = 0; d < hd; d++) dot += (double)qh[d] * (double)bf2f(kh[d]);
94 double score = dot * inv_sqrt_d, mn = m > score ? m : score, alpha = exp(m - mn), beta = exp(score - mn);
95 l = l * alpha + beta;
96 for (size_t d = 0; d < hd; d++) acc[d] = acc[d] * alpha + beta * (double)bf2f(vh[d]);
97 m = mn;
98 }
99 double inv = l > 0.0 ? 1.0 / l : 0.0;
100 for (size_t d = 0; d < hd; d++) out[h * hd + d] = (float)(acc[d] * inv);
101 }
102 free(acc);
103}
104static 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,
105 size_t layer, size_t nqh, size_t nkv, size_t hd, float *out) {
106 size_t stride = nqh * hd;
107 uint32_t *ids = malloc((maxb ? maxb : 1) * sizeof *ids);
108 for (size_t s = 0; s < nseq; s++) {
109 size_t ctx = ctxs[s] > 0 ? (size_t)ctxs[s] : 0, n = 0;
110 size_t total = nseq * maxb; /* the table array length as the trait sees it */
111 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];
112 oracle_paged(q + s * stride, pool, ly, ids, n, ctx, layer, nqh, nkv, hd, out + s * stride);
113 }
114 free(ids);
115}
116
117static size_t compare(const float *got, const float *want, size_t n, double rel, double abs_tol, double *worst) {
118 size_t bad = 0; *worst = 0.0;
119 for (size_t i = 0; i < n; i++) {
120 double d = fabs((double)got[i] - (double)want[i]);
121 double lim = rel * fabs((double)want[i]) + abs_tol;
122 double scaled = lim > 0 ? d / lim : (d > 0 ? INFINITY : 0.0);
123 if (scaled > *worst) *worst = scaled;
124 if (!(d <= lim)) bad++; /* NaN counts as bad */
125 }
126 return bad;
127}
128
129/* ------------------------------------------------------------- host only */
130static int nvdisasm_check(bool f32, const char *name, const char *const *must, int n_must) {
131 const char *nv = "/usr/local/cuda/bin/nvdisasm";
132 if (access(nv, X_OK) != 0) { printf("nvdisasm: not present, listing check skipped for %s\n", name); return 0; }
133 OmegaBlackwellKernel k; memset(&k, 0, sizeof k);
134 if (omega_gpu_attention_codegen(f32, f32 ? 12 : 4, 3, &k) != OMEGA_GPU_ATTN_OK) return -1;
135 char bin[64], lst[64], cmd[256];
136 snprintf(bin, sizeof bin, "/tmp/omega_attn_%s_%d.bin", name, (int)getpid());
137 snprintf(lst, sizeof lst, "/tmp/omega_attn_%s_%d.sass", name, (int)getpid());
138 FILE *f = fopen(bin, "wb"); if (!f) { free(k.code); return -1; }
139 fwrite(k.code, 1, k.code_size, f); fclose(f);
140 snprintf(cmd, sizeof cmd, "%s -b SM121 %s > %s 2>&1", nv, bin, lst);
141 int rc = system(cmd);
142 free(k.code);
143 FILE *l = fopen(lst, "r"); if (!l) return -1;
144 char line[512]; int seen[16] = {0}; int bad = 0, insns = 0;
145 while (fgets(line, sizeof line, l)) {
146 if (!strstr(line, "/*0")) continue;
147 insns++;
148 if (strstr(line, "?") || strstr(line, "error")) bad++;
149 for (int i = 0; i < n_must; i++) if (strstr(line, must[i])) seen[i] = 1;
150 }
151 fclose(l);
152 int miss = 0;
153 for (int i = 0; i < n_must; i++) if (!seen[i]) { printf(" %s: nvdisasm listing lacks %s\n", name, must[i]); miss++; }
154 printf("nvdisasm %s: rc=%d insns=%d undecodable=%d missing=%d (%s)\n", name, rc, insns, bad, miss, lst);
155 unlink(bin);
156 return (rc == 0 && bad == 0 && miss == 0) ? 0 : -1;
157}
158
159static OmegaGpuKvLayout layout_for(uint32_t num_blocks, uint32_t bs, uint32_t layers, uint32_t nkv, uint32_t hd) {
160 OmegaGpuKvLayout ly;
161 ly.head_stride_bytes = (uint64_t)hd * 2; ly.token_stride_bytes = ly.head_stride_bytes * nkv;
162 ly.kv_plane_stride_bytes = ly.token_stride_bytes * bs; ly.layer_stride_bytes = 2 * ly.kv_plane_stride_bytes;
163 ly.block_stride_bytes = ly.layer_stride_bytes * layers; ly.pool_bytes = ly.block_stride_bytes * num_blocks;
164 ly.num_blocks = num_blocks; ly.num_layers = layers; ly.block_size = bs;
165 return ly;
166}
167
168static void host_only(void) {
169 float q[64 * 64], kv[64 * 64], out[64 * 64]; memset(q, 0, sizeof q); memset(kv, 0, sizeof kv);
170 CHECK(omega_gpu_gqa_attention_f32(NULL, kv, kv, 1, 32, 4, 64, out, NULL) == OMEGA_GPU_ATTN_BAD_ARGS, "NULL q refused");
171 CHECK(omega_gpu_gqa_attention_f32(q, kv, kv, 1, 32, 4, 128, out, NULL) == OMEGA_GPU_ATTN_TOO_LARGE, "head_dim 128 refused (TOO_LARGE)");
172 CHECK(omega_gpu_gqa_attention_f32(q, kv, kv, 1, 6, 2, 64, out, NULL) == OMEGA_GPU_ATTN_BAD_ARGS, "gqa ratio 3 refused");
173 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");
174 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");
175 for (int i = 0; i < 64; i++) out[i] = 1.0f;
176 OmegaGpuAttnInfo info;
177 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");
178 OmegaGpuKvLayout ly = layout_for(8, 16, 2, 4, 64);
179 uint8_t *pool = calloc(ly.pool_bytes, 1);
180 uint32_t ids[2] = { 1, 9 };
181 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");
182 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");
183 OmegaGpuKvLayout bad = ly; bad.block_size = 12;
184 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");
185 bad = ly; bad.head_stride_bytes = 256;
186 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");
187 free(pool);
188 CHECK(strcmp(omega_gpu_attention_rc_name(OMEGA_GPU_ATTN_UNWRITTEN), "UNWRITTEN") == 0, "rc name");
189
190 /* with --divergent the listing must also show the region ops (last two entries) */
191 static const char *const must_bf16[] = { "MUFU.EX2", "MUFU.RCP", "FMNMX", "BAR.SYNC", "SHFL.DOWN", "@P0 BRA", "@!P0 BRA", "LDG.E.U16", "LDG.E ", "LDS R", "STS [R", "STG.E", "LOP3.LUT", "SHF.R.U32.HI", "BSSY", "BSYNC" };
192 static const char *const must_f32[] = { "MUFU.EX2", "MUFU.RCP", "FMNMX", "BAR.SYNC", "SHFL.DOWN", "@P0 BRA", "@!P0 BRA", "LDG.E ", "LDS R", "STS [R", "STG.E", "BSSY", "BSYNC" };
193 for (int f32 = 0; f32 < 2; f32++) {
194 const char *name = f32 ? "gqa_f32" : "paged_bf16";
195 OmegaBlackwellKernel k; memset(&k, 0, sizeof k);
196 int rc = omega_gpu_attention_codegen(f32 != 0, f32 ? 12 : 4, 3, &k);
197 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);
198 printf("codegen %s: %zu insns, %u gprs, %u ugprs\n", name, k.insn_count, k.gpr_count, k.uniform_gpr_count);
199 /* every mutant (1 .. COUNT-1) is a distinct kernel: different from the baseline and from
200 * every other mutant, named, and inside the register budget */
201 uint8_t digests[OMEGA_GPU_ATTN_MUTANT_COUNT][32]; memcpy(digests[0], k.code_digest, 32);
202 free(k.code);
203 for (int m = 1; m < OMEGA_GPU_ATTN_MUTANT_COUNT; m++) {
204 omega_gpu_attention_test_set_mutant((OmegaGpuAttnMutant)m);
205 memset(&k, 0, sizeof k);
206 int mrc = omega_gpu_attention_codegen(f32 != 0, f32 ? 12 : 4, 3, &k);
207 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);
208 CHECK(strcmp(omega_gpu_attention_mutant_name((OmegaGpuAttnMutant)m), "?") != 0, "mutant %d has a name", m);
209 memcpy(digests[m], k.code_digest, 32);
210 free(k.code);
211 omega_gpu_attention_test_set_mutant(OMEGA_GPU_ATTN_MUTANT_NONE);
212 for (int o = 0; o < m; o++)
213 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));
214 }
215 CHECK(strcmp(omega_gpu_attention_mutant_name(OMEGA_GPU_ATTN_MUTANT_COUNT), "?") == 0, "COUNT has no name");
216 /* a different shape key is a different kernel */
217 memset(&k, 0, sizeof k);
218 CHECK(omega_gpu_attention_codegen(f32 != 0, f32 ? 12 : 4, 2, &k) == OMEGA_GPU_ATTN_OK && memcmp(digests[0], k.code_digest, 32) != 0, "%s log2gqa 2 kernel differs from log2gqa 3", name);
219 free(k.code);
220 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);
221 }
222}
223
224/* ------------------------------------------------------------- chip gate */
225typedef 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;
226 int mutants_run, mutants_caught; char mutant_note[400];
227 uint64_t kv_staged, kv_naive; uint32_t blk_logical, blk_unique; } Case;
228static void case_info(Case *c, const OmegaGpuAttnInfo *i) {
229 c->chip_ns = i->elapsed_ns; c->call_ns = i->call_ns; c->calls = i->chip_calls; c->unwritten = i->unwritten_words;
230 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;
231}
232static Case g_cases[32]; static int g_ncases;
233static int g_mutant_caught[OMEGA_GPU_ATTN_MUTANT_COUNT], g_mutant_run[OMEGA_GPU_ATTN_MUTANT_COUNT];
234
235static void record(Case c, FILE *out) {
236 g_cases[g_ncases++] = c;
237 CHECK(c.pass, "%s rc=%s violations=%zu worst=%g", c.name, omega_gpu_attention_rc_name(c.rc), c.bad, c.worst);
238 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);
239 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",
240 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,
241 c.kv_staged, c.kv_naive, c.blk_unique, c.blk_logical, c.mutants_caught, c.mutants_run, c.mutant_note);
242 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,"
243 "\"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\"}",
244 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,
245 c.kv_staged, c.kv_naive, c.blk_unique, c.blk_logical, c.mutants_run, c.mutants_caught, c.mutant_note);
246}
247
248static const char *mutant_name(int m) { return omega_gpu_attention_mutant_name((OmegaGpuAttnMutant)m); }
249
250/* Runs the mutants listed in `ms` (terminated by 0) through `run` and counts the catches. */
251typedef int (*RunFn)(void *ctx, float *got, OmegaGpuAttnInfo *info);
252static 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) {
253 size_t pos = strlen(c->mutant_note); /* appends: a case may call this more than once */
254 for (int i = 0; ms[i]; i++) {
255 OmegaGpuAttnInfo info; double w;
256 omega_gpu_attention_test_set_mutant((OmegaGpuAttnMutant)ms[i]);
257 int rc = run(ctx, got, &info);
258 size_t bad = compare(got, want, n, rel, abs_tol, &w);
259 int caught = rc != OMEGA_GPU_ATTN_OK || bad > 0;
260 omega_gpu_attention_test_set_mutant(OMEGA_GPU_ATTN_MUTANT_NONE);
261 c->mutants_run++; c->mutants_caught += caught; g_mutant_run[ms[i]]++; g_mutant_caught[ms[i]] += caught;
262 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);
263 if (pos >= sizeof c->mutant_note) break;
264 }
265}
266
267typedef struct { const float *q, *kc, *vc; uint32_t seq, nqh, nkv; } GqaCtx;
268static 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, 64, got, info); }
269typedef struct { const float *q; const uint8_t *pool; const OmegaGpuKvLayout *ly; const uint32_t *ids; uint32_t nids, ctx, layer, nqh, nkv; } PagedCtx;
270static 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, 64, got, info); }
271typedef struct { const float *q; const uint8_t *pool; const OmegaGpuKvLayout *ly; const int32_t *tables, *ctxs; uint32_t maxb, nseq, layer, nqh, nkv; } BatchCtx;
272static 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, 64, got, info); }
273/* single vs batched parity and repeat (L6-KV, CAND-0 coverage): each sequence of a batch, run
274 * alone through the single-sequence entry point with the batch's own rules applied by hand
275 * (negative table entries removed, ctx <= 0 -> 0), must equal its row of the batched output bit
276 * for bit (same kernel, same per-CTA inputs; the batch only shares staging). Then the batch is
277 * called again with the same inputs: kernel cache hit, bit-identical output, identical staging
278 * counters. `got` must hold the batched output of `bc`. */
279static void batch_single_repeat_checks(const char *name, const BatchCtx *bc, const float *got, const Case *c) {
280 size_t row = (size_t)bc->nqh * 64, n = (size_t)bc->nseq * row;
281 float *one = malloc(row * 4), *again = malloc(n * 4);
282 uint32_t *ids = malloc((bc->maxb ? bc->maxb : 1) * 4);
283 for (uint32_t s = 0; s < bc->nseq; s++) {
284 uint32_t nb = 0;
285 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; }
286 uint32_t ctx = bc->ctxs[s] > 0 ? (uint32_t)bc->ctxs[s] : 0;
287 for (size_t i = 0; i < row; i++) one[i] = -7.0f; /* poison: an unwritten row cannot match */
288 OmegaGpuAttnInfo si;
289 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, 64, one, &si);
290 CHECK(src == OMEGA_GPU_ATTN_OK && memcmp(one, got + (size_t)s * row, row * 4) == 0,
291 "%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));
292 }
293 OmegaGpuAttnInfo ri;
294 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, 64, again, &ri);
295 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
296 && ri.kv_blocks_unique == c->blk_unique && ri.kv_blocks_logical == c->blk_logical,
297 "%s: repeated batch call is a cache hit, bit-identical, same staging counters (rc=%s hit=%d staged %" PRIu64 "/%" PRIu64 ")",
298 name, omega_gpu_attention_rc_name(rrc), (int)ri.kernel_cache_hit, ri.kv_bytes_staged, c->kv_staged);
299 free(one); free(again); free(ids);
300}
301
302
303static int chip(const char *out_path) {
304 FILE *out = out_path ? fopen(out_path, "w") : NULL;
305 if (out_path && !out) { printf("cannot open %s\n", out_path); return 2; }
306 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\":[");
307 uint32_t seed = 0xfb1c0005u;
308 const uint32_t hd = 64;
309 const struct { uint32_t nqh, nkv; const char *model; } shapes[2] = { { 32, 4, "tinyllama" }, { 32, 8, "llama32_1b" } };
310 /* 65, 129, 300 and 1000 end in a partial 64-token chunk after whole ones: the case that
311 * caught the diverged-warp shuffle on the chip (2026-10-04); 1, 17, 128, 256, 2048 did not. */
312 const uint32_t ctxs[9] = { 1, 17, 256, 2048, 65, 128, 129, 300, 1000 };
313 const int no_mutants[1] = { 0 };
314
315 /* 1. contiguous f32 KV (gqa_attention) */
316 for (int sh = 0; sh < 2; sh++) for (int ci = 0; ci < 9; ci++) {
317 uint32_t nqh = shapes[sh].nqh, nkv = shapes[sh].nkv, seq = ctxs[ci];
318 size_t n = (size_t)nqh * hd, nkvs = (size_t)seq * nkv * hd;
319 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);
320 for (size_t i = 0; i < n; i++) q[i] = frand(&seed, -1.0f, 1.0f);
321 for (size_t i = 0; i < nkvs; i++) { kc[i] = frand(&seed, -1.0f, 1.0f); vc[i] = frand(&seed, -1.0f, 1.0f); }
322 oracle_gqa(q, kc, vc, seq, nqh, nkv, hd, want);
323 char name[96]; snprintf(name, sizeof name, "gqa_f32_%s_%uq%ukv_ctx%u", shapes[sh].model, nqh, nkv, seq);
324 Case c = { .name = strdup(name), .n = n };
325 OmegaGpuAttnInfo info;
326 GqaCtx gc = { q, kc, vc, seq, nqh, nkv };
327 c.rc = run_gqa(&gc, got, &info);
328 c.bad = compare(got, want, n, 2e-4, 2e-5, &c.worst);
329 c.pass = c.rc == OMEGA_GPU_ATTN_OK && c.bad == 0; case_info(&c, &info);
330 if (ci == 3) {
331 OmegaGpuAttnInfo i2; int rc2 = run_gqa(&gc, again, &i2);
332 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);
333 /* negative control: the comparison must reject a wrong expectation (kv heads swapped) */
334 float *wrong = malloc(n * 4); double w2;
335 for (uint32_t h = 0; h < nqh; h++) memcpy(wrong + (size_t)h * hd, want + (size_t)((h + nqh / nkv) % nqh) * hd, hd * 4);
336 size_t neg = compare(got, wrong, n, 2e-4, 2e-5, &w2);
337 CHECK(neg > n / 2, "%s negative control: wrong expectation flagged (%zu of %zu)", name, neg, n);
338 free(wrong);
339 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 };
340 run_mutants(&c, ms, run_gqa, &gc, got, want, n, 2e-4, 2e-5);
341 } else if (ci == 1 && sh == 1) {
342 static const int ms[2] = { OMEGA_GPU_ATTN_MUTANT_KV_HEAD, 0 };
343 run_mutants(&c, ms, run_gqa, &gc, got, want, n, 2e-4, 2e-5);
344 } else run_mutants(&c, no_mutants, run_gqa, &gc, got, want, n, 2e-4, 2e-5);
345 record(c, out); free(q); free(kc); free(vc); free(got); free(want); free(again);
346 }
347 /* 2. large scores (q scaled by 200): the softmax without the running max overflows */
348 {
349 uint32_t nqh = 32, nkv = 4, seq = 256; size_t n = (size_t)nqh * hd, nkvs = (size_t)seq * nkv * hd;
350 float *q = malloc(n * 4), *kc = malloc(nkvs * 4), *vc = malloc(nkvs * 4), *got = malloc(n * 4), *want = malloc(n * 4);
351 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) */
352 for (size_t i = 0; i < nkvs; i++) { kc[i] = frand(&seed, -1.0f, 1.0f); vc[i] = frand(&seed, -1.0f, 1.0f); }
353 oracle_gqa(q, kc, vc, seq, nqh, nkv, hd, want);
354 Case c = { .name = "gqa_f32_large_scores_32q4kv_ctx256", .n = n };
355 OmegaGpuAttnInfo info; GqaCtx gc = { q, kc, vc, seq, nqh, nkv };
356 c.rc = run_gqa(&gc, got, &info);
357 c.bad = compare(got, want, n, 1e-3, 1e-4, &c.worst);
358 c.pass = c.rc == OMEGA_GPU_ATTN_OK && c.bad == 0; case_info(&c, &info);
359 static const int ms[2] = { OMEGA_GPU_ATTN_MUTANT_NO_MAX, 0 };
360 run_mutants(&c, ms, run_gqa, &gc, got, want, n, 1e-3, 1e-4);
361 record(c, out); free(q); free(kc); free(vc); free(got); free(want);
362 }
363 /* 2b. MHA (16q/16kv, ratio 1, ctx 300 = 4 full chunks + a partial one): the head-wiring
364 * mutants Q_ROW and OUT_ROW are observably different here (Q_ROW keeps kv head h, OUT_ROW
365 * lands on kv head h^1), unlike GQA where both swap the same pair of outputs. */
366 {
367 uint32_t nqh = 16, nkv = 16, seq = 300; 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), *got_q = 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 Case c = { .name = "gqa_f32_mha_16q16kv_ctx300", .n = n };
373 OmegaGpuAttnInfo info; GqaCtx gc = { q, kc, vc, seq, nqh, nkv };
374 c.rc = run_gqa(&gc, got, &info);
375 c.bad = compare(got, want, n, 2e-4, 2e-5, &c.worst);
376 c.pass = c.rc == OMEGA_GPU_ATTN_OK && c.bad == 0; case_info(&c, &info);
377 static const int ms_q[2] = { OMEGA_GPU_ATTN_MUTANT_Q_ROW, 0 };
378 static const int ms_o[3] = { OMEGA_GPU_ATTN_MUTANT_OUT_ROW, OMEGA_GPU_ATTN_MUTANT_KV_HEAD, 0 };
379 run_mutants(&c, ms_q, run_gqa, &gc, got, want, n, 2e-4, 2e-5);
380 memcpy(got_q, got, n * 4); /* Q_ROW output */
381 run_mutants(&c, ms_o, run_gqa, &gc, got, want, n, 2e-4, 2e-5);
382 /* `got` now holds the KV_HEAD output; rerun OUT_ROW alone to compare it with Q_ROW */
383 omega_gpu_attention_test_set_mutant(OMEGA_GPU_ATTN_MUTANT_OUT_ROW);
384 OmegaGpuAttnInfo i3; int rc3 = run_gqa(&gc, got, &i3);
385 omega_gpu_attention_test_set_mutant(OMEGA_GPU_ATTN_MUTANT_NONE);
386 double wq; size_t differ = compare(got, got_q, n, 2e-4, 2e-5, &wq);
387 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);
388 record(c, out); free(q); free(kc); free(vc); free(got); free(want); free(got_q);
389 }
390 /* 3. paged bf16 KV, block size 16, 2 layers (layer 1 under test), scattered block ids */
391 for (int sh = 0; sh < 2; sh++) for (int ci = 0; ci < 9; ci++) {
392 uint32_t nqh = shapes[sh].nqh, nkv = shapes[sh].nkv, ctx = ctxs[ci], bs = 16, layers = 2, layer = 1;
393 uint32_t nblk = (ctx + bs - 1) / bs, pool_blocks = nblk + 7;
394 OmegaGpuKvLayout ly = layout_for(pool_blocks, bs, layers, nkv, hd);
395 uint8_t *pool = malloc(ly.pool_bytes); uint16_t *pw = (uint16_t *)pool;
396 for (size_t i = 0; i < ly.pool_bytes / 2; i++) pw[i] = f2bf(frand(&seed, -1.0f, 1.0f));
397 uint32_t *ids = malloc(nblk * 4); /* a scattered permutation of the pool blocks */
398 for (uint32_t b = 0; b < nblk; b++) ids[b] = (b * 7 + 3) % pool_blocks;
399 size_t n = (size_t)nqh * hd;
400 float *q = malloc(n * 4), *got = malloc(n * 4), *want = malloc(n * 4);
401 for (size_t i = 0; i < n; i++) q[i] = frand(&seed, -1.0f, 1.0f);
402 oracle_paged(q, pool, &ly, ids, nblk, ctx, layer, nqh, nkv, hd, want);
403 char name[96]; snprintf(name, sizeof name, "paged_bf16_%s_%uq%ukv_bs%u_ctx%u", shapes[sh].model, nqh, nkv, bs, ctx);
404 Case c = { .name = strdup(name), .n = n };
405 OmegaGpuAttnInfo info; PagedCtx pc = { q, pool, &ly, ids, nblk, ctx, layer, nqh, nkv };
406 c.rc = run_paged(&pc, got, &info);
407 c.bad = compare(got, want, n, 2e-4, 2e-5, &c.worst);
408 c.pass = c.rc == OMEGA_GPU_ATTN_OK && c.bad == 0; case_info(&c, &info);
409 if (ci == 3) {
410 /* NO_MAX cannot overflow on unit-scale scores (softmax is shift invariant); it is caught by the large-score gqa case */
411 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 };
412 run_mutants(&c, ms3, run_paged, &pc, got, want, n, 2e-4, 2e-5);
413 } else if (ci == 1) {
414 static const int ms[3] = { OMEGA_GPU_ATTN_MUTANT_KV_HEAD, OMEGA_GPU_ATTN_MUTANT_SLOT, 0 };
415 run_mutants(&c, ms, run_paged, &pc, got, want, n, 2e-4, 2e-5);
416 } else if (ci == 0) {
417 /* one token: its softmax weight is 1 whatever K says, so a K-only slot shift is invisible; KV_HEAD still shows */
418 static const int ms[2] = { OMEGA_GPU_ATTN_MUTANT_KV_HEAD, 0 };
419 run_mutants(&c, ms, run_paged, &pc, got, want, n, 2e-4, 2e-5);
420 } else run_mutants(&c, no_mutants, run_paged, &pc, got, want, n, 2e-4, 2e-5);
421 record(c, out); free(pool); free(ids); free(q); free(got); free(want);
422 }
423 /* 4. batch: three sequences (short, empty, truncated by its table), a negative table entry, table rows of 16 */
424 {
425 uint32_t nqh = 32, nkv = 8, bs = 16, layers = 3, layer = 2, maxb = 16, nseq = 3, pool_blocks = 40;
426 OmegaGpuKvLayout ly = layout_for(pool_blocks, bs, layers, nkv, hd);
427 uint8_t *pool = malloc(ly.pool_bytes); uint16_t *pw = (uint16_t *)pool;
428 for (size_t i = 0; i < ly.pool_bytes / 2; i++) pw[i] = f2bf(frand(&seed, -1.0f, 1.0f));
429 int32_t *tables = malloc((size_t)nseq * maxb * 4);
430 for (size_t i = 0; i < (size_t)nseq * maxb; i++) tables[i] = -1;
431 /* seq 0: ctx 40 over blocks 5, 17 (-1 in the middle closes up), 29 */
432 tables[0] = 5; tables[1] = -1; tables[2] = 17; tables[3] = 29;
433 /* seq 1: ctx 0 with a table */
434 tables[maxb + 0] = 1;
435 /* seq 2: ctx 100 but only 4 blocks (64 tokens used) */
436 tables[2 * maxb + 0] = 30; tables[2 * maxb + 1] = 2; tables[2 * maxb + 2] = 33; tables[2 * maxb + 3] = 11;
437 int32_t ctxs2[3] = { 40, 0, 100 };
438 size_t n = (size_t)nseq * nqh * hd;
439 float *q = malloc(n * 4), *got = malloc(n * 4), *want = malloc(n * 4);
440 for (size_t i = 0; i < n; i++) q[i] = frand(&seed, -1.0f, 1.0f);
441 oracle_batch(q, pool, &ly, tables, ctxs2, maxb, nseq, layer, nqh, nkv, hd, want);
442 Case c = { .name = "paged_bf16_batch_3seq_32q8kv_ctx40_0_100", .n = n };
443 OmegaGpuAttnInfo info; BatchCtx bc = { q, pool, &ly, tables, ctxs2, maxb, nseq, layer, nqh, nkv };
444 c.rc = run_batch(&bc, got, &info);
445 c.bad = compare(got, want, n, 2e-4, 2e-5, &c.worst);
446 c.pass = c.rc == OMEGA_GPU_ATTN_OK && c.bad == 0; case_info(&c, &info);
447 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;
448 CHECK(zeros, "batch: the empty sequence is all zeros");
449 batch_single_repeat_checks(c.name, &bc, got, &c);
450 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 };
451 run_mutants(&c, ms, run_batch, &bc, got, want, n, 2e-4, 2e-5);
452 /* all 7 referenced blocks are distinct here, so dedupe stages exactly the naive figure */
453 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);
454 record(c, out); free(pool); free(tables); free(q); free(got); free(want);
455 }
456 /* 5. branch-heavy batch (attention hardening cut): four sequences share the same 10 physical
457 * prefix blocks (160 tokens, scattered ids) and own private tails of 1..3 blocks ending in a
458 * partial 64-token chunk. The shared prefix must be staged once per launch, keyed by the
459 * physical block id. Two head shapes: 8q/2kv puts all four sequences in one launch
460 * (unique = 10 + 9 tails), 32q/8kv splits them two per launch (unique = 2*10 + 9).
461 * Negative control: the legacy per-sequence staging (test hook) copies the prefix four
462 * times and the byte-reduction check must flag it. */
463 for (int sh = 0; sh < 2; sh++) {
464 uint32_t nqh = sh ? 32 : 8, nkv = sh ? 8 : 2, bs = 16, layers = 2, layer = 1, nseq = 4, prefix_blocks = 10, pool_blocks = 64;
465 uint32_t expect_unique = sh ? 2 * prefix_blocks + 9 : prefix_blocks + 9;
466 uint32_t maxb = prefix_blocks + 3;
467 OmegaGpuKvLayout ly = layout_for(pool_blocks, bs, layers, nkv, hd);
468 uint8_t *pool = malloc(ly.pool_bytes); uint16_t *pw = (uint16_t *)pool;
469 for (size_t i = 0; i < ly.pool_bytes / 2; i++) pw[i] = f2bf(frand(&seed, -1.0f, 1.0f));
470 int32_t *tables = malloc((size_t)nseq * maxb * 4);
471 for (size_t i = 0; i < (size_t)nseq * maxb; i++) tables[i] = -1;
472 const uint32_t tails[4] = { 1, 2, 3, 3 }; /* private blocks per sequence: 9 in all */
473 const int32_t ctxs5[4] = { 165, 180, 193, 207 }; /* 160 + 5, 20, 33, 47: every last chunk partial */
474 for (uint32_t s = 0; s < nseq; s++) {
475 for (uint32_t b = 0; b < prefix_blocks; b++) tables[s * maxb + b] = (int32_t)((b * 5 + 7) % pool_blocks); /* same scattered physical prefix */
476 for (uint32_t b = 0; b < tails[s]; b++) tables[s * maxb + prefix_blocks + b] = (int32_t)(50 + s * 3 + b); /* private, distinct */
477 }
478 size_t n = (size_t)nseq * nqh * hd;
479 float *q = malloc(n * 4), *got = malloc(n * 4), *want = malloc(n * 4), *legacy = malloc(n * 4);
480 for (size_t i = 0; i < n; i++) q[i] = frand(&seed, -1.0f, 1.0f);
481 oracle_batch(q, pool, &ly, tables, ctxs5, maxb, nseq, layer, nqh, nkv, hd, want);
482 char name[96]; snprintf(name, sizeof name, "paged_bf16_shared_prefix_4seq_%uq%ukv_10pre", nqh, nkv);
483 Case c = { .name = strdup(name), .n = n };
484 OmegaGpuAttnInfo info; BatchCtx bc = { q, pool, &ly, tables, ctxs5, maxb, nseq, layer, nqh, nkv };
485 c.rc = run_batch(&bc, got, &info);
486 c.bad = compare(got, want, n, 2e-4, 2e-5, &c.worst);
487 c.pass = c.rc == OMEGA_GPU_ATTN_OK && c.bad == 0; case_info(&c, &info);
488 uint32_t logical = 4 * prefix_blocks + 9;
489 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);
490 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,
491 "%s: staged %" PRIu64 " < naive %" PRIu64 " bytes (saved %" PRIu64 ")", name, c.kv_staged, c.kv_naive, c.kv_naive - c.kv_staged);
492 CHECK(info.kv_source == OMEGA_GPU_ATTN_KV_STAGED && info.q_bytes == n * 4 && info.out_bytes == n * 4 && 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);
493 /* negative control: legacy per-sequence staging duplicates the shared prefix; same answer, more bytes */
494 omega_gpu_attention_test_set_dedupe(false);
495 OmegaGpuAttnInfo li; int lrc = run_batch(&bc, legacy, &li);
496 omega_gpu_attention_test_set_dedupe(true);
497 double lw; size_t lbad = compare(legacy, want, n, 2e-4, 2e-5, &lw);
498 CHECK(lrc == OMEGA_GPU_ATTN_OK && lbad == 0, "%s legacy staging: parity (rc=%s bad=%zu)", name, omega_gpu_attention_rc_name(lrc), lbad);
499 CHECK(li.kv_blocks_unique == logical && li.kv_bytes_staged == li.kv_bytes_naive && li.kv_bytes_staged > c.kv_staged,
500 "%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);
501 CHECK(memcmp(got, legacy, n * 4) == 0, "%s: dedupe and legacy staging are bit-identical", name);
502 batch_single_repeat_checks(name, &bc, got, &c);
503 static const int ms5[3] = { OMEGA_GPU_ATTN_MUTANT_KV_HEAD, OMEGA_GPU_ATTN_MUTANT_SLOT, 0 };
504 run_mutants(&c, ms5, run_batch, &bc, got, want, n, 2e-4, 2e-5);
505 record(c, out); free(pool); free(tables); free(q); free(got); free(want); free(legacy);
506 }
507 /* every mutant the API knows (1 .. COUNT-1) ran at least once and was caught every time;
508 * a mutant added to the enum without a battery entry fails here */
509 for (int m = 1; m < OMEGA_GPU_ATTN_MUTANT_COUNT; m++) {
510 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]);
511 printf("mutant %s: caught %d of %d\n", mutant_name(m), g_mutant_caught[m], g_mutant_run[m]);
512 }
513 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());
514 printf("device_opens=%u\n", omega_gpu_session_open_count());
515 if (out) {
516 fprintf(out, "],\"mutant_count\":%d,\"mutants\":{", OMEGA_GPU_ATTN_MUTANT_COUNT - 1);
517 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]);
518 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");
519 fclose(out);
520 }
521 return 0;
522}
523
524/* ------------------------------------------------------------ host simulator
525 * Executes the allocated IR program (physical registers, so the register allocator's
526 * loop handling is under test too) for every CTA of a launch: 64 threads, 1 KB shared,
527 * host pointers as addresses, SHFL and BAR as lockstep points (all threads of the CTA
528 * must sit at the same instruction). EX2 and RCP are exact here; the chip's are approximate. */
529/* path: hash of every branch decision so far. The IR has no reconvergence instruction
530 * (no BSSY/BSYNC/WARPSYNC), so once a warp splits it may stay split on the chip, and a
531 * SHFL reading an inactive lane is undefined (CUDA guide, warp shuffle functions). Every
532 * SHFL therefore requires one path across the warp, or the simulator stops with error 7. */
533typedef struct { uint32_t r[256]; int pc; int p0; int done; uint64_t path; } SimThr;
534static uint32_t sim_cbank[256];
535static uint8_t sim_shared[1024];
536#define SIM_T 64
537static int g_sim_err;
538static int g_trace, g_trace_launch; static uint32_t g_trace_cx;
539static 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]; }
540static 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); }
541static 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; }
542static 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); }
543static float u2f(uint32_t u) { float f; memcpy(&f, &u, 4); return f; }
544static uint32_t f2u_(float f) { uint32_t u; memcpy(&u, &f, 4); return u; }
545/* run one thread until it reaches a SHFL or BAR (not executed) or EXIT; returns 1 if parked at a sync op */
546static int sim_step(SimThr *t, const BlackwellIRProgram *p, uint32_t tid, uint32_t cx, uint32_t cy) {
547 for (int guard = 0; guard < 50000000; guard++) {
548 if (t->done) return 0;
549 if (t->pc < 0 || (size_t)t->pc >= p->count) { g_sim_err = 1; t->done = 1; return 0; }
550 const BlackwellIRInsn *in = &p->insns[t->pc];
551 uint32_t a = rd(t, in->src1_vreg, p), b = rd(t, in->src2_vreg, p), c = rd(t, in->src3_vreg, p);
552 switch (in->op) {
553 case BW_IR_SHFL_DOWN: case BW_IR_BAR_SYNC: return 1;
554 case BW_IR_EXIT: if (!in->predicate_p0 || t->p0) { t->done = 1; return 0; } break;
555 case BW_IR_BRA: {
556 int take = !in->predicate_p0 || (in->predicate_not ? !t->p0 : t->p0);
557 t->path = t->path * 1000003u + (((uint64_t)t->pc << 1) | (uint64_t)take);
558 if (take) { if ((int32_t)in->imm == 0) { g_sim_err = 2; t->done = 1; return 0; } t->pc += (int32_t)in->imm; continue; }
559 break; }
560 case BW_IR_MOV_IMM: wr(t, in->dst_vreg, in->imm, p); break;
561 case BW_IR_MOV_RZ: wr(t, in->dst_vreg, 0, p); break;
562 case BW_IR_S2R: wr(t, in->dst_vreg, in->imm == BW_SR_TID_X ? tid : in->imm == BW_SR_CTAID_X ? cx : in->imm == BW_SR_CTAID_Y ? cy : 0, p); break;
563 case BW_IR_LDC: wr(t, in->dst_vreg, sim_cbank[in->imm / 4], p); break;
564 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;
565 case BW_IR_LDCU64: break; /* memory descriptor: not modelled */
566 case BW_IR_IMAD: wr(t, in->dst_vreg, in->src2_vreg >= 0 ? a * b + c : a * in->imm + c, p); break;
567 case BW_IR_IMAD_WIDE: wr64(t, in->dst_vreg, (uint64_t)a * in->imm + rd64(t, in->src3_vreg, p), p); break;
568 case BW_IR_IADD3: wr(t, in->dst_vreg, a + b, p); break;
569 case BW_IR_SHF_R: wr(t, in->dst_vreg, a >> (in->imm & 31), p); break;
570 case BW_IR_LOP3_AND: wr(t, in->dst_vreg, a & in->imm, p); break;
571 case BW_IR_LOP3_XOR: wr(t, in->dst_vreg, a ^ b, p); break;
572 case BW_IR_ISETP_GE_U32: t->p0 = a >= b; break;
573 case BW_IR_LDG_E: { uint32_t x; memcpy(&x, (const void *)(uintptr_t)rd64(t, in->src1_vreg, p), 4); wr(t, in->dst_vreg, x, p); break; }
574 case BW_IR_LDG_E_U16: { uint16_t x; memcpy(&x, (const void *)(uintptr_t)rd64(t, in->src1_vreg, p), 2); wr(t, in->dst_vreg, x, p); break; }
575 case BW_IR_STG_E: memcpy((void *)(uintptr_t)rd64(t, in->src1_vreg, p), &b, 4); break;
576 case BW_IR_LDS32: { uint32_t x; if (a + 4 > sizeof sim_shared) { g_sim_err = 3; t->done = 1; return 0; } memcpy(&x, sim_shared + a, 4); wr(t, in->dst_vreg, x, p); break; }
577 case BW_IR_STS32: if (a + 4 > sizeof sim_shared) { g_sim_err = 3; t->done = 1; return 0; } memcpy(sim_shared + a, &b, 4); break;
578 case BW_IR_FADD: wr(t, in->dst_vreg, f2u_(u2f(a) + u2f(b)), p); break;
579 case BW_IR_FSUB: wr(t, in->dst_vreg, f2u_(u2f(a) - u2f(b)), p); break;
580 case BW_IR_FMUL: wr(t, in->dst_vreg, f2u_(u2f(a) * u2f(b)), p); break;
581 case BW_IR_FFMA: wr(t, in->dst_vreg, f2u_(fmaf(u2f(a), u2f(b), u2f(c))), p); break;
582 case BW_IR_FMNMX_MAX: wr(t, in->dst_vreg, f2u_(fmaxf(u2f(a), u2f(b))), p); break;
583 case BW_IR_MUFU_EX2: wr(t, in->dst_vreg, f2u_(exp2f(u2f(a))), p); break;
584 case BW_IR_MUFU_RCP: wr(t, in->dst_vreg, f2u_(1.0f / u2f(a)), p); break;
585 default: g_sim_err = 100 + (int)in->op; t->done = 1; return 0;
586 }
587 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); }
588 t->pc++;
589 }
590 g_sim_err = 4; t->done = 1; return 0;
591}
592static int sim_launch(const void *progv, const OmegaGpuAttnLaunch *L, OmegaGpuAttnInfo *info) {
593 const BlackwellIRProgram *p = progv;
594 memset(sim_cbank, 0, sizeof sim_cbank);
595 uint64_t qa = (uintptr_t)L->q, pa = (uintptr_t)L->pool, oa = (uintptr_t)L->out, ta = (uintptr_t)L->tab;
596 sim_cbank[0x380 / 4] = (uint32_t)qa; sim_cbank[0x380 / 4 + 1] = (uint32_t)(qa >> 32);
597 sim_cbank[0x388 / 4] = (uint32_t)pa; sim_cbank[0x388 / 4 + 1] = (uint32_t)(pa >> 32);
598 sim_cbank[0x390 / 4] = (uint32_t)oa; sim_cbank[0x390 / 4 + 1] = (uint32_t)(oa >> 32);
599 sim_cbank[0x398 / 4] = (uint32_t)ta; sim_cbank[0x398 / 4 + 1] = (uint32_t)(ta >> 32);
600 memcpy(&sim_cbank[0x3a0 / 4], L->params, sizeof L->params);
601 uint32_t *outw = L->out; for (size_t i = 0; i < L->out_bytes / 4; i++) outw[i] = 0xffbadbadu;
602 g_sim_err = 0;
603 static SimThr th[SIM_T];
604 g_trace_launch++; if (getenv("ATTN_SIM_TRACE")) { g_trace = 1; g_trace_cx = (uint32_t)atoi(getenv("ATTN_SIM_TRACE")); }
605 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++) {
606 memset(th, 0, sizeof th); memset(sim_shared, 0, sizeof sim_shared);
607 for (;;) {
608 int parked = 0, alive = 0;
609 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); }
610 if (g_sim_err) break;
611 if (alive == 0) break;
612 if (parked == 0) continue; /* every live thread exited this round */
613 if (parked != alive) { g_sim_err = 5; break; } /* a thread exited while others wait at a barrier */
614 int pc = -1;
615 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; }
616 if (g_sim_err) break;
617 const BlackwellIRInsn *in = &p->insns[pc];
618 if (in->op == BW_IR_SHFL_DOWN) {
619 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;
620 if (g_sim_err) break;
621 uint32_t src[SIM_T];
622 for (int i = 0; i < SIM_T; i++) src[i] = rd(&th[i], in->src1_vreg, p);
623 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); }
624 }
625 for (int i = 0; i < SIM_T; i++) th[i].pc++;
626 }
627 }
628 uint32_t unwritten = 0; for (size_t i = 0; i < L->out_bytes / 4; i++) if (outw[i] == 0xffbadbadu) unwritten++;
629 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; }
630 if (g_sim_err) { printf("simulator error %d\n", g_sim_err); return OMEGA_GPU_ATTN_CHIP_FAIL; }
631 return unwritten ? OMEGA_GPU_ATTN_UNWRITTEN : OMEGA_GPU_ATTN_OK;
632}
633
634
635/* ---------------------------------------------------- timing (cut 4b) */
636/* One query step of TinyLlama attention at context 2048 (32 q heads, 4 kv heads,
637 * f32 KV) 100 times through the persistent session, every call checked against the
638 * oracle; gate: median wall time per call under 3 ms, one device open per process. */
639static double now_ms(void) { struct timespec t; clock_gettime(CLOCK_MONOTONIC, &t); return t.tv_sec * 1e3 + t.tv_nsec / 1e6; }
640static int cmp_d(const void *a, const void *b) { double x = *(const double *)a, y = *(const double *)b; return x < y ? -1 : x > y; }
641static int timing(const char *out_path) {
642 FILE *out = out_path ? fopen(out_path, "w") : NULL;
643 if (out_path && !out) { printf("cannot open %s\n", out_path); return 2; }
644 enum { N = 100 };
645 const uint32_t hd = 64, nqh = 32, nkv = 4, seq = 2048;
646 const char *name = "gqa_f32_tinyllama_32q4kv_ctx2048";
647 if (out) fprintf(out, "{\"schema\":\"OMEGA_GPU_ATTENTION_TIMING_V1\",\"gate_median_ms\":3.0,\"calls\":%d,\"cases\":[", N);
648 uint32_t seed = 0xfb1c004bu;
649 size_t n = (size_t)nqh * hd, nkvs = (size_t)seq * nkv * hd;
650 float *q = malloc(n * 4), *kc = malloc(nkvs * 4), *vc = malloc(nkvs * 4), *got = malloc(n * 4), *want = malloc(n * 4);
651 for (size_t i = 0; i < n; i++) q[i] = frand(&seed, -1.0f, 1.0f);
652 for (size_t i = 0; i < nkvs; i++) { kc[i] = frand(&seed, -1.0f, 1.0f); vc[i] = frand(&seed, -1.0f, 1.0f); }
653 oracle_gqa(q, kc, vc, seq, nqh, nkv, hd, want);
654 double samples[N]; int ok_calls = 0; size_t bad_total = 0; double worst = 0; uint64_t chip_sum = 0; int rc_last = 0;
655 OmegaGpuAttnInfo info;
656 /* warm-up: the first call opens the device and generates the kernel (not timed) */
657 int rc0 = omega_gpu_gqa_attention_f32(q, kc, vc, seq, nqh, nkv, hd, got, &info);
658 double first_ms = info.call_ns / 1e6;
659 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());
660 for (int i = 0; i < N; i++) {
661 double t0 = now_ms();
662 int rc = omega_gpu_gqa_attention_f32(q, kc, vc, seq, nqh, nkv, hd, got, &info);
663 samples[i] = now_ms() - t0;
664 double w; size_t bad = compare(got, want, n, 2e-4, 2e-5, &w);
665 if (w > worst) worst = w;
666 bad_total += bad; chip_sum += info.elapsed_ns; rc_last = rc;
667 if (rc == OMEGA_GPU_ATTN_OK && bad == 0) ok_calls++;
668 }
669 qsort(samples, N, sizeof samples[0], cmp_d);
670 double median = samples[N / 2], p90 = samples[N * 9 / 10], mn = samples[0], mx = samples[N - 1];
671 uint32_t opens = omega_gpu_session_open_count();
672 int pass = ok_calls == N && bad_total == 0 && median < 3.0 && opens == 1;
673 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());
674 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",
675 pass ? "PASS" : "FAIL", name, first_ms, ok_calls, N, bad_total, worst, median, p90, mn, mx, chip_sum / 1e3 / N, opens);
676 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}",
677 name, first_ms, ok_calls, bad_total, worst, median, p90, mn, mx, chip_sum / 1e3 / N, opens, pass ? "true" : "false");
678 free(q); free(kc); free(vc); free(got); free(want);
679 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); }
680 return 0;
681}
682
683/* ------------------------------------------------ head-scaling sweep (attention hardening cut)
684 * `--sweep [--out sweep.json]`: the production paged bf16 path at head_dim 64 over query-head
685 * counts 1, 2, 4, 8, 16, 24, 32, 64 and every divisor as the kv-head count, at context 256
686 * (latency) and 2048 (bandwidth), block size 16, scattered block ids. Points whose GQA ratio
687 * is not a power of two are mathematically legal (the generic contract allows them) but
688 * outside the current kernel envelope (codegen selects the kv head with a shift): they are
689 * called anyway, must be refused with BAD_ARGS, and are recorded as
690 * "unsupported_by_kernel_envelope" (no chip time). Every supported point is checked against
691 * the host oracle on its first call, then warmed and timed over N calls (median / p90 of the
692 * whole call and of the chip kernel time). Gates: parity, no unwritten word, one device open,
693 * every call OK; the timings are evidence, not a threshold. Only quantities the stack measures
694 * are recorded; SM occupancy, bandwidth utilisation and cache hit rates are not observable
695 * through this path and are reported as unavailable. Under --sim the timings are host-simulator
696 * timings and the receipt says so. */
697static int sweep(const char *out_path) {
698 FILE *out = out_path ? fopen(out_path, "w") : NULL;
699 if (out_path && !out) { printf("cannot open %s\n", out_path); return 2; }
700 const int N = g_sim_mode ? 1 : 20;
701 const uint32_t hd = 64, bs = 16, layers = 1, layer = 0;
702 static const uint32_t qheads[8] = { 1, 2, 4, 8, 16, 24, 32, 64 };
703 static const uint32_t ctxs[2] = { 256, 2048 };
704 uint32_t seed = 0xfb1c05eeu;
705 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,"
706 "\"tolerances\":{\"rel\":2e-4,\"abs\":2e-5},\"hardware_counters\":\"unavailable (SM occupancy, bandwidth utilisation, cache hit rates are not observable through this path)\",\"points\":[",
707 hd, bs, N, g_sim_mode ? "true" : "false");
708 int npoints = 0, supported = 0, unsupported = 0;
709 double *samples = malloc((size_t)N * sizeof *samples), *ksamples = malloc((size_t)N * sizeof *ksamples);
710 for (int qi = 0; qi < 8; qi++) for (uint32_t nkv = 1; nkv <= qheads[qi]; nkv++) {
711 uint32_t nqh = qheads[qi];
712 if (nqh % nkv) continue;
713 uint32_t ratio = nqh / nkv; int pow2 = (ratio & (ratio - 1)) == 0;
714 for (int ci = 0; ci < 2; ci++) {
715 uint32_t ctx = ctxs[ci], nblk = (ctx + bs - 1) / bs, pool_blocks = nblk + 5;
716 OmegaGpuKvLayout ly = layout_for(pool_blocks, bs, layers, nkv, hd);
717 uint8_t *pool = malloc(ly.pool_bytes); uint16_t *pw = (uint16_t *)pool;
718 for (size_t i = 0; i < ly.pool_bytes / 2; i++) pw[i] = f2bf(frand(&seed, -1.0f, 1.0f));
719 uint32_t *ids = malloc(nblk * 4);
720 for (uint32_t b = 0; b < nblk; b++) ids[b] = (b * 7 + 3) % pool_blocks;
721 size_t n = (size_t)nqh * hd;
722 float *q = malloc(n * 4), *got = malloc(n * 4), *want = malloc(n * 4);
723 for (size_t i = 0; i < n; i++) q[i] = frand(&seed, -1.0f, 1.0f);
724 OmegaGpuAttnInfo info; memset(&info, 0, sizeof info);
725 int rc = omega_gpu_paged_attention_bf16(q, pool, &ly, ids, nblk, ctx, layer, nqh, nkv, hd, got, &info);
726 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;
727 if (!pow2) {
728 klass = "unsupported_by_kernel_envelope";
729 pass = rc == OMEGA_GPU_ATTN_BAD_ARGS; unsupported++;
730 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));
731 } else {
732 klass = "supported"; supported++;
733 oracle_paged(q, pool, &ly, ids, nblk, ctx, layer, nqh, nkv, hd, want);
734 bad = compare(got, want, n, 2e-4, 2e-5, &worst);
735 unwritten = info.unwritten_words;
736 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;
737 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;
738 for (int i = 0; i < N; i++) {
739 OmegaGpuAttnInfo ti;
740 int trc = omega_gpu_paged_attention_bf16(q, pool, &ly, ids, nblk, ctx, layer, nqh, nkv, hd, got, &ti);
741 samples[i] = ti.call_ns / 1e6; ksamples[i] = ti.elapsed_ns / 1e6;
742 double w; size_t b2 = compare(got, want, n, 2e-4, 2e-5, &w);
743 if (w > worst) worst = w;
744 bad += b2; unwritten += ti.unwritten_words; cache_hits += ti.kernel_cache_hit;
745 if (trc == OMEGA_GPU_ATTN_OK && b2 == 0) ok_calls++;
746 }
747 qsort(samples, (size_t)N, sizeof samples[0], cmp_d); qsort(ksamples, (size_t)N, sizeof ksamples[0], cmp_d);
748 med = samples[N / 2]; p90 = samples[N * 9 / 10]; kmed = ksamples[N / 2]; kp90 = ksamples[N * 9 / 10];
749 pass = rc == OMEGA_GPU_ATTN_OK && bad == 0 && ok_calls == N && unwritten == 0 && cache_hits == (uint32_t)N;
750 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);
751 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",
752 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);
753 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,"
754 "\"violations\":%zu,\"worst_scaled_err\":%g,\"unwritten_words\":%u,\"launches_per_call\":%u,\"ctas_last_launch\":%u,\"threads_per_cta\":%u,"
755 "\"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,"
756 "\"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\"}",
757 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,
758 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");
759 npoints++;
760 }
761 if (!pow2) {
762 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));
763 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}",
764 npoints ? "," : "", nqh, nkv, ratio, hd, ctx, n, n, klass, omega_gpu_attention_rc_name(rc), pass ? "true" : "false");
765 npoints++;
766 }
767 free(pool); free(ids); free(q); free(got); free(want);
768 }
769 }
770 free(samples); free(ksamples);
771 uint32_t opens = omega_gpu_session_open_count();
772 CHECK(opens == (g_sim_mode ? 0u : 1u), "sweep: device opened %s (opens=%u)", g_sim_mode ? "never (simulator)" : "once", opens);
773 printf("sweep: %d points (%d supported, %d unsupported by the kernel envelope), device_opens=%u\n", npoints, supported, unsupported, opens);
774 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); }
775 return 0;
776}
777
778/* ------------------------------------------------------------ warp simulator (omega #308)
779 * The per-thread simulator above has no model of a warp (its SHFL rule is "one path across the
780 * warp or error 7"). With --divergent the kernel carries a real lane-dependent branch inside a
781 * BSSY/BSYNC region, and every launch runs through tests/bw_warp_sim.h instead: 32-lane
782 * fragments, barrier registers, SHFL/BAR participation. Each launch runs in both fragment
783 * orders and the two outputs must be bit-identical. */
784static uint64_t g_ws_issues, g_ws_launches;
785static int ws_attn_launch(const void *progv, const OmegaGpuAttnLaunch *L, OmegaGpuAttnInfo *info) {
786 const BlackwellIRProgram *p = progv;
787 uint32_t *outw = L->out; size_t nw = L->out_bytes / 4;
788 uint32_t *copy = malloc(L->out_bytes);
789 int err = 0; char msg[240] = "";
790 for (int order = 0; order < 2 && !err && copy; order++) {
791 WsSim s; memset(&s, 0, sizeof s);
792 s.p = p; s.threads = SIM_T; s.smem = sim_shared; s.smem_bytes = sizeof sim_shared; s.order = order;
793 uint64_t qa = (uintptr_t)L->q, pa = (uintptr_t)L->pool, oa = (uintptr_t)L->out, ta = (uintptr_t)L->tab;
794 s.cbank[0x380 / 4] = (uint32_t)qa; s.cbank[0x380 / 4 + 1] = (uint32_t)(qa >> 32);
795 s.cbank[0x388 / 4] = (uint32_t)pa; s.cbank[0x388 / 4 + 1] = (uint32_t)(pa >> 32);
796 s.cbank[0x390 / 4] = (uint32_t)oa; s.cbank[0x390 / 4 + 1] = (uint32_t)(oa >> 32);
797 s.cbank[0x398 / 4] = (uint32_t)ta; s.cbank[0x398 / 4 + 1] = (uint32_t)(ta >> 32);
798 memcpy(&s.cbank[0x3a0 / 4], L->params, sizeof L->params);
799 for (size_t i = 0; i < nw; i++) outw[i] = 0xffbadbadu;
800 err = ws_run(&s, L->grid_x, L->grid_y);
801 if (err) { snprintf(msg, sizeof msg, "order %d: %s", order, s.msg); break; }
802 g_ws_issues += s.warp_issues;
803 if (order == 0) memcpy(copy, outw, L->out_bytes);
804 else if (memcmp(copy, outw, L->out_bytes) != 0) { err = -1; snprintf(msg, sizeof msg, "the fragment order changed the result"); }
805 }
806 free(copy);
807 g_ws_launches++;
808 uint32_t unwritten = 0; for (size_t i = 0; i < nw; i++) if (outw[i] == 0xffbadbadu) unwritten++;
809 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; }
810 if (err) { printf("warp simulator error: %s\n", msg); return OMEGA_GPU_ATTN_CHIP_FAIL; }
811 return unwritten ? OMEGA_GPU_ATTN_UNWRITTEN : OMEGA_GPU_ATTN_OK;
812}
813/* Negative control for --divergent --sim: mode 2 builds the same kernel with the BSYNC dropped;
814 * the warp simulator must reject it (the whole point of the simulator: the old one could not). */
815static void divergent_negative_control(void) {
816 enum { SEQ = 65, NQH = 8, NKV = 2, HD = 64 };
817 float *q = malloc(NQH * HD * 4), *kv = malloc((size_t)SEQ * NKV * HD * 4), *out = malloc(NQH * HD * 4);
818 uint32_t seed = 0x308u;
819 for (int i = 0; i < NQH * HD; i++) q[i] = frand(&seed, -1.0f, 1.0f);
820 for (size_t i = 0; i < (size_t)SEQ * NKV * HD; i++) kv[i] = frand(&seed, -1.0f, 1.0f);
821 omega_gpu_attention_test_set_divergent(2);
822 int rc = omega_gpu_gqa_attention_f32(q, kv, kv, SEQ, NQH, NKV, HD, out, NULL);
823 omega_gpu_attention_test_set_divergent(1);
824 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));
825 int rc1 = omega_gpu_gqa_attention_f32(q, kv, kv, SEQ, NQH, NKV, HD, out, NULL);
826 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));
827 free(q); free(kv); free(out);
828}
829
830int main(int argc, char **argv) {
831 const char *out_path = NULL; int host = 0, sim = 0, timing_mode = 0, sweep_mode = 0;
832 for (int i = 1; i < argc; i++) {
833 if (strcmp(argv[i], "--host-only") == 0) host = 1;
834 else if (strcmp(argv[i], "--sim") == 0) sim = 1;
835 else if (strcmp(argv[i], "--divergent") == 0) g_divergent = 1;
836 else if (strcmp(argv[i], "--timing") == 0) timing_mode = 1;
837 else if (strcmp(argv[i], "--sweep") == 0) sweep_mode = 1;
838 else if (strcmp(argv[i], "--out") == 0 && i + 1 < argc) out_path = argv[++i];
839 }
840 if (g_divergent) omega_gpu_attention_test_set_divergent(1);
841 if (sim) { g_sim_mode = 1; omega_gpu_attention_test_set_simulator(g_divergent ? ws_attn_launch : sim_launch); }
842 if (sim && g_divergent && !host) divergent_negative_control();
843 if (host) host_only();
844 else if (timing_mode) { if (timing(out_path) != 0) return 2; }
845 else if (sweep_mode) { if (sweep(out_path) != 0) return 2; }
846 else if (chip(out_path) != 0) return 2;
847 printf("%s: %d checks, %d failed\n", g_failed ? "FAIL" : "PASS", g_checks, g_failed);
848 return g_failed ? 1 : 0;
849}