Interplane page as plain text, for reading tools and agents. English is the reference text: translate it with your own tool. Text in backticks and in ``` blocks (commands, fingerprints, file names) and link targets in <...> are exact: copy them, never translate them. Page: /drakestapleton/omega-mv/blob/main/evidence/FB1-CUT5-b016322/gpu_attention_test.c # omega-mv Omega: a language for verified programs, semantic identity and machine realization. Seed-born work and existing implementations have distinct provenance. Brought by drakestapleton Sign in to star 1 stars 0 watching About Files History Releases Proposed changes Issues For developers branch `main` Branches Tags History `omega-mv / evidence / FB1-CUT5-b016322 / gpu_attention_test.c` 498 lines ยท 36184 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 --out receipt.json chip gate: every shape against the host oracle, the 6 * mutants (deliberately wrong kernels) which the same 7 * check must catch, a negative control, timings 8 * 9 * Oracles re-state aien-sovereign-core crates/aien-inference-abi/src/backend.rs (main `8b5caed`) in C: 10 * ReferenceCpuBackend::gqa_attention (f64 scores, max, exp, sum, 1/max(sum,1e-12), f64 weighted sum), 11 * TensorBackend::paged_attention (f64 online softmax token by token over the paged bf16 pool, tokens 12 * past the block table dropped, zeros for empty context) and paged_attention_batch (ctx <= 0 -> 0, 13 * table rows past the array -> empty, negative entries removed). Compiled with -ffp-contract=off. 14 * 15 * Tolerance (why): the chip accumulates the 64-term dot products, the per-chunk sums and the 16 * rescaled running sums in f32 (worst case about n * 2^-24 relative over n = 2048 terms, 1.2e-4), 17 * uses MUFU.EX2 (PTX ex2.approx: 2^-22.5 relative) for every weight and for the 32 chunk rescale 18 * factors, and MUFU.RCP for the final normalisation. Every output is a convex combination of V 19 * values of unit scale, so |error| <= 2e-4 * |want| + 2e-5 covers these with margin; the mutants 20 * move results by 1e-2 or more (wrong head, wrong token) or produce NaN (overflow without the max). 21 * The large-score case (scores up to ~300) carries the f32 rounding of the score itself into the 22 * exponent (3e-5 absolute per score), so it uses 1e-3 relative + 1e-4 absolute. 23 */ 24 #include "omega_gpu_attention_api.h" 25 #include "omega_blackwell_codegen.h" 26 #include 27 #include 28 #include 29 #include 30 #include 31 #include 32 #include 33 34 static int g_checks, g_failed; 35 #define CHECK(cond, ...) do { g_checks++; if (!(cond)) { g_failed++; printf("FAIL: "); printf(__VA_ARGS__); printf("\n"); } } while (0) 36 37 static uint32_t lcg(uint32_t *s) { *s = *s * 1664525u + 1013904223u; return *s; } 38 static float frand(uint32_t *s, float lo, float hi) { return lo + (hi - lo) * ((float)(lcg(s) >> 8) / `16777216`.0f); } 39 static uint16_t f2bf(float f) { uint32_t u; memcpy(&u, &f, 4); uint32_t r = ((u >> 16) & 1u) + 0x7fffu; return (uint16_t)((u + r) >> 16); } 40 static float bf2f(uint16_t b) { uint32_t u = (uint32_t)b << 16; float f; memcpy(&f, &u, 4); return f; } 41 42 /* ----------------------------------------------------------------- oracles */ 43 static void oracle_gqa(const float *q, const float *kc, const float *vc, size_t seq_len, size_t nqh, size_t nkv, size_t hd, float *out) { 44 if (seq_len == 0) { memset(out, 0, nqh * hd * 4); return; } 45 size_t ratio = nqh / nkv; double inv_sqrt_d = 1.0 / sqrt((double)hd); 46 double *scores = malloc(seq_len * sizeof *scores); 47 for (size_t h = 0; h < nqh; h++) { 48 size_t kvh = h / ratio; const float *qh = q + h * hd; 49 for (size_t t = 0; t < seq_len; t++) { 50 const float *kt = kc + (t * nkv + kvh) * hd; double dot = 0.0; 51 for (size_t d = 0; d < hd; d++) dot += (double)qh[d] * (double)kt[d]; 52 scores[t] = dot * inv_sqrt_d; 53 } 54 double mx = -INFINITY; for (size_t t = 0; t < seq_len; t++) if (scores[t] > mx) mx = scores[t]; 55 double sum = 0.0; for (size_t t = 0; t < seq_len; t++) { scores[t] = exp(scores[t] - mx); sum += scores[t]; } 56 double inv = 1.0 / (sum > 1e-12 ? sum : 1e-12); 57 for (size_t t = 0; t < seq_len; t++) scores[t] *= inv; 58 for (size_t d = 0; d < hd; d++) { 59 double s = 0.0; 60 for (size_t t = 0; t < seq_len; t++) s += scores[t] * (double)vc[(t * nkv + kvh) * hd + d]; 61 out[h * hd + d] = (float)s; 62 } 63 } 64 free(scores); 65 } 66 /* bf16 pool in the canonical layout; the oracle's read_kv_head: element_offset(block, layer, is_value, token) + kv_head*head_dim*2 */ 67 static const uint16_t *kv_head(const uint8_t *pool, const OmegaGpuKvLayout *ly, size_t blk, size_t layer, int is_v, size_t tok, size_t kvh, size_t hd) { 68 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; 69 return (const uint16_t *)(pool + off); 70 } 71 static void oracle_paged(const float *q, const uint8_t *pool, const OmegaGpuKvLayout *ly, const uint32_t *ids, size_t nids, size_t ctx, size_t layer, 72 size_t nqh, size_t nkv, size_t hd, float *out) { 73 if (ctx == 0 || nids == 0) { memset(out, 0, nqh * hd * 4); return; } 74 size_t ratio = nqh / nkv; double inv_sqrt_d = 1.0 / sqrt((double)hd); size_t bs = ly->block_size; 75 double *acc = malloc(hd * sizeof *acc); 76 for (size_t h = 0; h < nqh; h++) { 77 size_t kvh = h / ratio; const float *qh = q + h * hd; 78 double m = -INFINITY, l = 0.0; for (size_t d = 0; d < hd; d++) acc[d] = 0.0; 79 for (size_t t = 0; t < ctx; t++) { 80 size_t bi = t / bs; if (bi >= nids) break; 81 const uint16_t *kh = kv_head(pool, ly, ids[bi], layer, 0, t % bs, kvh, hd); 82 const uint16_t *vh = kv_head(pool, ly, ids[bi], layer, 1, t % bs, kvh, hd); 83 double dot = 0.0; for (size_t d = 0; d < hd; d++) dot += (double)qh[d] * (double)bf2f(kh[d]); 84 double score = dot * inv_sqrt_d, mn = m > score ? m : score, alpha = exp(m - mn), beta = exp(score - mn); 85 l = l * alpha + beta; 86 for (size_t d = 0; d < hd; d++) acc[d] = acc[d] * alpha + beta * (double)bf2f(vh[d]); 87 m = mn; 88 } 89 double inv = l > 0.0 ? 1.0 / l : 0.0; 90 for (size_t d = 0; d < hd; d++) out[h * hd + d] = (float)(acc[d] * inv); 91 } 92 free(acc); 93 } 94 static void oracle_batch(const float *q, const uint8_t *pool, const OmegaGpuKvLayout *ly, const int32_t *tables, const int32_t *ctxs, size_t maxb, size_t nseq, 95 size_t layer, size_t nqh, size_t nkv, size_t hd, float *out) { 96 size_t stride = nqh * hd; 97 uint32_t *ids = malloc((maxb ? maxb : 1) * sizeof *ids); 98 for (size_t s = 0; s < nseq; s++) { 99 size_t ctx = ctxs[s] > 0 ? (size_t)ctxs[s] : 0, n = 0; 100 size_t total = nseq * maxb; /* the table array length as the trait sees it */ 101 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]; 102 oracle_paged(q + s * stride, pool, ly, ids, n, ctx, layer, nqh, nkv, hd, out + s * stride); 103 } 104 free(ids); 105 } 106 107 static size_t compare(const float *got, const float *want, size_t n, double rel, double abs_tol, double *worst) { 108 size_t bad = 0; *worst = 0.0; 109 for (size_t i = 0; i < n; i++) { 110 double d = fabs((double)got[i] - (double)want[i]); 111 double lim = rel * fabs((double)want[i]) + abs_tol; 112 double scaled = lim > 0 ? d / lim : (d > 0 ? INFINITY : 0.0); 113 if (scaled > *worst) *worst = scaled; 114 if (!(d <= lim)) bad++; /* NaN counts as bad */ 115 } 116 return bad; 117 } 118 119 /* ------------------------------------------------------------- host only */ 120 static int nvdisasm_check(bool f32, const char *name, const char *const *must, int n_must) { 121 const char *nv = "/usr/local/cuda/bin/nvdisasm"; 122 if (access(nv, X_OK) != 0) { printf("nvdisasm: not present, listing check skipped for %s\n", name); return 0; } 123 OmegaBlackwellKernel k; memset(&k, 0, sizeof k); 124 if (omega_gpu_attention_codegen(f32, f32 ? 12 : 4, 3, &k) != OMEGA_GPU_ATTN_OK) return -1; 125 char bin[64], lst[64], cmd[256]; 126 snprintf(bin, sizeof bin, "/tmp/omega_attn_%s_%d.bin", name, (int)getpid()); 127 snprintf(lst, sizeof lst, "/tmp/omega_attn_%s_%d.sass", name, (int)getpid()); 128 FILE *f = fopen(bin, "wb"); if (!f) { free(k.code); return -1; } 129 fwrite(k.code, 1, k.code_size, f); fclose(f); 130 snprintf(cmd, sizeof cmd, "%s -b SM121 %s > %s 2>&1", nv, bin, lst); 131 int rc = system(cmd); 132 free(k.code); 133 FILE *l = fopen(lst, "r"); if (!l) return -1; 134 char line[512]; int seen[16] = {0}; int bad = 0, insns = 0; 135 while (fgets(line, sizeof line, l)) { 136 if (!strstr(line, "/*0")) continue; 137 insns++; 138 if (strstr(line, "?") || strstr(line, "error")) bad++; 139 for (int i = 0; i < n_must; i++) if (strstr(line, must[i])) seen[i] = 1; 140 } 141 fclose(l); 142 int miss = 0; 143 for (int i = 0; i < n_must; i++) if (!seen[i]) { printf(" %s: nvdisasm listing lacks %s\n", name, must[i]); miss++; } 144 printf("nvdisasm %s: rc=%d insns=%d undecodable=%d missing=%d (%s)\n", name, rc, insns, bad, miss, lst); 145 unlink(bin); 146 return (rc == 0 && bad == 0 && miss == 0) ? 0 : -1; 147 } 148 149 static OmegaGpuKvLayout layout_for(uint32_t num_blocks, uint32_t bs, uint32_t layers, uint32_t nkv, uint32_t hd) { 150 OmegaGpuKvLayout ly; 151 ly.head_stride_bytes = (uint64_t)hd * 2; ly.token_stride_bytes = ly.head_stride_bytes * nkv; 152 ly.kv_plane_stride_bytes = ly.token_stride_bytes * bs; ly.layer_stride_bytes = 2 * ly.kv_plane_stride_bytes; 153 ly.block_stride_bytes = ly.layer_stride_bytes * layers; ly.pool_bytes = ly.block_stride_bytes * num_blocks; 154 ly.num_blocks = num_blocks; ly.num_layers = layers; ly.block_size = bs; 155 return ly; 156 } 157 158 static void host_only(void) { 159 float q[64 * 64], kv[64 * 64], out[64 * 64]; memset(q, 0, sizeof q); memset(kv, 0, sizeof kv); 160 CHECK(omega_gpu_gqa_attention_f32(NULL, kv, kv, 1, 32, 4, 64, out, NULL) == OMEGA_GPU_ATTN_BAD_ARGS, "NULL q refused"); 161 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)"); 162 CHECK(omega_gpu_gqa_attention_f32(q, kv, kv, 1, 6, 2, 64, out, NULL) == OMEGA_GPU_ATTN_BAD_ARGS, "gqa ratio 3 refused"); 163 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"); 164 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"); 165 for (int i = 0; i < 64; i++) out[i] = 1.0f; 166 OmegaGpuAttnInfo info; 167 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"); 168 OmegaGpuKvLayout ly = layout_for(8, 16, 2, 4, 64); 169 uint8_t *pool = calloc(ly.pool_bytes, 1); 170 uint32_t ids[2] = { 1, 9 }; 171 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"); 172 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"); 173 OmegaGpuKvLayout bad = ly; bad.block_size = 12; 174 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"); 175 bad = ly; bad.head_stride_bytes = 256; 176 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"); 177 free(pool); 178 CHECK(strcmp(omega_gpu_attention_rc_name(OMEGA_GPU_ATTN_UNWRITTEN), "UNWRITTEN") == 0, "rc name"); 179 180 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" }; 181 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" }; 182 for (int f32 = 0; f32 < 2; f32++) { 183 const char *name = f32 ? "gqa_f32" : "paged_bf16"; 184 OmegaBlackwellKernel k; memset(&k, 0, sizeof k); 185 int rc = omega_gpu_attention_codegen(f32 != 0, f32 ? 12 : 4, 3, &k); 186 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); 187 printf("codegen %s: %zu insns, %u gprs, %u ugprs\n", name, k.insn_count, k.gpr_count, k.uniform_gpr_count); 188 uint8_t digest[32]; memcpy(digest, k.code_digest, 32); 189 free(k.code); 190 for (int m = 1; m <= 4; m++) { 191 omega_gpu_attention_test_set_mutant((OmegaGpuAttnMutant)m); 192 memset(&k, 0, sizeof k); 193 CHECK(omega_gpu_attention_codegen(f32 != 0, f32 ? 12 : 4, 3, &k) == OMEGA_GPU_ATTN_OK && memcmp(digest, k.code_digest, 32) != 0, "%s mutant %d kernel differs", name, m); 194 free(k.code); 195 omega_gpu_attention_test_set_mutant(OMEGA_GPU_ATTN_MUTANT_NONE); 196 } 197 /* a different shape key is a different kernel */ 198 memset(&k, 0, sizeof k); 199 CHECK(omega_gpu_attention_codegen(f32 != 0, f32 ? 12 : 4, 2, &k) == OMEGA_GPU_ATTN_OK && memcmp(digest, k.code_digest, 32) != 0, "%s log2gqa 2 kernel differs from log2gqa 3", name); 200 free(k.code); 201 CHECK(nvdisasm_check(f32 != 0, name, f32 ? must_f32 : must_bf16, f32 ? 11 : 14) == 0, "%s nvdisasm listing decodes and shows the expected instructions", name); 202 } 203 } 204 205 /* ------------------------------------------------------------- chip gate */ 206 typedef struct { const char *name; size_t n; int rc; size_t bad; double worst; int pass; uint64_t chip_ns, call_ns; uint32_t calls, unwritten; 207 int mutants_run, mutants_caught; char mutant_note[160]; } Case; 208 static Case g_cases[32]; static int g_ncases; 209 static int g_mutant_caught[5], g_mutant_run[5]; 210 211 static void record(Case c, FILE *out) { 212 g_cases[g_ncases++] = c; 213 CHECK(c.pass, "%s rc=%s violations=%zu worst=%g", c.name, omega_gpu_attention_rc_name(c.rc), c.bad, c.worst); 214 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); 215 printf("%s %s n=%zu rc=%s violations=%zu worst_scaled_err=%g chip_ns=%" PRIu64 " call_ns=%" PRIu64 " calls=%u unwritten=%u | mutants %d/%d %s\n", 216 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, 217 c.mutants_caught, c.mutants_run, c.mutant_note); 218 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,\"mutants_run\":%d,\"mutants_caught\":%d,\"mutant_note\":\"%s\"}", 219 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, 220 c.mutants_run, c.mutants_caught, c.mutant_note); 221 } 222 223 static const char *mutant_name(int m) { static const char *n[5] = { "none", "NO_MAX", "KV_HEAD", "SLOT", "NO_RESCALE" }; return n[m]; } 224 225 /* Runs the mutants listed in `ms` (terminated by 0) through `run` and counts the catches. */ 226 typedef int (*RunFn)(void *ctx, float *got, OmegaGpuAttnInfo *info); 227 static void run_mutants(Case *c, const int *ms, RunFn run, void *ctx, float *got, const float *want, size_t n, double rel, double abs_tol) { 228 size_t pos = 0; 229 for (int i = 0; ms[i]; i++) { 230 OmegaGpuAttnInfo info; double w; 231 omega_gpu_attention_test_set_mutant((OmegaGpuAttnMutant)ms[i]); 232 int rc = run(ctx, got, &info); 233 size_t bad = compare(got, want, n, rel, abs_tol, &w); 234 int caught = rc != OMEGA_GPU_ATTN_OK || bad > 0; 235 omega_gpu_attention_test_set_mutant(OMEGA_GPU_ATTN_MUTANT_NONE); 236 c->mutants_run++; c->mutants_caught += caught; g_mutant_run[ms[i]]++; g_mutant_caught[ms[i]] += caught; 237 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); 238 if (pos >= sizeof c->mutant_note) break; 239 } 240 } 241 242 typedef struct { const float *q, *kc, *vc; uint32_t seq, nqh, nkv; } GqaCtx; 243 static int run_gqa(void *p, float *got, OmegaGpuAttnInfo *info) { GqaCtx *c = p; return omega_gpu_gqa_attention_f32(c->q, c->kc, c->vc, c->seq, c->nqh, c->nkv, 64, got, info); } 244 typedef struct { const float *q; const uint8_t *pool; const OmegaGpuKvLayout *ly; const uint32_t *ids; uint32_t nids, ctx, layer, nqh, nkv; } PagedCtx; 245 static int run_paged(void *p, float *got, OmegaGpuAttnInfo *info) { PagedCtx *c = p; return omega_gpu_paged_attention_bf16(c->q, c->pool, c->ly, c->ids, c->nids, c->ctx, c->layer, c->nqh, c->nkv, 64, got, info); } 246 typedef struct { const float *q; const uint8_t *pool; const OmegaGpuKvLayout *ly; const int32_t *tables, *ctxs; uint32_t maxb, nseq, layer, nqh, nkv; } BatchCtx; 247 static int run_batch(void *p, float *got, OmegaGpuAttnInfo *info) { BatchCtx *c = p; return omega_gpu_paged_attention_batch_bf16(c->q, c->pool, c->ly, c->tables, c->ctxs, c->maxb, c->nseq, c->layer, c->nqh, c->nkv, 64, got, info); } 248 249 static int chip(const char *out_path) { 250 FILE *out = out_path ? fopen(out_path, "w") : NULL; 251 if (out_path && !out) { printf("cannot open %s\n", out_path); return 2; } 252 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\":["); 253 uint32_t seed = 0xfb1c0005u; 254 const uint32_t hd = 64; 255 const struct { uint32_t nqh, nkv; const char *model; } shapes[2] = { { 32, 4, "tinyllama" }, { 32, 8, "llama32_1b" } }; 256 const uint32_t ctxs[4] = { 1, 17, 256, 2048 }; 257 const int no_mutants[1] = { 0 }; 258 259 /* 1. contiguous f32 KV (gqa_attention) */ 260 for (int sh = 0; sh < 2; sh++) for (int ci = 0; ci < 4; ci++) { 261 uint32_t nqh = shapes[sh].nqh, nkv = shapes[sh].nkv, seq = ctxs[ci]; 262 size_t n = (size_t)nqh * hd, nkvs = (size_t)seq * nkv * hd; 263 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); 264 for (size_t i = 0; i < n; i++) q[i] = frand(&seed, -1.0f, 1.0f); 265 for (size_t i = 0; i < nkvs; i++) { kc[i] = frand(&seed, -1.0f, 1.0f); vc[i] = frand(&seed, -1.0f, 1.0f); } 266 oracle_gqa(q, kc, vc, seq, nqh, nkv, hd, want); 267 char name[96]; snprintf(name, sizeof name, "gqa_f32_%s_%uq%ukv_ctx%u", shapes[sh].model, nqh, nkv, seq); 268 Case c = { .name = strdup(name), .n = n }; 269 OmegaGpuAttnInfo info; 270 GqaCtx gc = { q, kc, vc, seq, nqh, nkv }; 271 c.rc = run_gqa(&gc, got, &info); 272 c.bad = compare(got, want, n, 2e-4, 2e-5, &c.worst); 273 c.pass = c.rc == OMEGA_GPU_ATTN_OK && c.bad == 0; c.chip_ns = info.elapsed_ns; c.call_ns = info.call_ns; c.calls = info.chip_calls; c.unwritten = info.unwritten_words; 274 if (ci == 3) { 275 OmegaGpuAttnInfo i2; int rc2 = run_gqa(&gc, again, &i2); 276 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); 277 /* negative control: the comparison must reject a wrong expectation (kv heads swapped) */ 278 float *wrong = malloc(n * 4); double w2; 279 for (uint32_t h = 0; h < nqh; h++) memcpy(wrong + (size_t)h * hd, want + (size_t)((h + nqh / nkv) % nqh) * hd, hd * 4); 280 size_t neg = compare(got, wrong, n, 2e-4, 2e-5, &w2); 281 CHECK(neg > n / 2, "%s negative control: wrong expectation flagged (%zu of %zu)", name, neg, n); 282 free(wrong); 283 static const int ms[3] = { OMEGA_GPU_ATTN_MUTANT_SLOT, OMEGA_GPU_ATTN_MUTANT_NO_RESCALE, 0 }; 284 run_mutants(&c, ms, run_gqa, &gc, got, want, n, 2e-4, 2e-5); 285 } else if (ci == 1 && sh == 1) { 286 static const int ms[2] = { OMEGA_GPU_ATTN_MUTANT_KV_HEAD, 0 }; 287 run_mutants(&c, ms, run_gqa, &gc, got, want, n, 2e-4, 2e-5); 288 } else run_mutants(&c, no_mutants, run_gqa, &gc, got, want, n, 2e-4, 2e-5); 289 record(c, out); free(q); free(kc); free(vc); free(got); free(want); free(again); 290 } 291 /* 2. large scores (q scaled by 200): the softmax without the running max overflows */ 292 { 293 uint32_t nqh = 32, nkv = 4, seq = 256; size_t n = (size_t)nqh * hd, nkvs = (size_t)seq * nkv * hd; 294 float *q = malloc(n * 4), *kc = malloc(nkvs * 4), *vc = malloc(nkvs * 4), *got = malloc(n * 4), *want = malloc(n * 4); 295 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) */ 296 for (size_t i = 0; i < nkvs; i++) { kc[i] = frand(&seed, -1.0f, 1.0f); vc[i] = frand(&seed, -1.0f, 1.0f); } 297 oracle_gqa(q, kc, vc, seq, nqh, nkv, hd, want); 298 Case c = { .name = "gqa_f32_large_scores_32q4kv_ctx256", .n = n }; 299 OmegaGpuAttnInfo info; GqaCtx gc = { q, kc, vc, seq, nqh, nkv }; 300 c.rc = run_gqa(&gc, got, &info); 301 c.bad = compare(got, want, n, 1e-3, 1e-4, &c.worst); 302 c.pass = c.rc == OMEGA_GPU_ATTN_OK && c.bad == 0; c.chip_ns = info.elapsed_ns; c.call_ns = info.call_ns; c.calls = info.chip_calls; c.unwritten = info.unwritten_words; 303 static const int ms[2] = { OMEGA_GPU_ATTN_MUTANT_NO_MAX, 0 }; 304 run_mutants(&c, ms, run_gqa, &gc, got, want, n, 1e-3, 1e-4); 305 record(c, out); free(q); free(kc); free(vc); free(got); free(want); 306 } 307 /* 3. paged bf16 KV, block size 16, 2 layers (layer 1 under test), scattered block ids */ 308 for (int sh = 0; sh < 2; sh++) for (int ci = 0; ci < 4; ci++) { 309 uint32_t nqh = shapes[sh].nqh, nkv = shapes[sh].nkv, ctx = ctxs[ci], bs = 16, layers = 2, layer = 1; 310 uint32_t nblk = (ctx + bs - 1) / bs, pool_blocks = nblk + 7; 311 OmegaGpuKvLayout ly = layout_for(pool_blocks, bs, layers, nkv, hd); 312 uint8_t *pool = malloc(ly.pool_bytes); uint16_t *pw = (uint16_t *)pool; 313 for (size_t i = 0; i < ly.pool_bytes / 2; i++) pw[i] = f2bf(frand(&seed, -1.0f, 1.0f)); 314 uint32_t *ids = malloc(nblk * 4); /* a scattered permutation of the pool blocks */ 315 for (uint32_t b = 0; b < nblk; b++) ids[b] = (b * 7 + 3) % pool_blocks; 316 size_t n = (size_t)nqh * hd; 317 float *q = malloc(n * 4), *got = malloc(n * 4), *want = malloc(n * 4); 318 for (size_t i = 0; i < n; i++) q[i] = frand(&seed, -1.0f, 1.0f); 319 oracle_paged(q, pool, &ly, ids, nblk, ctx, layer, nqh, nkv, hd, want); 320 char name[96]; snprintf(name, sizeof name, "paged_bf16_%s_%uq%ukv_bs%u_ctx%u", shapes[sh].model, nqh, nkv, bs, ctx); 321 Case c = { .name = strdup(name), .n = n }; 322 OmegaGpuAttnInfo info; PagedCtx pc = { q, pool, &ly, ids, nblk, ctx, layer, nqh, nkv }; 323 c.rc = run_paged(&pc, got, &info); 324 c.bad = compare(got, want, n, 2e-4, 2e-5, &c.worst); 325 c.pass = c.rc == OMEGA_GPU_ATTN_OK && c.bad == 0; c.chip_ns = info.elapsed_ns; c.call_ns = info.call_ns; c.calls = info.chip_calls; c.unwritten = info.unwritten_words; 326 if (ci == 3) { 327 /* NO_MAX cannot overflow on unit-scale scores (softmax is shift invariant); it is caught by the large-score gqa case */ 328 static const int ms3[4] = { OMEGA_GPU_ATTN_MUTANT_KV_HEAD, OMEGA_GPU_ATTN_MUTANT_SLOT, OMEGA_GPU_ATTN_MUTANT_NO_RESCALE, 0 }; 329 run_mutants(&c, ms3, run_paged, &pc, got, want, n, 2e-4, 2e-5); 330 } else if (ci == 1) { 331 static const int ms[3] = { OMEGA_GPU_ATTN_MUTANT_KV_HEAD, OMEGA_GPU_ATTN_MUTANT_SLOT, 0 }; 332 run_mutants(&c, ms, run_paged, &pc, got, want, n, 2e-4, 2e-5); 333 } else if (ci == 0) { 334 /* one token: its softmax weight is 1 whatever K says, so a K-only slot shift is invisible; KV_HEAD still shows */ 335 static const int ms[2] = { OMEGA_GPU_ATTN_MUTANT_KV_HEAD, 0 }; 336 run_mutants(&c, ms, run_paged, &pc, got, want, n, 2e-4, 2e-5); 337 } else run_mutants(&c, no_mutants, run_paged, &pc, got, want, n, 2e-4, 2e-5); 338 record(c, out); free(pool); free(ids); free(q); free(got); free(want); 339 } 340 /* 4. batch: three sequences (short, empty, truncated by its table), a negative table entry, table rows of 16 */ 341 { 342 uint32_t nqh = 32, nkv = 8, bs = 16, layers = 3, layer = 2, maxb = 16, nseq = 3, pool_blocks = 40; 343 OmegaGpuKvLayout ly = layout_for(pool_blocks, bs, layers, nkv, hd); 344 uint8_t *pool = malloc(ly.pool_bytes); uint16_t *pw = (uint16_t *)pool; 345 for (size_t i = 0; i < ly.pool_bytes / 2; i++) pw[i] = f2bf(frand(&seed, -1.0f, 1.0f)); 346 int32_t *tables = malloc((size_t)nseq * maxb * 4); 347 for (size_t i = 0; i < (size_t)nseq * maxb; i++) tables[i] = -1; 348 /* seq 0: ctx 40 over blocks 5, 17 (-1 in the middle closes up), 29 */ 349 tables[0] = 5; tables[1] = -1; tables[2] = 17; tables[3] = 29; 350 /* seq 1: ctx 0 with a table */ 351 tables[maxb + 0] = 1; 352 /* seq 2: ctx 100 but only 4 blocks (64 tokens used) */ 353 tables[2 * maxb + 0] = 30; tables[2 * maxb + 1] = 2; tables[2 * maxb + 2] = 33; tables[2 * maxb + 3] = 11; 354 int32_t ctxs2[3] = { 40, 0, 100 }; 355 size_t n = (size_t)nseq * nqh * hd; 356 float *q = malloc(n * 4), *got = malloc(n * 4), *want = malloc(n * 4); 357 for (size_t i = 0; i < n; i++) q[i] = frand(&seed, -1.0f, 1.0f); 358 oracle_batch(q, pool, &ly, tables, ctxs2, maxb, nseq, layer, nqh, nkv, hd, want); 359 Case c = { .name = "paged_bf16_batch_3seq_32q8kv_ctx40_0_100", .n = n }; 360 OmegaGpuAttnInfo info; BatchCtx bc = { q, pool, &ly, tables, ctxs2, maxb, nseq, layer, nqh, nkv }; 361 c.rc = run_batch(&bc, got, &info); 362 c.bad = compare(got, want, n, 2e-4, 2e-5, &c.worst); 363 c.pass = c.rc == OMEGA_GPU_ATTN_OK && c.bad == 0; c.chip_ns = info.elapsed_ns; c.call_ns = info.call_ns; c.calls = info.chip_calls; c.unwritten = info.unwritten_words; 364 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; 365 CHECK(zeros, "batch: the empty sequence is all zeros"); 366 static const int ms[3] = { OMEGA_GPU_ATTN_MUTANT_KV_HEAD, OMEGA_GPU_ATTN_MUTANT_SLOT, 0 }; 367 run_mutants(&c, ms, run_batch, &bc, got, want, n, 2e-4, 2e-5); 368 record(c, out); free(pool); free(tables); free(q); free(got); free(want); 369 } 370 for (int m = 1; m <= 4; m++) { 371 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]); 372 printf("mutant %s: caught %d of %d\n", mutant_name(m), g_mutant_caught[m], g_mutant_run[m]); 373 } 374 if (out) { 375 fprintf(out, "],\"mutants\":{"); 376 for (int m = 1; m <= 4; m++) fprintf(out, "%s\"%s\":{\"run\":%d,\"caught\":%d}", m > 1 ? "," : "", mutant_name(m), g_mutant_run[m], g_mutant_caught[m]); 377 fprintf(out, "},\"checks\":%d,\"failed\":%d,\"verdict\":\"%s\"}\n", g_checks, g_failed, g_failed == 0 ? "OMEGA_GPU_ATTENTION_PASS" : "OMEGA_GPU_ATTENTION_FAIL"); 378 fclose(out); 379 } 380 return 0; 381 } 382 383 /* ------------------------------------------------------------ host simulator 384 * Executes the allocated IR program (physical registers, so the register allocator's 385 * loop handling is under test too) for every CTA of a launch: 64 threads, 1 KB shared, 386 * host pointers as addresses, SHFL and BAR as lockstep points (all threads of the CTA 387 * must sit at the same instruction). EX2 and RCP are exact here; the chip's are approximate. */ 388 typedef struct { uint32_t r[256]; int pc; int p0; int done; } SimThr; 389 static uint32_t sim_cbank[256]; 390 static uint8_t sim_shared[1024]; 391 #define SIM_T 64 392 static int g_sim_err; 393 static int g_trace, g_trace_launch; static uint32_t g_trace_cx; 394 static uint32_t rd(const SimThr *t, int v, const BlackwellIRProgram *p) { if (v < 0) return 0; int ph = p->regalloc.vreg_to_phys[v]; return ph < 0 ? 0 : t->r[ph & 0xff]; } 395 static uint64_t rd64(const SimThr *t, int v, const BlackwellIRProgram *p) { if (v < 0) return 0; int ph = p->regalloc.vreg_to_phys[v] & 0xff; return (uint64_t)t->r[ph] | ((uint64_t)t->r[ph + 1] << 32); } 396 static void wr(SimThr *t, int v, uint32_t x, const BlackwellIRProgram *p) { if (v < 0) return; int ph = p->regalloc.vreg_to_phys[v]; if (ph >= 0) t->r[ph & 0xff] = x; } 397 static void wr64(SimThr *t, int v, uint64_t x, const BlackwellIRProgram *p) { if (v < 0) return; int ph = p->regalloc.vreg_to_phys[v] & 0xff; t->r[ph] = (uint32_t)x; t->r[ph + 1] = (uint32_t)(x >> 32); } 398 static float u2f(uint32_t u) { float f; memcpy(&f, &u, 4); return f; } 399 static uint32_t f2u_(float f) { uint32_t u; memcpy(&u, &f, 4); return u; } 400 /* run one thread until it reaches a SHFL or BAR (not executed) or EXIT; returns 1 if parked at a sync op */ 401 static int sim_step(SimThr *t, const BlackwellIRProgram *p, uint32_t tid, uint32_t cx, uint32_t cy) { 402 for (int guard = 0; guard < `50000000`; guard++) { 403 if (t->done) return 0; 404 if (t->pc < 0 || (size_t)t->pc >= p->count) { g_sim_err = 1; t->done = 1; return 0; } 405 const BlackwellIRInsn *in = &p->insns[t->pc]; 406 uint32_t a = rd(t, in->src1_vreg, p), b = rd(t, in->src2_vreg, p), c = rd(t, in->src3_vreg, p); 407 switch (in->op) { 408 case BW_IR_SHFL_DOWN: case BW_IR_BAR_SYNC: return 1; 409 case BW_IR_EXIT: if (!in->predicate_p0 || t->p0) { t->done = 1; return 0; } break; 410 case BW_IR_BRA: { 411 int take = !in->predicate_p0 || (in->predicate_not ? !t->p0 : t->p0); 412 if (take) { if ((int32_t)in->imm == 0) { g_sim_err = 2; t->done = 1; return 0; } t->pc += (int32_t)in->imm; continue; } 413 break; } 414 case BW_IR_MOV_IMM: wr(t, in->dst_vreg, in->imm, p); break; 415 case BW_IR_MOV_RZ: wr(t, in->dst_vreg, 0, p); break; 416 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; 417 case BW_IR_LDC: wr(t, in->dst_vreg, sim_cbank[in->imm / 4], p); break; 418 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; 419 case BW_IR_LDCU64: break; /* memory descriptor: not modelled */ 420 case BW_IR_IMAD: wr(t, in->dst_vreg, in->src2_vreg >= 0 ? a * b + c : a * in->imm + c, p); break; 421 case BW_IR_IMAD_WIDE: wr64(t, in->dst_vreg, (uint64_t)a * in->imm + rd64(t, in->src3_vreg, p), p); break; 422 case BW_IR_IADD3: wr(t, in->dst_vreg, a + b, p); break; 423 case BW_IR_SHF_R: wr(t, in->dst_vreg, a >> (in->imm & 31), p); break; 424 case BW_IR_LOP3_AND: wr(t, in->dst_vreg, a & in->imm, p); break; 425 case BW_IR_LOP3_XOR: wr(t, in->dst_vreg, a ^ b, p); break; 426 case BW_IR_ISETP_GE_U32: t->p0 = a >= b; break; 427 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; } 428 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; } 429 case BW_IR_STG_E: memcpy((void *)(uintptr_t)rd64(t, in->src1_vreg, p), &b, 4); break; 430 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; } 431 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; 432 case BW_IR_FADD: wr(t, in->dst_vreg, f2u_(u2f(a) + u2f(b)), p); break; 433 case BW_IR_FSUB: wr(t, in->dst_vreg, f2u_(u2f(a) - u2f(b)), p); break; 434 case BW_IR_FMUL: wr(t, in->dst_vreg, f2u_(u2f(a) * u2f(b)), p); break; 435 case BW_IR_FFMA: wr(t, in->dst_vreg, f2u_(fmaf(u2f(a), u2f(b), u2f(c))), p); break; 436 case BW_IR_FMNMX_MAX: wr(t, in->dst_vreg, f2u_(fmaxf(u2f(a), u2f(b))), p); break; 437 case BW_IR_MUFU_EX2: wr(t, in->dst_vreg, f2u_(exp2f(u2f(a))), p); break; 438 case BW_IR_MUFU_RCP: wr(t, in->dst_vreg, f2u_(1.0f / u2f(a)), p); break; 439 default: g_sim_err = 100 + (int)in->op; t->done = 1; return 0; 440 } 441 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); } 442 t->pc++; 443 } 444 g_sim_err = 4; t->done = 1; return 0; 445 } 446 static int sim_launch(const void *progv, const OmegaGpuAttnLaunch *L, OmegaGpuAttnInfo *info) { 447 const BlackwellIRProgram *p = progv; 448 memset(sim_cbank, 0, sizeof sim_cbank); 449 uint64_t qa = (uintptr_t)L->q, pa = (uintptr_t)L->pool, oa = (uintptr_t)L->out, ta = (uintptr_t)L->tab; 450 sim_cbank[0x380 / 4] = (uint32_t)qa; sim_cbank[0x380 / 4 + 1] = (uint32_t)(qa >> 32); 451 sim_cbank[0x388 / 4] = (uint32_t)pa; sim_cbank[0x388 / 4 + 1] = (uint32_t)(pa >> 32); 452 sim_cbank[0x390 / 4] = (uint32_t)oa; sim_cbank[0x390 / 4 + 1] = (uint32_t)(oa >> 32); 453 sim_cbank[0x398 / 4] = (uint32_t)ta; sim_cbank[0x398 / 4 + 1] = (uint32_t)(ta >> 32); 454 memcpy(&sim_cbank[0x3a0 / 4], L->params, sizeof L->params); 455 uint32_t *outw = L->out; for (size_t i = 0; i < L->out_bytes / 4; i++) outw[i] = 0xffbadbadu; 456 g_sim_err = 0; 457 static SimThr th[SIM_T]; 458 g_trace_launch++; if (getenv("ATTN_SIM_TRACE")) { g_trace = 1; g_trace_cx = (uint32_t)atoi(getenv("ATTN_SIM_TRACE")); } 459 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++) { 460 memset(th, 0, sizeof th); memset(sim_shared, 0, sizeof sim_shared); 461 for (;;) { 462 int parked = 0, alive = 0; 463 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); } 464 if (g_sim_err) break; 465 if (alive == 0) break; 466 if (parked == 0) continue; /* every live thread exited this round */ 467 if (parked != alive) { g_sim_err = 5; break; } /* a thread exited while others wait at a barrier */ 468 int pc = -1; 469 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; } 470 if (g_sim_err) break; 471 const BlackwellIRInsn *in = &p->insns[pc]; 472 if (in->op == BW_IR_SHFL_DOWN) { 473 uint32_t src[SIM_T]; 474 for (int i = 0; i < SIM_T; i++) src[i] = rd(&th[i], in->src1_vreg, p); 475 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); } 476 } 477 for (int i = 0; i < SIM_T; i++) th[i].pc++; 478 } 479 } 480 uint32_t unwritten = 0; for (size_t i = 0; i < L->out_bytes / 4; i++) if (outw[i] == 0xffbadbadu) unwritten++; 481 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; } 482 if (g_sim_err) { printf("simulator error %d\n", g_sim_err); return OMEGA_GPU_ATTN_CHIP_FAIL; } 483 return unwritten ? OMEGA_GPU_ATTN_UNWRITTEN : OMEGA_GPU_ATTN_OK; 484 } 485 486 int main(int argc, char **argv) { 487 const char *out_path = NULL; int host = 0, sim = 0; 488 for (int i = 1; i < argc; i++) { 489 if (strcmp(argv[i], "--host-only") == 0) host = 1; 490 else if (strcmp(argv[i], "--sim") == 0) sim = 1; 491 else if (strcmp(argv[i], "--out") == 0 && i + 1 < argc) out_path = argv[++i]; 492 } 493 if (sim) omega_gpu_attention_test_set_simulator(sim_launch); 494 if (host) host_only(); 495 else if (chip(out_path) != 0) return 2; 496 printf("%s: %d checks, %d failed\n", g_failed ? "FAIL" : "PASS", g_checks, g_failed); 497 return g_failed ? 1 : 0; 498 }