interplane.Get Omega
Read in your language

CUDApp

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

Brought by drakestapleton

branch main Branches Tags History

CUDApp / evidence / FB1-CUT5-HD128-7dd92dc / FB1-CUT5-7dd92dc / omega_gpu_attention_api.c

909 lines · 50781 bytes Raw Blame History
1/* omega_gpu_attention_api.c: FB-1 cut 5 (2026-10-04). See the header.
2 *
3 * Layout: (1) kernel codegen on the BlackwellIR with the serialising scheduler
4 * of cut 4 (every instruction waits on everything still pending; slow and safe),
5 * extended with forward branches and more loops; (2) the launcher, cloned from
6 * cut 4's run_abc with a fourth buffer (block tables and context lengths), 16
7 * argument words, and cut 1b's shader-cache invalidate; (3) the public entry
8 * points, which stage the referenced KV blocks per launch and apply the oracle's
9 * argument rules (dropped tokens past the table, negative table entries, zero
10 * context) on the host.
11 *
12 * One CTA per (query head, sequence), head_dim threads (64 or 128; the text below says 64, the
13 * constants scale with KSpec.hd). The context is walked in chunks of head_dim tokens:
14 * phase A thread t owns token base+t: block lookup, K dot q (f32 FFMA), s = dot * scale
15 * (scale folds 1/sqrt(d) and log2 e), s and the token's byte offset go to shared;
16 * reduce chunk max (SHFL.DOWN tree per warp, lane partials to shared, BAR.SYNC, 2 LDS),
17 * m_new = max(m, chunk max), alpha = EX2(m - m_new), p = EX2(s - m_new) to shared,
18 * chunk sum the same way, l = l * alpha + chunk sum;
19 * phase B thread d owns dimension d: acc = acc * alpha + sum over the chunk of p_t * V[t][d].
20 * Then out[d] = acc * RCP(l). The first chunk sees m = -inf, so alpha = EX2(-inf) = 0 and
21 * the initial l and acc drop out (PTX ISA ex2.approx: ex2(-Inf) = +0).
22 *
23 * Shared memory (16 * head_dim bytes; hd 64: 1024 bytes, the QMD default): [0,4hd) q, [4hd,8hd) s then p,
24 * [8hd,12hd) token byte offsets, [12hd,16hd) warp partials for the reductions (hd 64: 0, 256, 512,
25 * 768; hd 128: 0, 512, 1024, 1536; the partials of warp w are read at 12hd + 128w).
26 */
27#include "omega_gpu_attention_api.h"
28#include "omega_blackwell_codegen.h"
29#include "omega_bw_reconv.h"
30#include "omega_blackwell_qmd.h"
31#include "omega_blackwell_submit.h"
32#include "omega_gpu_session.h"
33#include "sha256.h"
34#include <math.h>
35#include <stdio.h>
36#include <stdlib.h>
37#include <string.h>
38#include <time.h>
39
40/* ------------------------------------------------------------------ codegen */
41
42#define CW(stall, wbar, rbar, wait) \
43 (((uint32_t)(stall) << 9) | ((uint32_t)(wbar) << 14) | ((uint32_t)(rbar) << 17) | ((uint32_t)(wait) << 20))
44#define CW_YIELD 0x2000u
45#define SB_NONE 7u
46#define SB_GPR 0u
47#define SB_RD 1u
48#define SB_UGPR 2u
49
50enum { K_FIXED, K_PRED, K_VAR, K_UVAR, K_STORE, K_SYNC, K_EXIT, K_BRA, K_BSSY, K_BSYNC };
51
52#define AT_MAX_LOOPS 8
53typedef struct {
54 BlackwellIRProgram *p;
55 uint32_t pending;
56 int err;
57 int loop_start[AT_MAX_LOOPS], loop_end[AT_MAX_LOOPS];
58 int n_loops, depth, stack[AT_MAX_LOOPS];
59 BwRegions rg; /* structured reconvergence regions (omega #308) */
60 int rg_mutant; /* test only: 1 = drop the BSYNC at join (the 2026-10-04 bug shape; host sim must catch it) */
61} Em;
62
63static void emit(Em *e, BlackwellIRInsn in, int kind) {
64 uint32_t wait = e->pending;
65 switch (kind) {
66 case K_FIXED: in.control = CW(6, SB_NONE, SB_NONE, wait); e->pending = 0; break;
67 case K_PRED: in.control = CW(13, SB_NONE, SB_NONE, wait); e->pending = 0; break;
68 case K_VAR: in.control = CW(4, SB_GPR, SB_NONE, wait) | CW_YIELD; e->pending = 1u << SB_GPR; break;
69 case K_UVAR: in.control = CW(4, SB_UGPR, SB_NONE, wait) | CW_YIELD; e->pending = 1u << SB_UGPR; break;
70 case K_STORE: in.control = CW(4, SB_NONE, SB_RD, wait) | CW_YIELD; e->pending = 1u << SB_RD; break;
71 case K_SYNC: in.control = CW(6, SB_NONE, SB_NONE, wait); e->pending = 0; break;
72 case K_EXIT: in.control = CW(5, SB_NONE, SB_NONE, wait); e->pending = in.predicate_p0 ? wait : 0; break;
73 case K_BRA: in.control = CW(5, SB_NONE, SB_NONE, wait); e->pending = in.predicate_p0 ? wait : 0; break;
74 /* stall counts as nvcc 13.0.88 writes them for sm_121 (see src/omega_gpu_elementwise_api.c) */
75 case K_BSSY: in.control = CW(1, SB_NONE, SB_NONE, wait) | CW_YIELD; e->pending = 0; break;
76 case K_BSYNC: in.control = CW(5, SB_NONE, SB_NONE, wait) | CW_YIELD; e->pending = 0; break;
77 default: e->err = -1; return;
78 }
79 if (omega_bw_ir_append(e->p, &in) < 0) e->err = -1;
80}
81
82static int V(Em *e) { int v = omega_bw_ir_alloc_vreg(e->p); if (v < 0) e->err = -1; return v; }
83static int V64(Em *e) { int v = omega_bw_ir_alloc_vreg64(e->p); if (v < 0) e->err = -1; return v; }
84static int UV64(Em *e) { int v = omega_bw_ir_alloc_uvreg64(e->p); if (v < 0) e->err = -1; return v; }
85static int here(const Em *e) { return (int)e->p->count; }
86
87#define NOREG -1
88static BlackwellIRInsn I0(BlackwellIROpcode op) {
89 BlackwellIRInsn in; memset(&in, 0, sizeof in);
90 in.op = op; in.dst_vreg = NOREG; in.src1_vreg = NOREG; in.src2_vreg = NOREG; in.src3_vreg = NOREG; in.ureg = NOREG;
91 return in;
92}
93static 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); }
94static 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); }
95static 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); }
96static 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); }
97static 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); }
98static void movf(Em *e, int dst, float f) { uint32_t u; memcpy(&u, &f, 4); movi(e, dst, u); }
99static void movrz(Em *e, int dst) { BlackwellIRInsn i = I0(BW_IR_MOV_RZ); i.dst_vreg = dst; emit(e, i, K_FIXED); }
100/* dst = a * imm + c (c may be NOREG for RZ) */
101static 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); }
102/* dst = a * b + c (registers; c may be NOREG) */
103static 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); }
104static 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); }
105static 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); }
106static 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); }
107static 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); }
108/* dst64 = idx * imm + base64 (byte address) */
109static 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); }
110static 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); }
111static 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); }
112static 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); }
113static 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); }
114static 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); }
115static 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); }
116static 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); }
117static 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); }
118static 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); }
119/* SHFL and BAR.SYNC are refused inside an open reconvergence region (omega #308): on a split
120 * warp they read inactive lanes / count a partial warp, which is what produced wrong dims on
121 * the chip on 2026-10-04. The build fails closed instead. */
122static int in_region(Em *e) { if (e->rg.depth > 0) { e->err = -1; return 1; } return 0; }
123static void shfl_down(Em *e, int d, int a, uint32_t off) { if (in_region(e)) return; BlackwellIRInsn i = I0(BW_IR_SHFL_DOWN); i.dst_vreg = d; i.src1_vreg = a; i.imm = off; emit(e, i, K_VAR); }
124static 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); }
125static 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); }
126static void bar_sync(Em *e) { if (in_region(e)) return; emit(e, I0(BW_IR_BAR_SYNC), K_SYNC); }
127static 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); }
128static 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); }
129/* @P0 BRA forward; the target is patched in when known */
130static 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; }
131static 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; }
132
133/* ---- structured reconvergence regions (omega #308); same API as the elementwise emitter ---- */
134enum { RX_ALWAYS, RX_IF_P0, RX_IF_NOT_P0 };
135static int region_begin(Em *e) {
136 int bar = bw_regions_next_bar(&e->rg);
137 if (bar < 0) { e->err = -1; return -1; }
138 int at = here(e);
139 BlackwellIRInsn i = I0(BW_IR_BSSY); i.bar_reg = (uint8_t)bar; i.imm = 2; emit(e, i, K_BSSY);
140 if (bw_regions_begin(&e->rg, at) < 0) e->err = -1;
141 return bar;
142}
143static void region_exit(Em *e, int cond) {
144 int at = here(e);
145 BlackwellIRInsn i = I0(BW_IR_BRA); i.imm = 1;
146 if (cond != RX_ALWAYS) { i.predicate_p0 = true; i.predicate_not = (cond == RX_IF_NOT_P0); }
147 emit(e, i, K_BRA);
148 if (bw_regions_exit(&e->rg, at) < 0) e->err = -1;
149}
150static void region_join(Em *e) {
151 if (e->rg.depth <= 0) { e->err = -1; return; }
152 int d = e->rg.depth - 1, bsync = here(e);
153 BlackwellIRInsn i = I0(e->rg_mutant == 1 ? BW_IR_NOP : BW_IR_BSYNC); i.bar_reg = (uint8_t)d; emit(e, i, K_BSYNC);
154 if (e->rg_mutant == 1) {
155 BwRegions *r = &e->rg; r->depth--;
156 e->p->insns[r->bssy_at[d]].imm = (uint32_t)(bsync + 1 - r->bssy_at[d]);
157 for (int k = 0; k < r->n_exits[d]; k++) e->p->insns[r->exits[d][k]].imm = (uint32_t)(bsync - r->exits[d][k]);
158 return;
159 }
160 if (bw_regions_join(&e->rg, e->p, bsync) != d) e->err = -1;
161}
162static void tail(Em *e) {
163 emit(e, I0(BW_IR_EXIT), K_EXIT);
164 BlackwellIRInsn self = I0(BW_IR_BRA);
165 self.control = 0x000fc000u;
166 if (omega_bw_ir_append(e->p, &self) < 0) e->err = -1;
167}
168/* Loops nest; loop_end() extends every value defined before the loop and read inside
169 * it to the back-branch (the linear-scan allocator knows nothing about back-edges). */
170static void loop_begin(Em *e) {
171 if (e->depth >= AT_MAX_LOOPS || e->n_loops >= AT_MAX_LOOPS) { e->err = -1; return; }
172 e->stack[e->depth++] = here(e);
173}
174static void loop_end(Em *e) {
175 if (e->depth == 0 || e->n_loops >= AT_MAX_LOOPS) { e->err = -1; return; }
176 int start = e->stack[--e->depth], end = here(e) - 1;
177 e->loop_start[e->n_loops] = start; e->loop_end[e->n_loops] = end; e->n_loops++;
178 OmegaRegAlloc *ra = &e->p->regalloc;
179 for (int v = 0; v < ra->num_vregs; v++) {
180 OmegaLiveInterval *iv = &ra->intervals[v];
181 if (iv->first_def >= 0 && iv->first_def < start && iv->last_use >= start && iv->last_use < end) iv->last_use = end;
182 }
183}
184/* A value first defined inside a loop may not be read after it before being redefined. */
185static int check_loop_invariant(const Em *e) {
186 const OmegaRegAlloc *ra = &e->p->regalloc;
187 for (int L = 0; L < e->n_loops; L++)
188 for (int v = 0; v < ra->num_vregs; v++) {
189 int fd = ra->intervals[v].first_def;
190 if (fd < e->loop_start[L] || fd > e->loop_end[L]) continue;
191 for (size_t i = (size_t)e->loop_end[L] + 1; i < e->p->count; i++) {
192 const BlackwellIRInsn *in = &e->p->insns[i];
193 if (in->src1_vreg == v || in->src2_vreg == v || in->src3_vreg == v) return -1;
194 if (in->dst_vreg == v && !in->is_uniform) break;
195 }
196 }
197 return 0;
198}
199
200/* Kernel argument words (constant bank 0 at 0x380; the bank is 1024 bytes, so 32 words fit). */
201#define ARG_Q 0x380u
202#define ARG_POOL 0x388u
203#define ARG_OUT 0x390u
204#define ARG_TAB 0x398u
205#define ARG_MAXB 0x3a0u /* words per block-table row */
206#define ARG_SCALE 0x3a4u /* bits of log2(e) / sqrt(head_dim) */
207#define ARG_BSTRIDE 0x3a8u /* bytes between staged blocks */
208#define ARG_TSTRIDE 0x3acu /* bytes between tokens */
209#define ARG_KVP 0x3b0u /* bytes from the K plane to the V plane */
210#define ARG_HSTRIDE 0x3b4u /* bytes between kv heads */
211#define ARG_NQH 0x3b8u /* query heads (q and out row count per sequence) */
212#define ARG_CTXOFF 0x3bcu /* byte offset of the context-length array inside the table buffer */
213#define ARG_WORDS 16u
214#define DESC_OFF 0x358u
215
216/* Head dimension is a kernel parameter (64 or 128, see KSpec.hd). Shared memory is four arrays of hd words:
217 * q at SH_Q, s then p at hd*4, token byte offsets at hd*8, warp partials at hd*12 (hd 64: 0, 256, 512, 768,
218 * the layout of every cut before head_dim 128). */
219#define SH_Q 0u
220#define F32_NEG_INF 0xff800000u
221
222/* divergent (omega #308 regression R2): 0 = production branch-free chunk loop; 1 = the
223 * lane-dependent "j >= ctx" branch restored inside a reconvergence region (BSSY/BSYNC) so
224 * the SHFL reductions run on a joined warp; 2 = the same with the BSYNC dropped (the
225 * 2026-10-04 bug shape, a negative control the host simulator must catch). */
226typedef struct { bool f32; uint32_t log2bs, log2gqa; int mutant; int divergent; uint32_t hd; } KSpec;
227
228static void gen_attention(Em *e, const KSpec *k) {
229 const uint32_t elem = k->f32 ? 4u : 2u;
230 const uint32_t kstep = k->f32 ? 8u : 4u; /* bytes per inner iteration: two dims */
231 const uint32_t HD = k->hd, SH_S = HD * 4u, SH_O = HD * 8u, SH_R = HD * 12u; /* warps per CTA: HD / 32 */
232 int udesc = UV64(e), A = V64(e), B = V64(e), C = V64(e), D = V64(e);
233 int tid = V(e), h = V(e), seq = V(e);
234 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);
235 ldcu64(e, udesc, DESC_OFF);
236 ldc64(e, A, ARG_Q); ldc64(e, B, ARG_POOL); ldc64(e, C, ARG_OUT); ldc64(e, D, ARG_TAB);
237 ldc32(e, p_maxb, ARG_MAXB); ldc32(e, scale, ARG_SCALE); ldc32(e, p_bstride, ARG_BSTRIDE); ldc32(e, p_tstride, ARG_TSTRIDE);
238 ldc32(e, p_kvp, ARG_KVP); ldc32(e, p_hstride, ARG_HSTRIDE); ldc32(e, p_nqh, ARG_NQH); ldc32(e, p_ctxoff, ARG_CTXOFF);
239 s2r(e, tid, BW_SR_TID_X); s2r(e, h, BW_SR_CTAID_X); s2r(e, seq, BW_SR_CTAID_Y);
240
241 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);
242 /* c32 / c64 keep their hd 64 names: the inner (dim pair) loop trip count HD / 2 and the chunk size HD */
243 movi(e, c1, 1); movi(e, c4, 4); movi(e, c32, HD / 2); movi(e, c64, HD);
244 movi(e, c256, SH_S); movi(e, c512, SH_O); movi(e, c768, SH_R); movi(e, c896, SH_R + 128); movrz(e, zero);
245 /* warp partials 2 and 3 (lane 0 of warps 2 and 3): only a 128-thread CTA has them. Created and emitted only
246 * when HD == 128, so the hd 64 program (vreg numbering, instruction sequence) is exactly the one before. */
247 int c1024 = -1, c1152 = -1, rc_ = -1, rd_ = -1;
248 if (HD == 128) { c1024 = V(e); c1152 = V(e); rc_ = V(e); rd_ = V(e); movi(e, c1024, SH_R + 256); movi(e, c1152, SH_R + 384); }
249
250 /* q[tid] -> shared; out address kept for the end. Row = seq * num_q_heads + head for
251 * both q and out (flattened head-major, the oracle's layout). The head-wiring mutants
252 * swap the row of head h with h ^ 1 on one side only. */
253 int tid4 = V(e), qrow = V(e), qoff = V(e), qaddr = V64(e), qv = V(e), oaddr = V64(e);
254 int hq = h, ho = h;
255 if (k->mutant == OMEGA_GPU_ATTN_MUTANT_Q_ROW) { hq = V(e); lop3xor(e, hq, h, c1); }
256 if (k->mutant == OMEGA_GPU_ATTN_MUTANT_OUT_ROW) { ho = V(e); lop3xor(e, ho, h, c1); }
257 imadi(e, tid4, tid, 4, NOREG);
258 imadr(e, qrow, seq, p_nqh, hq);
259 imadi(e, qoff, qrow, HD * 4, tid4);
260 wide(e, qaddr, qoff, 1, A);
261 ldg(e, qv, qaddr, udesc);
262 sts32(e, tid4, qv); /* SH_Q + tid*4 */
263 if (ho == hq) wide(e, oaddr, qoff, 1, C);
264 else {
265 int orow = V(e), ooff = V(e);
266 imadr(e, orow, seq, p_nqh, ho);
267 imadi(e, ooff, orow, HD * 4, tid4);
268 wide(e, oaddr, ooff, 1, C);
269 }
270
271 /* kv head offset, this sequence's table row and context length */
272 int kvh = V(e), kvoff = V(e), t1 = V(e), tab = V64(e), ca = V64(e), ctx = V(e), vb = V64(e);
273 shri(e, kvh, h, k->log2gqa);
274 if (k->mutant == OMEGA_GPU_ATTN_MUTANT_KV_HEAD) lop3xor(e, kvh, kvh, c1);
275 imadr(e, kvoff, kvh, p_hstride, NOREG);
276 imadr(e, t1, seq, p_maxb, NOREG);
277 imadi(e, t1, t1, 4, NOREG);
278 wide(e, tab, t1, 1, D);
279 imadi(e, t1, seq, 4, p_ctxoff);
280 wide(e, ca, t1, 1, D);
281 ldg(e, ctx, ca, udesc);
282 /* V column base for dimension tid: pool + kv plane + tid * elem. The kv head offset is
283 * already inside the per-token offset phase A leaves in shared memory (found by the host
284 * simulator: adding it here too read V from the wrong head for every kv head but 0). */
285 wide(e, vb, tid, elem, B);
286 wide(e, vb, p_kvp, 1, vb);
287
288 int M = V(e), L = V(e), acc = V(e), base = V(e), sOff = V(e), oOff = V(e), rOff = V(e);
289 movi(e, M, F32_NEG_INF);
290 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 */
291 movrz(e, acc); movrz(e, base);
292 iadd3(e, sOff, tid4, c256); iadd3(e, oOff, tid4, c512); iadd3(e, rOff, tid4, c768);
293 bar_sync(e); /* q visible to every thread */
294 isetp_ge_u32(e, zero, ctx); /* ctx == 0: out = 0 */
295 int bZ = bra_fwd_if_p0(e);
296
297 /* ---------------- chunk loop ---------------- */
298 int j = V(e), s = V(e), koff = V(e);
299 int bi = V(e), sl = V(e), ta = V64(e), blk = V(e), ka = V64(e), dot = V(e), d = V(e);
300 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);
301 int dneg = V(e), over = V(e), ot = V(e), ctxm1 = V(e), cm1 = V(e), cninf = V(e), nb = V(e), ns = V(e);
302 movi(e, cm1, 0xFFFFFFFFu); iadd3(e, ctxm1, ctx, cm1); movi(e, cninf, F32_NEG_INF);
303 loop_begin(e);
304 int Lout = here(e);
305 /* No branch here: a warp split by "j >= ctx" stays split (the IR has no reconvergence
306 * instruction) and the SHFL reductions below then read inactive lanes, which is undefined
307 * (wrong dims tid >= tail on the chip, 2026-10-04). over = (j >= ctx) as 0/1 from the sign of
308 * ctx-1-j; out-of-range lanes read token `base` (always < ctx here) and their score
309 * is forced to -inf after the dot product with s = -max(-s, nb), nb = -inf or +inf. */
310 iadd3(e, j, base, tid);
311 movi(e, s, F32_NEG_INF);
312 movrz(e, koff);
313 if (k->divergent) {
314 /* omega #308 R2: the lane-dependent branch, inside a reconvergence region. Lanes with
315 * j >= ctx skip phase A (s stays -inf, koff 0); the BSYNC at region_join rejoins them
316 * before the SHFL reductions below. divergent == 2 drops that BSYNC (negative control). */
317 region_begin(e);
318 isetp_ge_u32(e, j, ctx);
319 region_exit(e, RX_IF_P0);
320 } else {
321 imadi(e, dneg, j, 0xFFFFFFFFu, ctxm1); /* ctx - 1 - j */
322 shri(e, over, dneg, 31);
323 imadr(e, ot, over, tid, NOREG);
324 imadi(e, j, ot, 0xFFFFFFFFu, j); /* j - over*tid */
325 }
326 /* phase A: token j */
327 shri(e, bi, j, k->log2bs);
328 lop3andi(e, sl, j, (1u << k->log2bs) - 1u);
329 wide(e, ta, bi, 4, tab);
330 ldg(e, blk, ta, udesc);
331 imadr(e, koff, blk, p_bstride, NOREG);
332 if (k->mutant == OMEGA_GPU_ATTN_MUTANT_SLOT) {
333 /* K read from slot (t + 1) % block_size, V from the right slot: a K/V mismatch.
334 * (Shifting both only permutes matched pairs inside a full block, which softmax cannot see.) */
335 int sl1 = V(e);
336 iadd3(e, j1, j, c1); lop3andi(e, sl1, j1, (1u << k->log2bs) - 1u);
337 imadr(e, sl1, sl1, p_tstride, koff);
338 iadd3(e, sl1, sl1, kvoff);
339 wide(e, ka, sl1, 1, B);
340 imadr(e, koff, sl, p_tstride, koff);
341 iadd3(e, koff, koff, kvoff);
342 } else {
343 imadr(e, koff, sl, p_tstride, koff);
344 iadd3(e, koff, koff, kvoff);
345 wide(e, ka, koff, 1, B);
346 }
347 movrz(e, dot); movrz(e, d);
348 loop_begin(e);
349 int Lin = here(e);
350 if (k->f32) {
351 ldg(e, lo, ka, udesc);
352 wide(e, ka2, c1, 4, ka);
353 ldg(e, hi, ka2, udesc);
354 } else {
355 ldg(e, x, ka, udesc);
356 imadi(e, lo, x, 0x10000u, NOREG); /* low bf16 -> f32: bits << 16 */
357 lop3andi(e, hi, x, 0xffff0000u); /* high bf16 -> f32: keep the top half */
358 }
359 imadi(e, qa, d, 8, NOREG);
360 lds32(e, q0, qa);
361 iadd3(e, qb, qa, c4);
362 lds32(e, q1, qb);
363 e_ffma(e, dot, q0, lo, dot);
364 e_ffma(e, dot, q1, hi, dot);
365 wide(e, ka, c1, kstep, ka);
366 iadd3(e, d, d, c1);
367 isetp_ge_u32(e, d, c32);
368 bra_back_if_not_p0(e, Lin);
369 loop_end(e);
370 e_fmul(e, s, dot, scale);
371 if (k->divergent) {
372 region_join(e); /* every lane back before the cross-lane reductions */
373 } else {
374 imadi(e, nb, over, 0x80000000u, cninf); /* over ? +inf : -inf (bits) */
375 e_fsub(e, ns, zero, s); e_fmax(e, ns, ns, nb); e_fsub(e, s, zero, ns);
376 }
377 sts32(e, sOff, s);
378 sts32(e, oOff, koff);
379
380 /* chunk max */
381 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);
382 static const uint32_t steps[5] = { 16, 8, 4, 2, 1 };
383 shfl_down(e, t, s, steps[0]); e_fmax(e, mw, s, t);
384 for (int i = 1; i < 5; i++) { shfl_down(e, t, mw, steps[i]); e_fmax(e, mw, mw, t); }
385 sts32(e, rOff, mw);
386 bar_sync(e);
387 lds32(e, ra, c768); lds32(e, rb, c896);
388 e_fmax(e, mc, ra, rb);
389 if (HD == 128) { lds32(e, rc_, c1024); lds32(e, rd_, c1152); e_fmax(e, mc, mc, rc_); e_fmax(e, mc, mc, rd_); }
390 e_fmax(e, Mn, M, mc);
391 if (k->mutant == OMEGA_GPU_ATTN_MUTANT_NO_MAX) {
392 movf(e, alpha, 1.0f);
393 mufu(e, BW_IR_MUFU_EX2, p, s);
394 e_fmax(e, M, Mn, mc);
395 } else {
396 e_fsub(e, diff, M, Mn);
397 mufu(e, BW_IR_MUFU_EX2, alpha, diff);
398 e_fmax(e, M, Mn, mc); /* M = Mn */
399 e_fsub(e, parg, s, Mn);
400 mufu(e, BW_IR_MUFU_EX2, p, parg);
401 }
402 bar_sync(e); /* everyone has read the max partials before they are overwritten */
403 sts32(e, sOff, p);
404 shfl_down(e, t, p, steps[0]); e_fadd(e, sw, p, t);
405 for (int i = 1; i < 5; i++) { shfl_down(e, t, sw, steps[i]); e_fadd(e, sw, sw, t); }
406 sts32(e, rOff, sw);
407 bar_sync(e);
408 lds32(e, ra, c768); lds32(e, rb, c896);
409 e_fadd(e, lc, ra, rb);
410 if (HD == 128) { lds32(e, rc_, c1024); lds32(e, rd_, c1152); e_fadd(e, lc, lc, rc_); e_fadd(e, lc, lc, rd_); }
411 e_ffma(e, L, L, alpha, lc);
412 if (k->mutant != OMEGA_GPU_ATTN_MUTANT_NO_RESCALE) e_fmul(e, acc, acc, alpha);
413
414 /* phase B: dimension tid over the chunk's tokens */
415 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);
416 movrz(e, kk);
417 loop_begin(e);
418 int LB = here(e);
419 iadd3(e, tt, base, kk);
420 isetp_ge_u32(e, tt, ctx);
421 int bB = bra_fwd_if_p0(e);
422 imadi(e, oa, kk, 4, c512);
423 lds32(e, ko, oa);
424 imadi(e, pa, kk, 4, c256);
425 lds32(e, pv, pa);
426 wide(e, va, ko, 1, vb);
427 if (k->f32) ldg(e, v, va, udesc);
428 else { ldg16(e, v, va, udesc); imadi(e, v, v, 0x10000u, NOREG); }
429 e_ffma(e, acc, pv, v, acc);
430 iadd3(e, kk, kk, c1);
431 isetp_ge_u32(e, kk, c64);
432 bra_back_if_not_p0(e, LB);
433 loop_end(e);
434 patch_fwd(e, bB);
435 bar_sync(e); /* phase B reads of s/p and offsets finish before the next chunk writes them */
436 iadd3(e, base, base, c64);
437 isetp_ge_u32(e, base, ctx);
438 bra_back_if_not_p0(e, Lout);
439 loop_end(e);
440
441 patch_fwd(e, bZ);
442 int inv = V(e), o = V(e);
443 mufu(e, BW_IR_MUFU_RCP, inv, L);
444 e_fmul(e, o, acc, inv);
445 stg(e, oaddr, o, udesc);
446 tail(e);
447}
448
449#define AT_GPR_BUDGET 64u
450
451static int build_kernel(const KSpec *k, OmegaBlackwellKernel *kernel, BlackwellIRProgram **keep) {
452 BlackwellIRProgram *prog = calloc(1, sizeof *prog);
453 if (!prog) return OMEGA_GPU_ATTN_CODEGEN_FAIL;
454 omega_bw_ir_init(prog);
455 Em e; memset(&e, 0, sizeof e); e.p = prog;
456 e.rg_mutant = (k->divergent == 2) ? 1 : 0;
457 gen_attention(&e, k);
458 if (e.depth != 0) e.err = -1;
459 if (e.rg.depth != 0) e.err = -1; /* a region left open has no join: refuse the build */
460 int rc = OMEGA_GPU_ATTN_CODEGEN_FAIL;
461 int ra_rc = (e.err == 0) ? omega_bw_regalloc_solve(prog) : -1;
462 int loop_rc = (ra_rc == 0) ? check_loop_invariant(&e) : -1;
463#ifdef OMEGA_ATTN_DEBUG
464 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",
465 (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);
466#endif
467 if (e.err == 0 && ra_rc == 0 && loop_rc == 0 && prog->regalloc.peak_gpr_usage <= AT_GPR_BUDGET) {
468 size_t max_bytes = (size_t)BW_MAX_IR_INSNS * 16;
469 memset(kernel, 0, sizeof *kernel);
470 kernel->code = malloc(max_bytes);
471 size_t emitted = 0;
472 if (kernel->code && omega_bw_encode_program(prog, kernel->code, max_bytes, &emitted) == 0) {
473 kernel->code_size = emitted;
474 kernel->insn_count = emitted / 16;
475 kernel->gpr_count = prog->regalloc.peak_gpr_usage;
476 kernel->uniform_gpr_count = prog->regalloc.peak_ugpr_usage;
477 sha256_hash(kernel->code, kernel->code_size, kernel->code_digest);
478 rc = OMEGA_GPU_ATTN_OK;
479 } else {
480 free(kernel->code); kernel->code = NULL;
481 }
482 }
483 if (keep && rc == OMEGA_GPU_ATTN_OK) *keep = prog; else free(prog);
484 return rc;
485}
486
487/* --------------------------------------------------------- kernel cache */
488
489/* One kernel per KSpec; the device copy is uploaded once and stays resident for
490 * the process (cut 4b). The IR program is kept for the host simulator. */
491static int g_mutant;
492static int g_divergent; /* omega #308 R2 test hook: see KSpec.divergent */
493static bool g_dedupe = true; /* shared-prefix staging dedupe; false = legacy per-sequence staging (test hook) */
494typedef struct { int used; KSpec k; OmegaBlackwellKernel kernel; BlackwellIRProgram *prog; NvrmMem code; } Slot;
495static OmegaGpuAttnSim g_sim;
496static Slot g_cache[8];
497static OmegaGpuScratch g_q, g_pool, g_tab, g_out; /* staging, grown to the high-water mark, reused per call */
498static bool g_hooked;
499#define LOCK() omega_gpu_session_lock()
500#define UNLOCK() omega_gpu_session_unlock()
501
502void omega_gpu_attention_test_set_simulator(OmegaGpuAttnSim sim) { LOCK(); g_sim = sim; UNLOCK(); }
503void omega_gpu_attention_test_set_dedupe(bool on) { LOCK(); g_dedupe = on; UNLOCK(); }
504
505static void cache_clear_locked(void) {
506 for (size_t i = 0; i < sizeof g_cache / sizeof g_cache[0]; i++)
507 if (g_cache[i].used) { free(g_cache[i].kernel.code); free(g_cache[i].prog); omega_gpu_session_free(&g_cache[i].code); memset(&g_cache[i], 0, sizeof g_cache[i]); }
508}
509
510void omega_gpu_attention_cache_clear(void) {
511 LOCK();
512 cache_clear_locked();
513 UNLOCK();
514}
515
516/* Called by the session (lock held, device still open) right before it closes. */
517static void on_session_close(void) {
518 cache_clear_locked();
519 omega_gpu_session_scratch_free(&g_q); omega_gpu_session_scratch_free(&g_pool);
520 omega_gpu_session_scratch_free(&g_tab); omega_gpu_session_scratch_free(&g_out);
521}
522
523void omega_gpu_attention_test_set_mutant(OmegaGpuAttnMutant m) {
524 LOCK();
525 g_mutant = (int)m;
526 cache_clear_locked();
527 UNLOCK();
528}
529
530/* Caller holds the lock. Builds the kernel if needed; uploads the device copy when
531 * `upload` (the chip path; the simulator never needs one). */
532static int kernel_for(bool f32, uint32_t log2bs, uint32_t log2gqa, uint32_t hd, bool upload, Slot **out, bool *hit) {
533 KSpec k = { .f32 = f32, .log2bs = log2bs, .log2gqa = log2gqa, .mutant = g_mutant, .divergent = g_divergent, .hd = hd };
534 Slot *s = NULL;
535 for (size_t i = 0; i < sizeof g_cache / sizeof g_cache[0]; i++)
536 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 && g_cache[i].k.divergent == k.divergent && g_cache[i].k.hd == k.hd) { /* field compare: memcmp would read struct padding */
537 s = &g_cache[i]; *hit = true; break;
538 }
539 if (!s) {
540 OmegaBlackwellKernel kern; BlackwellIRProgram *kp = NULL;
541 int rc = build_kernel(&k, &kern, &kp);
542 if (rc != OMEGA_GPU_ATTN_OK) return rc;
543 size_t slot = 0;
544 for (size_t i = 0; i < sizeof g_cache / sizeof g_cache[0]; i++) if (!g_cache[i].used) { slot = i; break; }
545 s = &g_cache[slot];
546 if (s->used) { free(s->kernel.code); free(s->prog); omega_gpu_session_free(&s->code); } /* full: evict slot 0 */
547 memset(s, 0, sizeof *s);
548 s->used = 1; s->k = k; s->kernel = kern; s->prog = kp;
549 *hit = false;
550 }
551 if (upload && !s->code.cpu) {
552 if (omega_gpu_session_alloc_code(s->kernel.code_size, &s->code) != 0) return OMEGA_GPU_ATTN_CHIP_FAIL;
553 memcpy(s->code.cpu, s->kernel.code, s->kernel.code_size);
554 __asm__ volatile("dsb sy" ::: "memory");
555 }
556 *out = s;
557 return OMEGA_GPU_ATTN_OK;
558}
559
560int omega_gpu_attention_codegen_hd(bool kv_f32, uint32_t log2_block_size, uint32_t log2_gqa, uint32_t head_dim, OmegaBlackwellKernel *kernel) {
561 if (!kernel || log2_block_size > 16 || log2_gqa > 6) return OMEGA_GPU_ATTN_BAD_ARGS;
562 if (head_dim != 64u && head_dim != 128u) return OMEGA_GPU_ATTN_TOO_LARGE;
563 LOCK();
564 KSpec k = { .f32 = kv_f32, .log2bs = log2_block_size, .log2gqa = log2_gqa, .mutant = g_mutant, .divergent = g_divergent, .hd = head_dim };
565 UNLOCK();
566 return build_kernel(&k, kernel, NULL);
567}
568
569int omega_gpu_attention_codegen(bool kv_f32, uint32_t log2_block_size, uint32_t log2_gqa, OmegaBlackwellKernel *kernel) {
570 return omega_gpu_attention_codegen_hd(kv_f32, log2_block_size, log2_gqa, OMEGA_GPU_ATTN_HEAD_DIM, kernel);
571}
572
573const char *omega_gpu_attention_last_error(void) { return omega_gpu_session_last_error(); }
574
575/* ------------------------------------------------------------ launcher */
576
577#define AT_POISON 0xffbadbadu
578#define AT_WAIT_MS 600000ull
579
580static uint64_t now_ns(void) {
581 struct timespec t; clock_gettime(CLOCK_MONOTONIC, &t);
582 return (uint64_t)t.tv_sec * 1000000000ULL + (uint64_t)t.tv_nsec;
583}
584
585typedef OmegaGpuAttnLaunch Launch;
586
587/* Caller holds the lock. Chip path: open the shared device on first use. */
588static int dev_open_locked(void) {
589 if (!g_hooked) { (void)omega_gpu_session_on_close(on_session_close); g_hooked = true; }
590 return omega_gpu_session_open() ? OMEGA_GPU_ATTN_OK : OMEGA_GPU_ATTN_CHIP_FAIL;
591}
592
593/* Where a call stages the KV slice it is about to hand the kernel: straight into the
594 * device staging buffer on the chip path (one copy), a host buffer under the simulator.
595 * Caller holds the lock; the result is valid until the next staging call. */
596static void *stage_target(size_t bytes, void **host_tmp) {
597 *host_tmp = NULL;
598 if (g_sim) { *host_tmp = malloc(bytes ? bytes : 1); return *host_tmp; }
599 if (omega_gpu_session_scratch(&g_pool, bytes) != 0) return NULL;
600 return g_pool.mem.cpu;
601}
602
603/* One launch through the shared session (omega_gpu_session_launch: shader-cache
604 * invalidate, constant bank, QMD0/QMD1, first marker, L2_FLUSH_DIRTY, second marker),
605 * then readback and the poison scan. L->pool may already be the pool staging buffer. */
606static int run_launch(const Slot *ks, const Launch *L, OmegaGpuAttnInfo *info) {
607 if (omega_gpu_session_scratch(&g_q, L->q_bytes) || omega_gpu_session_scratch(&g_tab, L->tab_bytes) ||
608 omega_gpu_session_scratch(&g_out, L->out_bytes) || (L->pool != g_pool.mem.cpu && omega_gpu_session_scratch(&g_pool, L->pool_bytes)))
609 return OMEGA_GPU_ATTN_CHIP_FAIL;
610 memcpy(g_q.mem.cpu, L->q, L->q_bytes);
611 if (L->pool != g_pool.mem.cpu) memcpy(g_pool.mem.cpu, L->pool, L->pool_bytes);
612 memcpy(g_tab.mem.cpu, L->tab, L->tab_bytes);
613 size_t out_words = L->out_bytes / 4;
614 uint32_t *out_dev = (uint32_t *)g_out.mem.cpu;
615 for (size_t i = 0; i < out_words; i++) out_dev[i] = AT_POISON;
616 __asm__ volatile("dsb sy" ::: "memory");
617
618 uint32_t args[ARG_WORDS];
619 args[0] = (uint32_t)g_q.mem.va; args[1] = (uint32_t)(g_q.mem.va >> 32);
620 args[2] = (uint32_t)g_pool.mem.va; args[3] = (uint32_t)(g_pool.mem.va >> 32);
621 args[4] = (uint32_t)g_out.mem.va; args[5] = (uint32_t)(g_out.mem.va >> 32);
622 args[6] = (uint32_t)g_tab.mem.va; args[7] = (uint32_t)(g_tab.mem.va >> 32);
623 memcpy(&args[8], L->params, sizeof L->params);
624 OmegaGpuLaunch GL = {
625 .code_va = ks->code.va, .gpr_count = AT_GPR_BUDGET, .threads_x = ks->k.hd, .threads_y = 1, .shared_bytes = 16u * ks->k.hd, /* 4 arrays of hd words: 1024 B for hd 64 (the QMD default), 2048 B for hd 128 */
626 .grid_x = L->grid_x, .grid_y = L->grid_y, .num_elements = out_words,
627 .args = args, .n_args = ARG_WORDS, .timeout_ms = AT_WAIT_MS,
628 };
629 uint64_t elapsed = 0; uint32_t marker = 0;
630 if (omega_gpu_session_launch(&GL, &elapsed, &marker) != 0) return OMEGA_GPU_ATTN_CHIP_FAIL;
631
632 memcpy(L->out, g_out.mem.cpu, L->out_bytes);
633 uint32_t unwritten = 0;
634 for (size_t i = 0; i < out_words; i++) if (((uint32_t *)L->out)[i] == AT_POISON) unwritten++;
635 if (info) {
636 info->chip_calls++;
637 info->elapsed_ns += elapsed;
638 info->completion_marker = marker;
639 info->unwritten_words += unwritten;
640 info->threads_per_cta = ks->k.hd;
641 info->ctas_last_launch = L->grid_x * L->grid_y;
642 }
643 return unwritten ? OMEGA_GPU_ATTN_UNWRITTEN : OMEGA_GPU_ATTN_OK;
644}
645
646/* Caller holds the lock. Accounts the launch's q / table / output traffic (the KV
647 * staging bytes are accounted where the slices are copied). */
648static int launch(const Slot *ks, const Launch *L, OmegaGpuAttnInfo *info) {
649 if (info) { info->q_bytes += L->q_bytes; info->tab_bytes += L->tab_bytes; info->out_bytes += L->out_bytes; info->kv_source = OMEGA_GPU_ATTN_KV_STAGED; }
650 if (g_sim) return g_sim(ks->prog, L, info);
651 return run_launch(ks, L, info);
652}
653
654/* ------------------------------------------------------- public entries */
655
656static void info_begin(OmegaGpuAttnInfo *info, const OmegaBlackwellKernel *k, bool hit) {
657 if (!info) return;
658 memset(info, 0, sizeof *info);
659 info->kernel_cache_hit = hit;
660 info->gpr_count = k->gpr_count;
661 info->insn_count = (uint32_t)k->insn_count;
662 snprintf(info->target_chip, sizeof info->target_chip, "NVIDIA DGX Spark (Grace Blackwell GB10)");
663 info->sm_architecture = 121;
664}
665static uint32_t f2u(float f) { uint32_t u; memcpy(&u, &f, 4); return u; }
666static int log2_exact(uint32_t v, uint32_t *out) {
667 if (v == 0 || (v & (v - 1))) return -1;
668 uint32_t l = 0; while ((1u << l) != v) l++;
669 *out = l; return 0;
670}
671/* log2(e) / sqrt(head_dim) with the square roots as literals (8 and 11.313708498984761 = sqrt(128), both exactly what sqrt() returns):
672 * the library must not need libm (omegatool links without -lm; a constant head_dim folded sqrt away, a runtime one does not). */
673static float score_scale(uint32_t hd) { return (float)(1.4426950408889634 / (hd == 128u ? 11.313708498984761 : 8.0)); }
674
675/* Common head-shape checks; returns log2 of the gqa ratio. */
676static int check_heads(uint32_t num_q_heads, uint32_t num_kv_heads, uint32_t head_dim, uint32_t *log2gqa) {
677 if (num_q_heads == 0 || num_kv_heads == 0 || head_dim == 0) return OMEGA_GPU_ATTN_BAD_ARGS;
678 if ((head_dim != 64u && head_dim != 128u) || num_q_heads > OMEGA_GPU_ATTN_MAX_Q_HEADS) return OMEGA_GPU_ATTN_TOO_LARGE;
679 if (num_q_heads % num_kv_heads != 0 || log2_exact(num_q_heads / num_kv_heads, log2gqa) != 0) return OMEGA_GPU_ATTN_BAD_ARGS;
680 return OMEGA_GPU_ATTN_OK;
681}
682
683/* Common prologue of every chip entry (lock held on success): device, kernel, info. */
684static int begin(bool f32, uint32_t log2bs, uint32_t log2gqa, uint32_t hd, Slot **ks, OmegaGpuAttnInfo *info) {
685 LOCK();
686 int rc = g_sim ? OMEGA_GPU_ATTN_OK : dev_open_locked();
687 bool hit = false;
688 if (rc == OMEGA_GPU_ATTN_OK) rc = kernel_for(f32, log2bs, log2gqa, hd, !g_sim, ks, &hit);
689 if (rc != OMEGA_GPU_ATTN_OK) { UNLOCK(); return rc; }
690 info_begin(info, &(*ks)->kernel, hit);
691 return OMEGA_GPU_ATTN_OK;
692}
693
694int omega_gpu_gqa_attention_f32(const float *q, const float *k_cache, const float *v_cache,
695 uint32_t seq_len, uint32_t num_q_heads, uint32_t num_kv_heads,
696 uint32_t head_dim, float *out, OmegaGpuAttnInfo *info) {
697 uint64_t t0 = now_ns();
698 if (!q || !k_cache || !v_cache || !out) return OMEGA_GPU_ATTN_BAD_ARGS;
699 uint32_t log2gqa;
700 int rc = check_heads(num_q_heads, num_kv_heads, head_dim, &log2gqa);
701 if (rc != OMEGA_GPU_ATTN_OK) return rc;
702 if (seq_len > OMEGA_GPU_ATTN_MAX_GQA_CTX) return OMEGA_GPU_ATTN_TOO_LARGE;
703 const uint32_t HD = head_dim;
704 size_t n_out = (size_t)num_q_heads * HD;
705 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; }
706 Slot *ks = NULL;
707 const uint32_t log2bs = 12; /* one block of 4096 slots */
708 rc = begin(true, log2bs, log2gqa, HD, &ks, info);
709 if (rc != OMEGA_GPU_ATTN_OK) return rc;
710 size_t plane = (size_t)seq_len * num_kv_heads * HD * 4;
711 void *host_tmp = NULL;
712 uint8_t *pool = stage_target(2 * plane, &host_tmp);
713 if (!pool) { UNLOCK(); return OMEGA_GPU_ATTN_CHIP_FAIL; }
714 memcpy(pool, k_cache, plane);
715 memcpy(pool + plane, v_cache, plane);
716 if (info) { info->kv_bytes_staged += 2 * plane; info->kv_bytes_naive += 2 * plane; info->kv_blocks_logical += 1; info->kv_blocks_unique += 1; } /* one contiguous pseudo-block */
717 uint32_t tab[2] = { 0, seq_len }; /* table row {0}, then the context length at byte 4 */
718 Launch L = {
719 .q = q, .q_bytes = n_out * 4, .pool = pool, .pool_bytes = 2 * plane, .tab = tab, .tab_bytes = sizeof tab,
720 .out = out, .out_bytes = n_out * 4, .grid_x = num_q_heads, .grid_y = 1,
721 .params = { 1, f2u(score_scale(HD)), (uint32_t)(2 * plane), num_kv_heads * HD * 4, (uint32_t)plane, HD * 4, num_q_heads, 4 }
722 };
723 rc = launch(ks, &L, info);
724 free(host_tmp);
725 UNLOCK();
726 if (info) info->call_ns = now_ns() - t0;
727 return rc;
728}
729
730/* Paged path shared by the single and batched entries. tables[s] has n_blocks[s] entries
731 * (already filtered of negatives), ctx[s] the context length. */
732static int paged_core(const float *q, const uint8_t *pool, const OmegaGpuKvLayout *ly,
733 const uint32_t *const *tables, const uint32_t *n_blocks, const uint32_t *ctx,
734 uint32_t num_seqs, uint32_t layer_idx, uint32_t num_q_heads, uint32_t num_kv_heads,
735 uint32_t head_dim, float *out, OmegaGpuAttnInfo *info) {
736 uint64_t t0 = now_ns();
737 uint32_t log2gqa, log2bs;
738 int rc = check_heads(num_q_heads, num_kv_heads, head_dim, &log2gqa);
739 if (rc != OMEGA_GPU_ATTN_OK) return rc;
740 const uint32_t HD = head_dim;
741 if (!ly || layer_idx >= ly->num_layers || log2_exact(ly->block_size, &log2bs) != 0) return OMEGA_GPU_ATTN_BAD_ARGS;
742 /* the oracle addresses heads as kv_head * head_dim * 2 inside a token: the layout must agree */
743 if (ly->head_stride_bytes != HD * 2 || ly->token_stride_bytes != (uint64_t)num_kv_heads * HD * 2 ||
744 ly->kv_plane_stride_bytes != (uint64_t)ly->block_size * ly->token_stride_bytes ||
745 ly->layer_stride_bytes != 2 * ly->kv_plane_stride_bytes || ly->block_stride_bytes < (uint64_t)ly->num_layers * ly->layer_stride_bytes)
746 return OMEGA_GPU_ATTN_BAD_ARGS;
747 size_t row = (size_t)num_q_heads * HD;
748 /* effective context per sequence and block id range check */
749 uint32_t *eff = calloc(num_seqs ? num_seqs : 1, sizeof *eff);
750 if (!eff) return OMEGA_GPU_ATTN_CHIP_FAIL;
751 for (uint32_t s = 0; s < num_seqs; s++) {
752 uint64_t cap = (uint64_t)n_blocks[s] * ly->block_size;
753 eff[s] = (uint32_t)(ctx[s] < cap ? ctx[s] : cap);
754 for (uint32_t b = 0; b < n_blocks[s]; b++) {
755 uint64_t id = tables[s][b];
756 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; }
757 }
758 }
759 Slot *ks = NULL;
760 rc = begin(false, log2bs, log2gqa, HD, &ks, info);
761 if (rc != OMEGA_GPU_ATTN_OK) { free(eff); return rc; }
762 uint32_t seqs_per_launch = OMEGA_GPU_ATTN_MAX_CTAS / num_q_heads;
763 if (seqs_per_launch == 0) seqs_per_launch = 1;
764 uint32_t maxb = 1;
765 for (uint32_t s = 0; s < num_seqs; s++) if (n_blocks[s] > maxb) maxb = n_blocks[s];
766 /* Dedupe map: physical block id -> staged slot of the current launch (-1 = not staged yet),
767 * plus the list of ids touched by the launch (in slot order) so the reset is O(unique). */
768 int32_t *slot_of = NULL; uint32_t *touched = NULL;
769 if (g_dedupe) {
770 size_t nb = ly->num_blocks ? ly->num_blocks : 1;
771 slot_of = malloc(nb * sizeof *slot_of);
772 touched = malloc(nb * sizeof *touched);
773 if (!slot_of || !touched) { free(slot_of); free(touched); free(eff); UNLOCK(); return OMEGA_GPU_ATTN_CHIP_FAIL; }
774 memset(slot_of, 0xff, nb * sizeof *slot_of); /* every entry -1 */
775 }
776 for (uint32_t s0 = 0; s0 < num_seqs && rc == OMEGA_GPU_ATTN_OK; s0 += seqs_per_launch) {
777 uint32_t ns = num_seqs - s0 < seqs_per_launch ? num_seqs - s0 : seqs_per_launch;
778 /* logical references: every sequence's blocks up to its (truncated) context */
779 uint32_t total = 0;
780 for (uint32_t s = 0; s < ns; s++) total += eff[s0 + s] ? (eff[s0 + s] + ly->block_size - 1) / ly->block_size : 0;
781 uint32_t *tab = calloc((size_t)ns * maxb + ns, sizeof *tab);
782 if (!tab) { rc = OMEGA_GPU_ATTN_CHIP_FAIL; break; }
783 /* pass 1: assign staged slots. Dedupe keys on the PHYSICAL block id (not the table
784 * position): a CoW prefix block shared by several branches gets one slot. Each
785 * sequence's compact table keeps its own block order and truncated context. */
786 uint32_t g = 0;
787 for (uint32_t s = 0; s < ns; s++) {
788 uint32_t need = eff[s0 + s] ? (eff[s0 + s] + ly->block_size - 1) / ly->block_size : 0;
789 for (uint32_t b = 0; b < need; b++) {
790 uint32_t id = tables[s0 + s][b];
791 if (g_dedupe) {
792 if (slot_of[id] < 0) { slot_of[id] = (int32_t)g; touched[g] = id; g++; }
793 tab[(size_t)s * maxb + b] = (uint32_t)slot_of[id];
794 } else {
795 tab[(size_t)s * maxb + b] = g++; /* legacy: one slot per reference */
796 }
797 }
798 tab[(size_t)ns * maxb + s] = eff[s0 + s];
799 }
800 uint64_t staged_bytes = (uint64_t)(g ? g : 1) * ly->layer_stride_bytes;
801 if (staged_bytes > 0xffffffffull) { free(tab); rc = OMEGA_GPU_ATTN_TOO_LARGE; break; }
802 void *host_tmp = NULL;
803 uint8_t *staged = stage_target((size_t)staged_bytes, &host_tmp);
804 if (!staged) { free(tab); rc = OMEGA_GPU_ATTN_CHIP_FAIL; break; }
805 /* pass 2: copy each staged slot's (physical block, layer) slice exactly once */
806 if (g_dedupe) {
807 for (uint32_t u = 0; u < g; u++) {
808 const uint8_t *src = pool + (size_t)touched[u] * ly->block_stride_bytes + (size_t)layer_idx * ly->layer_stride_bytes;
809 memcpy(staged + (size_t)u * ly->layer_stride_bytes, src, (size_t)ly->layer_stride_bytes);
810 slot_of[touched[u]] = -1; /* reset for the next launch */
811 }
812 } else {
813 uint32_t w = 0;
814 for (uint32_t s = 0; s < ns; s++) {
815 uint32_t need = eff[s0 + s] ? (eff[s0 + s] + ly->block_size - 1) / ly->block_size : 0;
816 for (uint32_t b = 0; b < need; b++, w++) {
817 const uint8_t *src = pool + (size_t)tables[s0 + s][b] * ly->block_stride_bytes + (size_t)layer_idx * ly->layer_stride_bytes;
818 memcpy(staged + (size_t)w * ly->layer_stride_bytes, src, (size_t)ly->layer_stride_bytes);
819 }
820 }
821 }
822 if (info) {
823 info->kv_blocks_logical += total; info->kv_blocks_unique += g;
824 info->kv_bytes_staged += (uint64_t)g * ly->layer_stride_bytes;
825 info->kv_bytes_naive += (uint64_t)total * ly->layer_stride_bytes;
826 }
827 Launch L = {
828 .q = q + (size_t)s0 * row, .q_bytes = (size_t)ns * row * 4, .pool = staged, .pool_bytes = (size_t)staged_bytes,
829 .tab = tab, .tab_bytes = ((size_t)ns * maxb + ns) * 4, .out = out + (size_t)s0 * row, .out_bytes = (size_t)ns * row * 4,
830 .grid_x = num_q_heads, .grid_y = ns,
831 .params = { maxb, f2u(score_scale(HD)), (uint32_t)ly->layer_stride_bytes, (uint32_t)ly->token_stride_bytes,
832 (uint32_t)ly->kv_plane_stride_bytes, (uint32_t)ly->head_stride_bytes, num_q_heads, ns * maxb * 4 }
833 };
834 rc = launch(ks, &L, info);
835 free(host_tmp); free(tab);
836 }
837 UNLOCK();
838 free(eff); free(slot_of); free(touched);
839 if (info) info->call_ns = now_ns() - t0;
840 return rc;
841}
842
843int omega_gpu_paged_attention_bf16(const float *q, const void *pool, const OmegaGpuKvLayout *layout,
844 const uint32_t *block_ids, uint32_t num_block_ids,
845 uint32_t context_len, uint32_t layer_idx,
846 uint32_t num_q_heads, uint32_t num_kv_heads, uint32_t head_dim,
847 float *out, OmegaGpuAttnInfo *info) {
848 if (!q || !pool || !layout || !out || (num_block_ids && !block_ids)) return OMEGA_GPU_ATTN_BAD_ARGS;
849 const uint32_t *tables[1] = { block_ids };
850 uint32_t nb[1] = { num_block_ids }, cx[1] = { context_len };
851 return paged_core(q, pool, layout, tables, nb, cx, 1, layer_idx, num_q_heads, num_kv_heads, head_dim, out, info);
852}
853
854int omega_gpu_paged_attention_batch_bf16(const float *q, const void *pool, const OmegaGpuKvLayout *layout,
855 const int32_t *block_tables, const int32_t *context_lens,
856 uint32_t max_blocks_per_seq, uint32_t num_seqs, uint32_t layer_idx,
857 uint32_t num_q_heads, uint32_t num_kv_heads, uint32_t head_dim,
858 float *out, OmegaGpuAttnInfo *info) {
859 if (!q || !pool || !layout || !out || !block_tables || !context_lens || num_seqs == 0) return OMEGA_GPU_ATTN_BAD_ARGS;
860 /* the oracle's rules: ctx <= 0 -> 0; a table row past the array -> empty; negatives removed */
861 uint32_t **tables = calloc(num_seqs, sizeof *tables);
862 uint32_t *nb = calloc(num_seqs, sizeof *nb), *cx = calloc(num_seqs, sizeof *cx);
863 if (!tables || !nb || !cx) { free(tables); free(nb); free(cx); return OMEGA_GPU_ATTN_CHIP_FAIL; }
864 int rc = OMEGA_GPU_ATTN_OK;
865 for (uint32_t s = 0; s < num_seqs; s++) {
866 cx[s] = context_lens[s] > 0 ? (uint32_t)context_lens[s] : 0;
867 tables[s] = calloc(max_blocks_per_seq ? max_blocks_per_seq : 1, sizeof **tables);
868 if (!tables[s]) { rc = OMEGA_GPU_ATTN_CHIP_FAIL; break; }
869 for (uint32_t b = 0; b < max_blocks_per_seq; b++) {
870 int32_t v = block_tables[(size_t)s * max_blocks_per_seq + b];
871 if (v >= 0) tables[s][nb[s]++] = (uint32_t)v;
872 }
873 }
874 if (rc == OMEGA_GPU_ATTN_OK)
875 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);
876 for (uint32_t s = 0; s < num_seqs; s++) free(tables[s]);
877 free(tables); free(nb); free(cx);
878 return rc;
879}
880
881static const char *const k_mutant_names[OMEGA_GPU_ATTN_MUTANT_COUNT] = {
882 "none", "NO_MAX", "KV_HEAD", "SLOT", "NO_RESCALE", "Q_ROW", "OUT_ROW"
883};
884_Static_assert(sizeof k_mutant_names / sizeof k_mutant_names[0] == OMEGA_GPU_ATTN_MUTANT_COUNT, "mutant name table");
885
886const char *omega_gpu_attention_mutant_name(OmegaGpuAttnMutant m) {
887 return (m >= 0 && m < OMEGA_GPU_ATTN_MUTANT_COUNT && k_mutant_names[m]) ? k_mutant_names[m] : "?";
888}
889
890const char *omega_gpu_attention_rc_name(int rc) {
891 switch (rc) {
892 case OMEGA_GPU_ATTN_OK: return "OK";
893 case OMEGA_GPU_ATTN_BAD_ARGS: return "BAD_ARGS";
894 case OMEGA_GPU_ATTN_TOO_LARGE: return "TOO_LARGE";
895 case OMEGA_GPU_ATTN_CODEGEN_FAIL: return "CODEGEN_FAIL";
896 case OMEGA_GPU_ATTN_CHIP_FAIL: return "CHIP_FAIL";
897 case OMEGA_GPU_ATTN_UNWRITTEN: return "UNWRITTEN";
898 default: return "UNKNOWN";
899 }
900}
901
902/* omega #308 R2 test hook: 0 production, 1 lane-dependent branch inside a reconvergence
903 * region, 2 the same with the BSYNC dropped (negative control). Clears the kernel cache. */
904void omega_gpu_attention_test_set_divergent(int mode) {
905 LOCK();
906 g_divergent = (mode < 0 || mode > 2) ? 0 : mode;
907 cache_clear_locked();
908 UNLOCK();
909}