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

GitHub aien-dev/omega-mv#261 (code only)

closed derived 39e7299b899e5662 #261

Imported from GitHub aien-dev/omega-mv#261 (code only)

GitHub's metadata for this pull request is unavailable: its state is DERIVED from the commits (merged: the head is reachable from this project's main; open: GitHub kept a merge ref; else closed).

Base 62804c30094b43f107b5809ce500b50bbaa6ff78 · Head d76218e16c3e1aa7d58083b2254048714c515b42

Apply it

git checkout -b patch-39e7299b899e5662 62804c30094b43f107b5809ce500b50bbaa6ff78
curl -fsSL https://interplane.io/drakestapleton/omega-mv/patches/39e7299b899e5662.patch | git am

Raw patch (mbox) · Diff

Provenance

This proposal is imported from GitHub; it is not signed by its author. Its import statement and source record:

github-import 1
aien-dev/omega-mv
261
d76218e16c3e1aa7d58083b2254048714c515b42
{"kind":"github-import","owner":"aien-dev","repo":"omega-mv","number":261,"url":"https://github.com/aien-dev/omega-mv/pull/261","export_sha256":"967c79e26a893657b5cdaa45efd442be5dbd2ecfe68e25f9a8c1b5da4d60d452","imported_utc":"2026-11-18T16:37:01Z","metadata":"unavailable","state_derived":true}

Changes

diff --git a/Makefile b/Makefile
index 876240429..609922011 100644
--- a/Makefile
+++ b/Makefile
@@ -19,7 +19,7 @@ SRCS = src/sha256.c src/omega_canonical.c src/omega_validate.c src/omega_core.c
 	src/omega_library.c src/omega_discovery.c src/omega_machine.c src/omega_realize_synth.c \
 	src/omega_matvec.c src/omega_accelerator.c src/omega_accelerator_world.c \
 	src/omega_vector.c src/omega_blackwell_encoder.c src/omega_blackwell_qmd.c \
-	src/omega_blackwell_realize.c src/omega_blackwell_submit.c src/omega_blackwell_engine.c src/omega_gpu_engine.c src/omega_blackwell_gates.c src/omega_blackwell_matmul.c src/omega_blackwell_codegen.c src/omega_gpu_matmul_api.c src/omega_gpu_elementwise_api.c src/omega_world_gates.c src/omega_gpu_wait.c \
+	src/omega_blackwell_realize.c src/omega_blackwell_submit.c src/omega_blackwell_engine.c src/omega_gpu_engine.c src/omega_blackwell_gates.c src/omega_blackwell_matmul.c src/omega_blackwell_codegen.c src/omega_gpu_matmul_api.c src/omega_gpu_elementwise_api.c src/omega_gpu_attention_api.c src/omega_world_gates.c src/omega_gpu_wait.c \
 	src/omega_evidence.c \
 	$(PHYSICS_DIR)/m16/m16_native.c $(PHYSICS_DIR)/nvrm/nvrm.c \
 	tools/omegatool.c
