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-cd80bf4 / omega_gpu_attention_api.c

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