interplane.Get Omega
Read in your language

omega-mv

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

Brought by drakestapleton

branch main Branches Tags History

omega-mv / evidence / FB1-CUT5-b016322 / omega_gpu_attention_api.c

776 lines · 43375 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), 64 threads (= head_dim). The context is
13 * walked in chunks of 64 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 (1024 bytes, the QMD's declared size): [0,256) q, [256,512) s then p,
24 * [512,768) token byte offsets, [768,1024) warp partials for the reductions.
25 */
26#include "omega_gpu_attention_api.h"
27#include "omega_blackwell_codegen.h"
28#include "omega_blackwell_qmd.h"
29#include "omega_blackwell_submit.h"
30#include "m16_native.h"
31#include "sha256.h"
32#include <math.h>
33#include <pthread.h>
34#include <stdio.h>
35#include <stdlib.h>
36#include <string.h>
37#include <time.h>
38
39/* ------------------------------------------------------------------ codegen */
40
41#define CW(stall, wbar, rbar, wait) \
42 (((uint32_t)(stall) << 9) | ((uint32_t)(wbar) << 14) | ((uint32_t)(rbar) << 17) | ((uint32_t)(wait) << 20))
43#define CW_YIELD 0x2000u
44#define SB_NONE 7u
45#define SB_GPR 0u
46#define SB_RD 1u
47#define SB_UGPR 2u
48
49enum { K_FIXED, K_PRED, K_VAR, K_UVAR, K_STORE, K_SYNC, K_EXIT, K_BRA };
50
51#define AT_MAX_LOOPS 8
52typedef struct {
53 BlackwellIRProgram *p;
54 uint32_t pending;
55 int err;
56 int loop_start[AT_MAX_LOOPS], loop_end[AT_MAX_LOOPS];
57 int n_loops, depth, stack[AT_MAX_LOOPS];
58} Em;
59
60static void emit(Em *e, BlackwellIRInsn in, int kind) {
61 uint32_t wait = e->pending;
62 switch (kind) {
63 case K_FIXED: in.control = CW(6, SB_NONE, SB_NONE, wait); e->pending = 0; break;
64 case K_PRED: in.control = CW(13, SB_NONE, SB_NONE, wait); e->pending = 0; break;
65 case K_VAR: in.control = CW(4, SB_GPR, SB_NONE, wait) | CW_YIELD; e->pending = 1u << SB_GPR; break;
66 case K_UVAR: in.control = CW(4, SB_UGPR, SB_NONE, wait) | CW_YIELD; e->pending = 1u << SB_UGPR; break;
67 case K_STORE: in.control = CW(4, SB_NONE, SB_RD, wait) | CW_YIELD; e->pending = 1u << SB_RD; break;
68 case K_SYNC: in.control = CW(6, SB_NONE, SB_NONE, wait); e->pending = 0; break;
69 case K_EXIT: in.control = CW(5, SB_NONE, SB_NONE, wait); e->pending = in.predicate_p0 ? wait : 0; break;
70 case K_BRA: in.control = CW(5, SB_NONE, SB_NONE, wait); e->pending = in.predicate_p0 ? wait : 0; break;
71 default: e->err = -1; return;
72 }
73 if (omega_bw_ir_append(e->p, &in) < 0) e->err = -1;
74}
75
76static int V(Em *e) { int v = omega_bw_ir_alloc_vreg(e->p); if (v < 0) e->err = -1; return v; }
77static int V64(Em *e) { int v = omega_bw_ir_alloc_vreg64(e->p); if (v < 0) e->err = -1; return v; }
78static int UV64(Em *e) { int v = omega_bw_ir_alloc_uvreg64(e->p); if (v < 0) e->err = -1; return v; }
79static int here(const Em *e) { return (int)e->p->count; }
80
81#define NOREG -1
82static BlackwellIRInsn I0(BlackwellIROpcode op) {
83 BlackwellIRInsn in; memset(&in, 0, sizeof in);
84 in.op = op; in.dst_vreg = NOREG; in.src1_vreg = NOREG; in.src2_vreg = NOREG; in.src3_vreg = NOREG; in.ureg = NOREG;
85 return in;
86}
87static 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); }
88static 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); }
89static 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); }
90static 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); }
91static 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); }
92static void movf(Em *e, int dst, float f) { uint32_t u; memcpy(&u, &f, 4); movi(e, dst, u); }
93static void movrz(Em *e, int dst) { BlackwellIRInsn i = I0(BW_IR_MOV_RZ); i.dst_vreg = dst; emit(e, i, K_FIXED); }
94/* dst = a * imm + c (c may be NOREG for RZ) */
95static 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); }
96/* dst = a * b + c (registers; c may be NOREG) */
97static 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); }
98static 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); }
99static 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); }
100static 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); }
101static 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); }
102/* dst64 = idx * imm + base64 (byte address) */
103static 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); }
104static 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); }
105static 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); }
106static 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); }
107static 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); }
108static 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); }
109static 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); }
110static 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); }
111static 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); }
112static 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); }
113static 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); }
114static 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); }
115static 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); }
116static void bar_sync(Em *e) { emit(e, I0(BW_IR_BAR_SYNC), K_SYNC); }
117static 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); }
118static 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); }
119/* @P0 BRA forward; the target is patched in when known */
120static 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; }
121static 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; }
122static void tail(Em *e) {
123 emit(e, I0(BW_IR_EXIT), K_EXIT);
124 BlackwellIRInsn self = I0(BW_IR_BRA);
125 self.control = 0x000fc000u;
126 if (omega_bw_ir_append(e->p, &self) < 0) e->err = -1;
127}
128/* Loops nest; loop_end() extends every value defined before the loop and read inside
129 * it to the back-branch (the linear-scan allocator knows nothing about back-edges). */
130static void loop_begin(Em *e) {
131 if (e->depth >= AT_MAX_LOOPS || e->n_loops >= AT_MAX_LOOPS) { e->err = -1; return; }
132 e->stack[e->depth++] = here(e);
133}
134static void loop_end(Em *e) {
135 if (e->depth == 0 || e->n_loops >= AT_MAX_LOOPS) { e->err = -1; return; }
136 int start = e->stack[--e->depth], end = here(e) - 1;
137 e->loop_start[e->n_loops] = start; e->loop_end[e->n_loops] = end; e->n_loops++;
138 OmegaRegAlloc *ra = &e->p->regalloc;
139 for (int v = 0; v < ra->num_vregs; v++) {
140 OmegaLiveInterval *iv = &ra->intervals[v];
141 if (iv->first_def >= 0 && iv->first_def < start && iv->last_use >= start && iv->last_use < end) iv->last_use = end;
142 }
143}
144/* A value first defined inside a loop may not be read after it before being redefined. */
145static int check_loop_invariant(const Em *e) {
146 const OmegaRegAlloc *ra = &e->p->regalloc;
147 for (int L = 0; L < e->n_loops; L++)
148 for (int v = 0; v < ra->num_vregs; v++) {
149 int fd = ra->intervals[v].first_def;
150 if (fd < e->loop_start[L] || fd > e->loop_end[L]) continue;
151 for (size_t i = (size_t)e->loop_end[L] + 1; i < e->p->count; i++) {
152 const BlackwellIRInsn *in = &e->p->insns[i];
153 if (in->src1_vreg == v || in->src2_vreg == v || in->src3_vreg == v) return -1;
154 if (in->dst_vreg == v && !in->is_uniform) break;
155 }
156 }
157 return 0;
158}
159
160/* Kernel argument words (constant bank 0 at 0x380; the bank is 1024 bytes, so 32 words fit). */
161#define ARG_Q 0x380u
162#define ARG_POOL 0x388u
163#define ARG_OUT 0x390u
164#define ARG_TAB 0x398u
165#define ARG_MAXB 0x3a0u /* words per block-table row */
166#define ARG_SCALE 0x3a4u /* bits of log2(e) / sqrt(head_dim) */
167#define ARG_BSTRIDE 0x3a8u /* bytes between staged blocks */
168#define ARG_TSTRIDE 0x3acu /* bytes between tokens */
169#define ARG_KVP 0x3b0u /* bytes from the K plane to the V plane */
170#define ARG_HSTRIDE 0x3b4u /* bytes between kv heads */
171#define ARG_NQH 0x3b8u /* query heads (q and out row count per sequence) */
172#define ARG_CTXOFF 0x3bcu /* byte offset of the context-length array inside the table buffer */
173#define ARG_WORDS 16u
174#define DESC_OFF 0x358u
175
176#define HD OMEGA_GPU_ATTN_HEAD_DIM
177#define SH_Q 0u
178#define SH_S 256u
179#define SH_O 512u
180#define SH_R 768u
181#define F32_NEG_INF 0xff800000u
182
183typedef struct { bool f32; uint32_t log2bs, log2gqa; int mutant; } KSpec;
184
185static void gen_attention(Em *e, const KSpec *k) {
186 const uint32_t elem = k->f32 ? 4u : 2u;
187 const uint32_t kstep = k->f32 ? 8u : 4u; /* bytes per inner iteration: two dims */
188 int udesc = UV64(e), A = V64(e), B = V64(e), C = V64(e), D = V64(e);
189 int tid = V(e), h = V(e), seq = V(e);
190 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);
191 ldcu64(e, udesc, DESC_OFF);
192 ldc64(e, A, ARG_Q); ldc64(e, B, ARG_POOL); ldc64(e, C, ARG_OUT); ldc64(e, D, ARG_TAB);
193 ldc32(e, p_maxb, ARG_MAXB); ldc32(e, scale, ARG_SCALE); ldc32(e, p_bstride, ARG_BSTRIDE); ldc32(e, p_tstride, ARG_TSTRIDE);
194 ldc32(e, p_kvp, ARG_KVP); ldc32(e, p_hstride, ARG_HSTRIDE); ldc32(e, p_nqh, ARG_NQH); ldc32(e, p_ctxoff, ARG_CTXOFF);
195 s2r(e, tid, BW_SR_TID_X); s2r(e, h, BW_SR_CTAID_X); s2r(e, seq, BW_SR_CTAID_Y);
196
197 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);
198 movi(e, c1, 1); movi(e, c4, 4); movi(e, c32, 32); movi(e, c64, 64);
199 movi(e, c256, SH_S); movi(e, c512, SH_O); movi(e, c768, SH_R); movi(e, c896, SH_R + 128); movrz(e, zero);
200
201 /* q[tid] -> shared; out address kept for the end */
202 int tid4 = V(e), qrow = V(e), qoff = V(e), qaddr = V64(e), qv = V(e), oaddr = V64(e);
203 imadi(e, tid4, tid, 4, NOREG);
204 imadr(e, qrow, seq, p_nqh, h);
205 imadi(e, qoff, qrow, HD * 4, tid4);
206 wide(e, qaddr, qoff, 1, A);
207 ldg(e, qv, qaddr, udesc);
208 sts32(e, tid4, qv); /* SH_Q + tid*4 */
209 wide(e, oaddr, qoff, 1, C);
210
211 /* kv head offset, this sequence's table row and context length */
212 int kvh = V(e), kvoff = V(e), t1 = V(e), tab = V64(e), ca = V64(e), ctx = V(e), vb = V64(e);
213 shri(e, kvh, h, k->log2gqa);
214 if (k->mutant == OMEGA_GPU_ATTN_MUTANT_KV_HEAD) lop3xor(e, kvh, kvh, c1);
215 imadr(e, kvoff, kvh, p_hstride, NOREG);
216 imadr(e, t1, seq, p_maxb, NOREG);
217 imadi(e, t1, t1, 4, NOREG);
218 wide(e, tab, t1, 1, D);
219 imadi(e, t1, seq, 4, p_ctxoff);
220 wide(e, ca, t1, 1, D);
221 ldg(e, ctx, ca, udesc);
222 /* V column base for dimension tid: pool + kv plane + tid * elem. The kv head offset is
223 * already inside the per-token offset phase A leaves in shared memory (found by the host
224 * simulator: adding it here too read V from the wrong head for every kv head but 0). */
225 wide(e, vb, tid, elem, B);
226 wide(e, vb, p_kvp, 1, vb);
227
228 int M = V(e), L = V(e), acc = V(e), base = V(e), sOff = V(e), oOff = V(e), rOff = V(e);
229 movi(e, M, F32_NEG_INF);
230 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 */
231 movrz(e, acc); movrz(e, base);
232 iadd3(e, sOff, tid4, c256); iadd3(e, oOff, tid4, c512); iadd3(e, rOff, tid4, c768);
233 bar_sync(e); /* q visible to every thread */
234 isetp_ge_u32(e, zero, ctx); /* ctx == 0: out = 0 */
235 int bZ = bra_fwd_if_p0(e);
236
237 /* ---------------- chunk loop ---------------- */
238 int j = V(e), s = V(e), koff = V(e);
239 int bi = V(e), sl = V(e), ta = V64(e), blk = V(e), ka = V64(e), dot = V(e), d = V(e);
240 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);
241 loop_begin(e);
242 int Lout = here(e);
243 iadd3(e, j, base, tid);
244 movi(e, s, F32_NEG_INF);
245 movrz(e, koff);
246 isetp_ge_u32(e, j, ctx);
247 int bA = bra_fwd_if_p0(e);
248 /* phase A: token j */
249 shri(e, bi, j, k->log2bs);
250 lop3andi(e, sl, j, (1u << k->log2bs) - 1u);
251 wide(e, ta, bi, 4, tab);
252 ldg(e, blk, ta, udesc);
253 imadr(e, koff, blk, p_bstride, NOREG);
254 if (k->mutant == OMEGA_GPU_ATTN_MUTANT_SLOT) {
255 /* K read from slot (t + 1) % block_size, V from the right slot: a K/V mismatch.
256 * (Shifting both only permutes matched pairs inside a full block, which softmax cannot see.) */
257 int sl1 = V(e);
258 iadd3(e, j1, j, c1); lop3andi(e, sl1, j1, (1u << k->log2bs) - 1u);
259 imadr(e, sl1, sl1, p_tstride, koff);
260 iadd3(e, sl1, sl1, kvoff);
261 wide(e, ka, sl1, 1, B);
262 imadr(e, koff, sl, p_tstride, koff);
263 iadd3(e, koff, koff, kvoff);
264 } else {
265 imadr(e, koff, sl, p_tstride, koff);
266 iadd3(e, koff, koff, kvoff);
267 wide(e, ka, koff, 1, B);
268 }
269 movrz(e, dot); movrz(e, d);
270 loop_begin(e);
271 int Lin = here(e);
272 if (k->f32) {
273 ldg(e, lo, ka, udesc);
274 wide(e, ka2, c1, 4, ka);
275 ldg(e, hi, ka2, udesc);
276 } else {
277 ldg(e, x, ka, udesc);
278 imadi(e, lo, x, 0x10000u, NOREG); /* low bf16 -> f32: bits << 16 */
279 lop3andi(e, hi, x, 0xffff0000u); /* high bf16 -> f32: keep the top half */
280 }
281 imadi(e, qa, d, 8, NOREG);
282 lds32(e, q0, qa);
283 iadd3(e, qb, qa, c4);
284 lds32(e, q1, qb);
285 e_ffma(e, dot, q0, lo, dot);
286 e_ffma(e, dot, q1, hi, dot);
287 wide(e, ka, c1, kstep, ka);
288 iadd3(e, d, d, c1);
289 isetp_ge_u32(e, d, c32);
290 bra_back_if_not_p0(e, Lin);
291 loop_end(e);
292 e_fmul(e, s, dot, scale);
293 patch_fwd(e, bA);
294 sts32(e, sOff, s);
295 sts32(e, oOff, koff);
296
297 /* chunk max */
298 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);
299 static const uint32_t steps[5] = { 16, 8, 4, 2, 1 };
300 shfl_down(e, t, s, steps[0]); e_fmax(e, mw, s, t);
301 for (int i = 1; i < 5; i++) { shfl_down(e, t, mw, steps[i]); e_fmax(e, mw, mw, t); }
302 sts32(e, rOff, mw);
303 bar_sync(e);
304 lds32(e, ra, c768); lds32(e, rb, c896);
305 e_fmax(e, mc, ra, rb);
306 e_fmax(e, Mn, M, mc);
307 if (k->mutant == OMEGA_GPU_ATTN_MUTANT_NO_MAX) {
308 movf(e, alpha, 1.0f);
309 mufu(e, BW_IR_MUFU_EX2, p, s);
310 e_fmax(e, M, Mn, mc);
311 } else {
312 e_fsub(e, diff, M, Mn);
313 mufu(e, BW_IR_MUFU_EX2, alpha, diff);
314 e_fmax(e, M, Mn, mc); /* M = Mn */
315 e_fsub(e, parg, s, Mn);
316 mufu(e, BW_IR_MUFU_EX2, p, parg);
317 }
318 bar_sync(e); /* everyone has read the max partials before they are overwritten */
319 sts32(e, sOff, p);
320 shfl_down(e, t, p, steps[0]); e_fadd(e, sw, p, t);
321 for (int i = 1; i < 5; i++) { shfl_down(e, t, sw, steps[i]); e_fadd(e, sw, sw, t); }
322 sts32(e, rOff, sw);
323 bar_sync(e);
324 lds32(e, ra, c768); lds32(e, rb, c896);
325 e_fadd(e, lc, ra, rb);
326 e_ffma(e, L, L, alpha, lc);
327 if (k->mutant != OMEGA_GPU_ATTN_MUTANT_NO_RESCALE) e_fmul(e, acc, acc, alpha);
328
329 /* phase B: dimension tid over the chunk's tokens */
330 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);
331 movrz(e, kk);
332 loop_begin(e);
333 int LB = here(e);
334 iadd3(e, tt, base, kk);
335 isetp_ge_u32(e, tt, ctx);
336 int bB = bra_fwd_if_p0(e);
337 imadi(e, oa, kk, 4, c512);
338 lds32(e, ko, oa);
339 imadi(e, pa, kk, 4, c256);
340 lds32(e, pv, pa);
341 wide(e, va, ko, 1, vb);
342 if (k->f32) ldg(e, v, va, udesc);
343 else { ldg16(e, v, va, udesc); imadi(e, v, v, 0x10000u, NOREG); }
344 e_ffma(e, acc, pv, v, acc);
345 iadd3(e, kk, kk, c1);
346 isetp_ge_u32(e, kk, c64);
347 bra_back_if_not_p0(e, LB);
348 loop_end(e);
349 patch_fwd(e, bB);
350 bar_sync(e); /* phase B reads of s/p and offsets finish before the next chunk writes them */
351 iadd3(e, base, base, c64);
352 isetp_ge_u32(e, base, ctx);
353 bra_back_if_not_p0(e, Lout);
354 loop_end(e);
355
356 patch_fwd(e, bZ);
357 int inv = V(e), o = V(e);
358 mufu(e, BW_IR_MUFU_RCP, inv, L);
359 e_fmul(e, o, acc, inv);
360 stg(e, oaddr, o, udesc);
361 tail(e);
362}
363
364#define AT_GPR_BUDGET 64u
365
366static int build_kernel(const KSpec *k, OmegaBlackwellKernel *kernel, BlackwellIRProgram **keep) {
367 BlackwellIRProgram *prog = calloc(1, sizeof *prog);
368 if (!prog) return OMEGA_GPU_ATTN_CODEGEN_FAIL;
369 omega_bw_ir_init(prog);
370 Em e; memset(&e, 0, sizeof e); e.p = prog;
371 gen_attention(&e, k);
372 if (e.depth != 0) e.err = -1;
373 int rc = OMEGA_GPU_ATTN_CODEGEN_FAIL;
374 int ra_rc = (e.err == 0) ? omega_bw_regalloc_solve(prog) : -1;
375 int loop_rc = (ra_rc == 0) ? check_loop_invariant(&e) : -1;
376#ifdef OMEGA_ATTN_DEBUG
377 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",
378 (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);
379#endif
380 if (e.err == 0 && ra_rc == 0 && loop_rc == 0 && prog->regalloc.peak_gpr_usage <= AT_GPR_BUDGET) {
381 size_t max_bytes = (size_t)BW_MAX_IR_INSNS * 16;
382 memset(kernel, 0, sizeof *kernel);
383 kernel->code = malloc(max_bytes);
384 size_t emitted = 0;
385 if (kernel->code && omega_bw_encode_program(prog, kernel->code, max_bytes, &emitted) == 0) {
386 kernel->code_size = emitted;
387 kernel->insn_count = emitted / 16;
388 kernel->gpr_count = prog->regalloc.peak_gpr_usage;
389 kernel->uniform_gpr_count = prog->regalloc.peak_ugpr_usage;
390 sha256_hash(kernel->code, kernel->code_size, kernel->code_digest);
391 rc = OMEGA_GPU_ATTN_OK;
392 } else {
393 free(kernel->code); kernel->code = NULL;
394 }
395 }
396 if (keep && rc == OMEGA_GPU_ATTN_OK) *keep = prog; else free(prog);
397 return rc;
398}
399
400/* --------------------------------------------------------- kernel cache */
401
402static int g_mutant;
403typedef struct { int used; KSpec k; OmegaBlackwellKernel kernel; BlackwellIRProgram *prog; } Slot;
404static OmegaGpuAttnSim g_sim;
405static Slot g_cache[8];
406static pthread_mutex_t g_mu = PTHREAD_MUTEX_INITIALIZER;
407void omega_gpu_attention_test_set_simulator(OmegaGpuAttnSim sim) { pthread_mutex_lock(&g_mu); g_sim = sim; pthread_mutex_unlock(&g_mu); }
408
409void omega_gpu_attention_cache_clear(void) {
410 pthread_mutex_lock(&g_mu);
411 for (size_t i = 0; i < sizeof g_cache / sizeof g_cache[0]; i++)
412 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]); }
413 pthread_mutex_unlock(&g_mu);
414}
415
416void omega_gpu_attention_test_set_mutant(OmegaGpuAttnMutant m) {
417 pthread_mutex_lock(&g_mu);
418 g_mutant = (int)m;
419 pthread_mutex_unlock(&g_mu);
420 omega_gpu_attention_cache_clear();
421}
422
423static int kernel_for(bool f32, uint32_t log2bs, uint32_t log2gqa, OmegaBlackwellKernel *out, const BlackwellIRProgram **prog, bool *hit) {
424 pthread_mutex_lock(&g_mu);
425 KSpec k = { .f32 = f32, .log2bs = log2bs, .log2gqa = log2gqa, .mutant = g_mutant };
426 for (size_t i = 0; i < sizeof g_cache / sizeof g_cache[0]; i++)
427 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 */
428 *out = g_cache[i].kernel; *prog = g_cache[i].prog; *hit = true; pthread_mutex_unlock(&g_mu); return OMEGA_GPU_ATTN_OK;
429 }
430 OmegaBlackwellKernel kern; BlackwellIRProgram *kp = NULL;
431 int rc = build_kernel(&k, &kern, &kp);
432 if (rc == OMEGA_GPU_ATTN_OK) {
433 size_t slot = sizeof g_cache / sizeof g_cache[0];
434 for (size_t i = 0; i < sizeof g_cache / sizeof g_cache[0]; i++) if (!g_cache[i].used) { slot = i; break; }
435 if (slot == sizeof g_cache / sizeof g_cache[0]) { slot = 0; free(g_cache[0].kernel.code); free(g_cache[0].prog); }
436 g_cache[slot].used = 1; g_cache[slot].k = k; g_cache[slot].kernel = kern; g_cache[slot].prog = kp;
437 *out = kern; *prog = kp; *hit = false;
438 }
439 pthread_mutex_unlock(&g_mu);
440 return rc;
441}
442
443int omega_gpu_attention_codegen(bool kv_f32, uint32_t log2_block_size, uint32_t log2_gqa, OmegaBlackwellKernel *kernel) {
444 if (!kernel || log2_block_size > 16 || log2_gqa > 6) return OMEGA_GPU_ATTN_BAD_ARGS;
445 pthread_mutex_lock(&g_mu);
446 KSpec k = { .f32 = kv_f32, .log2bs = log2_block_size, .log2gqa = log2_gqa, .mutant = g_mutant };
447 pthread_mutex_unlock(&g_mu);
448 return build_kernel(&k, kernel, NULL);
449}
450
451/* ------------------------------------------------------------ launcher */
452
453#define AT_POISON 0xffbadbadu
454#define AT_WAIT_MS 600000ull
455
456static const uint32_t SETUP_WORDS[18] = {
457 0x20012061, 0x0000cec0, 0x20012092, 0x00000001, 0x200120a8, 0x0000000f, 0x2001255d, 0x00000003,
458 0x2001255e, 0x20000000, 0x2001255f, 0x000fffff, 0x20012557, 0x00000003, 0x20012558, 0x22000000,
459 0x20012559, 0x00000000,
460};
461
462static uint64_t now_ns(void) {
463 struct timespec t; clock_gettime(CLOCK_MONOTONIC, &t);
464 return (uint64_t)t.tv_sec * 1000000000ULL + (uint64_t)t.tv_nsec;
465}
466static size_t page_round(size_t b) { b = (b + 0xFFFULL) & ~0xFFFULL; return b < 0x1000 ? 0x1000 : b; }
467
468typedef OmegaGpuAttnLaunch Launch;
469
470/* One launch. Cloned from cut 4's run_abc (itself from omega_blackwell_execute_matmul_tensor):
471 * every buffer GPU-uncached, shader caches invalidated (cut 1b), first marker, L2_FLUSH_DIRTY,
472 * second marker, readback, poison scan. */
473static int run_launch(const OmegaBlackwellKernel *kernel, const Launch *L, OmegaGpuAttnInfo *info) {
474 M16NativeContext ctx;
475 if (m16_native_open(&ctx) != 0) return OMEGA_GPU_ATTN_CHIP_FAIL;
476 if (m16_native_create_channel(&ctx) != 0) { m16_native_close(&ctx); return OMEGA_GPU_ATTN_CHIP_FAIL; }
477 NvrmMem large_pb;
478 if (nvrm_alloc_gpu_uncached(&ctx.rm, 0x10000, &large_pb) != 0) { m16_native_close(&ctx); return OMEGA_GPU_ATTN_CHIP_FAIL; }
479 ctx.pb_mem = large_pb;
480
481 NvrmMem code_mem, cbank_mem, q_mem, pool_mem, tab_mem, out_mem, marker_mem, qmd_mem;
482#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; }
483 AT_ALLOC(code_mem, page_round(kernel->code_size));
484 AT_ALLOC(cbank_mem, 0x1000);
485 AT_ALLOC(q_mem, page_round(L->q_bytes));
486 AT_ALLOC(pool_mem, page_round(L->pool_bytes));
487 AT_ALLOC(tab_mem, page_round(L->tab_bytes));
488 AT_ALLOC(out_mem, page_round(L->out_bytes));
489 AT_ALLOC(marker_mem, 0x1000);
490 AT_ALLOC(qmd_mem, 0x10000);
491#undef AT_ALLOC
492 memcpy(code_mem.cpu, kernel->code, kernel->code_size);
493 memcpy(q_mem.cpu, L->q, L->q_bytes);
494 memcpy(pool_mem.cpu, L->pool, L->pool_bytes);
495 memcpy(tab_mem.cpu, L->tab, L->tab_bytes);
496 size_t out_words = L->out_bytes / 4;
497 uint32_t *out_dev = (uint32_t *)out_mem.cpu;
498 for (size_t i = 0; i < out_words; i++) out_dev[i] = AT_POISON;
499
500 const uint32_t threads_x = HD;
501 uint32_t cbank_data[OMEGA_BW_CBANK_DRIVER_WORDS];
502 omega_blackwell_build_cbank_driver_2d(cbank_data, cbank_mem.va, threads_x, 1, L->grid_x, L->grid_y);
503 uint32_t cbank_args[ARG_WORDS];
504 cbank_args[0] = (uint32_t)q_mem.va; cbank_args[1] = (uint32_t)(q_mem.va >> 32);
505 cbank_args[2] = (uint32_t)pool_mem.va; cbank_args[3] = (uint32_t)(pool_mem.va >> 32);
506 cbank_args[4] = (uint32_t)out_mem.va; cbank_args[5] = (uint32_t)(out_mem.va >> 32);
507 cbank_args[6] = (uint32_t)tab_mem.va; cbank_args[7] = (uint32_t)(tab_mem.va >> 32);
508 memcpy(&cbank_args[8], L->params, sizeof L->params);
509 memcpy(cbank_mem.cpu, cbank_data, sizeof(cbank_data));
510 memcpy((uint8_t *)cbank_mem.cpu + 0x380, cbank_args, sizeof(cbank_args));
511
512 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;
513 OmegaBlackwellQmdConfig qmd_cfg = {
514 .code_va = code_mem.va, .cbank_va = cbank_mem.va, .scratch_va = scratch_va, .sem_va = sem_va,
515 .qmd0_va = qmd0_va, .qmd1_va = qmd1_va, .num_elements = out_words, .threads_per_block = threads_x,
516 .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,
517 .gpr_count = AT_GPR_BUDGET
518 };
519 uint32_t qmd0_words[OMEGA_BW_QMD_WORDS], qmd1_words[OMEGA_BW_QMD_WORDS];
520 omega_blackwell_build_qmd0(qmd0_words, qmd0_va, qmd1_va);
521 omega_blackwell_build_qmd1(qmd1_words, &qmd_cfg);
522 if (omega_blackwell_verify_qmd_invariants(qmd1_words) != 0) { m16_native_close(&ctx); return OMEGA_GPU_ATTN_CHIP_FAIL; }
523 memcpy(qmd_mem.cpu, qmd0_words, sizeof(qmd0_words));
524 memcpy((uint8_t *)qmd_mem.cpu + 0x1000, qmd1_words, sizeof(qmd1_words));
525
526 volatile uint32_t *hsem = (volatile uint32_t *)((uint8_t *)qmd_mem.cpu + 0x2000);
527 volatile uint32_t *hmarker = (volatile uint32_t *)marker_mem.cpu;
528 volatile uint32_t *hmarker2 = (volatile uint32_t *)((uint8_t *)marker_mem.cpu + 0x10);
529 *hsem = 0; *hmarker = 0; *hmarker2 = 0;
530 __asm__ volatile("dsb sy" ::: "memory");
531
532 uint32_t pb[1024];
533 size_t n = 0;
534 memcpy(&pb[n], SETUP_WORDS, sizeof(SETUP_WORDS)); n += sizeof(SETUP_WORDS) / 4;
535 /* NVCEC0_INVALIDATE_SHADER_CACHES 0x021c: INSTRUCTION 0:0, DATA 4:4, CONSTANT 12:12
536 * (clcec0.h; cut 1b: the SM instruction cache served stale code at a reused code address). */
537 pb[n++] = nvrm_mthd(1, 0x021c, 1); pb[n++] = (1u << 0) | (1u << 4) | (1u << 12);
538 pb[n++] = nvrm_mthd(1, 0x0188, 2); pb[n++] = (uint32_t)(cbank_mem.va >> 32); pb[n++] = (uint32_t)cbank_mem.va;
539 pb[n++] = nvrm_mthd(1, 0x0180, 2); pb[n++] = 0x00000380; pb[n++] = 0x00000001;
540 pb[n++] = nvrm_mthd(1, 0x01b0, 1); pb[n++] = 0x00000041;
541 pb[n++] = (224 << 16) | (1 << 13) | (0x01b4 >> 2) | (6u << 28);
542 memcpy(&pb[n], cbank_data, 224 * 4); n += 224;
543 pb[n++] = nvrm_mthd(1, 0x0188, 2); pb[n++] = (uint32_t)((cbank_mem.va + 0x380) >> 32); pb[n++] = (uint32_t)(cbank_mem.va + 0x380);
544 pb[n++] = nvrm_mthd(1, 0x0180, 2); pb[n++] = ARG_WORDS * 4; pb[n++] = 0x00000001;
545 pb[n++] = nvrm_mthd(1, 0x01b0, 1); pb[n++] = 0x00000041;
546 pb[n++] = (ARG_WORDS << 16) | (1 << 13) | (0x01b4 >> 2) | (6u << 28);
547 memcpy(&pb[n], cbank_args, ARG_WORDS * 4); n += ARG_WORDS;
548 pb[n++] = (98 << 16) | (1 << 13) | (0x0318 >> 2) | (2u << 28);
549 pb[n++] = (1u << 30) | (uint32_t)((qmd0_va >> 40) & 0x1ff); pb[n++] = (uint32_t)(qmd0_va >> 8);
550 memcpy(&pb[n], qmd0_words, 96 * 4); n += 96;
551 pb[n++] = nvrm_mthd(1, 0x0188, 2); pb[n++] = (uint32_t)(sem_va >> 32); pb[n++] = (uint32_t)sem_va;
552 pb[n++] = nvrm_mthd(1, 0x0180, 2); pb[n++] = 0x00000004; pb[n++] = 0x00000001;
553 pb[n++] = nvrm_mthd(1, 0x01b0, 1); pb[n++] = 0x00000041;
554 pb[n++] = (1 << 16) | (1 << 13) | (0x01b4 >> 2) | (6u << 28);
555 pb[n++] = OMEGA_BW_SEMAPHORE_INTERMEDIATE_INIT;
556 pb[n++] = (98 << 16) | (1 << 13) | (0x0318 >> 2) | (2u << 28);
557 pb[n++] = (1u << 30) | (uint32_t)((qmd1_va >> 40) & 0x1ff); pb[n++] = (uint32_t)(qmd1_va >> 8);
558 memcpy(&pb[n], qmd1_words, 96 * 4); n += 96;
559 pb[n++] = nvrm_mthd(0, 0x005c, 5);
560 pb[n++] = (uint32_t)marker_mem.va; pb[n++] = (uint32_t)(marker_mem.va >> 32);
561 pb[n++] = OMEGA_BW_MARKER_COMPLETION_PAYLOAD; pb[n++] = 0; pb[n++] = 0x1 | (1u << 20);
562 /* C3 tail: L2_FLUSH_DIRTY, then the second release the host waits for before reading */
563 pb[n++] = nvrm_mthd(0, 0x0028, 4); pb[n++] = 0; pb[n++] = 0; pb[n++] = 0; pb[n++] = (0x10u << 27);
564 pb[n++] = nvrm_mthd(0, 0x005c, 5);
565 pb[n++] = (uint32_t)(marker_mem.va + 0x10); pb[n++] = (uint32_t)((marker_mem.va + 0x10) >> 32);
566 pb[n++] = OMEGA_BW_MARKER2_PAYLOAD; pb[n++] = 0; pb[n++] = 0x1 | (1u << 20);
567
568 uint64_t t0 = now_ns();
569 if (m16_native_submit_methods(&ctx, pb, n) != 0) { m16_native_close(&ctx); return OMEGA_GPU_ATTN_CHIP_FAIL; }
570 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; }
571 if (m16_native_wait_marker(hmarker2, OMEGA_BW_MARKER2_PAYLOAD, AT_WAIT_MS) != 0) { m16_native_close(&ctx); return OMEGA_GPU_ATTN_CHIP_FAIL; }
572 __asm__ volatile("dsb sy" ::: "memory");
573 uint64_t t1 = now_ns();
574 if (*hsem != OMEGA_BW_SEMAPHORE_INTERMEDIATE_DONE) { m16_native_close(&ctx); return OMEGA_GPU_ATTN_CHIP_FAIL; }
575
576 memcpy(L->out, out_mem.cpu, L->out_bytes);
577 uint32_t unwritten = 0;
578 for (size_t i = 0; i < out_words; i++) if (((uint32_t *)L->out)[i] == AT_POISON) unwritten++;
579 if (info) {
580 info->chip_calls++;
581 info->elapsed_ns += (t1 > t0) ? (t1 - t0) : 0;
582 info->completion_marker = *hmarker;
583 info->unwritten_words += unwritten;
584 info->threads_per_cta = threads_x;
585 info->ctas_last_launch = L->grid_x * L->grid_y;
586 }
587 m16_native_close(&ctx);
588 return unwritten ? OMEGA_GPU_ATTN_UNWRITTEN : OMEGA_GPU_ATTN_OK;
589}
590
591static int launch(const OmegaBlackwellKernel *kernel, const BlackwellIRProgram *prog, const Launch *L, OmegaGpuAttnInfo *info) {
592 pthread_mutex_lock(&g_mu); OmegaGpuAttnSim sim = g_sim; pthread_mutex_unlock(&g_mu);
593 if (sim) return sim(prog, L, info);
594 return run_launch(kernel, L, info);
595}
596
597/* ------------------------------------------------------- public entries */
598
599static void info_begin(OmegaGpuAttnInfo *info, const OmegaBlackwellKernel *k, bool hit) {
600 if (!info) return;
601 memset(info, 0, sizeof *info);
602 info->kernel_cache_hit = hit;
603 info->gpr_count = k->gpr_count;
604 info->insn_count = (uint32_t)k->insn_count;
605 snprintf(info->target_chip, sizeof info->target_chip, "NVIDIA DGX Spark (Grace Blackwell GB10)");
606 info->sm_architecture = 121;
607}
608static uint32_t f2u(float f) { uint32_t u; memcpy(&u, &f, 4); return u; }
609static int log2_exact(uint32_t v, uint32_t *out) {
610 if (v == 0 || (v & (v - 1))) return -1;
611 uint32_t l = 0; while ((1u << l) != v) l++;
612 *out = l; return 0;
613}
614static float score_scale(void) { return (float)(1.4426950408889634 / sqrt((double)HD)); }
615
616/* Common head-shape checks; returns log2 of the gqa ratio. */
617static int check_heads(uint32_t num_q_heads, uint32_t num_kv_heads, uint32_t head_dim, uint32_t *log2gqa) {
618 if (num_q_heads == 0 || num_kv_heads == 0 || head_dim == 0) return OMEGA_GPU_ATTN_BAD_ARGS;
619 if (head_dim != HD || num_q_heads > OMEGA_GPU_ATTN_MAX_Q_HEADS) return OMEGA_GPU_ATTN_TOO_LARGE;
620 if (num_q_heads % num_kv_heads != 0 || log2_exact(num_q_heads / num_kv_heads, log2gqa) != 0) return OMEGA_GPU_ATTN_BAD_ARGS;
621 return OMEGA_GPU_ATTN_OK;
622}
623
624int omega_gpu_gqa_attention_f32(const float *q, const float *k_cache, const float *v_cache,
625 uint32_t seq_len, uint32_t num_q_heads, uint32_t num_kv_heads,
626 uint32_t head_dim, float *out, OmegaGpuAttnInfo *info) {
627 uint64_t t0 = now_ns();
628 if (!q || !k_cache || !v_cache || !out) return OMEGA_GPU_ATTN_BAD_ARGS;
629 uint32_t log2gqa;
630 int rc = check_heads(num_q_heads, num_kv_heads, head_dim, &log2gqa);
631 if (rc != OMEGA_GPU_ATTN_OK) return rc;
632 if (seq_len > OMEGA_GPU_ATTN_MAX_GQA_CTX) return OMEGA_GPU_ATTN_TOO_LARGE;
633 size_t n_out = (size_t)num_q_heads * HD;
634 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; }
635 OmegaBlackwellKernel k; const BlackwellIRProgram *kp = NULL; bool hit = false;
636 const uint32_t log2bs = 12; /* one block of 4096 slots */
637 rc = kernel_for(true, log2bs, log2gqa, &k, &kp, &hit);
638 if (rc != OMEGA_GPU_ATTN_OK) return rc;
639 info_begin(info, &k, hit);
640 size_t plane = (size_t)seq_len * num_kv_heads * HD * 4;
641 uint8_t *pool = malloc(2 * plane);
642 if (!pool) return OMEGA_GPU_ATTN_CHIP_FAIL;
643 memcpy(pool, k_cache, plane);
644 memcpy(pool + plane, v_cache, plane);
645 uint32_t tab[2] = { 0, seq_len }; /* table row {0}, then the context length at byte 4 */
646 Launch L = {
647 .q = q, .q_bytes = n_out * 4, .pool = pool, .pool_bytes = 2 * plane, .tab = tab, .tab_bytes = sizeof tab,
648 .out = out, .out_bytes = n_out * 4, .grid_x = num_q_heads, .grid_y = 1,
649 .params = { 1, f2u(score_scale()), (uint32_t)(2 * plane), num_kv_heads * HD * 4, (uint32_t)plane, HD * 4, num_q_heads, 4 }
650 };
651 rc = launch(&k, kp, &L, info);
652 free(pool);
653 if (info) info->call_ns = now_ns() - t0;
654 return rc;
655}
656
657/* Paged path shared by the single and batched entries. tables[s] has n_blocks[s] entries
658 * (already filtered of negatives), ctx[s] the context length. */
659static int paged_core(const float *q, const uint8_t *pool, const OmegaGpuKvLayout *ly,
660 const uint32_t *const *tables, const uint32_t *n_blocks, const uint32_t *ctx,
661 uint32_t num_seqs, uint32_t layer_idx, uint32_t num_q_heads, uint32_t num_kv_heads,
662 uint32_t head_dim, float *out, OmegaGpuAttnInfo *info) {
663 uint64_t t0 = now_ns();
664 uint32_t log2gqa, log2bs;
665 int rc = check_heads(num_q_heads, num_kv_heads, head_dim, &log2gqa);
666 if (rc != OMEGA_GPU_ATTN_OK) return rc;
667 if (!ly || layer_idx >= ly->num_layers || log2_exact(ly->block_size, &log2bs) != 0) return OMEGA_GPU_ATTN_BAD_ARGS;
668 /* the oracle addresses heads as kv_head * head_dim * 2 inside a token: the layout must agree */
669 if (ly->head_stride_bytes != HD * 2 || ly->token_stride_bytes != (uint64_t)num_kv_heads * HD * 2 ||
670 ly->kv_plane_stride_bytes != (uint64_t)ly->block_size * ly->token_stride_bytes ||
671 ly->layer_stride_bytes != 2 * ly->kv_plane_stride_bytes || ly->block_stride_bytes < (uint64_t)ly->num_layers * ly->layer_stride_bytes)
672 return OMEGA_GPU_ATTN_BAD_ARGS;
673 size_t row = (size_t)num_q_heads * HD;
674 /* effective context per sequence and block id range check */
675 uint32_t *eff = calloc(num_seqs ? num_seqs : 1, sizeof *eff);
676 if (!eff) return OMEGA_GPU_ATTN_CHIP_FAIL;
677 for (uint32_t s = 0; s < num_seqs; s++) {
678 uint64_t cap = (uint64_t)n_blocks[s] * ly->block_size;
679 eff[s] = (uint32_t)(ctx[s] < cap ? ctx[s] : cap);
680 for (uint32_t b = 0; b < n_blocks[s]; b++) {
681 uint64_t id = tables[s][b];
682 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; }
683 }
684 }
685 OmegaBlackwellKernel k; const BlackwellIRProgram *kp = NULL; bool hit = false;
686 rc = kernel_for(false, log2bs, log2gqa, &k, &kp, &hit);
687 if (rc != OMEGA_GPU_ATTN_OK) { free(eff); return rc; }
688 info_begin(info, &k, hit);
689 uint32_t seqs_per_launch = OMEGA_GPU_ATTN_MAX_CTAS / num_q_heads;
690 if (seqs_per_launch == 0) seqs_per_launch = 1;
691 uint32_t maxb = 1;
692 for (uint32_t s = 0; s < num_seqs; s++) if (n_blocks[s] > maxb) maxb = n_blocks[s];
693 for (uint32_t s0 = 0; s0 < num_seqs && rc == OMEGA_GPU_ATTN_OK; s0 += seqs_per_launch) {
694 uint32_t ns = num_seqs - s0 < seqs_per_launch ? num_seqs - s0 : seqs_per_launch;
695 /* stage the referenced blocks' layer slice, renumbered in table order */
696 uint32_t total = 0;
697 for (uint32_t s = 0; s < ns; s++) total += eff[s0 + s] ? (eff[s0 + s] + ly->block_size - 1) / ly->block_size : 0;
698 uint64_t staged_bytes = (uint64_t)(total ? total : 1) * ly->layer_stride_bytes;
699 if (staged_bytes > 0xffffffffull) { rc = OMEGA_GPU_ATTN_TOO_LARGE; break; }
700 uint8_t *staged = malloc((size_t)staged_bytes);
701 uint32_t *tab = calloc((size_t)ns * maxb + ns, sizeof *tab);
702 if (!staged || !tab) { free(staged); free(tab); rc = OMEGA_GPU_ATTN_CHIP_FAIL; break; }
703 uint32_t g = 0;
704 for (uint32_t s = 0; s < ns; s++) {
705 uint32_t need = eff[s0 + s] ? (eff[s0 + s] + ly->block_size - 1) / ly->block_size : 0;
706 for (uint32_t b = 0; b < need; b++, g++) {
707 const uint8_t *src = pool + (size_t)tables[s0 + s][b] * ly->block_stride_bytes + (size_t)layer_idx * ly->layer_stride_bytes;
708 memcpy(staged + (size_t)g * ly->layer_stride_bytes, src, (size_t)ly->layer_stride_bytes);
709 tab[(size_t)s * maxb + b] = g;
710 }
711 tab[(size_t)ns * maxb + s] = eff[s0 + s];
712 }
713 Launch L = {
714 .q = q + (size_t)s0 * row, .q_bytes = (size_t)ns * row * 4, .pool = staged, .pool_bytes = (size_t)staged_bytes,
715 .tab = tab, .tab_bytes = ((size_t)ns * maxb + ns) * 4, .out = out + (size_t)s0 * row, .out_bytes = (size_t)ns * row * 4,
716 .grid_x = num_q_heads, .grid_y = ns,
717 .params = { maxb, f2u(score_scale()), (uint32_t)ly->layer_stride_bytes, (uint32_t)ly->token_stride_bytes,
718 (uint32_t)ly->kv_plane_stride_bytes, (uint32_t)ly->head_stride_bytes, num_q_heads, ns * maxb * 4 }
719 };
720 rc = launch(&k, kp, &L, info);
721 free(staged); free(tab);
722 }
723 free(eff);
724 if (info) info->call_ns = now_ns() - t0;
725 return rc;
726}
727
728int omega_gpu_paged_attention_bf16(const float *q, const void *pool, const OmegaGpuKvLayout *layout,
729 const uint32_t *block_ids, uint32_t num_block_ids,
730 uint32_t context_len, uint32_t layer_idx,
731 uint32_t num_q_heads, uint32_t num_kv_heads, uint32_t head_dim,
732 float *out, OmegaGpuAttnInfo *info) {
733 if (!q || !pool || !layout || !out || (num_block_ids && !block_ids)) return OMEGA_GPU_ATTN_BAD_ARGS;
734 const uint32_t *tables[1] = { block_ids };
735 uint32_t nb[1] = { num_block_ids }, cx[1] = { context_len };
736 return paged_core(q, pool, layout, tables, nb, cx, 1, layer_idx, num_q_heads, num_kv_heads, head_dim, out, info);
737}
738
739int omega_gpu_paged_attention_batch_bf16(const float *q, const void *pool, const OmegaGpuKvLayout *layout,
740 const int32_t *block_tables, const int32_t *context_lens,
741 uint32_t max_blocks_per_seq, uint32_t num_seqs, uint32_t layer_idx,
742 uint32_t num_q_heads, uint32_t num_kv_heads, uint32_t head_dim,
743 float *out, OmegaGpuAttnInfo *info) {
744 if (!q || !pool || !layout || !out || !block_tables || !context_lens || num_seqs == 0) return OMEGA_GPU_ATTN_BAD_ARGS;
745 /* the oracle's rules: ctx <= 0 -> 0; a table row past the array -> empty; negatives removed */
746 uint32_t **tables = calloc(num_seqs, sizeof *tables);
747 uint32_t *nb = calloc(num_seqs, sizeof *nb), *cx = calloc(num_seqs, sizeof *cx);
748 if (!tables || !nb || !cx) { free(tables); free(nb); free(cx); return OMEGA_GPU_ATTN_CHIP_FAIL; }
749 int rc = OMEGA_GPU_ATTN_OK;
750 for (uint32_t s = 0; s < num_seqs; s++) {
751 cx[s] = context_lens[s] > 0 ? (uint32_t)context_lens[s] : 0;
752 tables[s] = calloc(max_blocks_per_seq ? max_blocks_per_seq : 1, sizeof **tables);
753 if (!tables[s]) { rc = OMEGA_GPU_ATTN_CHIP_FAIL; break; }
754 for (uint32_t b = 0; b < max_blocks_per_seq; b++) {
755 int32_t v = block_tables[(size_t)s * max_blocks_per_seq + b];
756 if (v >= 0) tables[s][nb[s]++] = (uint32_t)v;
757 }
758 }
759 if (rc == OMEGA_GPU_ATTN_OK)
760 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);
761 for (uint32_t s = 0; s < num_seqs; s++) free(tables[s]);
762 free(tables); free(nb); free(cx);
763 return rc;
764}
765
766const char *omega_gpu_attention_rc_name(int rc) {
767 switch (rc) {
768 case OMEGA_GPU_ATTN_OK: return "OK";
769 case OMEGA_GPU_ATTN_BAD_ARGS: return "BAD_ARGS";
770 case OMEGA_GPU_ATTN_TOO_LARGE: return "TOO_LARGE";
771 case OMEGA_GPU_ATTN_CODEGEN_FAIL: return "CODEGEN_FAIL";
772 case OMEGA_GPU_ATTN_CHIP_FAIL: return "CHIP_FAIL";
773 case OMEGA_GPU_ATTN_UNWRITTEN: return "UNWRITTEN";
774 default: return "UNKNOWN";
775 }
776}