@@ -2154,3 +2154,16 @@ $(GPU_EW_TEST): tests/gpu_elementwise_test.c src/omega_gpu_elementwise_api.h $(O
 	$(CC) $(CFLAGS) -ffp-contract=off -o $@ tests/gpu_elementwise_test.c $(OUT_DIR)/libomega_gpu.a -lpthread -lm
 test-gpu-elementwise: $(GPU_EW_TEST)
 	./$(GPU_EW_TEST) --host-only
+
+# FB-1 cut 5: native gqa_attention (f32 KV) and paged_attention (bf16 KV, + batch).
+# test-gpu-attention runs host-only (refusals, codegen, nvdisasm listing) and then the
+# whole parity battery through the host IR simulator (--sim, no chip); the chip
+# gate is `./build/gpu_attention_test --out receipt.json` through the heavy queue
+# (tools/run_gpu_attention_chip.sh). -ffp-contract=off keeps the oracle free of FMA.
+.PHONY: test-gpu-attention
+GPU_ATTN_TEST = $(OUT_DIR)/gpu_attention_test
+$(GPU_ATTN_TEST): tests/gpu_attention_test.c src/omega_gpu_attention_api.h $(OUT_DIR)/libomega_gpu.a
+	$(CC) $(CFLAGS) -ffp-contract=off -o $@ tests/gpu_attention_test.c $(OUT_DIR)/libomega_gpu.a -lpthread -lm
+test-gpu-attention: $(GPU_ATTN_TEST)
+	./$(GPU_ATTN_TEST) --host-only
+	./$(GPU_ATTN_TEST) --sim
diff --git a/docs/numeric/FB1_CUT5_ATTENTION.md b/docs/numeric/FB1_CUT5_ATTENTION.md
new file mode 100644
index 000000000..c535f727b
--- /dev/null
+++ b/docs/numeric/FB1_CUT5_ATTENTION.md
@@ -0,0 +1,105 @@
+# FB-1 cut 5: native gqa + paged attention (no CUDA)
+
+Status: host battery PASS, host IR simulator PASS (45/45), chip gate PASS (45/45, receipt ~/workspace/evidence-out/FB1-CUT5-b016322, PR #261).
+Files: `src/omega_gpu_attention_api.{h,c}`, `tests/gpu_attention_test.c`,
+`tools/run_gpu_attention_chip.sh`. Library: `libomega_gpu.a`.
+
+## DOCS READ (recorded with `docs-read omega ...` before the codegen edits)
+
+- `clcec0.h` (mesa copy `~/workspace/.ref/mesa/src/nouveau/headers/nvidia/classes/clcec0.h:262`):
+  `NVCEC0_INVALIDATE_SHADER_CACHES 0x021c`; bits 0 (instruction), 4 (data), 12 (constant)
+  are set before every launch, as cut 1b found necessary when code addresses are reused.
+- `nvos.h` ~1112: `NVOS32_ATTR2_GPU_CACHEABLE_YES` "for system memory this will not be
+  coherent with direct CPU mappings" -> every buffer the host reads back or the chip reads
+  after a host write is `nvrm_alloc_gpu_uncached`.
+- `clcec0qmd.h:252` `NVCEC0_QMDV05_00_SHARED_MEMORY_SIZE_SHIFTED7 MW(1162:1152)` and
+  `src/omega_blackwell_qmd.c` word 36 (`0x04b44808`): the QMD declares 1024 bytes of shared
+  memory and one barrier. This is why head_dim is fixed at 64 in this cut (below).
+- PTX ISA `ex2.approx.f32` (max 2 ulp over the full range) and the bf16 definition (top 16
+  bits of an f32): bf16 -> f32 is a 16-bit shift, done with IMAD x * 0x10000 (low half) and
+  LOP3 AND 0xffff0000 (high half of a 32-bit pair).
+
+## Oracle (aien-sovereign-core `crates/aien-inference-abi/src/backend.rs`, main 8b5caed)
+
+- `gqa_attention`: f32 KV `[seq][num_kv_heads][head_dim]`, query head h reads kv head
+  `h / (num_q_heads / num_kv_heads)`, score = q.k / sqrt(head_dim), softmax over the whole
+  history (decode: one query, no mask), seq_len 0 -> zeros, `inv = 1 / max(sum, 1e-12)`.
+- `paged_attention`: bf16 pool in aien-kv-cache `KvLayout` order (block, layer, plane K=0 V=1,
+  token, head); token t is `block_ids[t / block_size]` slot `t % block_size`; tokens whose
+  block index is past `block_ids` are dropped; context 0 or no blocks -> zeros.
+- `paged_attention_batch`: `context_lens[s] <= 0` -> 0; the row is
+  `block_tables[s*max .. (s+1)*max]` (empty if it runs past the array); negative entries are
+  removed and the rest close up.
+
+Documented deviation: a block id `>= layout.num_blocks` is refused with `BAD_ARGS`; the
+oracle reads zeros for it. A layer index past `num_layers` is refused the same way.
+
+## Kernel
+
+One CTA per (query head = CTAID.X, sequence = CTAID.Y), 64 threads, grid
+`(num_q_heads, sequences per launch)` with at most 64 CTAs per launch (I42 envelope).
+Shared memory map (1024 bytes): `[0,256)` q, `[256,512)` scores then probabilities,
+`[512,768)` per-token byte offsets, `[768,1024)` warp partials.
+
+The context is walked in chunks of 64 tokens with online softmax:
+
+1. Phase A, thread = token: block-table lookup, `K.q` over 64 dims in f32 FFMA (K read as
+   32-bit pairs with LDG.E: two f32 dims or two bf16 dims per load), `s = dot * scale` with
+   `scale = log2(e) / sqrt(64)` folded in so EX2 gives e^x.
+2. Chunk max: SHFL.DOWN tree per warp, two warp partials through shared memory, BAR.SYNC.
+   `alpha = EX2(m_old - m_new)`, `p = EX2(s - m_new)`, chunk sum the same way,
+   `L = L * alpha + sum`, `acc *= alpha`.
+3. Phase B, thread = dimension: `acc += p_t * V[t][tid]` over the chunk's tokens (V bf16 by
+   LDG.E.U16, f32 by LDG.E).
+4. Epilogue: `out = acc * RCP(L)`. The first chunk starts with `m = -inf`, so `alpha = 0`
+   wipes the initial `L = 1`, `acc = 0`. Context 0 jumps straight to the epilogue (zeros).
+
+Both kernels are 152 instructions, 42 GPRs, 6 UGPRs (budget 64 GPRs). Kernels are
+specialised on `{kv f32 or bf16, log2 block size, log2 gqa ratio}` and cached (8 slots).
+The gqa path stages `[K plane | V plane]` as one 4096-slot block, so context <= 4096 there.
+The paged path stages the referenced blocks' layer slice renumbered in table order; the
+kernel itself walks the (renumbered) block table.
+
+## Tolerances
+
+- Standard cases: `2e-4 * |want| + 2e-5`. Budget: f32 sums over <= 2048 terms
+  (~1.2e-4 relative), MUFU.EX2 (2 ulp), MUFU.RCP (1 ulp), bf16 inputs are exact in f32.
+  Observed worst in the simulator (exact EX2/RCP): 0.0033 of the tolerance.
+- Large-score case (q scaled by 200, scores ~ +-200 natural): `1e-3 * |want| + 1e-4`.
+  Observed worst in the simulator: 0.041 of the tolerance.
+
+## Mutants (deliberately wrong kernels the test must catch)
+
+| mutant | what it breaks | where it shows |
+|---|---|---|
+| NO_MAX | no running-max subtraction | only when EX2 overflows: the large-score case (softmax is shift invariant on unit-scale data) |
+| KV_HEAD | reads kv head `(h / ratio) ^ 1` | every context length including 1 |
+| SLOT | K read from slot `(t + 1) % block_size`, V from slot t | every context >= 2 (with one token the softmax weight is 1 whatever K says). Shifting both K and V would only permute matched pairs inside a full block, which softmax cannot see, so the mutant is K-only |
+| NO_RESCALE | accumulator not multiplied by alpha when the max moves | context > 64 (more than one chunk) |
+
+Negative control: the comparison must reject the oracle with kv heads swapped. Repeat run
+on a cache hit must be bit-identical.
+
+## Host IR simulator (`gpu_attention_test --sim`)
+
+Executes the allocated IR program (physical registers, so the register allocator's loop
+handling is under test) for every CTA: 64 threads, 1 KB shared, host pointers as addresses,
+SHFL and BAR as lockstep points. It found the one kernel bug before chip time: the kv-head
+byte offset was added to the V base twice (once inside the per-token offset phase A leaves
+in shared memory, once in the V column base), so every head mapped to a kv head other
+than 0 read V from the wrong head. It also found a kernel-cache key compared with memcmp
+over struct padding (cache misses at random). `ATTN_SIM_TRACE=<ctaid.x>` prints thread 0
+of that CTA instruction by instruction.
+
+## Limits of this cut
+
+- head_dim 64 only (TinyLlama, Llama-3.2-1B). Larger heads need a bigger shared-memory
+  declaration in the QMD (word 36) and a second thread-per-token tiling.
+- Staging copy of q, the referenced KV blocks and the tables per call; the device is opened
+  per call (cut 1b's resident handle API is the path to remove both).
+- Serialising instruction schedule (every instruction waits on everything pending), as in
+  cut 4: correctness first, throughput later.
+- Context <= 4096 on the contiguous gqa path.
+- UNVERIFIED on chip until the gate run: forward predicated `@P0 BRA`, bf16 K loads as
+  32-bit pairs (the 16-bit widening itself is cut 4's), one launcher opening the device
+  while another API in the same process holds it.
diff --git a/src/omega_gpu_attention_api.c b/src/omega_gpu_attention_api.c
new file mode 100644
index 000000000..1425f8e9d
--- /dev/null
+++ b/src/omega_gpu_attention_api.c
@@ -0,0 +1,776 @@
+/* omega_gpu_attention_api.c: FB-1 cut 5 (2026-10-04). See the header.
+ *
+ * Layout: (1) kernel codegen on the BlackwellIR with the serialising scheduler
+ * of cut 4 (every instruction waits on everything still pending; slow and safe),
+ * extended with forward branches and more loops; (2) the launcher, cloned from
+ * cut 4's run_abc with a fourth buffer (block tables and context lengths), 16
+ * argument words, and cut 1b's shader-cache invalidate; (3) the public entry
+ * points, which stage the referenced KV blocks per launch and apply the oracle's
+ * argument rules (dropped tokens past the table, negative table entries, zero
+ * context) on the host.
+ *
+ * One CTA per (query head, sequence), 64 threads (= head_dim). The context is
+ * walked in chunks of 64 tokens:
+ *   phase A  thread t owns token base+t: block lookup, K dot q (f32 FFMA), s = dot * scale
+ *            (scale folds 1/sqrt(d) and log2 e), s and the token's byte offset go to shared;
+ *   reduce   chunk max (SHFL.DOWN tree per warp, lane partials to shared, BAR.SYNC, 2 LDS),
+ *            m_new = max(m, chunk max), alpha = EX2(m - m_new), p = EX2(s - m_new) to shared,
+ *            chunk sum the same way, l = l * alpha + chunk sum;
+ *   phase B  thread d owns dimension d: acc = acc * alpha + sum over the chunk of p_t * V[t][d].
+ * Then out[d] = acc * RCP(l). The first chunk sees m = -inf, so alpha = EX2(-inf) = 0 and
+ * the initial l and acc drop out (PTX ISA ex2.approx: ex2(-Inf) = +0).
+ *
+ * Shared memory (1024 bytes, the QMD's declared size): [0,256) q, [256,512) s then p,
+ * [512,768) token byte offsets, [768,1024) warp partials for the reductions.
+ */
+#include "omega_gpu_attention_api.h"
+#include "omega_blackwell_codegen.h"
+#include "omega_blackwell_qmd.h"
+#include "omega_blackwell_submit.h"
+#include "m16_native.h"
+#include "sha256.h"
+#include <math.h>
+#include <pthread.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <time.h>
+
+/* ------------------------------------------------------------------ codegen */
+
+#define CW(stall, wbar, rbar, wait) \
+    (((uint32_t)(stall) << 9) | ((uint32_t)(wbar) << 14) | ((uint32_t)(rbar) << 17) | ((uint32_t)(wait) << 20))
+#define CW_YIELD 0x2000u
+#define SB_NONE 7u
+#define SB_GPR 0u
+#define SB_RD 1u
+#define SB_UGPR 2u
+
+enum { K_FIXED, K_PRED, K_VAR, K_UVAR, K_STORE, K_SYNC, K_EXIT, K_BRA };
+
+#define AT_MAX_LOOPS 8
+typedef struct {
+    BlackwellIRProgram *p;
+    uint32_t pending;
+    int err;
+    int loop_start[AT_MAX_LOOPS], loop_end[AT_MAX_LOOPS];
+    int n_loops, depth, stack[AT_MAX_LOOPS];
+} Em;
+
+static void emit(Em *e, BlackwellIRInsn in, int kind) {
+    uint32_t wait = e->pending;
+    switch (kind) {
+    case K_FIXED: in.control = CW(6, SB_NONE, SB_NONE, wait); e->pending = 0; break;
+    case K_PRED:  in.control = CW(13, SB_NONE, SB_NONE, wait); e->pending = 0; break;
+    case K_VAR:   in.control = CW(4, SB_GPR, SB_NONE, wait) | CW_YIELD; e->pending = 1u << SB_GPR; break;
+    case K_UVAR:  in.control = CW(4, SB_UGPR, SB_NONE, wait) | CW_YIELD; e->pending = 1u << SB_UGPR; break;
+    case K_STORE: in.control = CW(4, SB_NONE, SB_RD, wait) | CW_YIELD; e->pending = 1u << SB_RD; break;
+    case K_SYNC:  in.control = CW(6, SB_NONE, SB_NONE, wait); e->pending = 0; break;
+    case K_EXIT:  in.control = CW(5, SB_NONE, SB_NONE, wait); e->pending = in.predicate_p0 ? wait : 0; break;
+    case K_BRA:   in.control = CW(5, SB_NONE, SB_NONE, wait); e->pending = in.predicate_p0 ? wait : 0; break;
+    default: e->err = -1; return;
+    }
+    if (omega_bw_ir_append(e->p, &in) < 0) e->err = -1;
+}
+
+static int V(Em *e) { int v = omega_bw_ir_alloc_vreg(e->p); if (v < 0) e->err = -1; return v; }
+static int V64(Em *e) { int v = omega_bw_ir_alloc_vreg64(e->p); if (v < 0) e->err = -1; return v; }
+static int UV64(Em *e) { int v = omega_bw_ir_alloc_uvreg64(e->p); if (v < 0) e->err = -1; return v; }
+static int here(const Em *e) { return (int)e->p->count; }
+
+#define NOREG -1
+static BlackwellIRInsn I0(BlackwellIROpcode op) {
+    BlackwellIRInsn in; memset(&in, 0, sizeof in);
+    in.op = op; in.dst_vreg = NOREG; in.src1_vreg = NOREG; in.src2_vreg = NOREG; in.src3_vreg = NOREG; in.ureg = NOREG;
+    return in;
+}
+static void ldcu64(Em *e, int udst, uint32_t off) { BlackwellIRInsn i = I0(BW_IR_LDCU64); i.dst_vreg = udst; i.imm = off; i.is_uniform = true; emit(e, i, K_UVAR); }
+static void ldc64(Em *e, int dst64, uint32_t off) { BlackwellIRInsn i = I0(BW_IR_LDC64); i.dst_vreg = dst64; i.imm = off; emit(e, i, K_VAR); }
+static void ldc32(Em *e, int dst, uint32_t off) { BlackwellIRInsn i = I0(BW_IR_LDC); i.dst_vreg = dst; i.imm = off; emit(e, i, K_VAR); }
+static void s2r(Em *e, int dst, uint32_t sr) { BlackwellIRInsn i = I0(BW_IR_S2R); i.dst_vreg = dst; i.imm = sr; emit(e, i, K_VAR); }
+static void movi(Em *e, int dst, uint32_t imm) { BlackwellIRInsn i = I0(BW_IR_MOV_IMM); i.dst_vreg = dst; i.imm = imm; emit(e, i, K_FIXED); }
+static void movf(Em *e, int dst, float f) { uint32_t u; memcpy(&u, &f, 4); movi(e, dst, u); }
+static void movrz(Em *e, int dst) { BlackwellIRInsn i = I0(BW_IR_MOV_RZ); i.dst_vreg = dst; emit(e, i, K_FIXED); }
+/* dst = a * imm + c (c may be NOREG for RZ) */
+static void imadi(Em *e, int dst, int a, uint32_t imm, int c) { BlackwellIRInsn i = I0(BW_IR_IMAD); i.dst_vreg = dst; i.src1_vreg = a; i.imm = imm; i.src3_vreg = c; emit(e, i, K_FIXED); }
+/* dst = a * b + c (registers; c may be NOREG) */
+static void imadr(Em *e, int dst, int a, int b, int c) { BlackwellIRInsn i = I0(BW_IR_IMAD); i.dst_vreg = dst; i.src1_vreg = a; i.src2_vreg = b; i.src3_vreg = c; emit(e, i, K_FIXED); }
+static void iadd3(Em *e, int dst, int a, int b) { BlackwellIRInsn i = I0(BW_IR_IADD3); i.dst_vreg = dst; i.src1_vreg = a; i.src2_vreg = b; emit(e, i, K_FIXED); }
+static void lop3xor(Em *e, int dst, int a, int b) { BlackwellIRInsn i = I0(BW_IR_LOP3_XOR); i.dst_vreg = dst; i.src1_vreg = a; i.src2_vreg = b; emit(e, i, K_FIXED); }
+static void lop3andi(Em *e, int dst, int a, uint32_t imm) { BlackwellIRInsn i = I0(BW_IR_LOP3_AND); i.dst_vreg = dst; i.src1_vreg = a; i.imm = imm; emit(e, i, K_FIXED); }
+static void shri(Em *e, int dst, int a, uint32_t imm) { BlackwellIRInsn i = I0(BW_IR_SHF_R); i.dst_vreg = dst; i.src1_vreg = a; i.imm = imm; emit(e, i, K_FIXED); }
+/* dst64 = idx * imm + base64 (byte address) */
+static void wide(Em *e, int dst64, int idx, uint32_t imm, int base64) { BlackwellIRInsn i = I0(BW_IR_IMAD_WIDE); i.dst_vreg = dst64; i.src1_vreg = idx; i.imm = imm; i.src3_vreg = base64; emit(e, i, K_FIXED); }
+static void ldg(Em *e, int dst, int addr64, int udesc) { BlackwellIRInsn i = I0(BW_IR_LDG_E); i.dst_vreg = dst; i.src1_vreg = addr64; i.ureg = udesc; emit(e, i, K_VAR); }
+static void ldg16(Em *e, int dst, int addr64, int udesc) { BlackwellIRInsn i = I0(BW_IR_LDG_E_U16); i.dst_vreg = dst; i.src1_vreg = addr64; i.ureg = udesc; emit(e, i, K_VAR); }
+static void stg(Em *e, int addr64, int val, int udesc) { BlackwellIRInsn i = I0(BW_IR_STG_E); i.src1_vreg = addr64; i.src2_vreg = val; i.ureg = udesc; emit(e, i, K_STORE); }
+static void e_fadd(Em *e, int d, int a, int b) { BlackwellIRInsn i = I0(BW_IR_FADD); i.dst_vreg = d; i.src1_vreg = a; i.src2_vreg = b; emit(e, i, K_FIXED); }
+static void e_fsub(Em *e, int d, int a, int b) { BlackwellIRInsn i = I0(BW_IR_FSUB); i.dst_vreg = d; i.src1_vreg = a; i.src2_vreg = b; emit(e, i, K_FIXED); }
+static void e_fmul(Em *e, int d, int a, int b) { BlackwellIRInsn i = I0(BW_IR_FMUL); i.dst_vreg = d; i.src1_vreg = a; i.src2_vreg = b; emit(e, i, K_FIXED); }
+static void e_ffma(Em *e, int d, int a, int b, int c) { BlackwellIRInsn i = I0(BW_IR_FFMA); i.dst_vreg = d; i.src1_vreg = a; i.src2_vreg = b; i.src3_vreg = c; emit(e, i, K_FIXED); }
+static void e_fmax(Em *e, int d, int a, int b) { BlackwellIRInsn i = I0(BW_IR_FMNMX_MAX); i.dst_vreg = d; i.src1_vreg = a; i.src2_vreg = b; emit(e, i, K_FIXED); }
+static void mufu(Em *e, BlackwellIROpcode op, int d, int a) { BlackwellIRInsn i = I0(op); i.dst_vreg = d; i.src1_vreg = a; emit(e, i, K_VAR); }
+static void shfl_down(Em *e, int d, int a, uint32_t off) { BlackwellIRInsn i = I0(BW_IR_SHFL_DOWN); i.dst_vreg = d; i.src1_vreg = a; i.imm = off; emit(e, i, K_VAR); }
+static void sts32(Em *e, int addr, int val) { BlackwellIRInsn i = I0(BW_IR_STS32); i.src1_vreg = addr; i.src2_vreg = val; emit(e, i, K_STORE); }
+static void lds32(Em *e, int d, int addr) { BlackwellIRInsn i = I0(BW_IR_LDS32); i.dst_vreg = d; i.src1_vreg = addr; emit(e, i, K_VAR); }
+static void bar_sync(Em *e) { emit(e, I0(BW_IR_BAR_SYNC), K_SYNC); }
+static void isetp_ge_u32(Em *e, int a, int b) { BlackwellIRInsn i = I0(BW_IR_ISETP_GE_U32); i.src1_vreg = a; i.src2_vreg = b; emit(e, i, K_PRED); }
+static void bra_back_if_not_p0(Em *e, int target) { BlackwellIRInsn i = I0(BW_IR_BRA); i.predicate_p0 = true; i.predicate_not = true; i.imm = (uint32_t)(target - here(e)); emit(e, i, K_BRA); }
+/* @P0 BRA forward; the target is patched in when known */
+static int bra_fwd_if_p0(Em *e) { int at = here(e); BlackwellIRInsn i = I0(BW_IR_BRA); i.predicate_p0 = true; i.imm = 0; emit(e, i, K_BRA); return at; }
+static void patch_fwd(Em *e, int at) { if (at >= 0 && (size_t)at < e->p->count) e->p->insns[at].imm = (uint32_t)(here(e) - at); else e->err = -1; }
+static void tail(Em *e) {
+    emit(e, I0(BW_IR_EXIT), K_EXIT);
+    BlackwellIRInsn self = I0(BW_IR_BRA);
+    self.control = 0x000fc000u;
+    if (omega_bw_ir_append(e->p, &self) < 0) e->err = -1;
+}
+/* Loops nest; loop_end() extends every value defined before the loop and read inside
+ * it to the back-branch (the linear-scan allocator knows nothing about back-edges). */
+static void loop_begin(Em *e) {
+    if (e->depth >= AT_MAX_LOOPS || e->n_loops >= AT_MAX_LOOPS) { e->err = -1; return; }
+    e->stack[e->depth++] = here(e);
+}
+static void loop_end(Em *e) {
+    if (e->depth == 0 || e->n_loops >= AT_MAX_LOOPS) { e->err = -1; return; }
+    int start = e->stack[--e->depth], end = here(e) - 1;
+    e->loop_start[e->n_loops] = start; e->loop_end[e->n_loops] = end; e->n_loops++;
+    OmegaRegAlloc *ra = &e->p->regalloc;
+    for (int v = 0; v < ra->num_vregs; v++) {
+        OmegaLiveInterval *iv = &ra->intervals[v];
+        if (iv->first_def >= 0 && iv->first_def < start && iv->last_use >= start && iv->last_use < end) iv->last_use = end;
+    }
+}
+/* A value first defined inside a loop may not be read after it before being redefined. */
+static int check_loop_invariant(const Em *e) {
+    const OmegaRegAlloc *ra = &e->p->regalloc;
+    for (int L = 0; L < e->n_loops; L++)
+        for (int v = 0; v < ra->num_vregs; v++) {
+            int fd = ra->intervals[v].first_def;
+            if (fd < e->loop_start[L] || fd > e->loop_end[L]) continue;
+            for (size_t i = (size_t)e->loop_end[L] + 1; i < e->p->count; i++) {
+                const BlackwellIRInsn *in = &e->p->insns[i];
+                if (in->src1_vreg == v || in->src2_vreg == v || in->src3_vreg == v) return -1;
+                if (in->dst_vreg == v && !in->is_uniform) break;
+            }
+        }
+    return 0;
+}
+
+/* Kernel argument words (constant bank 0 at 0x380; the bank is 1024 bytes, so 32 words fit). */
+#define ARG_Q 0x380u
+#define ARG_POOL 0x388u
+#define ARG_OUT 0x390u
+#define ARG_TAB 0x398u
+#define ARG_MAXB 0x3a0u    /* words per block-table row */
+#define ARG_SCALE 0x3a4u   /* bits of log2(e) / sqrt(head_dim) */
+#define ARG_BSTRIDE 0x3a8u /* bytes between staged blocks */
+#define ARG_TSTRIDE 0x3acu /* bytes between tokens */
+#define ARG_KVP 0x3b0u     /* bytes from the K plane to the V plane */
+#define ARG_HSTRIDE 0x3b4u /* bytes between kv heads */
+#define ARG_NQH 0x3b8u     /* query heads (q and out row count per sequence) */
+#define ARG_CTXOFF 0x3bcu  /* byte offset of the context-length array inside the table buffer */
+#define ARG_WORDS 16u
+#define DESC_OFF 0x358u
+
+#define HD OMEGA_GPU_ATTN_HEAD_DIM
+#define SH_Q 0u
+#define SH_S 256u
+#define SH_O 512u
+#define SH_R 768u
+#define F32_NEG_INF 0xff800000u
+
+typedef struct { bool f32; uint32_t log2bs, log2gqa; int mutant; } KSpec;
+
+static void gen_attention(Em *e, const KSpec *k) {
+    const uint32_t elem = k->f32 ? 4u : 2u;
+    const uint32_t kstep = k->f32 ? 8u : 4u; /* bytes per inner iteration: two dims */
+    int udesc = UV64(e), A = V64(e), B = V64(e), C = V64(e), D = V64(e);
+    int tid = V(e), h = V(e), seq = V(e);
+    int p_maxb = V(e), scale = V(e), p_bstride = V(e), p_tstride = V(e), p_kvp = V(e), p_hstride = V(e), p_nqh = V(e), p_ctxoff = V(e);
+    ldcu64(e, udesc, DESC_OFF);
+    ldc64(e, A, ARG_Q); ldc64(e, B, ARG_POOL); ldc64(e, C, ARG_OUT); ldc64(e, D, ARG_TAB);
+    ldc32(e, p_maxb, ARG_MAXB); ldc32(e, scale, ARG_SCALE); ldc32(e, p_bstride, ARG_BSTRIDE); ldc32(e, p_tstride, ARG_TSTRIDE);
+    ldc32(e, p_kvp, ARG_KVP); ldc32(e, p_hstride, ARG_HSTRIDE); ldc32(e, p_nqh, ARG_NQH); ldc32(e, p_ctxoff, ARG_CTXOFF);
+    s2r(e, tid, BW_SR_TID_X); s2r(e, h, BW_SR_CTAID_X); s2r(e, seq, BW_SR_CTAID_Y);
+
+    int c1 = V(e), c4 = V(e), c32 = V(e), c64 = V(e), c256 = V(e), c512 = V(e), c768 = V(e), c896 = V(e), zero = V(e);
+    movi(e, c1, 1); movi(e, c4, 4); movi(e, c32, 32); movi(e, c64, 64);
+    movi(e, c256, SH_S); movi(e, c512, SH_O); movi(e, c768, SH_R); movi(e, c896, SH_R + 128); movrz(e, zero);
+
+    /* q[tid] -> shared; out address kept for the end */
+    int tid4 = V(e), qrow = V(e), qoff = V(e), qaddr = V64(e), qv = V(e), oaddr = V64(e);
+    imadi(e, tid4, tid, 4, NOREG);
+    imadr(e, qrow, seq, p_nqh, h);
+    imadi(e, qoff, qrow, HD * 4, tid4);
+    wide(e, qaddr, qoff, 1, A);
+    ldg(e, qv, qaddr, udesc);
+    sts32(e, tid4, qv); /* SH_Q + tid*4 */
+    wide(e, oaddr, qoff, 1, C);
+
+    /* kv head offset, this sequence's table row and context length */
+    int kvh = V(e), kvoff = V(e), t1 = V(e), tab = V64(e), ca = V64(e), ctx = V(e), vb = V64(e);
+    shri(e, kvh, h, k->log2gqa);
+    if (k->mutant == OMEGA_GPU_ATTN_MUTANT_KV_HEAD) lop3xor(e, kvh, kvh, c1);
+    imadr(e, kvoff, kvh, p_hstride, NOREG);
+    imadr(e, t1, seq, p_maxb, NOREG);
+    imadi(e, t1, t1, 4, NOREG);
+    wide(e, tab, t1, 1, D);
+    imadi(e, t1, seq, 4, p_ctxoff);
+    wide(e, ca, t1, 1, D);
+    ldg(e, ctx, ca, udesc);
+    /* V column base for dimension tid: pool + kv plane + tid * elem. The kv head offset is
+     * already inside the per-token offset phase A leaves in shared memory (found by the host
+     * simulator: adding it here too read V from the wrong head for every kv head but 0). */
+    wide(e, vb, tid, elem, B);
+    wide(e, vb, p_kvp, 1, vb);
+
+    int M = V(e), L = V(e), acc = V(e), base = V(e), sOff = V(e), oOff = V(e), rOff = V(e);
+    movi(e, M, F32_NEG_INF);
+    if (k->mutant == OMEGA_GPU_ATTN_MUTANT_NO_MAX) movrz(e, L); else movf(e, L, 1.0f); /* alpha = 0 on the first chunk clears it */
+    movrz(e, acc); movrz(e, base);
+    iadd3(e, sOff, tid4, c256); iadd3(e, oOff, tid4, c512); iadd3(e, rOff, tid4, c768);
+    bar_sync(e); /* q visible to every thread */
+    isetp_ge_u32(e, zero, ctx); /* ctx == 0: out = 0 */
+    int bZ = bra_fwd_if_p0(e);
+
+    /* ---------------- chunk loop ---------------- */
+    int j = V(e), s = V(e), koff = V(e);
+    int bi = V(e), sl = V(e), ta = V64(e), blk = V(e), ka = V64(e), dot = V(e), d = V(e);
+    int x = V(e), lo = V(e), hi = V(e), qa = V(e), qb = V(e), q0 = V(e), q1 = V(e), ka2 = V64(e), j1 = V(e);
+    loop_begin(e);
+    int Lout = here(e);
+    iadd3(e, j, base, tid);
+    movi(e, s, F32_NEG_INF);
+    movrz(e, koff);
+    isetp_ge_u32(e, j, ctx);
+    int bA = bra_fwd_if_p0(e);
+    /* phase A: token j */
+    shri(e, bi, j, k->log2bs);
+    lop3andi(e, sl, j, (1u << k->log2bs) - 1u);
+    wide(e, ta, bi, 4, tab);
+    ldg(e, blk, ta, udesc);
+    imadr(e, koff, blk, p_bstride, NOREG);
+    if (k->mutant == OMEGA_GPU_ATTN_MUTANT_SLOT) {
+        /* K read from slot (t + 1) % block_size, V from the right slot: a K/V mismatch.
+         * (Shifting both only permutes matched pairs inside a full block, which softmax cannot see.) */
+        int sl1 = V(e);
+        iadd3(e, j1, j, c1); lop3andi(e, sl1, j1, (1u << k->log2bs) - 1u);
+        imadr(e, sl1, sl1, p_tstride, koff);
+        iadd3(e, sl1, sl1, kvoff);
+        wide(e, ka, sl1, 1, B);
+        imadr(e, koff, sl, p_tstride, koff);
+        iadd3(e, koff, koff, kvoff);
+    } else {
+        imadr(e, koff, sl, p_tstride, koff);
+        iadd3(e, koff, koff, kvoff);
+        wide(e, ka, koff, 1, B);
+    }
+    movrz(e, dot); movrz(e, d);
+    loop_begin(e);
+    int Lin = here(e);
+    if (k->f32) {
+        ldg(e, lo, ka, udesc);
+        wide(e, ka2, c1, 4, ka);
+        ldg(e, hi, ka2, udesc);
+    } else {
+        ldg(e, x, ka, udesc);
+        imadi(e, lo, x, 0x10000u, NOREG);   /* low bf16 -> f32: bits << 16 */
+        lop3andi(e, hi, x, 0xffff0000u);    /* high bf16 -> f32: keep the top half */
+    }
+    imadi(e, qa, d, 8, NOREG);
+    lds32(e, q0, qa);
+    iadd3(e, qb, qa, c4);
+    lds32(e, q1, qb);
+    e_ffma(e, dot, q0, lo, dot);
+    e_ffma(e, dot, q1, hi, dot);
+    wide(e, ka, c1, kstep, ka);
+    iadd3(e, d, d, c1);
+    isetp_ge_u32(e, d, c32);
+    bra_back_if_not_p0(e, Lin);
+    loop_end(e);
+    e_fmul(e, s, dot, scale);
+    patch_fwd(e, bA);
+    sts32(e, sOff, s);
+    sts32(e, oOff, koff);
+
+    /* chunk max */
+    int t = V(e), mw = V(e), ra = V(e), rb = V(e), mc = V(e), Mn = V(e), diff = V(e), alpha = V(e), parg = V(e), p = V(e), sw = V(e), lc = V(e);
+    static const uint32_t steps[5] = { 16, 8, 4, 2, 1 };
+    shfl_down(e, t, s, steps[0]); e_fmax(e, mw, s, t);
+    for (int i = 1; i < 5; i++) { shfl_down(e, t, mw, steps[i]); e_fmax(e, mw, mw, t); }
+    sts32(e, rOff, mw);
+    bar_sync(e);
+    lds32(e, ra, c768); lds32(e, rb, c896);
+    e_fmax(e, mc, ra, rb);
+    e_fmax(e, Mn, M, mc);
+    if (k->mutant == OMEGA_GPU_ATTN_MUTANT_NO_MAX) {
+        movf(e, alpha, 1.0f);
+        mufu(e, BW_IR_MUFU_EX2, p, s);
+        e_fmax(e, M, Mn, mc);
+    } else {
+        e_fsub(e, diff, M, Mn);
+        mufu(e, BW_IR_MUFU_EX2, alpha, diff);
+        e_fmax(e, M, Mn, mc); /* M = Mn */
+        e_fsub(e, parg, s, Mn);
+        mufu(e, BW_IR_MUFU_EX2, p, parg);
+    }
+    bar_sync(e); /* everyone has read the max partials before they are overwritten */
+    sts32(e, sOff, p);
+    shfl_down(e, t, p, steps[0]); e_fadd(e, sw, p, t);
+    for (int i = 1; i < 5; i++) { shfl_down(e, t, sw, steps[i]); e_fadd(e, sw, sw, t); }
+    sts32(e, rOff, sw);
+    bar_sync(e);
+    lds32(e, ra, c768); lds32(e, rb, c896);
+    e_fadd(e, lc, ra, rb);
+    e_ffma(e, L, L, alpha, lc);
+    if (k->mutant != OMEGA_GPU_ATTN_MUTANT_NO_RESCALE) e_fmul(e, acc, acc, alpha);
+
+    /* phase B: dimension tid over the chunk's tokens */
+    int kk = V(e), tt = V(e), oa = V(e), ko = V(e), pa = V(e), pv = V(e), va = V64(e), v = V(e);
+    movrz(e, kk);
+    loop_begin(e);
+    int LB = here(e);
+    iadd3(e, tt, base, kk);
+    isetp_ge_u32(e, tt, ctx);
+    int bB = bra_fwd_if_p0(e);
+    imadi(e, oa, kk, 4, c512);
+    lds32(e, ko, oa);
+    imadi(e, pa, kk, 4, c256);
+    lds32(e, pv, pa);
+    wide(e, va, ko, 1, vb);
+    if (k->f32) ldg(e, v, va, udesc);
+    else { ldg16(e, v, va, udesc); imadi(e, v, v, 0x10000u, NOREG); }
+    e_ffma(e, acc, pv, v, acc);
+    iadd3(e, kk, kk, c1);
+    isetp_ge_u32(e, kk, c64);
+    bra_back_if_not_p0(e, LB);
+    loop_end(e);
+    patch_fwd(e, bB);
+    bar_sync(e); /* phase B reads of s/p and offsets finish before the next chunk writes them */
+    iadd3(e, base, base, c64);
+    isetp_ge_u32(e, base, ctx);
+    bra_back_if_not_p0(e, Lout);
+    loop_end(e);
+
+    patch_fwd(e, bZ);
+    int inv = V(e), o = V(e);
+    mufu(e, BW_IR_MUFU_RCP, inv, L);
+    e_fmul(e, o, acc, inv);
+    stg(e, oaddr, o, udesc);
+    tail(e);
+}
+
+#define AT_GPR_BUDGET 64u
+
+static int build_kernel(const KSpec *k, OmegaBlackwellKernel *kernel, BlackwellIRProgram **keep) {
+    BlackwellIRProgram *prog = calloc(1, sizeof *prog);
+    if (!prog) return OMEGA_GPU_ATTN_CODEGEN_FAIL;
+    omega_bw_ir_init(prog);
+    Em e; memset(&e, 0, sizeof e); e.p = prog;
+    gen_attention(&e, k);
+    if (e.depth != 0) e.err = -1;
+    int rc = OMEGA_GPU_ATTN_CODEGEN_FAIL;
+    int ra_rc = (e.err == 0) ? omega_bw_regalloc_solve(prog) : -1;
+    int loop_rc = (ra_rc == 0) ? check_loop_invariant(&e) : -1;
+#ifdef OMEGA_ATTN_DEBUG
+    fprintf(stderr, "attn codegen f32=%d log2bs=%u log2gqa=%u mutant=%d emit_err=%d insns=%zu vregs=%d regalloc=%d loops=%d peak_gpr=%u\n",
+            (int)k->f32, k->log2bs, k->log2gqa, k->mutant, e.err, prog->count, prog->regalloc.num_vregs, ra_rc, loop_rc, prog->regalloc.peak_gpr_usage);
+#endif
+    if (e.err == 0 && ra_rc == 0 && loop_rc == 0 && prog->regalloc.peak_gpr_usage <= AT_GPR_BUDGET) {
+        size_t max_bytes = (size_t)BW_MAX_IR_INSNS * 16;
+        memset(kernel, 0, sizeof *kernel);
+        kernel->code = malloc(max_bytes);
+        size_t emitted = 0;
+        if (kernel->code && omega_bw_encode_program(prog, kernel->code, max_bytes, &emitted) == 0) {
+            kernel->code_size = emitted;
+            kernel->insn_count = emitted / 16;
+            kernel->gpr_count = prog->regalloc.peak_gpr_usage;
+            kernel->uniform_gpr_count = prog->regalloc.peak_ugpr_usage;
+            sha256_hash(kernel->code, kernel->code_size, kernel->code_digest);
+            rc = OMEGA_GPU_ATTN_OK;
+        } else {
+            free(kernel->code); kernel->code = NULL;
+        }
+    }
+    if (keep && rc == OMEGA_GPU_ATTN_OK) *keep = prog; else free(prog);
+    return rc;
+}
+
+/* --------------------------------------------------------- kernel cache */
+
+static int g_mutant;
+typedef struct { int used; KSpec k; OmegaBlackwellKernel kernel; BlackwellIRProgram *prog; } Slot;
+static OmegaGpuAttnSim g_sim;
+static Slot g_cache[8];
+static pthread_mutex_t g_mu = PTHREAD_MUTEX_INITIALIZER;
+void omega_gpu_attention_test_set_simulator(OmegaGpuAttnSim sim) { pthread_mutex_lock(&g_mu); g_sim = sim; pthread_mutex_unlock(&g_mu); }
+
+void omega_gpu_attention_cache_clear(void) {
+    pthread_mutex_lock(&g_mu);
+    for (size_t i = 0; i < sizeof g_cache / sizeof g_cache[0]; i++)
+        if (g_cache[i].used) { free(g_cache[i].kernel.code); free(g_cache[i].prog); memset(&g_cache[i], 0, sizeof g_cache[i]); }
+    pthread_mutex_unlock(&g_mu);
+}
+
+void omega_gpu_attention_test_set_mutant(OmegaGpuAttnMutant m) {
+    pthread_mutex_lock(&g_mu);
+    g_mutant = (int)m;
+    pthread_mutex_unlock(&g_mu);
+    omega_gpu_attention_cache_clear();
+}
+
+static int kernel_for(bool f32, uint32_t log2bs, uint32_t log2gqa, OmegaBlackwellKernel *out, const BlackwellIRProgram **prog, bool *hit) {
+    pthread_mutex_lock(&g_mu);
+    KSpec k = { .f32 = f32, .log2bs = log2bs, .log2gqa = log2gqa, .mutant = g_mutant };
+    for (size_t i = 0; i < sizeof g_cache / sizeof g_cache[0]; i++)
+        if (g_cache[i].used && g_cache[i].k.f32 == k.f32 && g_cache[i].k.log2bs == k.log2bs && g_cache[i].k.log2gqa == k.log2gqa && g_cache[i].k.mutant == k.mutant) { /* field compare: memcmp would read struct padding */
+            *out = g_cache[i].kernel; *prog = g_cache[i].prog; *hit = true; pthread_mutex_unlock(&g_mu); return OMEGA_GPU_ATTN_OK;
+        }
+    OmegaBlackwellKernel kern; BlackwellIRProgram *kp = NULL;
+    int rc = build_kernel(&k, &kern, &kp);
+    if (rc == OMEGA_GPU_ATTN_OK) {
+        size_t slot = sizeof g_cache / sizeof g_cache[0];
+        for (size_t i = 0; i < sizeof g_cache / sizeof g_cache[0]; i++) if (!g_cache[i].used) { slot = i; break; }
+        if (slot == sizeof g_cache / sizeof g_cache[0]) { slot = 0; free(g_cache[0].kernel.code); free(g_cache[0].prog); }
+        g_cache[slot].used = 1; g_cache[slot].k = k; g_cache[slot].kernel = kern; g_cache[slot].prog = kp;
+        *out = kern; *prog = kp; *hit = false;
+    }
+    pthread_mutex_unlock(&g_mu);
+    return rc;
+}
+
+int omega_gpu_attention_codegen(bool kv_f32, uint32_t log2_block_size, uint32_t log2_gqa, OmegaBlackwellKernel *kernel) {
+    if (!kernel || log2_block_size > 16 || log2_gqa > 6) return OMEGA_GPU_ATTN_BAD_ARGS;
+    pthread_mutex_lock(&g_mu);
+    KSpec k = { .f32 = kv_f32, .log2bs = log2_block_size, .log2gqa = log2_gqa, .mutant = g_mutant };
+    pthread_mutex_unlock(&g_mu);
+    return build_kernel(&k, kernel, NULL);
+}
+
+/* ------------------------------------------------------------ launcher */
+
+#define AT_POISON 0xffbadbadu
+#define AT_WAIT_MS 600000ull
+
+static const uint32_t SETUP_WORDS[18] = {
+    0x20012061, 0x0000cec0, 0x20012092, 0x00000001, 0x200120a8, 0x0000000f, 0x2001255d, 0x00000003,
+    0x2001255e, 0x20000000, 0x2001255f, 0x000fffff, 0x20012557, 0x00000003, 0x20012558, 0x22000000,
+    0x20012559, 0x00000000,
+};
+
+static uint64_t now_ns(void) {
+    struct timespec t; clock_gettime(CLOCK_MONOTONIC, &t);
+    return (uint64_t)t.tv_sec * 1000000000ULL + (uint64_t)t.tv_nsec;
+}
+static size_t page_round(size_t b) { b = (b + 0xFFFULL) & ~0xFFFULL; return b < 0x1000 ? 0x1000 : b; }
+
+typedef OmegaGpuAttnLaunch Launch;
+
+/* One launch. Cloned from cut 4's run_abc (itself from omega_blackwell_execute_matmul_tensor):
+ * every buffer GPU-uncached, shader caches invalidated (cut 1b), first marker, L2_FLUSH_DIRTY,
+ * second marker, readback, poison scan. */
+static int run_launch(const OmegaBlackwellKernel *kernel, const Launch *L, OmegaGpuAttnInfo *info) {
+    M16NativeContext ctx;
+    if (m16_native_open(&ctx) != 0) return OMEGA_GPU_ATTN_CHIP_FAIL;
+    if (m16_native_create_channel(&ctx) != 0) { m16_native_close(&ctx); return OMEGA_GPU_ATTN_CHIP_FAIL; }
+    NvrmMem large_pb;
+    if (nvrm_alloc_gpu_uncached(&ctx.rm, 0x10000, &large_pb) != 0) { m16_native_close(&ctx); return OMEGA_GPU_ATTN_CHIP_FAIL; }
+    ctx.pb_mem = large_pb;
+
+    NvrmMem code_mem, cbank_mem, q_mem, pool_mem, tab_mem, out_mem, marker_mem, qmd_mem;
+#define AT_ALLOC(mem, bytes) if (nvrm_alloc_gpu_uncached(&ctx.rm, (bytes), &(mem)) != 0) { m16_native_close(&ctx); return OMEGA_GPU_ATTN_CHIP_FAIL; }
+    AT_ALLOC(code_mem, page_round(kernel->code_size));
+    AT_ALLOC(cbank_mem, 0x1000);
+    AT_ALLOC(q_mem, page_round(L->q_bytes));
+    AT_ALLOC(pool_mem, page_round(L->pool_bytes));
+    AT_ALLOC(tab_mem, page_round(L->tab_bytes));
+    AT_ALLOC(out_mem, page_round(L->out_bytes));
+    AT_ALLOC(marker_mem, 0x1000);
+    AT_ALLOC(qmd_mem, 0x10000);
+#undef AT_ALLOC
+    memcpy(code_mem.cpu, kernel->code, kernel->code_size);
+    memcpy(q_mem.cpu, L->q, L->q_bytes);
+    memcpy(pool_mem.cpu, L->pool, L->pool_bytes);
+    memcpy(tab_mem.cpu, L->tab, L->tab_bytes);
+    size_t out_words = L->out_bytes / 4;
+    uint32_t *out_dev = (uint32_t *)out_mem.cpu;
+    for (size_t i = 0; i < out_words; i++) out_dev[i] = AT_POISON;
+
+    const uint32_t threads_x = HD;
+    uint32_t cbank_data[OMEGA_BW_CBANK_DRIVER_WORDS];
+    omega_blackwell_build_cbank_driver_2d(cbank_data, cbank_mem.va, threads_x, 1, L->grid_x, L->grid_y);
+    uint32_t cbank_args[ARG_WORDS];
+    cbank_args[0] = (uint32_t)q_mem.va; cbank_args[1] = (uint32_t)(q_mem.va >> 32);
+    cbank_args[2] = (uint32_t)pool_mem.va; cbank_args[3] = (uint32_t)(pool_mem.va >> 32);
+    cbank_args[4] = (uint32_t)out_mem.va; cbank_args[5] = (uint32_t)(out_mem.va >> 32);
+    cbank_args[6] = (uint32_t)tab_mem.va; cbank_args[7] = (uint32_t)(tab_mem.va >> 32);
+    memcpy(&cbank_args[8], L->params, sizeof L->params);
+    memcpy(cbank_mem.cpu, cbank_data, sizeof(cbank_data));
+    memcpy((uint8_t *)cbank_mem.cpu + 0x380, cbank_args, sizeof(cbank_args));
+
+    uint64_t qmd0_va = qmd_mem.va, qmd1_va = qmd_mem.va + 0x1000, sem_va = qmd_mem.va + 0x2000, scratch_va = qmd_mem.va + 0x4000;
+    OmegaBlackwellQmdConfig qmd_cfg = {
+        .code_va = code_mem.va, .cbank_va = cbank_mem.va, .scratch_va = scratch_va, .sem_va = sem_va,
+        .qmd0_va = qmd0_va, .qmd1_va = qmd1_va, .num_elements = out_words, .threads_per_block = threads_x,
+        .grid_width = L->grid_x * L->grid_y, .threads_x = threads_x, .threads_y = 1, .grid_x = L->grid_x, .grid_y = L->grid_y,
+        .gpr_count = AT_GPR_BUDGET
+    };
+    uint32_t qmd0_words[OMEGA_BW_QMD_WORDS], qmd1_words[OMEGA_BW_QMD_WORDS];
+    omega_blackwell_build_qmd0(qmd0_words, qmd0_va, qmd1_va);
+    omega_blackwell_build_qmd1(qmd1_words, &qmd_cfg);
+    if (omega_blackwell_verify_qmd_invariants(qmd1_words) != 0) { m16_native_close(&ctx); return OMEGA_GPU_ATTN_CHIP_FAIL; }
+    memcpy(qmd_mem.cpu, qmd0_words, sizeof(qmd0_words));
+    memcpy((uint8_t *)qmd_mem.cpu + 0x1000, qmd1_words, sizeof(qmd1_words));
+
+    volatile uint32_t *hsem = (volatile uint32_t *)((uint8_t *)qmd_mem.cpu + 0x2000);
+    volatile uint32_t *hmarker = (volatile uint32_t *)marker_mem.cpu;
+    volatile uint32_t *hmarker2 = (volatile uint32_t *)((uint8_t *)marker_mem.cpu + 0x10);
+    *hsem = 0; *hmarker = 0; *hmarker2 = 0;
+    __asm__ volatile("dsb sy" ::: "memory");
+
+    uint32_t pb[1024];
+    size_t n = 0;
+    memcpy(&pb[n], SETUP_WORDS, sizeof(SETUP_WORDS)); n += sizeof(SETUP_WORDS) / 4;
+    /* NVCEC0_INVALIDATE_SHADER_CACHES 0x021c: INSTRUCTION 0:0, DATA 4:4, CONSTANT 12:12
+     * (clcec0.h; cut 1b: the SM instruction cache served stale code at a reused code address). */
+    pb[n++] = nvrm_mthd(1, 0x021c, 1); pb[n++] = (1u << 0) | (1u << 4) | (1u << 12);
+    pb[n++] = nvrm_mthd(1, 0x0188, 2); pb[n++] = (uint32_t)(cbank_mem.va >> 32); pb[n++] = (uint32_t)cbank_mem.va;
+    pb[n++] = nvrm_mthd(1, 0x0180, 2); pb[n++] = 0x00000380; pb[n++] = 0x00000001;
+    pb[n++] = nvrm_mthd(1, 0x01b0, 1); pb[n++] = 0x00000041;
+    pb[n++] = (224 << 16) | (1 << 13) | (0x01b4 >> 2) | (6u << 28);
+    memcpy(&pb[n], cbank_data, 224 * 4); n += 224;
+    pb[n++] = nvrm_mthd(1, 0x0188, 2); pb[n++] = (uint32_t)((cbank_mem.va + 0x380) >> 32); pb[n++] = (uint32_t)(cbank_mem.va + 0x380);
+    pb[n++] = nvrm_mthd(1, 0x0180, 2); pb[n++] = ARG_WORDS * 4; pb[n++] = 0x00000001;
+    pb[n++] = nvrm_mthd(1, 0x01b0, 1); pb[n++] = 0x00000041;
+    pb[n++] = (ARG_WORDS << 16) | (1 << 13) | (0x01b4 >> 2) | (6u << 28);
+    memcpy(&pb[n], cbank_args, ARG_WORDS * 4); n += ARG_WORDS;
+    pb[n++] = (98 << 16) | (1 << 13) | (0x0318 >> 2) | (2u << 28);
+    pb[n++] = (1u << 30) | (uint32_t)((qmd0_va >> 40) & 0x1ff); pb[n++] = (uint32_t)(qmd0_va >> 8);
+    memcpy(&pb[n], qmd0_words, 96 * 4); n += 96;
+    pb[n++] = nvrm_mthd(1, 0x0188, 2); pb[n++] = (uint32_t)(sem_va >> 32); pb[n++] = (uint32_t)sem_va;
+    pb[n++] = nvrm_mthd(1, 0x0180, 2); pb[n++] = 0x00000004; pb[n++] = 0x00000001;
+    pb[n++] = nvrm_mthd(1, 0x01b0, 1); pb[n++] = 0x00000041;
+    pb[n++] = (1 << 16) | (1 << 13) | (0x01b4 >> 2) | (6u << 28);
+    pb[n++] = OMEGA_BW_SEMAPHORE_INTERMEDIATE_INIT;
+    pb[n++] = (98 << 16) | (1 << 13) | (0x0318 >> 2) | (2u << 28);
+    pb[n++] = (1u << 30) | (uint32_t)((qmd1_va >> 40) & 0x1ff); pb[n++] = (uint32_t)(qmd1_va >> 8);
+    memcpy(&pb[n], qmd1_words, 96 * 4); n += 96;
+    pb[n++] = nvrm_mthd(0, 0x005c, 5);
+    pb[n++] = (uint32_t)marker_mem.va; pb[n++] = (uint32_t)(marker_mem.va >> 32);
+    pb[n++] = OMEGA_BW_MARKER_COMPLETION_PAYLOAD; pb[n++] = 0; pb[n++] = 0x1 | (1u << 20);
+    /* C3 tail: L2_FLUSH_DIRTY, then the second release the host waits for before reading */
+    pb[n++] = nvrm_mthd(0, 0x0028, 4); pb[n++] = 0; pb[n++] = 0; pb[n++] = 0; pb[n++] = (0x10u << 27);
+    pb[n++] = nvrm_mthd(0, 0x005c, 5);
+    pb[n++] = (uint32_t)(marker_mem.va + 0x10); pb[n++] = (uint32_t)((marker_mem.va + 0x10) >> 32);
+    pb[n++] = OMEGA_BW_MARKER2_PAYLOAD; pb[n++] = 0; pb[n++] = 0x1 | (1u << 20);
+
+    uint64_t t0 = now_ns();
+    if (m16_native_submit_methods(&ctx, pb, n) != 0) { m16_native_close(&ctx); return OMEGA_GPU_ATTN_CHIP_FAIL; }
+    if (m16_native_wait_marker(hmarker, OMEGA_BW_MARKER_COMPLETION_PAYLOAD, AT_WAIT_MS) != 0) { m16_native_close(&ctx); return OMEGA_GPU_ATTN_CHIP_FAIL; }
+    if (m16_native_wait_marker(hmarker2, OMEGA_BW_MARKER2_PAYLOAD, AT_WAIT_MS) != 0) { m16_native_close(&ctx); return OMEGA_GPU_ATTN_CHIP_FAIL; }
+    __asm__ volatile("dsb sy" ::: "memory");
+    uint64_t t1 = now_ns();
+    if (*hsem != OMEGA_BW_SEMAPHORE_INTERMEDIATE_DONE) { m16_native_close(&ctx); return OMEGA_GPU_ATTN_CHIP_FAIL; }
+
+    memcpy(L->out, out_mem.cpu, L->out_bytes);
+    uint32_t unwritten = 0;
+    for (size_t i = 0; i < out_words; i++) if (((uint32_t *)L->out)[i] == AT_POISON) unwritten++;
+    if (info) {
+        info->chip_calls++;
+        info->elapsed_ns += (t1 > t0) ? (t1 - t0) : 0;
+        info->completion_marker = *hmarker;
+        info->unwritten_words += unwritten;
+        info->threads_per_cta = threads_x;
+        info->ctas_last_launch = L->grid_x * L->grid_y;
+    }
+    m16_native_close(&ctx);
+    return unwritten ? OMEGA_GPU_ATTN_UNWRITTEN : OMEGA_GPU_ATTN_OK;
+}
+
+static int launch(const OmegaBlackwellKernel *kernel, const BlackwellIRProgram *prog, const Launch *L, OmegaGpuAttnInfo *info) {
+    pthread_mutex_lock(&g_mu); OmegaGpuAttnSim sim = g_sim; pthread_mutex_unlock(&g_mu);
+    if (sim) return sim(prog, L, info);
+    return run_launch(kernel, L, info);
+}
+
+/* ------------------------------------------------------- public entries */
+
+static void info_begin(OmegaGpuAttnInfo *info, const OmegaBlackwellKernel *k, bool hit) {
+    if (!info) return;
+    memset(info, 0, sizeof *info);
+    info->kernel_cache_hit = hit;
+    info->gpr_count = k->gpr_count;
+    info->insn_count = (uint32_t)k->insn_count;
+    snprintf(info->target_chip, sizeof info->target_chip, "NVIDIA DGX Spark (Grace Blackwell GB10)");
+    info->sm_architecture = 121;
+}
+static uint32_t f2u(float f) { uint32_t u; memcpy(&u, &f, 4); return u; }
+static int log2_exact(uint32_t v, uint32_t *out) {
+    if (v == 0 || (v & (v - 1))) return -1;
+    uint32_t l = 0; while ((1u << l) != v) l++;
+    *out = l; return 0;
+}
+static float score_scale(void) { return (float)(1.4426950408889634 / sqrt((double)HD)); }
+
+/* Common head-shape checks; returns log2 of the gqa ratio. */
+static int check_heads(uint32_t num_q_heads, uint32_t num_kv_heads, uint32_t head_dim, uint32_t *log2gqa) {
+    if (num_q_heads == 0 || num_kv_heads == 0 || head_dim == 0) return OMEGA_GPU_ATTN_BAD_ARGS;
+    if (head_dim != HD || num_q_heads > OMEGA_GPU_ATTN_MAX_Q_HEADS) return OMEGA_GPU_ATTN_TOO_LARGE;
+    if (num_q_heads % num_kv_heads != 0 || log2_exact(num_q_heads / num_kv_heads, log2gqa) != 0) return OMEGA_GPU_ATTN_BAD_ARGS;
+    return OMEGA_GPU_ATTN_OK;
+}
+
+int omega_gpu_gqa_attention_f32(const float *q, const float *k_cache, const float *v_cache,
+                                uint32_t seq_len, uint32_t num_q_heads, uint32_t num_kv_heads,
+                                uint32_t head_dim, float *out, OmegaGpuAttnInfo *info) {
+    uint64_t t0 = now_ns();
+    if (!q || !k_cache || !v_cache || !out) return OMEGA_GPU_ATTN_BAD_ARGS;
+    uint32_t log2gqa;
+    int rc = check_heads(num_q_heads, num_kv_heads, head_dim, &log2gqa);
+    if (rc != OMEGA_GPU_ATTN_OK) return rc;
+    if (seq_len > OMEGA_GPU_ATTN_MAX_GQA_CTX) return OMEGA_GPU_ATTN_TOO_LARGE;
+    size_t n_out = (size_t)num_q_heads * HD;
+    if (seq_len == 0) { memset(out, 0, n_out * 4); if (info) { memset(info, 0, sizeof *info); info->call_ns = now_ns() - t0; } return OMEGA_GPU_ATTN_OK; }
+    OmegaBlackwellKernel k; const BlackwellIRProgram *kp = NULL; bool hit = false;
+    const uint32_t log2bs = 12; /* one block of 4096 slots */
+    rc = kernel_for(true, log2bs, log2gqa, &k, &kp, &hit);
+    if (rc != OMEGA_GPU_ATTN_OK) return rc;
+    info_begin(info, &k, hit);
+    size_t plane = (size_t)seq_len * num_kv_heads * HD * 4;
+    uint8_t *pool = malloc(2 * plane);
+    if (!pool) return OMEGA_GPU_ATTN_CHIP_FAIL;
+    memcpy(pool, k_cache, plane);
+    memcpy(pool + plane, v_cache, plane);
+    uint32_t tab[2] = { 0, seq_len }; /* table row {0}, then the context length at byte 4 */
+    Launch L = {
+        .q = q, .q_bytes = n_out * 4, .pool = pool, .pool_bytes = 2 * plane, .tab = tab, .tab_bytes = sizeof tab,
+        .out = out, .out_bytes = n_out * 4, .grid_x = num_q_heads, .grid_y = 1,
+        .params = { 1, f2u(score_scale()), (uint32_t)(2 * plane), num_kv_heads * HD * 4, (uint32_t)plane, HD * 4, num_q_heads, 4 }
+    };
+    rc = launch(&k, kp, &L, info);
+    free(pool);
+    if (info) info->call_ns = now_ns() - t0;
+    return rc;
+}
+
+/* Paged path shared by the single and batched entries. tables[s] has n_blocks[s] entries
+ * (already filtered of negatives), ctx[s] the context length. */
+static int paged_core(const float *q, const uint8_t *pool, const OmegaGpuKvLayout *ly,
+                      const uint32_t *const *tables, const uint32_t *n_blocks, const uint32_t *ctx,
+                      uint32_t num_seqs, uint32_t layer_idx, uint32_t num_q_heads, uint32_t num_kv_heads,
+                      uint32_t head_dim, float *out, OmegaGpuAttnInfo *info) {
+    uint64_t t0 = now_ns();
+    uint32_t log2gqa, log2bs;
+    int rc = check_heads(num_q_heads, num_kv_heads, head_dim, &log2gqa);
+    if (rc != OMEGA_GPU_ATTN_OK) return rc;
+    if (!ly || layer_idx >= ly->num_layers || log2_exact(ly->block_size, &log2bs) != 0) return OMEGA_GPU_ATTN_BAD_ARGS;
+    /* the oracle addresses heads as kv_head * head_dim * 2 inside a token: the layout must agree */
+    if (ly->head_stride_bytes != HD * 2 || ly->token_stride_bytes != (uint64_t)num_kv_heads * HD * 2 ||
+        ly->kv_plane_stride_bytes != (uint64_t)ly->block_size * ly->token_stride_bytes ||
+        ly->layer_stride_bytes != 2 * ly->kv_plane_stride_bytes || ly->block_stride_bytes < (uint64_t)ly->num_layers * ly->layer_stride_bytes)
+        return OMEGA_GPU_ATTN_BAD_ARGS;
+    size_t row = (size_t)num_q_heads * HD;
+    /* effective context per sequence and block id range check */
+    uint32_t *eff = calloc(num_seqs ? num_seqs : 1, sizeof *eff);
+    if (!eff) return OMEGA_GPU_ATTN_CHIP_FAIL;
+    for (uint32_t s = 0; s < num_seqs; s++) {
+        uint64_t cap = (uint64_t)n_blocks[s] * ly->block_size;
+        eff[s] = (uint32_t)(ctx[s] < cap ? ctx[s] : cap);
+        for (uint32_t b = 0; b < n_blocks[s]; b++) {
+            uint64_t id = tables[s][b];
+            if (id >= ly->num_blocks || id * ly->block_stride_bytes + (uint64_t)(layer_idx + 1) * ly->layer_stride_bytes > ly->pool_bytes) { free(eff); return OMEGA_GPU_ATTN_BAD_ARGS; }
+        }
+    }
+    OmegaBlackwellKernel k; const BlackwellIRProgram *kp = NULL; bool hit = false;
+    rc = kernel_for(false, log2bs, log2gqa, &k, &kp, &hit);
+    if (rc != OMEGA_GPU_ATTN_OK) { free(eff); return rc; }
+    info_begin(info, &k, hit);
+    uint32_t seqs_per_launch = OMEGA_GPU_ATTN_MAX_CTAS / num_q_heads;
+    if (seqs_per_launch == 0) seqs_per_launch = 1;
+    uint32_t maxb = 1;
+    for (uint32_t s = 0; s < num_seqs; s++) if (n_blocks[s] > maxb) maxb = n_blocks[s];
+    for (uint32_t s0 = 0; s0 < num_seqs && rc == OMEGA_GPU_ATTN_OK; s0 += seqs_per_launch) {
+        uint32_t ns = num_seqs - s0 < seqs_per_launch ? num_seqs - s0 : seqs_per_launch;
+        /* stage the referenced blocks' layer slice, renumbered in table order */
+        uint32_t total = 0;
+        for (uint32_t s = 0; s < ns; s++) total += eff[s0 + s] ? (eff[s0 + s] + ly->block_size - 1) / ly->block_size : 0;
+        uint64_t staged_bytes = (uint64_t)(total ? total : 1) * ly->layer_stride_bytes;
+        if (staged_bytes > 0xffffffffull) { rc = OMEGA_GPU_ATTN_TOO_LARGE; break; }
+        uint8_t *staged = malloc((size_t)staged_bytes);
+        uint32_t *tab = calloc((size_t)ns * maxb + ns, sizeof *tab);
+        if (!staged || !tab) { free(staged); free(tab); rc = OMEGA_GPU_ATTN_CHIP_FAIL; break; }
+        uint32_t g = 0;
+        for (uint32_t s = 0; s < ns; s++) {
+            uint32_t need = eff[s0 + s] ? (eff[s0 + s] + ly->block_size - 1) / ly->block_size : 0;
+            for (uint32_t b = 0; b < need; b++, g++) {
+                const uint8_t *src = pool + (size_t)tables[s0 + s][b] * ly->block_stride_bytes + (size_t)layer_idx * ly->layer_stride_bytes;
+                memcpy(staged + (size_t)g * ly->layer_stride_bytes, src, (size_t)ly->layer_stride_bytes);
+                tab[(size_t)s * maxb + b] = g;
+            }
+            tab[(size_t)ns * maxb + s] = eff[s0 + s];
+        }
+        Launch L = {
+            .q = q + (size_t)s0 * row, .q_bytes = (size_t)ns * row * 4, .pool = staged, .pool_bytes = (size_t)staged_bytes,
+            .tab = tab, .tab_bytes = ((size_t)ns * maxb + ns) * 4, .out = out + (size_t)s0 * row, .out_bytes = (size_t)ns * row * 4,
+            .grid_x = num_q_heads, .grid_y = ns,
+            .params = { maxb, f2u(score_scale()), (uint32_t)ly->layer_stride_bytes, (uint32_t)ly->token_stride_bytes,
+                        (uint32_t)ly->kv_plane_stride_bytes, (uint32_t)ly->head_stride_bytes, num_q_heads, ns * maxb * 4 }
+        };
+        rc = launch(&k, kp, &L, info);
+        free(staged); free(tab);
+    }
+    free(eff);
+    if (info) info->call_ns = now_ns() - t0;
+    return rc;
+}
+
+int omega_gpu_paged_attention_bf16(const float *q, const void *pool, const OmegaGpuKvLayout *layout,
+                                   const uint32_t *block_ids, uint32_t num_block_ids,
+                                   uint32_t context_len, uint32_t layer_idx,
+                                   uint32_t num_q_heads, uint32_t num_kv_heads, uint32_t head_dim,
+                                   float *out, OmegaGpuAttnInfo *info) {
+    if (!q || !pool || !layout || !out || (num_block_ids && !block_ids)) return OMEGA_GPU_ATTN_BAD_ARGS;
+    const uint32_t *tables[1] = { block_ids };
+    uint32_t nb[1] = { num_block_ids }, cx[1] = { context_len };
+    return paged_core(q, pool, layout, tables, nb, cx, 1, layer_idx, num_q_heads, num_kv_heads, head_dim, out, info);
+}
+
+int omega_gpu_paged_attention_batch_bf16(const float *q, const void *pool, const OmegaGpuKvLayout *layout,
+                                         const int32_t *block_tables, const int32_t *context_lens,
+                                         uint32_t max_blocks_per_seq, uint32_t num_seqs, uint32_t layer_idx,
+                                         uint32_t num_q_heads, uint32_t num_kv_heads, uint32_t head_dim,
+                                         float *out, OmegaGpuAttnInfo *info) {
+    if (!q || !pool || !layout || !out || !block_tables || !context_lens || num_seqs == 0) return OMEGA_GPU_ATTN_BAD_ARGS;
+    /* the oracle's rules: ctx <= 0 -> 0; a table row past the array -> empty; negatives removed */
+    uint32_t **tables = calloc(num_seqs, sizeof *tables);
+    uint32_t *nb = calloc(num_seqs, sizeof *nb), *cx = calloc(num_seqs, sizeof *cx);
+    if (!tables || !nb || !cx) { free(tables); free(nb); free(cx); return OMEGA_GPU_ATTN_CHIP_FAIL; }
+    int rc = OMEGA_GPU_ATTN_OK;
+    for (uint32_t s = 0; s < num_seqs; s++) {
+        cx[s] = context_lens[s] > 0 ? (uint32_t)context_lens[s] : 0;
+        tables[s] = calloc(max_blocks_per_seq ? max_blocks_per_seq : 1, sizeof **tables);
+        if (!tables[s]) { rc = OMEGA_GPU_ATTN_CHIP_FAIL; break; }
+        for (uint32_t b = 0; b < max_blocks_per_seq; b++) {
+            int32_t v = block_tables[(size_t)s * max_blocks_per_seq + b];
+            if (v >= 0) tables[s][nb[s]++] = (uint32_t)v;
+        }
+    }
+    if (rc == OMEGA_GPU_ATTN_OK)
+        rc = paged_core(q, pool, layout, (const uint32_t *const *)tables, nb, cx, num_seqs, layer_idx, num_q_heads, num_kv_heads, head_dim, out, info);
+    for (uint32_t s = 0; s < num_seqs; s++) free(tables[s]);
+    free(tables); free(nb); free(cx);
+    return rc;
+}
+
+const char *omega_gpu_attention_rc_name(int rc) {
+    switch (rc) {
+    case OMEGA_GPU_ATTN_OK: return "OK";
+    case OMEGA_GPU_ATTN_BAD_ARGS: return "BAD_ARGS";
+    case OMEGA_GPU_ATTN_TOO_LARGE: return "TOO_LARGE";
+    case OMEGA_GPU_ATTN_CODEGEN_FAIL: return "CODEGEN_FAIL";
+    case OMEGA_GPU_ATTN_CHIP_FAIL: return "CHIP_FAIL";
+    case OMEGA_GPU_ATTN_UNWRITTEN: return "UNWRITTEN";
+    default: return "UNKNOWN";
+    }
+}
diff --git a/src/omega_gpu_attention_api.h b/src/omega_gpu_attention_api.h
new file mode 100644
index 000000000..4baf67c49
--- /dev/null
+++ b/src/omega_gpu_attention_api.h
@@ -0,0 +1,161 @@
+#ifndef OMEGA_GPU_ATTENTION_API_H
+#define OMEGA_GPU_ATTENTION_API_H
+/*
+ * omega_gpu_attention_api: native (no CUDA) decode attention for the AIEN
+ * inference stack (FB-1 cut 5, 2026-10-04).
+ *
+ * Two kernel families, one query per (sequence, query head), generated by our
+ * own codegen (src/omega_blackwell_codegen.c IR) and launched through the same
+ * chip-proven sequence as cuts 1b and 4: every buffer GPU-uncached (nvos.h
+ * NVOS32_ATTR2_GPU_CACHEABLE: system memory cached by the GPU is not coherent
+ * with CPU mappings), shader caches invalidated before the launch (clcec0.h
+ * NVCEC0_INVALIDATE_SHADER_CACHES, cut 1b finding), first marker,
+ * L2_FLUSH_DIRTY, second marker (C3 tail), poison-filled output scanned for
+ * unwritten words after readback.
+ *
+ * The math follows aien-sovereign-core crates/aien-inference-abi/src/backend.rs
+ * (ReferenceCpuBackend / TensorBackend defaults), read 2026-10-04 at main 8b5caed:
+ *   gqa_attention(out, q, k_cache, v_cache, seq_len, num_q_heads, num_kv_heads, head_dim)
+ *     k_cache / v_cache are f32 [seq_len][num_kv_heads][head_dim]; query head h reads
+ *     kv head h / (num_q_heads / num_kv_heads); score = (q . k) / sqrt(head_dim);
+ *     softmax over all seq_len tokens (no mask: one query attends to the whole history);
+ *     out[h] = sum_t softmax_t v_t.  seq_len == 0 writes zeros.
+ *   paged_attention(out, q, pool, block_ids, context_len, layer_idx, ...)
+ *     the KV pool is bf16 in aien-kv-cache's canonical layout (KvLayout strides in
+ *     bytes: block, layer, kv plane (0 = K, 1 = V), token, head); token t lives in
+ *     block_ids[t / block_size] at slot t % block_size; tokens whose block index is
+ *     past the end of block_ids are dropped; context_len == 0 or no blocks writes zeros.
+ *   paged_attention_batch: per sequence s, context_lens[s] <= 0 means 0, the block
+ *     table row is block_tables[s*max_blocks .. (s+1)*max_blocks] (empty if that row
+ *     runs past the array), negative entries are removed (the rest close up).
+ *
+ * Chip math: scores in f32 (FFMA over the head), online softmax per chunk of
+ * head_dim tokens: running max (FMNMX), p = EX2((s - m) * log2 e) folded into the
+ * score scale, rescale factor alpha = EX2(m_old - m_new), f32 sums, final MUFU.RCP.
+ * bf16 K is read as 32-bit pairs (LDG.E) and widened by a 16-bit shift (bf16 is
+ * the top half of an f32); bf16 V by LDG.E.U16 and the same shift. f32 K/V are
+ * read directly. Tolerances are stated and justified in tests/gpu_attention_test.c.
+ *
+ * Launch envelope: at most OMEGA_GPU_ATTN_MAX_CTAS CTAs per launch (investigation
+ * I42, same as cuts 1b and 4): grid = (num_q_heads, sequences per launch).
+ * Shared memory: the QMD declares 1024 bytes (clcec0qmd.h SHARED_MEMORY_SIZE_SHIFTED7,
+ * src/omega_blackwell_qmd.c word 36); the kernel uses exactly 4 x 256 bytes for
+ * head_dim 64, so head_dim is fixed at 64 in this cut (TinyLlama and Llama-3.2-1B).
+ *
+ * Staging (this cut): the host copies q, the referenced KV blocks' layer slice, the
+ * (compacted, renumbered) block tables and the context lengths into GPU-uncached
+ * buffers for each launch and copies the result back. The kernel itself walks the
+ * block table; a resident pool handle is a later cut.
+ */
+#include <stdbool.h>
+#include <stddef.h>
+#include <stdint.h>
+#include "omega_blackwell_matmul.h" /* OmegaBlackwellKernel */
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+enum {
+    OMEGA_GPU_ATTN_OK = 0,
+    OMEGA_GPU_ATTN_BAD_ARGS = -1,     /* NULL pointer, zero dimension, head mapping or block id out of range */
+    OMEGA_GPU_ATTN_TOO_LARGE = -2,    /* head_dim != 64, num_q_heads > 64, context past the envelope */
+    OMEGA_GPU_ATTN_CODEGEN_FAIL = -3, /* our codegen refused or exceeded the register budget */
+    OMEGA_GPU_ATTN_CHIP_FAIL = -4,    /* device open, alloc, submit, marker or release failed */
+    OMEGA_GPU_ATTN_UNWRITTEN = -5     /* output words still equal to their poison after the run */
+};
+
+#define OMEGA_GPU_ATTN_HEAD_DIM 64u      /* threads per CTA = head_dim (one thread per dimension / per token of a chunk) */
+#define OMEGA_GPU_ATTN_MAX_CTAS 64u
+#define OMEGA_GPU_ATTN_MAX_Q_HEADS 64u
+#define OMEGA_GPU_ATTN_MAX_GQA_CTX 4096u /* contiguous path: one block of 2^12 slots */
+
+/* Mirror of aien-kv-cache KvLayoutDesc (crates/aien-kv-cache/src/lib.rs, main 8b5caed),
+ * field for field, strides in bytes. */
+typedef struct {
+    uint64_t block_stride_bytes;
+    uint64_t layer_stride_bytes;
+    uint64_t kv_plane_stride_bytes;
+    uint64_t token_stride_bytes;
+    uint64_t head_stride_bytes;
+    uint64_t pool_bytes;
+    uint32_t num_blocks;
+    uint32_t num_layers;
+    uint32_t block_size; /* must be a power of two (the kernel shifts and masks) */
+} OmegaGpuKvLayout;
+
+typedef struct {
+    uint32_t chip_calls;        /* launches made */
+    uint64_t elapsed_ns;        /* sum of submit-to-second-marker over the launches */
+    uint64_t call_ns;           /* wall time of the whole API call (staging, launches, copy-out) */
+    uint32_t completion_marker; /* first marker word of the last launch */
+    uint32_t unwritten_words;   /* poison words left in the outputs (0 on OK) */
+    uint32_t gpr_count, insn_count;
+    bool kernel_cache_hit;      /* the kernel was already generated */
+    uint32_t ctas_last_launch, threads_per_cta;
+    char target_chip[64];
+    uint32_t sm_architecture;
+} OmegaGpuAttnInfo;
+
+/* Contiguous f32 KV (TensorBackend::gqa_attention). q and out: [num_q_heads][head_dim]. */
+int omega_gpu_gqa_attention_f32(const float *q, const float *k_cache, const float *v_cache,
+                                uint32_t seq_len, uint32_t num_q_heads, uint32_t num_kv_heads,
+                                uint32_t head_dim, float *out, OmegaGpuAttnInfo *info);
+
+/* Paged bf16 KV (TensorBackend::paged_attention). pool points at the pool base. */
+int omega_gpu_paged_attention_bf16(const float *q, const void *pool, const OmegaGpuKvLayout *layout,
+                                   const uint32_t *block_ids, uint32_t num_block_ids,
+                                   uint32_t context_len, uint32_t layer_idx,
+                                   uint32_t num_q_heads, uint32_t num_kv_heads, uint32_t head_dim,
+                                   float *out, OmegaGpuAttnInfo *info);
+
+/* Batched (TensorBackend::paged_attention_batch). block_tables: [num_seqs][max_blocks_per_seq] i32
+ * (negative = none), context_lens: [num_seqs] i32. q and out: [num_seqs][num_q_heads][head_dim]. */
+int omega_gpu_paged_attention_batch_bf16(const float *q, const void *pool, const OmegaGpuKvLayout *layout,
+                                         const int32_t *block_tables, const int32_t *context_lens,
+                                         uint32_t max_blocks_per_seq, uint32_t num_seqs, uint32_t layer_idx,
+                                         uint32_t num_q_heads, uint32_t num_kv_heads, uint32_t head_dim,
+                                         float *out, OmegaGpuAttnInfo *info);
+
+const char *omega_gpu_attention_rc_name(int rc);
+void omega_gpu_attention_cache_clear(void);
+
+/* Test hooks. Mutants are deliberately wrong kernels the parity test must catch;
+ * never set in production. */
+typedef enum {
+    OMEGA_GPU_ATTN_MUTANT_NONE = 0,
+    OMEGA_GPU_ATTN_MUTANT_NO_MAX,     /* softmax without the running-max subtraction (overflows for large scores) */
+    OMEGA_GPU_ATTN_MUTANT_KV_HEAD,    /* reads kv head (h / ratio) ^ 1 */
+    OMEGA_GPU_ATTN_MUTANT_SLOT,       /* K read from slot (t + 1) % block_size while V keeps slot t (K/V mismatch) */
+    OMEGA_GPU_ATTN_MUTANT_NO_RESCALE  /* the accumulator is not rescaled when the max moves between chunks */
+} OmegaGpuAttnMutant;
+void omega_gpu_attention_test_set_mutant(OmegaGpuAttnMutant m);
+
+/* Generate a kernel without launching (host tests, nvdisasm listings).
+ * log2_block_size: shift for token -> block; log2_gqa: shift for query head -> kv head. */
+int omega_gpu_attention_codegen(bool kv_f32, uint32_t log2_block_size, uint32_t log2_gqa,
+                                OmegaBlackwellKernel *kernel);
+
+/* One launch as the launcher sees it (test hook below). Pointers are host buffers;
+ * params are the eight argument words after the four buffer addresses:
+ * max_blocks, scale bits, block stride, token stride, kv plane stride, head stride,
+ * num_q_heads, context-array byte offset. */
+typedef struct {
+    const void *q; size_t q_bytes;
+    const void *pool; size_t pool_bytes;
+    const void *tab; size_t tab_bytes;
+    void *out; size_t out_bytes;
+    uint32_t grid_x, grid_y;
+    uint32_t params[8];
+} OmegaGpuAttnLaunch;
+
+/* Host simulator hook (tests): when set, every launch runs the allocated IR program
+ * through `sim` instead of the chip. Lets the whole battery run on the host first
+ * (review before chip time). The program is post register allocation. */
+struct BlackwellIRProgramTag;
+typedef int (*OmegaGpuAttnSim)(const void *prog /* const BlackwellIRProgram * */, const OmegaGpuAttnLaunch *L, OmegaGpuAttnInfo *info);
+void omega_gpu_attention_test_set_simulator(OmegaGpuAttnSim sim);
+
+#ifdef __cplusplus
+}
+#endif
+#endif /* OMEGA_GPU_ATTENTION_API_H */
diff --git a/tests/gpu_attention_test.c b/tests/gpu_attention_test.c
new file mode 100644
index 000000000..47d0fdf28
--- /dev/null
+++ b/tests/gpu_attention_test.c
@@ -0,0 +1,498 @@
+/* gpu_attention_test: FB-1 cut 5 gate for omega_gpu_attention_api.
+ *
+ *   ./gpu_attention_test --host-only          refusals, codegen (both kernel families and every
+ *                                             mutant), register budget, nvdisasm listing check
+ *   ./gpu_attention_test --out receipt.json   chip gate: every shape against the host oracle, the
+ *                                             mutants (deliberately wrong kernels) which the same
+ *                                             check must catch, a negative control, timings
+ *
+ * Oracles re-state aien-sovereign-core crates/aien-inference-abi/src/backend.rs (main 8b5caed) in C:
+ * ReferenceCpuBackend::gqa_attention (f64 scores, max, exp, sum, 1/max(sum,1e-12), f64 weighted sum),
+ * TensorBackend::paged_attention (f64 online softmax token by token over the paged bf16 pool, tokens
+ * past the block table dropped, zeros for empty context) and paged_attention_batch (ctx <= 0 -> 0,
+ * table rows past the array -> empty, negative entries removed). Compiled with -ffp-contract=off.
+ *
+ * Tolerance (why): the chip accumulates the 64-term dot products, the per-chunk sums and the
+ * rescaled running sums in f32 (worst case about n * 2^-24 relative over n = 2048 terms, 1.2e-4),
+ * uses MUFU.EX2 (PTX ex2.approx: 2^-22.5 relative) for every weight and for the 32 chunk rescale
+ * factors, and MUFU.RCP for the final normalisation. Every output is a convex combination of V
+ * values of unit scale, so |error| <= 2e-4 * |want| + 2e-5 covers these with margin; the mutants
+ * move results by 1e-2 or more (wrong head, wrong token) or produce NaN (overflow without the max).
+ * The large-score case (scores up to ~300) carries the f32 rounding of the score itself into the
+ * exponent (3e-5 absolute per score), so it uses 1e-3 relative + 1e-4 absolute.
+ */
+#include "omega_gpu_attention_api.h"
+#include "omega_blackwell_codegen.h"
+#include <inttypes.h>
+#include <math.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <time.h>
+#include <unistd.h>
+
+static int g_checks, g_failed;
+#define CHECK(cond, ...) do { g_checks++; if (!(cond)) { g_failed++; printf("FAIL: "); printf(__VA_ARGS__); printf("\n"); } } while (0)
+
+static uint32_t lcg(uint32_t *s) { *s = *s * 1664525u + 1013904223u; return *s; }
+static float frand(uint32_t *s, float lo, float hi) { return lo + (hi - lo) * ((float)(lcg(s) >> 8) / 16777216.0f); }
+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); }
+static float bf2f(uint16_t b) { uint32_t u = (uint32_t)b << 16; float f; memcpy(&f, &u, 4); return f; }
+
+/* ----------------------------------------------------------------- oracles */
+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) {
+    if (seq_len == 0) { memset(out, 0, nqh * hd * 4); return; }
+    size_t ratio = nqh / nkv; double inv_sqrt_d = 1.0 / sqrt((double)hd);
+    double *scores = malloc(seq_len * sizeof *scores);
+    for (size_t h = 0; h < nqh; h++) {
+        size_t kvh = h / ratio; const float *qh = q + h * hd;
+        for (size_t t = 0; t < seq_len; t++) {
+            const float *kt = kc + (t * nkv + kvh) * hd; double dot = 0.0;
+            for (size_t d = 0; d < hd; d++) dot += (double)qh[d] * (double)kt[d];
+            scores[t] = dot * inv_sqrt_d;
+        }
+        double mx = -INFINITY; for (size_t t = 0; t < seq_len; t++) if (scores[t] > mx) mx = scores[t];
+        double sum = 0.0; for (size_t t = 0; t < seq_len; t++) { scores[t] = exp(scores[t] - mx); sum += scores[t]; }
+        double inv = 1.0 / (sum > 1e-12 ? sum : 1e-12);
+        for (size_t t = 0; t < seq_len; t++) scores[t] *= inv;
+        for (size_t d = 0; d < hd; d++) {
+            double s = 0.0;
+            for (size_t t = 0; t < seq_len; t++) s += scores[t] * (double)vc[(t * nkv + kvh) * hd + d];
+            out[h * hd + d] = (float)s;
+        }
+    }
+    free(scores);
+}
+/* bf16 pool in the canonical layout; the oracle's read_kv_head: element_offset(block, layer, is_value, token) + kv_head*head_dim*2 */
+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) {
+    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;
+    return (const uint16_t *)(pool + off);
+}
+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,
+                         size_t nqh, size_t nkv, size_t hd, float *out) {
+    if (ctx == 0 || nids == 0) { memset(out, 0, nqh * hd * 4); return; }
+    size_t ratio = nqh / nkv; double inv_sqrt_d = 1.0 / sqrt((double)hd); size_t bs = ly->block_size;
+    double *acc = malloc(hd * sizeof *acc);
+    for (size_t h = 0; h < nqh; h++) {
+        size_t kvh = h / ratio; const float *qh = q + h * hd;
+        double m = -INFINITY, l = 0.0; for (size_t d = 0; d < hd; d++) acc[d] = 0.0;
+        for (size_t t = 0; t < ctx; t++) {
+            size_t bi = t / bs; if (bi >= nids) break;
+            const uint16_t *kh = kv_head(pool, ly, ids[bi], layer, 0, t % bs, kvh, hd);
+            const uint16_t *vh = kv_head(pool, ly, ids[bi], layer, 1, t % bs, kvh, hd);
+            double dot = 0.0; for (size_t d = 0; d < hd; d++) dot += (double)qh[d] * (double)bf2f(kh[d]);
+            double score = dot * inv_sqrt_d, mn = m > score ? m : score, alpha = exp(m - mn), beta = exp(score - mn);
+            l = l * alpha + beta;
+            for (size_t d = 0; d < hd; d++) acc[d] = acc[d] * alpha + beta * (double)bf2f(vh[d]);
+            m = mn;
+        }
+        double inv = l > 0.0 ? 1.0 / l : 0.0;
+        for (size_t d = 0; d < hd; d++) out[h * hd + d] = (float)(acc[d] * inv);
+    }
+    free(acc);
+}
+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,
+                         size_t layer, size_t nqh, size_t nkv, size_t hd, float *out) {
+    size_t stride = nqh * hd;
+    uint32_t *ids = malloc((maxb ? maxb : 1) * sizeof *ids);
+    for (size_t s = 0; s < nseq; s++) {
+        size_t ctx = ctxs[s] > 0 ? (size_t)ctxs[s] : 0, n = 0;
+        size_t total = nseq * maxb; /* the table array length as the trait sees it */
+        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];
+        oracle_paged(q + s * stride, pool, ly, ids, n, ctx, layer, nqh, nkv, hd, out + s * stride);
+    }
+    free(ids);
+}
+
+static size_t compare(const float *got, const float *want, size_t n, double rel, double abs_tol, double *worst) {
+    size_t bad = 0; *worst = 0.0;
+    for (size_t i = 0; i < n; i++) {
+        double d = fabs((double)got[i] - (double)want[i]);
+        double lim = rel * fabs((double)want[i]) + abs_tol;
+        double scaled = lim > 0 ? d / lim : (d > 0 ? INFINITY : 0.0);
+        if (scaled > *worst) *worst = scaled;
+        if (!(d <= lim)) bad++; /* NaN counts as bad */
+    }
+    return bad;
+}
+
+/* ------------------------------------------------------------- host only */
+static int nvdisasm_check(bool f32, const char *name, const char *const *must, int n_must) {
+    const char *nv = "/usr/local/cuda/bin/nvdisasm";
+    if (access(nv, X_OK) != 0) { printf("nvdisasm: not present, listing check skipped for %s\n", name); return 0; }
+    OmegaBlackwellKernel k; memset(&k, 0, sizeof k);
+    if (omega_gpu_attention_codegen(f32, f32 ? 12 : 4, 3, &k) != OMEGA_GPU_ATTN_OK) return -1;
+    char bin[64], lst[64], cmd[256];
+    snprintf(bin, sizeof bin, "/tmp/omega_attn_%s_%d.bin", name, (int)getpid());
+    snprintf(lst, sizeof lst, "/tmp/omega_attn_%s_%d.sass", name, (int)getpid());
+    FILE *f = fopen(bin, "wb"); if (!f) { free(k.code); return -1; }
+    fwrite(k.code, 1, k.code_size, f); fclose(f);
+    snprintf(cmd, sizeof cmd, "%s -b SM121 %s > %s 2>&1", nv, bin, lst);
+    int rc = system(cmd);
+    free(k.code);
+    FILE *l = fopen(lst, "r"); if (!l) return -1;
+    char line[512]; int seen[16] = {0}; int bad = 0, insns = 0;
+    while (fgets(line, sizeof line, l)) {
+        if (!strstr(line, "/*0")) continue;
+        insns++;
+        if (strstr(line, "?") || strstr(line, "error")) bad++;
+        for (int i = 0; i < n_must; i++) if (strstr(line, must[i])) seen[i] = 1;
+    }
+    fclose(l);
+    int miss = 0;
+    for (int i = 0; i < n_must; i++) if (!seen[i]) { printf("  %s: nvdisasm listing lacks %s\n", name, must[i]); miss++; }
+    printf("nvdisasm %s: rc=%d insns=%d undecodable=%d missing=%d (%s)\n", name, rc, insns, bad, miss, lst);
+    unlink(bin);
+    return (rc == 0 && bad == 0 && miss == 0) ? 0 : -1;
+}
+
+static OmegaGpuKvLayout layout_for(uint32_t num_blocks, uint32_t bs, uint32_t layers, uint32_t nkv, uint32_t hd) {
+    OmegaGpuKvLayout ly;
+    ly.head_stride_bytes = (uint64_t)hd * 2; ly.token_stride_bytes = ly.head_stride_bytes * nkv;
+    ly.kv_plane_stride_bytes = ly.token_stride_bytes * bs; ly.layer_stride_bytes = 2 * ly.kv_plane_stride_bytes;
+    ly.block_stride_bytes = ly.layer_stride_bytes * layers; ly.pool_bytes = ly.block_stride_bytes * num_blocks;
+    ly.num_blocks = num_blocks; ly.num_layers = layers; ly.block_size = bs;
+    return ly;
+}
+
+static void host_only(void) {
+    float q[64 * 64], kv[64 * 64], out[64 * 64]; memset(q, 0, sizeof q); memset(kv, 0, sizeof kv);
+    CHECK(omega_gpu_gqa_attention_f32(NULL, kv, kv, 1, 32, 4, 64, out, NULL) == OMEGA_GPU_ATTN_BAD_ARGS, "NULL q refused");
+    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)");
+    CHECK(omega_gpu_gqa_attention_f32(q, kv, kv, 1, 6, 2, 64, out, NULL) == OMEGA_GPU_ATTN_BAD_ARGS, "gqa ratio 3 refused");
+    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");
+    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");
+    for (int i = 0; i < 64; i++) out[i] = 1.0f;
+    OmegaGpuAttnInfo info;
+    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");
+    OmegaGpuKvLayout ly = layout_for(8, 16, 2, 4, 64);
+    uint8_t *pool = calloc(ly.pool_bytes, 1);
+    uint32_t ids[2] = { 1, 9 };
+    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");
+    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");
+    OmegaGpuKvLayout bad = ly; bad.block_size = 12;
+    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");
+    bad = ly; bad.head_stride_bytes = 256;
+    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");
+    free(pool);
+    CHECK(strcmp(omega_gpu_attention_rc_name(OMEGA_GPU_ATTN_UNWRITTEN), "UNWRITTEN") == 0, "rc name");
+
+    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" };
+    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" };
+    for (int f32 = 0; f32 < 2; f32++) {
+        const char *name = f32 ? "gqa_f32" : "paged_bf16";
+        OmegaBlackwellKernel k; memset(&k, 0, sizeof k);
+        int rc = omega_gpu_attention_codegen(f32 != 0, f32 ? 12 : 4, 3, &k);
+        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);
+        printf("codegen %s: %zu insns, %u gprs, %u ugprs\n", name, k.insn_count, k.gpr_count, k.uniform_gpr_count);
+        uint8_t digest[32]; memcpy(digest, k.code_digest, 32);
+        free(k.code);
+        for (int m = 1; m <= 4; m++) {
+            omega_gpu_attention_test_set_mutant((OmegaGpuAttnMutant)m);
+            memset(&k, 0, sizeof k);
+            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);
+            free(k.code);
+            omega_gpu_attention_test_set_mutant(OMEGA_GPU_ATTN_MUTANT_NONE);
+        }
+        /* a different shape key is a different kernel */
+        memset(&k, 0, sizeof k);
+        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);
+        free(k.code);
+        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);
+    }
+}
+
+/* ------------------------------------------------------------- chip gate */
+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;
+                 int mutants_run, mutants_caught; char mutant_note[160]; } Case;
+static Case g_cases[32]; static int g_ncases;
+static int g_mutant_caught[5], g_mutant_run[5];
+
+static void record(Case c, FILE *out) {
+    g_cases[g_ncases++] = c;
+    CHECK(c.pass, "%s rc=%s violations=%zu worst=%g", c.name, omega_gpu_attention_rc_name(c.rc), c.bad, c.worst);
+    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);
+    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",
+           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,
+           c.mutants_caught, c.mutants_run, c.mutant_note);
+    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\"}",
+                     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,
+                     c.mutants_run, c.mutants_caught, c.mutant_note);
+}
+
+static const char *mutant_name(int m) { static const char *n[5] = { "none", "NO_MAX", "KV_HEAD", "SLOT", "NO_RESCALE" }; return n[m]; }
+
+/* Runs the mutants listed in `ms` (terminated by 0) through `run` and counts the catches. */
+typedef int (*RunFn)(void *ctx, float *got, OmegaGpuAttnInfo *info);
+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) {
+    size_t pos = 0;
+    for (int i = 0; ms[i]; i++) {
+        OmegaGpuAttnInfo info; double w;
+        omega_gpu_attention_test_set_mutant((OmegaGpuAttnMutant)ms[i]);
+        int rc = run(ctx, got, &info);
+        size_t bad = compare(got, want, n, rel, abs_tol, &w);
+        int caught = rc != OMEGA_GPU_ATTN_OK || bad > 0;
+        omega_gpu_attention_test_set_mutant(OMEGA_GPU_ATTN_MUTANT_NONE);
+        c->mutants_run++; c->mutants_caught += caught; g_mutant_run[ms[i]]++; g_mutant_caught[ms[i]] += caught;
+        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);
+        if (pos >= sizeof c->mutant_note) break;
+    }
+}
+
+typedef struct { const float *q, *kc, *vc; uint32_t seq, nqh, nkv; } GqaCtx;
+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); }
+typedef struct { const float *q; const uint8_t *pool; const OmegaGpuKvLayout *ly; const uint32_t *ids; uint32_t nids, ctx, layer, nqh, nkv; } PagedCtx;
+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); }
+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;
+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); }
+
+static int chip(const char *out_path) {
+    FILE *out = out_path ? fopen(out_path, "w") : NULL;
+    if (out_path && !out) { printf("cannot open %s\n", out_path); return 2; }
+    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\":[");
+    uint32_t seed = 0xfb1c0005u;
+    const uint32_t hd = 64;
+    const struct { uint32_t nqh, nkv; const char *model; } shapes[2] = { { 32, 4, "tinyllama" }, { 32, 8, "llama32_1b" } };
+    const uint32_t ctxs[4] = { 1, 17, 256, 2048 };
+    const int no_mutants[1] = { 0 };
+
+    /* 1. contiguous f32 KV (gqa_attention) */
+    for (int sh = 0; sh < 2; sh++) for (int ci = 0; ci < 4; ci++) {
+        uint32_t nqh = shapes[sh].nqh, nkv = shapes[sh].nkv, seq = ctxs[ci];
+        size_t n = (size_t)nqh * hd, nkvs = (size_t)seq * nkv * hd;
+        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);
+        for (size_t i = 0; i < n; i++) q[i] = frand(&seed, -1.0f, 1.0f);
+        for (size_t i = 0; i < nkvs; i++) { kc[i] = frand(&seed, -1.0f, 1.0f); vc[i] = frand(&seed, -1.0f, 1.0f); }
+        oracle_gqa(q, kc, vc, seq, nqh, nkv, hd, want);
+        char name[96]; snprintf(name, sizeof name, "gqa_f32_%s_%uq%ukv_ctx%u", shapes[sh].model, nqh, nkv, seq);
+        Case c = { .name = strdup(name), .n = n };
+        OmegaGpuAttnInfo info;
+        GqaCtx gc = { q, kc, vc, seq, nqh, nkv };
+        c.rc = run_gqa(&gc, got, &info);
+        c.bad = compare(got, want, n, 2e-4, 2e-5, &c.worst);
+        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;
+        if (ci == 3) {
+            OmegaGpuAttnInfo i2; int rc2 = run_gqa(&gc, again, &i2);
+            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);
+            /* negative control: the comparison must reject a wrong expectation (kv heads swapped) */
+            float *wrong = malloc(n * 4); double w2;
+            for (uint32_t h = 0; h < nqh; h++) memcpy(wrong + (size_t)h * hd, want + (size_t)((h + nqh / nkv) % nqh) * hd, hd * 4);
+            size_t neg = compare(got, wrong, n, 2e-4, 2e-5, &w2);
+            CHECK(neg > n / 2, "%s negative control: wrong expectation flagged (%zu of %zu)", name, neg, n);
+            free(wrong);
+            static const int ms[3] = { OMEGA_GPU_ATTN_MUTANT_SLOT, OMEGA_GPU_ATTN_MUTANT_NO_RESCALE, 0 };
+            run_mutants(&c, ms, run_gqa, &gc, got, want, n, 2e-4, 2e-5);
+        } else if (ci == 1 && sh == 1) {
+            static const int ms[2] = { OMEGA_GPU_ATTN_MUTANT_KV_HEAD, 0 };
+            run_mutants(&c, ms, run_gqa, &gc, got, want, n, 2e-4, 2e-5);
+        } else run_mutants(&c, no_mutants, run_gqa, &gc, got, want, n, 2e-4, 2e-5);
+        record(c, out); free(q); free(kc); free(vc); free(got); free(want); free(again);
+    }
+    /* 2. large scores (q scaled by 200): the softmax without the running max overflows */
+    {
+        uint32_t nqh = 32, nkv = 4, seq = 256; size_t n = (size_t)nqh * hd, nkvs = (size_t)seq * nkv * hd;
+        float *q = malloc(n * 4), *kc = malloc(nkvs * 4), *vc = malloc(nkvs * 4), *got = malloc(n * 4), *want = malloc(n * 4);
+        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) */
+        for (size_t i = 0; i < nkvs; i++) { kc[i] = frand(&seed, -1.0f, 1.0f); vc[i] = frand(&seed, -1.0f, 1.0f); }
+        oracle_gqa(q, kc, vc, seq, nqh, nkv, hd, want);
+        Case c = { .name = "gqa_f32_large_scores_32q4kv_ctx256", .n = n };
+        OmegaGpuAttnInfo info; GqaCtx gc = { q, kc, vc, seq, nqh, nkv };
+        c.rc = run_gqa(&gc, got, &info);
+        c.bad = compare(got, want, n, 1e-3, 1e-4, &c.worst);
+        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;
+        static const int ms[2] = { OMEGA_GPU_ATTN_MUTANT_NO_MAX, 0 };
+        run_mutants(&c, ms, run_gqa, &gc, got, want, n, 1e-3, 1e-4);
+        record(c, out); free(q); free(kc); free(vc); free(got); free(want);
+    }
+    /* 3. paged bf16 KV, block size 16, 2 layers (layer 1 under test), scattered block ids */
+    for (int sh = 0; sh < 2; sh++) for (int ci = 0; ci < 4; ci++) {
+        uint32_t nqh = shapes[sh].nqh, nkv = shapes[sh].nkv, ctx = ctxs[ci], bs = 16, layers = 2, layer = 1;
+        uint32_t nblk = (ctx + bs - 1) / bs, pool_blocks = nblk + 7;
+        OmegaGpuKvLayout ly = layout_for(pool_blocks, bs, layers, nkv, hd);
+        uint8_t *pool = malloc(ly.pool_bytes); uint16_t *pw = (uint16_t *)pool;
+        for (size_t i = 0; i < ly.pool_bytes / 2; i++) pw[i] = f2bf(frand(&seed, -1.0f, 1.0f));
+        uint32_t *ids = malloc(nblk * 4); /* a scattered permutation of the pool blocks */
+        for (uint32_t b = 0; b < nblk; b++) ids[b] = (b * 7 + 3) % pool_blocks;
+        size_t n = (size_t)nqh * hd;
+        float *q = malloc(n * 4), *got = malloc(n * 4), *want = malloc(n * 4);
+        for (size_t i = 0; i < n; i++) q[i] = frand(&seed, -1.0f, 1.0f);
+        oracle_paged(q, pool, &ly, ids, nblk, ctx, layer, nqh, nkv, hd, want);
+        char name[96]; snprintf(name, sizeof name, "paged_bf16_%s_%uq%ukv_bs%u_ctx%u", shapes[sh].model, nqh, nkv, bs, ctx);
+        Case c = { .name = strdup(name), .n = n };
+        OmegaGpuAttnInfo info; PagedCtx pc = { q, pool, &ly, ids, nblk, ctx, layer, nqh, nkv };
+        c.rc = run_paged(&pc, got, &info);
+        c.bad = compare(got, want, n, 2e-4, 2e-5, &c.worst);
+        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;
+        if (ci == 3) {
+            /* NO_MAX cannot overflow on unit-scale scores (softmax is shift invariant); it is caught by the large-score gqa case */
+            static const int ms3[4] = { OMEGA_GPU_ATTN_MUTANT_KV_HEAD, OMEGA_GPU_ATTN_MUTANT_SLOT, OMEGA_GPU_ATTN_MUTANT_NO_RESCALE, 0 };
+            run_mutants(&c, ms3, run_paged, &pc, got, want, n, 2e-4, 2e-5);
+        } else if (ci == 1) {
+            static const int ms[3] = { OMEGA_GPU_ATTN_MUTANT_KV_HEAD, OMEGA_GPU_ATTN_MUTANT_SLOT, 0 };
+            run_mutants(&c, ms, run_paged, &pc, got, want, n, 2e-4, 2e-5);
+        } else if (ci == 0) {
+            /* one token: its softmax weight is 1 whatever K says, so a K-only slot shift is invisible; KV_HEAD still shows */
+            static const int ms[2] = { OMEGA_GPU_ATTN_MUTANT_KV_HEAD, 0 };
+            run_mutants(&c, ms, run_paged, &pc, got, want, n, 2e-4, 2e-5);
+        } else run_mutants(&c, no_mutants, run_paged, &pc, got, want, n, 2e-4, 2e-5);
+        record(c, out); free(pool); free(ids); free(q); free(got); free(want);
+    }
+    /* 4. batch: three sequences (short, empty, truncated by its table), a negative table entry, table rows of 16 */
+    {
+        uint32_t nqh = 32, nkv = 8, bs = 16, layers = 3, layer = 2, maxb = 16, nseq = 3, pool_blocks = 40;
+        OmegaGpuKvLayout ly = layout_for(pool_blocks, bs, layers, nkv, hd);
+        uint8_t *pool = malloc(ly.pool_bytes); uint16_t *pw = (uint16_t *)pool;
+        for (size_t i = 0; i < ly.pool_bytes / 2; i++) pw[i] = f2bf(frand(&seed, -1.0f, 1.0f));
+        int32_t *tables = malloc((size_t)nseq * maxb * 4);
+        for (size_t i = 0; i < (size_t)nseq * maxb; i++) tables[i] = -1;
+        /* seq 0: ctx 40 over blocks 5, 17 (-1 in the middle closes up), 29 */
+        tables[0] = 5; tables[1] = -1; tables[2] = 17; tables[3] = 29;
+        /* seq 1: ctx 0 with a table */
+        tables[maxb + 0] = 1;
+        /* seq 2: ctx 100 but only 4 blocks (64 tokens used) */
+        tables[2 * maxb + 0] = 30; tables[2 * maxb + 1] = 2; tables[2 * maxb + 2] = 33; tables[2 * maxb + 3] = 11;
+        int32_t ctxs2[3] = { 40, 0, 100 };
+        size_t n = (size_t)nseq * nqh * hd;
+        float *q = malloc(n * 4), *got = malloc(n * 4), *want = malloc(n * 4);
+        for (size_t i = 0; i < n; i++) q[i] = frand(&seed, -1.0f, 1.0f);
+        oracle_batch(q, pool, &ly, tables, ctxs2, maxb, nseq, layer, nqh, nkv, hd, want);
+        Case c = { .name = "paged_bf16_batch_3seq_32q8kv_ctx40_0_100", .n = n };
+        OmegaGpuAttnInfo info; BatchCtx bc = { q, pool, &ly, tables, ctxs2, maxb, nseq, layer, nqh, nkv };
+        c.rc = run_batch(&bc, got, &info);
+        c.bad = compare(got, want, n, 2e-4, 2e-5, &c.worst);
+        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;
+        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;
+        CHECK(zeros, "batch: the empty sequence is all zeros");
+        static const int ms[3] = { OMEGA_GPU_ATTN_MUTANT_KV_HEAD, OMEGA_GPU_ATTN_MUTANT_SLOT, 0 };
+        run_mutants(&c, ms, run_batch, &bc, got, want, n, 2e-4, 2e-5);
+        record(c, out); free(pool); free(tables); free(q); free(got); free(want);
+    }
+    for (int m = 1; m <= 4; m++) {
+        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]);
+        printf("mutant %s: caught %d of %d\n", mutant_name(m), g_mutant_caught[m], g_mutant_run[m]);
+    }
+    if (out) {
+        fprintf(out, "],\"mutants\":{");
+        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]);
+        fprintf(out, "},\"checks\":%d,\"failed\":%d,\"verdict\":\"%s\"}\n", g_checks, g_failed, g_failed == 0 ? "OMEGA_GPU_ATTENTION_PASS" : "OMEGA_GPU_ATTENTION_FAIL");
+        fclose(out);
+    }
+    return 0;
+}
+
+/* ------------------------------------------------------------ host simulator
+ * Executes the allocated IR program (physical registers, so the register allocator's
+ * loop handling is under test too) for every CTA of a launch: 64 threads, 1 KB shared,
+ * host pointers as addresses, SHFL and BAR as lockstep points (all threads of the CTA
+ * must sit at the same instruction). EX2 and RCP are exact here; the chip's are approximate. */
+typedef struct { uint32_t r[256]; int pc; int p0; int done; } SimThr;
+static uint32_t sim_cbank[256];
+static uint8_t sim_shared[1024];
+#define SIM_T 64
+static int g_sim_err;
+static int g_trace, g_trace_launch; static uint32_t g_trace_cx;
+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]; }
+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); }
+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; }
+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); }
+static float u2f(uint32_t u) { float f; memcpy(&f, &u, 4); return f; }
+static uint32_t f2u_(float f) { uint32_t u; memcpy(&u, &f, 4); return u; }
+/* run one thread until it reaches a SHFL or BAR (not executed) or EXIT; returns 1 if parked at a sync op */
+static int sim_step(SimThr *t, const BlackwellIRProgram *p, uint32_t tid, uint32_t cx, uint32_t cy) {
+    for (int guard = 0; guard < 50000000; guard++) {
+        if (t->done) return 0;
+        if (t->pc < 0 || (size_t)t->pc >= p->count) { g_sim_err = 1; t->done = 1; return 0; }
+        const BlackwellIRInsn *in = &p->insns[t->pc];
+        uint32_t a = rd(t, in->src1_vreg, p), b = rd(t, in->src2_vreg, p), c = rd(t, in->src3_vreg, p);
+        switch (in->op) {
+        case BW_IR_SHFL_DOWN: case BW_IR_BAR_SYNC: return 1;
+        case BW_IR_EXIT: if (!in->predicate_p0 || t->p0) { t->done = 1; return 0; } break;
+        case BW_IR_BRA: {
+            int take = !in->predicate_p0 || (in->predicate_not ? !t->p0 : t->p0);
+            if (take) { if ((int32_t)in->imm == 0) { g_sim_err = 2; t->done = 1; return 0; } t->pc += (int32_t)in->imm; continue; }
+            break; }
+        case BW_IR_MOV_IMM: wr(t, in->dst_vreg, in->imm, p); break;
+        case BW_IR_MOV_RZ: wr(t, in->dst_vreg, 0, p); break;
+        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;
+        case BW_IR_LDC: wr(t, in->dst_vreg, sim_cbank[in->imm / 4], p); break;
+        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;
+        case BW_IR_LDCU64: break; /* memory descriptor: not modelled */
+        case BW_IR_IMAD: wr(t, in->dst_vreg, in->src2_vreg >= 0 ? a * b + c : a * in->imm + c, p); break;
+        case BW_IR_IMAD_WIDE: wr64(t, in->dst_vreg, (uint64_t)a * in->imm + rd64(t, in->src3_vreg, p), p); break;
+        case BW_IR_IADD3: wr(t, in->dst_vreg, a + b, p); break;
+        case BW_IR_SHF_R: wr(t, in->dst_vreg, a >> (in->imm & 31), p); break;
+        case BW_IR_LOP3_AND: wr(t, in->dst_vreg, a & in->imm, p); break;
+        case BW_IR_LOP3_XOR: wr(t, in->dst_vreg, a ^ b, p); break;
+        case BW_IR_ISETP_GE_U32: t->p0 = a >= b; break;
+        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; }
+        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; }
+        case BW_IR_STG_E: memcpy((void *)(uintptr_t)rd64(t, in->src1_vreg, p), &b, 4); break;
+        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; }
+        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;
+        case BW_IR_FADD: wr(t, in->dst_vreg, f2u_(u2f(a) + u2f(b)), p); break;
+        case BW_IR_FSUB: wr(t, in->dst_vreg, f2u_(u2f(a) - u2f(b)), p); break;
+        case BW_IR_FMUL: wr(t, in->dst_vreg, f2u_(u2f(a) * u2f(b)), p); break;
+        case BW_IR_FFMA: wr(t, in->dst_vreg, f2u_(fmaf(u2f(a), u2f(b), u2f(c))), p); break;
+        case BW_IR_FMNMX_MAX: wr(t, in->dst_vreg, f2u_(fmaxf(u2f(a), u2f(b))), p); break;
+        case BW_IR_MUFU_EX2: wr(t, in->dst_vreg, f2u_(exp2f(u2f(a))), p); break;
+        case BW_IR_MUFU_RCP: wr(t, in->dst_vreg, f2u_(1.0f / u2f(a)), p); break;
+        default: g_sim_err = 100 + (int)in->op; t->done = 1; return 0;
+        }
+        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); }
+        t->pc++;
+    }
+    g_sim_err = 4; t->done = 1; return 0;
+}
+static int sim_launch(const void *progv, const OmegaGpuAttnLaunch *L, OmegaGpuAttnInfo *info) {
+    const BlackwellIRProgram *p = progv;
+    memset(sim_cbank, 0, sizeof sim_cbank);
+    uint64_t qa = (uintptr_t)L->q, pa = (uintptr_t)L->pool, oa = (uintptr_t)L->out, ta = (uintptr_t)L->tab;
+    sim_cbank[0x380 / 4] = (uint32_t)qa; sim_cbank[0x380 / 4 + 1] = (uint32_t)(qa >> 32);
+    sim_cbank[0x388 / 4] = (uint32_t)pa; sim_cbank[0x388 / 4 + 1] = (uint32_t)(pa >> 32);
+    sim_cbank[0x390 / 4] = (uint32_t)oa; sim_cbank[0x390 / 4 + 1] = (uint32_t)(oa >> 32);
+    sim_cbank[0x398 / 4] = (uint32_t)ta; sim_cbank[0x398 / 4 + 1] = (uint32_t)(ta >> 32);
+    memcpy(&sim_cbank[0x3a0 / 4], L->params, sizeof L->params);
+    uint32_t *outw = L->out; for (size_t i = 0; i < L->out_bytes / 4; i++) outw[i] = 0xffbadbadu;
+    g_sim_err = 0;
+    static SimThr th[SIM_T];
+    g_trace_launch++; if (getenv("ATTN_SIM_TRACE")) { g_trace = 1; g_trace_cx = (uint32_t)atoi(getenv("ATTN_SIM_TRACE")); }
+    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++) {
+        memset(th, 0, sizeof th); memset(sim_shared, 0, sizeof sim_shared);
+        for (;;) {
+            int parked = 0, alive = 0;
+            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); }
+            if (g_sim_err) break;
+            if (alive == 0) break;
+            if (parked == 0) continue; /* every live thread exited this round */
+            if (parked != alive) { g_sim_err = 5; break; } /* a thread exited while others wait at a barrier */
+            int pc = -1;
+            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; }
+            if (g_sim_err) break;
+            const BlackwellIRInsn *in = &p->insns[pc];
+            if (in->op == BW_IR_SHFL_DOWN) {
+                uint32_t src[SIM_T];
+                for (int i = 0; i < SIM_T; i++) src[i] = rd(&th[i], in->src1_vreg, p);
+                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); }
+            }
+            for (int i = 0; i < SIM_T; i++) th[i].pc++;
+        }
+    }
+    uint32_t unwritten = 0; for (size_t i = 0; i < L->out_bytes / 4; i++) if (outw[i] == 0xffbadbadu) unwritten++;
+    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; }
+    if (g_sim_err) { printf("simulator error %d\n", g_sim_err); return OMEGA_GPU_ATTN_CHIP_FAIL; }
+    return unwritten ? OMEGA_GPU_ATTN_UNWRITTEN : OMEGA_GPU_ATTN_OK;
+}
+
+int main(int argc, char **argv) {
+    const char *out_path = NULL; int host = 0, sim = 0;
+    for (int i = 1; i < argc; i++) {
+        if (strcmp(argv[i], "--host-only") == 0) host = 1;
+        else if (strcmp(argv[i], "--sim") == 0) sim = 1;
+        else if (strcmp(argv[i], "--out") == 0 && i + 1 < argc) out_path = argv[++i];
+    }
+    if (sim) omega_gpu_attention_test_set_simulator(sim_launch);
+    if (host) host_only();
+    else if (chip(out_path) != 0) return 2;
+    printf("%s: %d checks, %d failed\n", g_failed ? "FAIL" : "PASS", g_checks, g_failed);
+    return g_failed ? 1 : 0;
+}
diff --git a/tools/run_gpu_attention_chip.sh b/tools/run_gpu_attention_chip.sh
new file mode 100755
index 000000000..4e3753a98
--- /dev/null
+++ b/tools/run_gpu_attention_chip.sh
@@ -0,0 +1,42 @@
+#!/bin/sh
+# tools/run_gpu_attention_chip.sh [OUT_ROOT]
+# FB-1 cut 5 chip gate: gqa_attention (f32 KV) and paged_attention (+ batch, bf16 KV)
+# for the TinyLlama (32q/4kv) and Llama-3.2-1B (32q/8kv) head shapes at context
+# 1, 17, 256 and 2048, each against the host oracle (the ReferenceCpuBackend math),
+# then against the mutant kernels (NO_MAX, KV_HEAD, SLOT, NO_RESCALE), with a
+# negative control and a cache-hit repeat. Sealed receipt folder
+# OUT_ROOT/FB1-CUT5-<sha>/ (default ~/workspace/evidence-out):
+#   receipt.json  machine-readable verdict per case      run.log    test output
+#   device.txt    kernel, driver, omega and physics shas  build.log  compiler output
+#   sim.log       the same battery through the host IR simulator, run first
+#   copies of the three source files the verdict depends on, SHA256SUMS over all
+# Run it through the heavy queue only (lanes.sh queue --heavy); never kill it.
+set -u
+cd "$(dirname "$0")/.." || exit 2
+P=${PHYSICS_DIR:-../physics}
+SHA=$(git rev-parse --short HEAD)
+OUT=${1:-$HOME/workspace/evidence-out}/FB1-CUT5-$SHA
+mkdir -p "$OUT"
+if ! make PHYSICS_DIR="$P" build/gpu_attention_test > "$OUT/build.log" 2>&1; then
+    echo "FB1-CUT5 BUILD FAIL (see $OUT/build.log)"; exit 1
+fi
+{
+    uname -a
+    nvidia-smi --query-gpu=name,driver_version --format=csv,noheader 2>/dev/null || echo "nvidia-smi: unavailable"
+    echo "omega $(git rev-parse HEAD) ($(git status --porcelain | wc -l) uncommitted paths)"
+    echo "physics $(git -C "$P" rev-parse HEAD)"
+    date -u +%FT%TZ
+} > "$OUT/device.txt"
+# host simulator first: a kernel that is wrong on the host never gets chip time
+./build/gpu_attention_test --sim > "$OUT/sim.log" 2>&1
+sim_rc=$?
+if [ "$sim_rc" -ne 0 ]; then
+    echo "FB1-CUT5 SIMULATOR FAIL rc=$sim_rc (see $OUT/sim.log)"; exit 1
+fi
+./build/gpu_attention_test --out "$OUT/receipt.json" > "$OUT/run.log" 2>&1
+rc=$?
+cp src/omega_gpu_attention_api.c src/omega_gpu_attention_api.h tests/gpu_attention_test.c "$OUT/"
+(cd "$OUT" && sha256sum -- * > SHA256SUMS)
+tail -1 "$OUT/run.log"
+echo "FB1-CUT5 chip gate rc=$rc receipt=$OUT/receipt.json"
+exit $rc