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 / OWN30B-REQUAL-MAIN-710d438c-20261015 / gates / cut4b / FB1-CUT4B-710d438c / omega_gpu_attention_api.c

1436 lines · 87411 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 "omega_gpu_fmt.h"
34#include "sha256.h"
35#ifdef OMEGA_ATTN_DEBUG
36#include <stdio.h> /* the debug trace only; never in the freestanding build */
37#endif
38#include <string.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#define SB_LD2 4u /* second scoreboard for batched loads (the matmul kernel's B-load word, omega #328) */
50#define SB_LD3 3u /* third: phase B keeps shared loads and the two halves of the V loads on separate scoreboards */
51#define AT_BATCH_MAX 4 /* loads in flight per scoreboard: 4 complete on the chip, 8 never did (omega #328) */
52
53enum { K_FIXED, K_PRED, K_VAR, K_UVAR, K_STORE, K_SYNC, K_EXIT, K_BRA, K_BSSY, K_BSYNC };
54
55#define AT_MAX_LOOPS 8
56typedef struct {
57 BlackwellIRProgram *p;
58 uint32_t pending;
59 uint32_t batch; /* scoreboards the open load batch is filling (no wait on them inside the batch) */
60 int batch_n[8]; /* loads issued per scoreboard in the open batch */
61 int err;
62 int loop_start[AT_MAX_LOOPS], loop_end[AT_MAX_LOOPS];
63 int n_loops, depth, stack[AT_MAX_LOOPS];
64 BwRegions rg; /* structured reconvergence regions (omega #308) */
65 int rg_mutant; /* test only: 1 = drop the BSYNC at join (the 2026-10-04 bug shape; host sim must catch it) */
66} Em;
67
68static void emit(Em *e, BlackwellIRInsn in, int kind) {
69 uint32_t wait = e->pending;
70 e->batch = 0; memset(e->batch_n, 0, sizeof e->batch_n); /* an ordinary instruction waits on the whole batch */
71 switch (kind) {
72 case K_FIXED: in.control = CW(6, SB_NONE, SB_NONE, wait); e->pending = 0; break;
73 case K_PRED: in.control = CW(13, SB_NONE, SB_NONE, wait); e->pending = 0; break;
74 case K_VAR: in.control = CW(4, SB_GPR, SB_NONE, wait) | CW_YIELD; e->pending = 1u << SB_GPR; break;
75 case K_UVAR: in.control = CW(4, SB_UGPR, SB_NONE, wait) | CW_YIELD; e->pending = 1u << SB_UGPR; break;
76 case K_STORE: in.control = CW(4, SB_NONE, SB_RD, wait) | CW_YIELD; e->pending = 1u << SB_RD; break;
77 case K_SYNC: in.control = CW(6, SB_NONE, SB_NONE, wait); e->pending = 0; break;
78 case K_EXIT: in.control = CW(5, SB_NONE, SB_NONE, wait); e->pending = in.predicate_p0 ? wait : 0; break;
79 case K_BRA: in.control = CW(5, SB_NONE, SB_NONE, wait); e->pending = in.predicate_p0 ? wait : 0; break;
80 /* stall counts as nvcc 13.0.88 writes them for sm_121 (see src/omega_gpu_elementwise_api.c) */
81 case K_BSSY: in.control = CW(1, SB_NONE, SB_NONE, wait) | CW_YIELD; e->pending = 0; break;
82 case K_BSYNC: in.control = CW(5, SB_NONE, SB_NONE, wait) | CW_YIELD; e->pending = 0; break;
83 default: e->err = -1; return;
84 }
85 if (omega_bw_ir_append(e->p, &in) < 0) e->err = -1;
86}
87
88static int V(Em *e) { int v = omega_bw_ir_alloc_vreg(e->p); if (v < 0) e->err = -1; return v; }
89static int V64(Em *e) { int v = omega_bw_ir_alloc_vreg64(e->p); if (v < 0) e->err = -1; return v; }
90static int V128(Em *e) { int v = omega_bw_ir_alloc_vreg128(e->p); if (v < 0) e->err = -1; return v; }
91static int UV64(Em *e) { int v = omega_bw_ir_alloc_uvreg64(e->p); if (v < 0) e->err = -1; return v; }
92static int here(const Em *e) { return (int)e->p->count; }
93
94#define NOREG -1
95static BlackwellIRInsn I0(BlackwellIROpcode op) {
96 BlackwellIRInsn in; memset(&in, 0, sizeof in);
97 in.op = op; in.dst_vreg = NOREG; in.src1_vreg = NOREG; in.src2_vreg = NOREG; in.src3_vreg = NOREG; in.ureg = NOREG;
98 return in;
99}
100static 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); }
101static 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); }
102static 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); }
103static 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); }
104static 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); }
105static void movf(Em *e, int dst, float f) { uint32_t u; memcpy(&u, &f, 4); movi(e, dst, u); }
106static void movrz(Em *e, int dst) { BlackwellIRInsn i = I0(BW_IR_MOV_RZ); i.dst_vreg = dst; emit(e, i, K_FIXED); }
107/* dst = a * imm + c (c may be NOREG for RZ) */
108static 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); }
109/* dst = a * b + c (registers; c may be NOREG) */
110static 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); }
111static 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); }
112static 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); }
113static 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); }
114static 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); }
115/* dst64 = idx * imm + base64 (byte address) */
116static 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); }
117static 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); }
118/* Batched loads (2026-10-12, long-context finding): every load above waits on the previous one, so
119 * phase A paid one global latency per dim pair and phase B one per token (~6 GB/s at 1268 ctx). A
120 * batched load sets `sb` and waits on every pending scoreboard except the ones the open batch is
121 * filling (and SB_RD, its read barrier), so up to AT_BATCH_MAX loads per scoreboard are in flight.
122 * The next ordinary instruction (emit) waits on all of them. SB_RD covers the address register: the
123 * allocator may hand that register to a later load's data before this load has read it. */
124static void emit_batched(Em *e, BlackwellIRInsn in, uint32_t sb) {
125 if (sb >= 8 || e->batch_n[sb] >= AT_BATCH_MAX) { e->err = -1; return; }
126 in.control = CW(4, sb, SB_RD, e->pending & ~e->batch) | CW_YIELD;
127 e->batch |= (1u << sb) | (1u << SB_RD); e->batch_n[sb]++;
128 e->pending |= (1u << sb) | (1u << SB_RD);
129 if (omega_bw_ir_append(e->p, &in) < 0) e->err = -1;
130}
131/* A fixed-latency instruction inside an open load batch: it waits on the batch's read barrier (its
132 * destination may be a load's address register, which the load may read late) but not on the loads'
133 * data, so the address of the next load is computed while the earlier loads are in flight. Only for
134 * instructions that read no result of the open batch. */
135static void emit_fixed_in_batch(Em *e, BlackwellIRInsn in) {
136 uint32_t wait = (e->pending & ~e->batch) | (e->batch ? (1u << SB_RD) : 0u);
137 in.control = CW(6, SB_NONE, SB_NONE, wait);
138 if (omega_bw_ir_append(e->p, &in) < 0) e->err = -1;
139}
140static void ldg128_b(Em *e, int dst128, int addr64, uint32_t imm, int udesc, uint32_t sb) { BlackwellIRInsn i = I0(BW_IR_LDG_E_128); i.dst_vreg = dst128; i.src1_vreg = addr64; i.imm = imm; i.ureg = udesc; emit_batched(e, i, sb); }
141static void ldg_b(Em *e, int dst, int addr64, int udesc, uint32_t sb) { BlackwellIRInsn i = I0(BW_IR_LDG_E); i.dst_vreg = dst; i.src1_vreg = addr64; i.ureg = udesc; emit_batched(e, i, sb); }
142static void ldg16_b(Em *e, int dst, int addr64, int udesc, uint32_t sb) { BlackwellIRInsn i = I0(BW_IR_LDG_E_U16); i.dst_vreg = dst; i.src1_vreg = addr64; i.ureg = udesc; emit_batched(e, i, sb); }
143static void lds128_b(Em *e, int dst128, int addr, uint32_t imm, uint32_t sb) { BlackwellIRInsn i = I0(BW_IR_LDS128); i.dst_vreg = dst128; i.src1_vreg = addr; i.imm = imm; emit_batched(e, i, sb); }
144/* sub-register operands of a quad */
145static void e_ffma_s(Em *e, int d, int a, int as, int b, int bs, int c) { BlackwellIRInsn i = I0(BW_IR_FFMA); i.dst_vreg = d; i.src1_vreg = a; i.src1_subreg = (uint8_t)as; i.src2_vreg = b; i.src2_subreg = (uint8_t)bs; i.src3_vreg = c; emit(e, i, K_FIXED); }
146static void imadi_s(Em *e, int dst, int a, int as, uint32_t imm, int c) { BlackwellIRInsn i = I0(BW_IR_IMAD); i.dst_vreg = dst; i.src1_vreg = a; i.src1_subreg = (uint8_t)as; i.imm = imm; i.src3_vreg = c; emit(e, i, K_FIXED); }
147static void lop3andi_s(Em *e, int dst, int a, int as, uint32_t imm) { BlackwellIRInsn i = I0(BW_IR_LOP3_AND); i.dst_vreg = dst; i.src1_vreg = a; i.src1_subreg = (uint8_t)as; i.imm = imm; emit(e, i, K_FIXED); }
148static void wide_s(Em *e, int dst64, int idx, int is, uint32_t imm, int base64) { BlackwellIRInsn i = I0(BW_IR_IMAD_WIDE); i.dst_vreg = dst64; i.src1_vreg = idx; i.src1_subreg = (uint8_t)is; i.imm = imm; i.src3_vreg = base64; emit(e, i, K_FIXED); }
149static void wide_s_b(Em *e, int dst64, int idx, int is, uint32_t imm, int base64) { BlackwellIRInsn i = I0(BW_IR_IMAD_WIDE); i.dst_vreg = dst64; i.src1_vreg = idx; i.src1_subreg = (uint8_t)is; i.imm = imm; i.src3_vreg = base64; emit_fixed_in_batch(e, i); }
150static 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); }
151static 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); }
152static 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); }
153static 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); }
154static 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); }
155static 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); }
156static 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); }
157/* SHFL and BAR.SYNC are refused inside an open reconvergence region (omega #308): on a split
158 * warp they read inactive lanes / count a partial warp, which is what produced wrong dims on
159 * the chip on 2026-10-04. The build fails closed instead. */
160static int in_region(Em *e) { if (e->rg.depth > 0) { e->err = -1; return 1; } return 0; }
161static 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); }
162static 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); }
163static 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); }
164static void bar_sync(Em *e) { if (in_region(e)) return; emit(e, I0(BW_IR_BAR_SYNC), K_SYNC); }
165static 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); }
166static 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); }
167/* @P0 BRA forward; the target is patched in when known */
168static 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; }
169static 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; }
170
171/* ---- structured reconvergence regions (omega #308); same API as the elementwise emitter ---- */
172enum { RX_ALWAYS, RX_IF_P0, RX_IF_NOT_P0 };
173static int region_begin(Em *e) {
174 int bar = bw_regions_next_bar(&e->rg);
175 if (bar < 0) { e->err = -1; return -1; }
176 int at = here(e);
177 BlackwellIRInsn i = I0(BW_IR_BSSY); i.bar_reg = (uint8_t)bar; i.imm = 2; emit(e, i, K_BSSY);
178 if (bw_regions_begin(&e->rg, at) < 0) e->err = -1;
179 return bar;
180}
181static void region_exit(Em *e, int cond) {
182 int at = here(e);
183 BlackwellIRInsn i = I0(BW_IR_BRA); i.imm = 1;
184 if (cond != RX_ALWAYS) { i.predicate_p0 = true; i.predicate_not = (cond == RX_IF_NOT_P0); }
185 emit(e, i, K_BRA);
186 if (bw_regions_exit(&e->rg, at) < 0) e->err = -1;
187}
188static void region_join(Em *e) {
189 if (e->rg.depth <= 0) { e->err = -1; return; }
190 int d = e->rg.depth - 1, bsync = here(e);
191 BlackwellIRInsn i = I0(e->rg_mutant == 1 ? BW_IR_NOP : BW_IR_BSYNC); i.bar_reg = (uint8_t)d; emit(e, i, K_BSYNC);
192 if (e->rg_mutant == 1) {
193 BwRegions *r = &e->rg; r->depth--;
194 e->p->insns[r->bssy_at[d]].imm = (uint32_t)(bsync + 1 - r->bssy_at[d]);
195 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]);
196 return;
197 }
198 if (bw_regions_join(&e->rg, e->p, bsync) != d) e->err = -1;
199}
200static void tail(Em *e) {
201 emit(e, I0(BW_IR_EXIT), K_EXIT);
202 BlackwellIRInsn self = I0(BW_IR_BRA);
203 self.control = 0x000fc000u;
204 if (omega_bw_ir_append(e->p, &self) < 0) e->err = -1;
205}
206/* Loops nest; loop_end() extends every value defined before the loop and read inside
207 * it to the back-branch (the linear-scan allocator knows nothing about back-edges). */
208static void loop_begin(Em *e) {
209 if (e->depth >= AT_MAX_LOOPS || e->n_loops >= AT_MAX_LOOPS) { e->err = -1; return; }
210 e->stack[e->depth++] = here(e);
211}
212static void loop_end(Em *e) {
213 if (e->depth == 0 || e->n_loops >= AT_MAX_LOOPS) { e->err = -1; return; }
214 int start = e->stack[--e->depth], end = here(e) - 1;
215 e->loop_start[e->n_loops] = start; e->loop_end[e->n_loops] = end; e->n_loops++;
216 OmegaRegAlloc *ra = &e->p->regalloc;
217 for (int v = 0; v < ra->num_vregs; v++) {
218 OmegaLiveInterval *iv = &ra->intervals[v];
219 if (iv->first_def >= 0 && iv->first_def < start && iv->last_use >= start && iv->last_use < end) iv->last_use = end;
220 }
221}
222/* A value first defined inside a loop may not be read after it before being redefined. */
223static int check_loop_invariant(const Em *e) {
224 const OmegaRegAlloc *ra = &e->p->regalloc;
225 for (int L = 0; L < e->n_loops; L++)
226 for (int v = 0; v < ra->num_vregs; v++) {
227 int fd = ra->intervals[v].first_def;
228 if (fd < e->loop_start[L] || fd > e->loop_end[L]) continue;
229 for (size_t i = (size_t)e->loop_end[L] + 1; i < e->p->count; i++) {
230 const BlackwellIRInsn *in = &e->p->insns[i];
231 if (in->src1_vreg == v || in->src2_vreg == v || in->src3_vreg == v) return -1;
232 if (in->dst_vreg == v && !in->is_uniform) break;
233 }
234 }
235 return 0;
236}
237
238/* Kernel argument words (constant bank 0 at 0x380; the bank is 1024 bytes, so 32 words fit). */
239#define ARG_Q 0x380u
240#define ARG_POOL 0x388u
241#define ARG_OUT 0x390u
242#define ARG_TAB 0x398u
243#define ARG_MAXB 0x3a0u /* words per block-table row */
244#define ARG_SCALE 0x3a4u /* bits of log2(e) / sqrt(head_dim) */
245#define ARG_BSTRIDE 0x3a8u /* bytes between staged blocks */
246#define ARG_TSTRIDE 0x3acu /* bytes between tokens */
247#define ARG_KVP 0x3b0u /* bytes from the K plane to the V plane */
248#define ARG_HSTRIDE 0x3b4u /* bytes between kv heads */
249#define ARG_NQH 0x3b8u /* query heads (q and out row count per sequence) */
250#define ARG_CTXOFF 0x3bcu /* byte offset of the context-length array inside the table buffer */
251#define ARG_WORDS 16u
252#define DESC_OFF 0x358u
253
254/* Head dimension is a kernel parameter (64 or 128, see KSpec.hd). Shared memory is four arrays of hd words:
255 * 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,
256 * the layout of every cut before head_dim 128). */
257#define SH_Q 0u
258#define F32_NEG_INF 0xff800000u
259
260/* divergent (omega #308 regression R2): 0 = production branch-free chunk loop; 1 = the
261 * lane-dependent "j >= ctx" branch restored inside a reconvergence region (BSSY/BSYNC) so
262 * the SHFL reductions run on a joined warp; 2 = the same with the BSYNC dropped (the
263 * 2026-10-04 bug shape, a negative control the host simulator must catch). */
264typedef struct { bool f32; uint32_t log2bs, log2gqa; int mutant; int divergent; uint32_t hd; int split; } KSpec;
265/* split (cut F, 2026-10-12): -1 = direct output (the gqa f32 and rows callers; byte for byte the kernel before).
266 * 0..MAX_LOG2SPLIT = the paged path: 2^split CTAs share one (sequence, head). Each sequence derives its own split
267 * count from its own context (so its result never depends on the other sequences in the launch), every CTA writes
268 * an unnormalised partial (acc[hd], running max, running sum; an empty slice writes acc 0, max -inf) and the host
269 * combines them, also when split == 0. */
270
271/* cut K (2026-10-12, GQA group): at head_dim 128 one CTA serves the GC query heads of one kv head, GC =
272 * min(2^log2gqa, 4), so every K and V byte of a launch is read once instead of once per query head. The KV
273 * pool is GPU-uncached (host-written), so the four CTAs of a GQA group were four DRAM reads of the same
274 * bytes: 21 MB per call at 1268 tokens, the memory ceiling (sc leg smoke-ctx-chunk: 152 us per call).
275 * Grid x is the head group (num_q_heads / GC CTAs per sequence and split). Shared memory: q, scores and
276 * warp partials per head, token offsets once. GC = 1 (every hd 64 kernel, hd 128 with gqa 1) emits exactly
277 * the program before this cut (digest fixtures). */
278static uint32_t heads_per_cta(uint32_t hd, uint32_t log2gqa) { return hd == 128u ? (1u << (log2gqa < 2u ? log2gqa : 2u)) : 1u; }
279static uint32_t shared_bytes_for(uint32_t hd, uint32_t log2gqa) { return (3u * heads_per_cta(hd, log2gqa) + 1u) * hd * 4u; }
280uint32_t omega_gpu_attention_heads_per_cta(uint32_t head_dim, uint32_t log2_gqa) { return heads_per_cta(head_dim, log2_gqa); }
281
282static void gen_attention(Em *e, const KSpec *k) {
283 const uint32_t elem = k->f32 ? 4u : 2u;
284 const uint32_t HD = k->hd, GC = heads_per_cta(HD, k->log2gqa), log2gc = GC == 4u ? 2u : GC == 2u ? 1u : 0u;
285 const uint32_t HB = HD * 4u; /* bytes of one per-head shared array */
286 const uint32_t SH_S = GC * HB, SH_O = 2u * GC * HB, SH_R = SH_O + HB; /* warps per CTA: HD / 32 */
287 int udesc = UV64(e), A = V64(e), B = V64(e), C = V64(e), D = V64(e);
288 int tid = V(e), h = V(e), seq = V(e);
289 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);
290 ldcu64(e, udesc, DESC_OFF);
291 ldc64(e, A, ARG_Q); ldc64(e, B, ARG_POOL); ldc64(e, C, ARG_OUT); ldc64(e, D, ARG_TAB);
292 ldc32(e, p_maxb, ARG_MAXB); ldc32(e, scale, ARG_SCALE); ldc32(e, p_bstride, ARG_BSTRIDE); ldc32(e, p_tstride, ARG_TSTRIDE);
293 ldc32(e, p_kvp, ARG_KVP); ldc32(e, p_hstride, ARG_HSTRIDE); ldc32(e, p_nqh, ARG_NQH); ldc32(e, p_ctxoff, ARG_CTXOFF);
294 s2r(e, tid, BW_SR_TID_X); s2r(e, h, BW_SR_CTAID_X); s2r(e, seq, BW_SR_CTAID_Y);
295
296 /* cut F, partial mode: grid y = sequence * S + split; the split index picks this CTA's slice of the context (below) */
297 const bool part = k->split >= 0;
298 const uint32_t LS = part ? (uint32_t)k->split : 0u, S = 1u << LS, log2hd = (HD == 128u) ? 7u : 6u;
299 int split = -1, kb = -1, kend = -1;
300 if (part) { split = V(e); if (LS) { lop3andi(e, split, seq, S - 1u); shri(e, seq, seq, LS); } else movrz(e, split); }
301
302 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);
303 /* c32 / c64 keep their hd 64 names: the inner (dim pair) loop trip count HD / 2 and the chunk size HD */
304 movi(e, c1, 1); movi(e, c4, 4); movi(e, c32, HD / 2); movi(e, c64, HD);
305 movi(e, c256, SH_S); movi(e, c512, SH_O); movi(e, c768, SH_R); movi(e, c896, SH_R + 128); movrz(e, zero);
306 /* warp partials 2 and 3 (lane 0 of warps 2 and 3): only a 128-thread CTA has them. Created and emitted only
307 * when HD == 128, so the hd 64 program (vreg numbering, instruction sequence) is exactly the one before. */
308 int c1024 = -1, c1152 = -1, rc_ = -1, rd_ = -1;
309 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); }
310
311 /* q[tid] -> shared; out address kept for the end. Row = seq * num_q_heads + head for
312 * both q and out (flattened head-major, the oracle's layout). The head-wiring mutants
313 * swap the row of head h with h ^ 1 on one side only. GC > 1: head g of the group is
314 * h * GC + g; q goes to SH_Q + g * HB; the output rows are derived in the epilogue. */
315 int tid4 = V(e), qrow = V(e), qoff = V(e), qaddr = V64(e), qv = V(e), oaddr = GC == 1 ? V64(e) : -1;
316 int hq = h, ho = h;
317 if (GC == 1 && k->mutant == OMEGA_GPU_ATTN_MUTANT_Q_ROW) { hq = V(e); lop3xor(e, hq, h, c1); }
318 if (GC == 1 && k->mutant == OMEGA_GPU_ATTN_MUTANT_OUT_ROW) { ho = V(e); lop3xor(e, ho, h, c1); }
319 imadi(e, tid4, tid, 4, NOREG);
320 if (GC == 1) {
321 imadr(e, qrow, seq, p_nqh, hq);
322 imadi(e, qoff, qrow, HD * 4, tid4);
323 wide(e, qaddr, qoff, 1, A);
324 ldg(e, qv, qaddr, udesc);
325 sts32(e, tid4, qv); /* SH_Q + tid*4 */
326 if (!part) { /* direct output address; partial mode derives its row in the epilogue */
327 if (ho == hq) wide(e, oaddr, qoff, 1, C);
328 else {
329 int orow = V(e), ooff = V(e);
330 imadr(e, orow, seq, p_nqh, ho);
331 imadi(e, ooff, orow, HD * 4, tid4);
332 wide(e, oaddr, ooff, 1, C);
333 }
334 }
335 } else {
336 int h0 = V(e), hg = V(e), qsh = V(e);
337 imadi(e, h0, h, GC, NOREG);
338 for (uint32_t g = 0; g < GC; g++) {
339 imadi(e, hg, c1, g, h0);
340 if (k->mutant == OMEGA_GPU_ATTN_MUTANT_Q_ROW) lop3xor(e, hg, hg, c1);
341 imadr(e, qrow, seq, p_nqh, hg);
342 imadi(e, qoff, qrow, HD * 4, tid4);
343 wide(e, qaddr, qoff, 1, A);
344 ldg(e, qv, qaddr, udesc);
345 imadi(e, qsh, c1, g * HB, tid4);
346 sts32(e, qsh, qv);
347 }
348 }
349
350 /* kv head offset, this sequence's table row and context length */
351 int kvh = V(e), kvoff = V(e), t1 = V(e), tab = V64(e), ca = V64(e), ctx = V(e), vb = V64(e);
352 shri(e, kvh, h, k->log2gqa - log2gc); /* GC heads per CTA: kv head = (h * GC) >> log2gqa */
353 if (k->mutant == OMEGA_GPU_ATTN_MUTANT_KV_HEAD) lop3xor(e, kvh, kvh, c1);
354 imadr(e, kvoff, kvh, p_hstride, NOREG);
355 imadr(e, t1, seq, p_maxb, NOREG);
356 imadi(e, t1, t1, 4, NOREG);
357 wide(e, tab, t1, 1, D);
358 imadi(e, t1, seq, 4, p_ctxoff);
359 wide(e, ca, t1, 1, D);
360 ldg(e, ctx, ca, udesc);
361 if (part) {
362 /* This sequence's own split count s_own = min(S, pow2floor(chunks)), chunks = ceil(ctx / HD), from its own
363 * context alone (the host picks the launch S the same way over the batch); per = roundup(ceil(ctx / s_own), HD)
364 * whole chunks per split; this CTA's slice is [kb, kend), kend = min(ctx, kb + per) through the sign bit of
365 * ctx - (kb + per). Splits past s_own get kb >= kend: an empty partial. Branch-free: candidate 2^c replaces
366 * per when chunks >= 2^c; the candidates nest, so the largest that fits wins. */
367 int per = V(e), x = V(e), cand = V(e), dd = V(e), lt = V(e), cH1 = V(e), cK = V(e);
368 kb = V(e); kend = V(e);
369 movi(e, cH1, HD - 1u);
370 iadd3(e, per, ctx, cH1); lop3andi(e, per, per, ~(HD - 1u)); /* roundup(ctx, HD): one split takes it all */
371 shri(e, x, per, log2hd); /* chunks (cut J: one whole chunk per split) */
372 for (uint32_t c = 1; c <= LS; c++) {
373 movi(e, cK, (1u << c) - 1u); iadd3(e, cand, ctx, cK); shri(e, cand, cand, c);
374 iadd3(e, cand, cand, cH1); lop3andi(e, cand, cand, ~(HD - 1u)); /* roundup(ceil(ctx / 2^c), HD) */
375 movi(e, cK, 0u - (1u << c)); iadd3(e, dd, x, cK); shri(e, lt, dd, 31); /* lt = (x < 2^c) */
376 imadi(e, dd, cand, 0xFFFFFFFFu, per); /* per - cand */
377 imadr(e, per, lt, dd, cand); /* lt ? per : cand */
378 }
379 imadr(e, kb, split, per, NOREG);
380 iadd3(e, kend, kb, per);
381 imadi(e, dd, kend, 0xFFFFFFFFu, ctx);
382 shri(e, lt, dd, 31);
383 imadr(e, kend, lt, dd, kend);
384 }
385 const int lim = part ? kend : ctx; /* the end of this CTA's token range */
386 /* V column base for dimension tid: pool + kv plane + tid * elem. The kv head offset is
387 * already inside the per-token offset phase A leaves in shared memory (found by the host
388 * simulator: adding it here too read V from the wrong head for every kv head but 0). */
389 wide(e, vb, tid, elem, B);
390 wide(e, vb, p_kvp, 1, vb);
391
392 /* running max, sum and accumulator per head of the group (GC = 1: one of each, as before) */
393 int M[4], L[4], acc[4];
394 for (uint32_t g = 0; g < GC; g++) M[g] = V(e);
395 for (uint32_t g = 0; g < GC; g++) L[g] = V(e);
396 for (uint32_t g = 0; g < GC; g++) acc[g] = V(e);
397 int base = V(e), sOff = V(e), oOff = V(e), rOff = V(e);
398 for (uint32_t g = 0; g < GC; g++) movi(e, M[g], F32_NEG_INF);
399 for (uint32_t g = 0; g < GC; g++) { if (k->mutant == OMEGA_GPU_ATTN_MUTANT_NO_MAX) movrz(e, L[g]); else movf(e, L[g], 1.0f); } /* alpha = 0 on the first chunk clears it */
400 for (uint32_t g = 0; g < GC; g++) movrz(e, acc[g]);
401 if (part) iadd3(e, base, kb, zero); else movrz(e, base);
402 iadd3(e, sOff, tid4, c256); iadd3(e, oOff, tid4, c512); iadd3(e, rOff, tid4, c768);
403 bar_sync(e); /* q visible to every thread */
404 if (part) isetp_ge_u32(e, kb, kend); else isetp_ge_u32(e, zero, ctx); /* empty range: out = 0 (an empty partial) */
405 int bZ = bra_fwd_if_p0(e);
406
407 /* ---------------- chunk loop ---------------- */
408 int j = V(e), s[4], koff;
409 for (uint32_t g = 0; g < GC; g++) s[g] = V(e);
410 koff = V(e);
411 int bi = V(e), sl = V(e), ta = V64(e), blk = V(e), ka = V64(e), dot[4], d;
412 for (uint32_t g = 0; g < GC; g++) dot[g] = V(e);
413 d = V(e);
414 int lo = V(e), hi = V(e), qa = V(e), j1 = V(e);
415 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);
416 int tsh = GC > 1 ? V(e) : -1; /* per-head shared address temporary (GC > 1 only) */
417 movi(e, cm1, 0xFFFFFFFFu); iadd3(e, ctxm1, lim, cm1); movi(e, cninf, F32_NEG_INF);
418 loop_begin(e);
419 int Lout = here(e);
420 /* No branch here: a warp split by "j >= ctx" without a BSSY/BSYNC region stays split, and
421 * the SHFL reductions below then read inactive lanes, which is undefined (wrong dims
422 * tid >= tail on the chip, 2026-10-04). The IR has BSSY/BSYNC regions since omega #310
423 * (omega_bw_reconv.h); this kernel stays branchless and does not use them.
424 * over = (j >= ctx) as 0/1 from the sign of ctx-1-j; out-of-range lanes read token `base`
425 * (always < ctx here) and their score is forced to -inf after the dot product with s = -max(-s, nb), nb = -inf or +inf. */
426 iadd3(e, j, base, tid);
427 for (uint32_t g = 0; g < GC; g++) movi(e, s[g], F32_NEG_INF);
428 movrz(e, koff);
429 if (k->divergent) {
430 /* omega #308 R2: the lane-dependent branch, inside a reconvergence region. Lanes with
431 * j >= ctx skip phase A (s stays -inf, koff 0); the BSYNC at region_join rejoins them
432 * before the SHFL reductions below. divergent == 2 drops that BSYNC (negative control). */
433 region_begin(e);
434 isetp_ge_u32(e, j, lim);
435 region_exit(e, RX_IF_P0);
436 } else {
437 imadi(e, dneg, j, 0xFFFFFFFFu, ctxm1); /* ctx - 1 - j */
438 shri(e, over, dneg, 31);
439 imadr(e, ot, over, tid, NOREG);
440 imadi(e, j, ot, 0xFFFFFFFFu, j); /* j - over*tid */
441 }
442 /* phase A: token j */
443 shri(e, bi, j, k->log2bs);
444 lop3andi(e, sl, j, (1u << k->log2bs) - 1u);
445 wide(e, ta, bi, 4, tab);
446 ldg(e, blk, ta, udesc);
447 imadr(e, koff, blk, p_bstride, NOREG);
448 if (k->mutant == OMEGA_GPU_ATTN_MUTANT_SLOT) {
449 /* K read from slot (t + 1) % block_size, V from the right slot: a K/V mismatch.
450 * (Shifting both only permutes matched pairs inside a full block, which softmax cannot see.) */
451 int sl1 = V(e);
452 iadd3(e, j1, j, c1); lop3andi(e, sl1, j1, (1u << k->log2bs) - 1u);
453 imadr(e, sl1, sl1, p_tstride, koff);
454 iadd3(e, sl1, sl1, kvoff);
455 wide(e, ka, sl1, 1, B);
456 imadr(e, koff, sl, p_tstride, koff);
457 iadd3(e, koff, koff, kvoff);
458 } else {
459 imadr(e, koff, sl, p_tstride, koff);
460 iadd3(e, koff, koff, kvoff);
461 wide(e, ka, koff, 1, B);
462 }
463 /* phase A inner loop (batched, 2026-10-12): two 128-bit global loads of K per pass on SB_GPR (16 dims
464 * bf16, 8 dims f32) with the first half of the matching q slice as 128-bit shared loads on SB_LD2, one
465 * wait; then the second half of q, one more (short) wait. The serial loop before paid one global
466 * latency per dim pair. Two halves keep the pass inside AT_GPR_BUDGET (the whole slice at once is
467 * 65 to 76 registers). qa = d * 4 is the shared byte offset of q[d]. GC > 1: the same K pass feeds
468 * every head of the group, each from its own q slice at SH_Q + g * HB (cut K). */
469 const uint32_t dims = k->f32 ? 8u : 16u; /* dims per pass: 32 bytes of K either way */
470 const uint32_t nq = dims / 4u; /* q quads per pass, loaded in two halves */
471 int kx[2], qq[4];
472 kx[0] = V128(e); kx[1] = V128(e);
473 for (uint32_t i = 0; i < nq; i++) qq[i] = V128(e);
474 for (uint32_t g = 0; g < GC; g++) movrz(e, dot[g]);
475 movrz(e, d);
476 loop_begin(e);
477 int Lin = here(e);
478 imadi(e, qa, d, 4, NOREG);
479 ldg128_b(e, kx[0], ka, 0u, udesc, SB_GPR);
480 ldg128_b(e, kx[1], ka, 16u, udesc, SB_GPR);
481 for (uint32_t g = 0; g < GC; g++) {
482 for (int hh = 0; hh < 2; hh++) {
483 for (uint32_t i = 0; i < nq / 2u; i++) { uint32_t qi = (uint32_t)hh * (nq / 2u) + i; lds128_b(e, qq[qi], qa, g * HB + qi * 16u, SB_LD2); }
484 if (k->f32) {
485 for (int s4 = 0; s4 < 4; s4++) e_ffma_s(e, dot[g], qq[hh], s4, kx[hh], s4, dot[g]); /* dim hh*4+s4 */
486 } else {
487 for (int s4 = 0; s4 < 4; s4++) {
488 int pi = hh * 4 + s4; /* bf16 pair: dims 2*pi (low half) and 2*pi+1 (high half) */
489 imadi_s(e, lo, kx[hh], s4, 0x10000u, NOREG); /* low bf16 -> f32: bits << 16 */
490 lop3andi_s(e, hi, kx[hh], s4, 0xffff0000u); /* high bf16 -> f32: keep the top half */
491 e_ffma_s(e, dot[g], qq[pi / 2], (pi % 2) * 2, lo, 0, dot[g]);
492 e_ffma_s(e, dot[g], qq[pi / 2], (pi % 2) * 2 + 1, hi, 0, dot[g]);
493 }
494 }
495 }
496 }
497 wide(e, ka, c1, 32u, ka);
498 imadi(e, d, c1, dims, d);
499 isetp_ge_u32(e, d, c64);
500 bra_back_if_not_p0(e, Lin);
501 loop_end(e);
502 for (uint32_t g = 0; g < GC; g++) e_fmul(e, s[g], dot[g], scale);
503 if (k->divergent) {
504 region_join(e); /* every lane back before the cross-lane reductions */
505 } else {
506 imadi(e, nb, over, 0x80000000u, cninf); /* over ? +inf : -inf (bits) */
507 for (uint32_t g = 0; g < GC; g++) { e_fsub(e, ns, zero, s[g]); e_fmax(e, ns, ns, nb); e_fsub(e, s[g], zero, ns); }
508 }
509 for (uint32_t g = 0; g < GC; g++) {
510 if (g == 0) sts32(e, sOff, s[0]);
511 else { imadi(e, tsh, c1, g * HB, sOff); sts32(e, tsh, s[g]); }
512 }
513 sts32(e, oOff, koff);
514
515 /* chunk max, per head */
516 int t = V(e), mw = V(e), ra = V(e), rb = V(e), mc = V(e), Mn = V(e), diff = V(e), alpha[4], parg, p, sw, lc;
517 alpha[0] = V(e); parg = V(e); p = V(e); sw = V(e); lc = V(e);
518 for (uint32_t g = 1; g < GC; g++) alpha[g] = V(e);
519 static const uint32_t steps[5] = { 16, 8, 4, 2, 1 };
520 for (uint32_t g = 0; g < GC; g++) {
521 shfl_down(e, t, s[g], steps[0]); e_fmax(e, mw, s[g], t);
522 for (int i = 1; i < 5; i++) { shfl_down(e, t, mw, steps[i]); e_fmax(e, mw, mw, t); }
523 if (g == 0) sts32(e, rOff, mw);
524 else { imadi(e, tsh, c1, g * HB, rOff); sts32(e, tsh, mw); }
525 }
526 bar_sync(e);
527 for (uint32_t g = 0; g < GC; g++) {
528 const int pg = GC == 1 ? p : s[g]; /* GC > 1: p overwrites the score register of its head */
529 if (g == 0) { lds32(e, ra, c768); lds32(e, rb, c896); }
530 else { imadi(e, tsh, c1, g * HB, c768); lds32(e, ra, tsh); imadi(e, tsh, c1, g * HB, c896); lds32(e, rb, tsh); }
531 e_fmax(e, mc, ra, rb);
532 if (HD == 128) {
533 if (g == 0) { lds32(e, rc_, c1024); lds32(e, rd_, c1152); }
534 else { imadi(e, tsh, c1, g * HB, c1024); lds32(e, rc_, tsh); imadi(e, tsh, c1, g * HB, c1152); lds32(e, rd_, tsh); }
535 e_fmax(e, mc, mc, rc_); e_fmax(e, mc, mc, rd_);
536 }
537 e_fmax(e, Mn, M[g], mc);
538 if (k->mutant == OMEGA_GPU_ATTN_MUTANT_NO_MAX) {
539 movf(e, alpha[g], 1.0f);
540 mufu(e, BW_IR_MUFU_EX2, pg, s[g]);
541 e_fmax(e, M[g], Mn, mc);
542 } else {
543 e_fsub(e, diff, M[g], Mn);
544 mufu(e, BW_IR_MUFU_EX2, alpha[g], diff);
545 e_fmax(e, M[g], Mn, mc); /* M = Mn */
546 e_fsub(e, parg, s[g], Mn);
547 mufu(e, BW_IR_MUFU_EX2, pg, parg);
548 }
549 }
550 bar_sync(e); /* everyone has read the max partials before they are overwritten */
551 for (uint32_t g = 0; g < GC; g++) {
552 const int pg = GC == 1 ? p : s[g];
553 if (g == 0) sts32(e, sOff, pg);
554 else { imadi(e, tsh, c1, g * HB, sOff); sts32(e, tsh, pg); }
555 shfl_down(e, t, pg, steps[0]); e_fadd(e, sw, pg, t);
556 for (int i = 1; i < 5; i++) { shfl_down(e, t, sw, steps[i]); e_fadd(e, sw, sw, t); }
557 if (g == 0) sts32(e, rOff, sw);
558 else { imadi(e, tsh, c1, g * HB, rOff); sts32(e, tsh, sw); }
559 }
560 bar_sync(e);
561 for (uint32_t g = 0; g < GC; g++) {
562 if (g == 0) { lds32(e, ra, c768); lds32(e, rb, c896); }
563 else { imadi(e, tsh, c1, g * HB, c768); lds32(e, ra, tsh); imadi(e, tsh, c1, g * HB, c896); lds32(e, rb, tsh); }
564 e_fadd(e, lc, ra, rb);
565 if (HD == 128) {
566 if (g == 0) { lds32(e, rc_, c1024); lds32(e, rd_, c1152); }
567 else { imadi(e, tsh, c1, g * HB, c1024); lds32(e, rc_, tsh); imadi(e, tsh, c1, g * HB, c1152); lds32(e, rd_, tsh); }
568 e_fadd(e, lc, lc, rc_); e_fadd(e, lc, lc, rd_);
569 }
570 e_ffma(e, L[g], L[g], alpha[g], lc);
571 if (k->mutant != OMEGA_GPU_ATTN_MUTANT_NO_RESCALE) e_fmul(e, acc[g], acc[g], alpha[g]);
572 }
573
574 /* phase B (batched, 2026-10-12): dimension tid over the chunk's tokens, AT_TOK tokens per pass. The
575 * token offsets of a pass come in two 128-bit shared loads (SB_LD2, one wait), then each V address is
576 * computed into one register pair while the earlier V loads are in flight (emit_fixed_in_batch: the
577 * read barrier orders the overwrite after the load has read it) and its load issued on SB_GPR or
578 * SB_LD3; the p values follow as two more shared loads on SB_LD2; one wait for all of it. A token past
579 * ctx inside a pass has p = 0 and the offset of a real token (phase A), so it adds exactly 0.
580 * GC > 1: one V load per token feeds every head's accumulator from that head's p slice (cut K). */
581 enum { AT_TOK = 8 };
582 int kk = V(e), tt = V(e), oa = V(e), pa = V(e), ko4[2], pv4[2], va = V64(e), v[AT_TOK];
583 for (int i = 0; i < 2; i++) { ko4[i] = V128(e); pv4[i] = V128(e); }
584 for (int i = 0; i < AT_TOK; i++) v[i] = V(e);
585 movrz(e, kk);
586 loop_begin(e);
587 int LB = here(e);
588 iadd3(e, tt, base, kk);
589 isetp_ge_u32(e, tt, lim);
590 int bB = bra_fwd_if_p0(e);
591 imadi(e, oa, kk, 4, c512);
592 imadi(e, pa, kk, 4, c256);
593 for (int i = 0; i < 2; i++) lds128_b(e, ko4[i], oa, (uint32_t)i * 16u, SB_LD2);
594 for (int i = 0; i < AT_TOK; i++) {
595 if (i == 0) wide_s(e, va, ko4[0], 0, 1, vb); /* ordinary: waits for the offsets */
596 else wide_s_b(e, va, ko4[i / 4], i % 4, 1, vb);
597 uint32_t sb = (i < AT_TOK / 2) ? SB_GPR : SB_LD3;
598 if (k->f32) ldg_b(e, v[i], va, udesc, sb); else ldg16_b(e, v[i], va, udesc, sb);
599 }
600 if (GC == 1) {
601 for (int i = 0; i < 2; i++) lds128_b(e, pv4[i], pa, (uint32_t)i * 16u, SB_LD2);
602 for (int i = 0; i < AT_TOK; i++) {
603 if (!k->f32) imadi(e, v[i], v[i], 0x10000u, NOREG);
604 e_ffma_s(e, acc[0], pv4[i / 4], i % 4, v[i], 0, acc[0]);
605 }
606 } else {
607 if (!k->f32) for (int i = 0; i < AT_TOK; i++) imadi(e, v[i], v[i], 0x10000u, NOREG);
608 for (uint32_t g = 0; g < GC; g++) {
609 for (int i = 0; i < 2; i++) lds128_b(e, pv4[i], pa, g * HB + (uint32_t)i * 16u, SB_LD2);
610 for (int i = 0; i < AT_TOK; i++) e_ffma_s(e, acc[g], pv4[i / 4], i % 4, v[i], 0, acc[g]);
611 }
612 }
613 imadi(e, kk, c1, AT_TOK, kk);
614 isetp_ge_u32(e, kk, c64);
615 bra_back_if_not_p0(e, LB);
616 loop_end(e);
617 patch_fwd(e, bB);
618 bar_sync(e); /* phase B reads of s/p and offsets finish before the next chunk writes them */
619 iadd3(e, base, base, c64);
620 isetp_ge_u32(e, base, lim);
621 bra_back_if_not_p0(e, Lout);
622 loop_end(e);
623
624 patch_fwd(e, bZ);
625 if (part && GC == 1) {
626 /* partial row (seq * nqh + out head) * S + split: acc[HD] unnormalised, then M and L at words HD and HD + 1
627 * (every lane stores the same CTA-wide M and L). Everything is re-derived here from the CTA ids and the
628 * constant bank so no extra value lives across the chunk loop (the hd 128 kernel sits at the register budget). */
629 int cy = V(e), sq = V(e), sp = V(e), hh = V(e), nq_ = V(e), t4 = V(e), prow = V(e), poff = V(e);
630 int paddr = V64(e), maddr = V64(e), laddr = V64(e), Cp = V64(e);
631 s2r(e, cy, BW_SR_CTAID_Y); s2r(e, hh, BW_SR_CTAID_X); ldc32(e, nq_, ARG_NQH); ldc64(e, Cp, ARG_OUT);
632 if (k->mutant == OMEGA_GPU_ATTN_MUTANT_OUT_ROW) lop3xor(e, hh, hh, c1);
633 if (LS) { lop3andi(e, sp, cy, S - 1u); shri(e, sq, cy, LS); } else { movrz(e, sp); iadd3(e, sq, cy, zero); }
634 imadr(e, prow, sq, nq_, hh);
635 imadi(e, prow, prow, S, sp);
636 imadi(e, t4, tid, 4, NOREG);
637 imadi(e, poff, prow, (HD + 2u) * 4u, t4);
638 wide(e, paddr, poff, 1, Cp);
639 stg(e, paddr, acc[0], udesc);
640 imadi(e, poff, prow, (HD + 2u) * 4u, NOREG);
641 wide(e, maddr, poff, 1, Cp);
642 wide(e, maddr, c64, 4, maddr);
643 stg(e, maddr, M[0], udesc);
644 wide(e, laddr, c1, 4, maddr);
645 stg(e, laddr, L[0], udesc);
646 } else if (part) {
647 /* GC heads: row (seq * nqh + h * GC + g) * S + split for head g (OUT_ROW: g ^ 1 on the output side) */
648 int cy = V(e), sq = V(e), sp = V(e), h0 = V(e), hg = V(e), nq_ = V(e), t4 = V(e), prow = V(e), poff = V(e);
649 int paddr = V64(e), maddr = V64(e), laddr = V64(e), Cp = V64(e);
650 s2r(e, cy, BW_SR_CTAID_Y); s2r(e, h0, BW_SR_CTAID_X); ldc32(e, nq_, ARG_NQH); ldc64(e, Cp, ARG_OUT);
651 imadi(e, h0, h0, GC, NOREG);
652 if (LS) { lop3andi(e, sp, cy, S - 1u); shri(e, sq, cy, LS); } else { movrz(e, sp); iadd3(e, sq, cy, zero); }
653 imadi(e, t4, tid, 4, NOREG);
654 for (uint32_t g = 0; g < GC; g++) {
655 imadi(e, hg, c1, g, h0);
656 if (k->mutant == OMEGA_GPU_ATTN_MUTANT_OUT_ROW) lop3xor(e, hg, hg, c1);
657 imadr(e, prow, sq, nq_, hg);
658 imadi(e, prow, prow, S, sp);
659 imadi(e, poff, prow, (HD + 2u) * 4u, t4);
660 wide(e, paddr, poff, 1, Cp);
661 stg(e, paddr, acc[g], udesc);
662 imadi(e, poff, prow, (HD + 2u) * 4u, NOREG);
663 wide(e, maddr, poff, 1, Cp);
664 wide(e, maddr, c64, 4, maddr);
665 stg(e, maddr, M[g], udesc);
666 wide(e, laddr, c1, 4, maddr);
667 stg(e, laddr, L[g], udesc);
668 }
669 } else if (GC == 1) {
670 int inv = V(e), o = V(e);
671 mufu(e, BW_IR_MUFU_RCP, inv, L[0]);
672 e_fmul(e, o, acc[0], inv);
673 stg(e, oaddr, o, udesc);
674 } else {
675 /* direct output, GC heads: row seq * nqh + h * GC + g (OUT_ROW: g ^ 1), re-derived from the CTA ids */
676 int inv = V(e), o = V(e), cy = V(e), h0 = V(e), hg = V(e), nq_ = V(e), t4 = V(e), orow = V(e), ooff = V(e);
677 int oa64 = V64(e), Cp = V64(e);
678 s2r(e, cy, BW_SR_CTAID_Y); s2r(e, h0, BW_SR_CTAID_X); ldc32(e, nq_, ARG_NQH); ldc64(e, Cp, ARG_OUT);
679 imadi(e, h0, h0, GC, NOREG);
680 imadi(e, t4, tid, 4, NOREG);
681 for (uint32_t g = 0; g < GC; g++) {
682 imadi(e, hg, c1, g, h0);
683 if (k->mutant == OMEGA_GPU_ATTN_MUTANT_OUT_ROW) lop3xor(e, hg, hg, c1);
684 imadr(e, orow, cy, nq_, hg);
685 imadi(e, ooff, orow, HD * 4, t4);
686 wide(e, oa64, ooff, 1, Cp);
687 mufu(e, BW_IR_MUFU_RCP, inv, L[g]);
688 e_fmul(e, o, acc[g], inv);
689 stg(e, oa64, o, udesc);
690 }
691 }
692 tail(e);
693}
694
695#define AT_GPR_BUDGET 96u /* cut K: the GQA-group hd 128 kernel carries four heads of running state (the matmul blocked kernels launch at 108) */
696
697static int build_kernel(const KSpec *k, OmegaBlackwellKernel *kernel, BlackwellIRProgram **keep) {
698 BlackwellIRProgram *prog = omega_gpu_host_calloc(1, sizeof *prog);
699 if (!prog) return OMEGA_GPU_ATTN_CODEGEN_FAIL;
700 omega_bw_ir_init(prog);
701 Em e; memset(&e, 0, sizeof e); e.p = prog;
702 e.rg_mutant = (k->divergent == 2) ? 1 : 0;
703 gen_attention(&e, k);
704 if (e.depth != 0) e.err = -1;
705 if (e.rg.depth != 0) e.err = -1; /* a region left open has no join: refuse the build */
706 int rc = OMEGA_GPU_ATTN_CODEGEN_FAIL;
707 int ra_rc = (e.err == 0) ? omega_bw_regalloc_solve(prog) : -1;
708 int loop_rc = (ra_rc == 0) ? check_loop_invariant(&e) : -1;
709#ifdef OMEGA_ATTN_DEBUG
710 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",
711 (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);
712#endif
713 if (e.err == 0 && ra_rc == 0 && loop_rc == 0 && prog->regalloc.peak_gpr_usage <= AT_GPR_BUDGET) {
714 size_t max_bytes = (size_t)BW_MAX_IR_INSNS * 16;
715 memset(kernel, 0, sizeof *kernel);
716 kernel->code = omega_gpu_host_alloc(max_bytes);
717 size_t emitted = 0;
718 if (kernel->code && omega_bw_encode_program(prog, kernel->code, max_bytes, &emitted) == 0) {
719 kernel->code_size = emitted;
720 kernel->insn_count = emitted / 16;
721 kernel->gpr_count = prog->regalloc.peak_gpr_usage;
722 kernel->uniform_gpr_count = prog->regalloc.peak_ugpr_usage;
723 sha256_hash(kernel->code, kernel->code_size, kernel->code_digest);
724 rc = OMEGA_GPU_ATTN_OK;
725 } else {
726 omega_gpu_host_free(kernel->code); kernel->code = NULL;
727 }
728 }
729 if (keep && rc == OMEGA_GPU_ATTN_OK) *keep = prog; else omega_gpu_host_free(prog);
730 return rc;
731}
732
733/* --------------------------------------------------------- kernel cache */
734
735/* One kernel per KSpec; the device copy is uploaded once and stays resident for
736 * the process (cut 4b). The IR program is kept for the host simulator. */
737static int g_mutant;
738static int g_divergent; /* omega #308 R2 test hook: see KSpec.divergent */
739static bool g_dedupe = true; /* shared-prefix staging dedupe; false = legacy per-sequence staging (test hook) */
740typedef struct { int used; KSpec k; OmegaBlackwellKernel kernel; BlackwellIRProgram *prog; OmegaGpuMem code; } Slot;
741static OmegaGpuAttnSim g_sim;
742static Slot g_cache[16]; /* split variants (cut F) multiply the shapes in flight */
743static int g_split = -1; /* test hook: forced log2split (0..OMEGA_GPU_ATTN_MAX_LOG2SPLIT), -1 = chosen per launch from the context */
744static OmegaGpuScratch g_q, g_pool, g_tab, g_out; /* staging, grown to the high-water mark, reused per call */
745static OmegaGpuMem g_resident; /* the resident KV pool (omega_gpu_attention_pool_alloc); cpu NULL = none */
746static bool g_hooked;
747#define LOCK() omega_gpu_session_lock()
748#define UNLOCK() omega_gpu_session_unlock()
749
750void omega_gpu_attention_test_set_simulator(OmegaGpuAttnSim sim) { LOCK(); g_sim = sim; UNLOCK(); }
751static uint32_t g_sim_shared_bytes; /* shared bytes the launcher would declare for the kernel the simulator is running */
752uint32_t omega_gpu_attention_test_shared_bytes(void) { return g_sim_shared_bytes; }
753void omega_gpu_attention_test_set_dedupe(bool on) { LOCK(); g_dedupe = on; UNLOCK(); }
754void omega_gpu_attention_test_set_split(int log2split) { LOCK(); g_split = (log2split >= 0 && log2split <= (int)OMEGA_GPU_ATTN_MAX_LOG2SPLIT) ? log2split : -1; UNLOCK(); }
755
756/* ---- resident KV pool (see the header) ---- */
757
758static int dev_open_locked(void);
759
760/* The kernel computes block_id * block_stride + slot * token_stride + head offset in 32 bits before
761 * widening onto the 64-bit layer base: one layer slice (both planes, every token and head of the
762 * block) past the block's start must stay inside 32 bits. */
763static bool resident_fits(const OmegaGpuKvLayout *ly, uint32_t block_id) {
764 return ly->block_stride_bytes <= 0xffffffffull &&
765 (uint64_t)block_id * ly->block_stride_bytes + ly->layer_stride_bytes <= 0xffffffffull;
766}
767bool omega_gpu_attention_test_resident_fits(const OmegaGpuKvLayout *layout, uint32_t block_id) {
768 return layout && resident_fits(layout, block_id);
769}
770
771int omega_gpu_attention_pool_alloc(size_t bytes, void **cpu) {
772 if (!cpu || bytes == 0) return OMEGA_GPU_ATTN_BAD_ARGS;
773 *cpu = NULL;
774 LOCK();
775 if (g_resident.cpu) { omega_gpu_session_set_error("attention pool: already allocated"); UNLOCK(); return OMEGA_GPU_ATTN_BAD_ARGS; }
776 if (g_sim) {
777 g_resident.cpu = omega_gpu_host_calloc(1, bytes);
778 if (!g_resident.cpu) { UNLOCK(); return OMEGA_GPU_ATTN_CHIP_FAIL; }
779 g_resident.va = (uintptr_t)g_resident.cpu; g_resident.size = bytes;
780 } else {
781 int rc = dev_open_locked();
782 if (rc != OMEGA_GPU_ATTN_OK) { UNLOCK(); return rc; }
783 if (omega_gpu_session_alloc(bytes, &g_resident) != 0) { memset(&g_resident, 0, sizeof g_resident); UNLOCK(); return OMEGA_GPU_ATTN_CHIP_FAIL; }
784 }
785 *cpu = g_resident.cpu;
786 UNLOCK();
787 return OMEGA_GPU_ATTN_OK;
788}
789
790void omega_gpu_attention_pool_free(void) {
791 LOCK();
792 if (g_resident.cpu) { if (g_sim) omega_gpu_host_free(g_resident.cpu); else omega_gpu_session_free(&g_resident); }
793 memset(&g_resident, 0, sizeof g_resident);
794 UNLOCK();
795}
796
797static void cache_clear_locked(void) {
798 for (size_t i = 0; i < sizeof g_cache / sizeof g_cache[0]; i++)
799 if (g_cache[i].used) { omega_gpu_host_free(g_cache[i].kernel.code); omega_gpu_host_free(g_cache[i].prog); omega_gpu_session_free(&g_cache[i].code); memset(&g_cache[i], 0, sizeof g_cache[i]); }
800}
801
802void omega_gpu_attention_cache_clear(void) {
803 LOCK();
804 cache_clear_locked();
805 UNLOCK();
806}
807
808/* Called by the session (lock held, device still open) right before it closes. */
809static void on_session_close(void) {
810 cache_clear_locked();
811 memset(&g_resident, 0, sizeof g_resident); /* the session's memory goes with it; the caller's mapping is dead */
812 omega_gpu_session_scratch_free(&g_q); omega_gpu_session_scratch_free(&g_pool);
813 omega_gpu_session_scratch_free(&g_tab); omega_gpu_session_scratch_free(&g_out);
814}
815
816void omega_gpu_attention_test_set_mutant(OmegaGpuAttnMutant m) {
817 LOCK();
818 g_mutant = (int)m;
819 cache_clear_locked();
820 UNLOCK();
821}
822
823/* Caller holds the lock. Builds the kernel if needed; uploads the device copy when
824 * `upload` (the chip path; the simulator never needs one). */
825static int kernel_for(bool f32, uint32_t log2bs, uint32_t log2gqa, uint32_t hd, int split, bool upload, Slot **out, bool *hit) {
826 KSpec k = { .f32 = f32, .log2bs = log2bs, .log2gqa = log2gqa, .mutant = g_mutant, .divergent = g_divergent, .hd = hd, .split = split };
827 Slot *s = NULL;
828 for (size_t i = 0; i < sizeof g_cache / sizeof g_cache[0]; i++)
829 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 && g_cache[i].k.split == k.split) { /* field compare: memcmp would read struct padding */
830 s = &g_cache[i]; *hit = true; break;
831 }
832 if (!s) {
833 OmegaBlackwellKernel kern; BlackwellIRProgram *kp = NULL;
834 int rc = build_kernel(&k, &kern, &kp);
835 if (rc != OMEGA_GPU_ATTN_OK) return rc;
836 size_t slot = 0;
837 for (size_t i = 0; i < sizeof g_cache / sizeof g_cache[0]; i++) if (!g_cache[i].used) { slot = i; break; }
838 s = &g_cache[slot];
839 if (s->used) { omega_gpu_host_free(s->kernel.code); omega_gpu_host_free(s->prog); omega_gpu_session_free(&s->code); } /* full: evict slot 0 */
840 memset(s, 0, sizeof *s);
841 s->used = 1; s->k = k; s->kernel = kern; s->prog = kp;
842 *hit = false;
843 }
844 if (upload && !s->code.cpu) {
845 if (omega_gpu_session_alloc_code(s->kernel.code_size, &s->code) != 0) return OMEGA_GPU_ATTN_CHIP_FAIL;
846 memcpy(s->code.cpu, s->kernel.code, s->kernel.code_size);
847 if (omega_gpu_session_sync_to_gpu(&s->code) != 0) { omega_gpu_session_free(&s->code); return OMEGA_GPU_ATTN_CHIP_FAIL; }
848 }
849 *out = s;
850 return OMEGA_GPU_ATTN_OK;
851}
852
853int omega_gpu_attention_codegen_hd(bool kv_f32, uint32_t log2_block_size, uint32_t log2_gqa, uint32_t head_dim, OmegaBlackwellKernel *kernel) {
854 if (!kernel || log2_block_size > 16 || log2_gqa > 6) return OMEGA_GPU_ATTN_BAD_ARGS;
855 if (head_dim != 64u && head_dim != 128u) return OMEGA_GPU_ATTN_TOO_LARGE;
856 LOCK();
857 KSpec k = { .f32 = kv_f32, .log2bs = log2_block_size, .log2gqa = log2_gqa, .mutant = g_mutant, .divergent = g_divergent, .hd = head_dim, .split = -1 };
858 UNLOCK();
859 return build_kernel(&k, kernel, NULL);
860}
861
862int omega_gpu_attention_codegen(bool kv_f32, uint32_t log2_block_size, uint32_t log2_gqa, OmegaBlackwellKernel *kernel) {
863 return omega_gpu_attention_codegen_hd(kv_f32, log2_block_size, log2_gqa, OMEGA_GPU_ATTN_HEAD_DIM, kernel);
864}
865
866const char *omega_gpu_attention_last_error(void) { return omega_gpu_session_last_error(); }
867
868/* ------------------------------------------------------------ launcher */
869
870#define AT_POISON 0xffbadbadu
871#define AT_WAIT_MS 600000ull
872
873static uint64_t now_ns(void) { return omega_gpu_session_now_ns(); } /* the platform clock (CLOCK_NS) */
874
875typedef OmegaGpuAttnLaunch Launch;
876
877/* Caller holds the lock. Chip path: open the shared device on first use. */
878static int dev_open_locked(void) {
879 if (!g_hooked) { (void)omega_gpu_session_on_close(on_session_close); g_hooked = true; }
880 return omega_gpu_session_open() ? OMEGA_GPU_ATTN_OK : OMEGA_GPU_ATTN_CHIP_FAIL;
881}
882
883/* Where a call stages the KV slice it is about to hand the kernel: straight into the
884 * device staging buffer on the chip path (one copy), a host buffer under the simulator.
885 * Caller holds the lock; the result is valid until the next staging call. */
886static void *stage_target(size_t bytes, void **host_tmp, int *fail_rc) {
887 *host_tmp = NULL;
888 *fail_rc = OMEGA_GPU_ATTN_CHIP_FAIL;
889 if (g_sim) { *host_tmp = omega_gpu_host_alloc(bytes ? bytes : 1); return *host_tmp; }
890 int r = omega_gpu_session_scratch(&g_pool, bytes);
891 if (r != 0) { if (r == OMEGA_GPU_SESSION_SCRATCH_RESERVED) *fail_rc = OMEGA_GPU_ATTN_TOO_LARGE; return NULL; } /* reserved bound exceeded: loud, no allocation */
892 return g_pool.mem.cpu;
893}
894
895/* One launch through the shared session (omega_gpu_session_launch: shader-cache
896 * invalidate, constant bank, QMD0/QMD1, first marker, L2_FLUSH_DIRTY, second marker),
897 * then readback and the poison scan. L->pool may already be the pool staging buffer. */
898static int run_launch(const Slot *ks, const Launch *L, OmegaGpuAttnInfo *info) {
899 int sr = omega_gpu_session_scratch(&g_q, L->q_bytes);
900 if (!sr) sr = omega_gpu_session_scratch(&g_tab, L->tab_bytes);
901 if (!sr) sr = omega_gpu_session_scratch(&g_out, L->out_bytes);
902 if (!sr && !L->pool_va && L->pool != g_pool.mem.cpu) sr = omega_gpu_session_scratch(&g_pool, L->pool_bytes);
903 if (sr) return sr == OMEGA_GPU_SESSION_SCRATCH_RESERVED ? OMEGA_GPU_ATTN_TOO_LARGE : OMEGA_GPU_ATTN_CHIP_FAIL;
904 memcpy(g_q.mem.cpu, L->q, L->q_bytes);
905 if (!L->pool_va && L->pool != g_pool.mem.cpu) memcpy(g_pool.mem.cpu, L->pool, L->pool_bytes);
906 const uint64_t pool_va = L->pool_va ? L->pool_va : g_pool.mem.va; /* resident: the caller's KV, read in place */
907 memcpy(g_tab.mem.cpu, L->tab, L->tab_bytes);
908 size_t out_words = L->out_bytes / 4;
909 uint32_t *out_dev = (uint32_t *)g_out.mem.cpu;
910 for (size_t i = 0; i < out_words; i++) out_dev[i] = AT_POISON;
911 /* the KV this launch reads: the staged pool, or the resident pool the caller wrote in place */
912 if (omega_gpu_session_sync_to_gpu(&g_q.mem) != 0 || omega_gpu_session_sync_to_gpu(&g_tab.mem) != 0 ||
913 omega_gpu_session_sync_to_gpu(&g_out.mem) != 0 || omega_gpu_session_sync_to_gpu(L->pool_va ? &g_resident : &g_pool.mem) != 0)
914 return OMEGA_GPU_ATTN_CHIP_FAIL;
915
916 uint32_t args[ARG_WORDS];
917 args[0] = (uint32_t)g_q.mem.va; args[1] = (uint32_t)(g_q.mem.va >> 32);
918 args[2] = (uint32_t)pool_va; args[3] = (uint32_t)(pool_va >> 32);
919 args[4] = (uint32_t)g_out.mem.va; args[5] = (uint32_t)(g_out.mem.va >> 32);
920 args[6] = (uint32_t)g_tab.mem.va; args[7] = (uint32_t)(g_tab.mem.va >> 32);
921 memcpy(&args[8], L->params, sizeof L->params);
922 OmegaGpuLaunch GL = {
923 .code_va = ks->code.va, .gpr_count = AT_GPR_BUDGET, .threads_x = ks->k.hd, .threads_y = 1, .shared_bytes = shared_bytes_for(ks->k.hd, ks->k.log2gqa), /* (3 GC + 1) arrays of hd words: 1024 B for hd 64, 2048 B for hd 128 gqa 1, 6656 B for hd 128 gqa 4 */
924 .grid_x = L->grid_x, .grid_y = L->grid_y, .num_elements = out_words,
925 .args = args, .n_args = ARG_WORDS, .timeout_ms = AT_WAIT_MS,
926 };
927 uint64_t elapsed = 0; uint32_t marker = 0;
928 if (omega_gpu_session_launch(&GL, &elapsed, &marker) != 0) return OMEGA_GPU_ATTN_CHIP_FAIL;
929 if (omega_gpu_session_sync_to_cpu(&g_out.mem) != 0) return OMEGA_GPU_ATTN_CHIP_FAIL;
930
931 memcpy(L->out, g_out.mem.cpu, L->out_bytes);
932 uint32_t unwritten = 0;
933 for (size_t i = 0; i < out_words; i++) if (((uint32_t *)L->out)[i] == AT_POISON) unwritten++;
934 if (info) {
935 info->chip_calls++;
936 info->elapsed_ns += elapsed;
937 info->completion_marker = marker;
938 info->unwritten_words += unwritten;
939 info->threads_per_cta = ks->k.hd;
940 info->ctas_last_launch = L->grid_x * L->grid_y;
941 }
942 return unwritten ? OMEGA_GPU_ATTN_UNWRITTEN : OMEGA_GPU_ATTN_OK;
943}
944
945/* Caller holds the lock. Accounts the launch's q / table / output traffic (the KV
946 * staging bytes are accounted where the slices are copied). */
947static int launch(const Slot *ks, const Launch *L, OmegaGpuAttnInfo *info) {
948 if (info) {
949 info->q_bytes += L->q_bytes; info->tab_bytes += L->tab_bytes; info->out_bytes += L->out_bytes;
950 info->kv_source = L->pool_va ? OMEGA_GPU_ATTN_KV_RESIDENT : OMEGA_GPU_ATTN_KV_STAGED;
951 }
952 if (g_sim) { g_sim_shared_bytes = shared_bytes_for(ks->k.hd, ks->k.log2gqa); return g_sim(ks->prog, L, info); }
953 return run_launch(ks, L, info);
954}
955
956/* ---- opt-in serving reservation (see the header) ---- */
957
958static int check_heads(uint32_t num_q_heads, uint32_t num_kv_heads, uint32_t head_dim, uint32_t *log2gqa);
959static int log2_exact(uint32_t v, uint32_t *out);
960
961int omega_gpu_attention_reserve(uint32_t max_context, uint32_t max_seqs, uint32_t num_q_heads, uint32_t num_kv_heads, uint32_t head_dim, uint32_t kv_block_size) {
962 uint32_t log2gqa, log2bs;
963 if (max_context == 0 || max_seqs == 0) { omega_gpu_session_set_error("attention reserve: zero bound"); return OMEGA_GPU_ATTN_BAD_ARGS; }
964 if (kv_block_size && log2_exact(kv_block_size, &log2bs) != 0) { omega_gpu_session_set_error("attention reserve: block size not a power of two"); return OMEGA_GPU_ATTN_BAD_ARGS; }
965 int rc = check_heads(num_q_heads, num_kv_heads, head_dim, &log2gqa);
966 if (rc != OMEGA_GPU_ATTN_OK) { omega_gpu_session_set_error("attention reserve: bad head shape"); return rc; }
967 /* KV staging, worst case over the two paths, per sequence: contiguous f32 holds both planes for max_context tokens
968 * (2 * ctx * kvh * hd * 4); paged bf16 stages whole blocks of both planes (round_up(ctx, block) * kvh * hd * 4), which
969 * is the larger one when max_context is under half a block. */
970 size_t per_seq = 2u * max_context * (size_t)num_kv_heads * head_dim * 4u;
971 if (kv_block_size) {
972 size_t paged = ((size_t)max_context + kv_block_size - 1) / kv_block_size * kv_block_size * num_kv_heads * head_dim * 4u;
973 if (paged > per_seq) per_seq = paged;
974 }
975 const size_t pool = per_seq * max_seqs;
976 /* q rows for every sequence, and the output buffer sized for the paged path's partials of one launch
977 * (cut J: up to 2^MAX_LOG2SPLIT partials of head_dim + 2 words per (sequence, head), at most
978 * MAX_CTAS / num_q_heads sequences per launch; the rows reserve usually asks for more). */
979 const size_t q_bytes = (size_t)max_seqs * num_q_heads * head_dim * 4u;
980 size_t launch_seqs = OMEGA_GPU_ATTN_MAX_CTAS / num_q_heads;
981 if (launch_seqs == 0) launch_seqs = 1;
982 if (launch_seqs > max_seqs) launch_seqs = max_seqs;
983 const size_t partials = launch_seqs * num_q_heads * ((size_t)1u << OMEGA_GPU_ATTN_MAX_LOG2SPLIT) * ((size_t)head_dim + 2u) * 4u;
984 const size_t qo = q_bytes > partials ? q_bytes : partials;
985 const size_t tab = ((size_t)max_seqs * max_context + max_seqs) * 4u;
986 LOCK();
987 rc = OMEGA_GPU_ATTN_OK;
988 if (g_sim) rc = OMEGA_GPU_ATTN_OK; /* the simulator stages in host memory: nothing to reserve */
989 else if (dev_open_locked() != OMEGA_GPU_ATTN_OK) rc = OMEGA_GPU_ATTN_CHIP_FAIL;
990 else if (omega_gpu_session_scratch_reserve(&g_pool, pool) || omega_gpu_session_scratch_reserve(&g_q, q_bytes) ||
991 omega_gpu_session_scratch_reserve(&g_out, qo) || omega_gpu_session_scratch_reserve(&g_tab, tab < 8 ? 8 : tab)) {
992 /* roll back this API's own buffers: a failed reserve leaves nothing flagged (growth allowed as before) */
993 omega_gpu_session_scratch_unreserve(&g_pool); omega_gpu_session_scratch_unreserve(&g_q);
994 omega_gpu_session_scratch_unreserve(&g_out); omega_gpu_session_scratch_unreserve(&g_tab);
995 rc = OMEGA_GPU_ATTN_CHIP_FAIL;
996 }
997 UNLOCK();
998 return rc;
999}
1000
1001int omega_gpu_attention_reserve_rows(uint32_t max_rows, uint32_t num_q_heads, uint32_t head_dim) {
1002 if (max_rows == 0 || num_q_heads == 0 || num_q_heads > OMEGA_GPU_ATTN_MAX_Q_HEADS || (head_dim != 64u && head_dim != 128u)) {
1003 omega_gpu_session_set_error("attention reserve rows: bad bound");
1004 return OMEGA_GPU_ATTN_BAD_ARGS;
1005 }
1006 uint32_t per = OMEGA_GPU_ATTN_ROWS_MAX_CTAS / num_q_heads;
1007 if (per == 0) per = 1;
1008 if (per > max_rows) per = max_rows;
1009 const size_t qo = (size_t)per * num_q_heads * head_dim * 4u, tab = (size_t)per * 8u;
1010 LOCK();
1011 int rc = OMEGA_GPU_ATTN_OK;
1012 if (g_sim) rc = OMEGA_GPU_ATTN_OK;
1013 else if (dev_open_locked() != OMEGA_GPU_ATTN_OK) rc = OMEGA_GPU_ATTN_CHIP_FAIL;
1014 else if ((qo > g_q.cap && omega_gpu_session_scratch_reserve(&g_q, qo)) ||
1015 (qo > g_out.cap && omega_gpu_session_scratch_reserve(&g_out, qo)) ||
1016 (tab > g_tab.cap && omega_gpu_session_scratch_reserve(&g_tab, tab)))
1017 rc = OMEGA_GPU_ATTN_CHIP_FAIL; /* growth failed; whatever grew stays reserved at its larger size */
1018 UNLOCK();
1019 return rc;
1020}
1021void omega_gpu_attention_unreserve(void) {
1022 LOCK();
1023 omega_gpu_session_scratch_unreserve(&g_pool); omega_gpu_session_scratch_unreserve(&g_q);
1024 omega_gpu_session_scratch_unreserve(&g_out); omega_gpu_session_scratch_unreserve(&g_tab);
1025 UNLOCK();
1026}
1027
1028/* ------------------------------------------------------- public entries */
1029
1030static void info_begin(OmegaGpuAttnInfo *info, const OmegaBlackwellKernel *k, bool hit) {
1031 if (!info) return;
1032 memset(info, 0, sizeof *info);
1033 info->kernel_cache_hit = hit;
1034 info->gpr_count = k->gpr_count;
1035 info->insn_count = (uint32_t)k->insn_count;
1036 omega_gpu_fmt(info->target_chip, sizeof info->target_chip, "NVIDIA DGX Spark (Grace Blackwell GB10)");
1037 info->sm_architecture = 121;
1038}
1039static uint32_t f2u(float f) { uint32_t u; memcpy(&u, &f, 4); return u; }
1040static int log2_exact(uint32_t v, uint32_t *out) {
1041 if (v == 0 || (v & (v - 1))) return -1;
1042 uint32_t l = 0; while ((1u << l) != v) l++;
1043 *out = l; return 0;
1044}
1045/* log2(e) / sqrt(head_dim) with the square roots as literals (8 and 11.313708498984761 = sqrt(128), both exactly what sqrt() returns):
1046 * the library must not need libm (omegatool links without -lm; a constant head_dim folded sqrt away, a runtime one does not). */
1047static float score_scale(uint32_t hd) { return (float)(1.4426950408889634 / (hd == 128u ? 11.313708498984761 : 8.0)); }
1048
1049/* Common head-shape checks; returns log2 of the gqa ratio. */
1050static int check_heads(uint32_t num_q_heads, uint32_t num_kv_heads, uint32_t head_dim, uint32_t *log2gqa) {
1051 if (num_q_heads == 0 || num_kv_heads == 0 || head_dim == 0) return OMEGA_GPU_ATTN_BAD_ARGS;
1052 if ((head_dim != 64u && head_dim != 128u) || num_q_heads > OMEGA_GPU_ATTN_MAX_Q_HEADS) return OMEGA_GPU_ATTN_TOO_LARGE;
1053 if (num_q_heads % num_kv_heads != 0 || log2_exact(num_q_heads / num_kv_heads, log2gqa) != 0) return OMEGA_GPU_ATTN_BAD_ARGS;
1054 return OMEGA_GPU_ATTN_OK;
1055}
1056
1057/* Common prologue of every chip entry (lock held on success): device, kernel, info. */
1058static int begin(bool f32, uint32_t log2bs, uint32_t log2gqa, uint32_t hd, int split, Slot **ks, OmegaGpuAttnInfo *info) {
1059 LOCK();
1060 int rc = g_sim ? OMEGA_GPU_ATTN_OK : dev_open_locked();
1061 bool hit = false;
1062 if (rc == OMEGA_GPU_ATTN_OK) rc = kernel_for(f32, log2bs, log2gqa, hd, split, !g_sim, ks, &hit);
1063 if (rc != OMEGA_GPU_ATTN_OK) { UNLOCK(); return rc; }
1064 info_begin(info, &(*ks)->kernel, hit);
1065 return OMEGA_GPU_ATTN_OK;
1066}
1067
1068int omega_gpu_gqa_attention_f32(const float *q, const float *k_cache, const float *v_cache,
1069 uint32_t seq_len, uint32_t num_q_heads, uint32_t num_kv_heads,
1070 uint32_t head_dim, float *out, OmegaGpuAttnInfo *info) {
1071 uint64_t t0 = now_ns();
1072 if (!q || !k_cache || !v_cache || !out) return OMEGA_GPU_ATTN_BAD_ARGS;
1073 uint32_t log2gqa;
1074 int rc = check_heads(num_q_heads, num_kv_heads, head_dim, &log2gqa);
1075 if (rc != OMEGA_GPU_ATTN_OK) return rc;
1076 if (seq_len > OMEGA_GPU_ATTN_MAX_GQA_CTX) return OMEGA_GPU_ATTN_TOO_LARGE;
1077 const uint32_t HD = head_dim;
1078 size_t n_out = (size_t)num_q_heads * HD;
1079 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; }
1080 Slot *ks = NULL;
1081 const uint32_t log2bs = 12; /* one block of 4096 slots */
1082 rc = begin(true, log2bs, log2gqa, HD, -1, &ks, info);
1083 if (rc != OMEGA_GPU_ATTN_OK) return rc;
1084 size_t plane = (size_t)seq_len * num_kv_heads * HD * 4;
1085 void *host_tmp = NULL;
1086 int stage_rc;
1087 uint8_t *pool = stage_target(2 * plane, &host_tmp, &stage_rc);
1088 if (!pool) { UNLOCK(); return stage_rc; }
1089 memcpy(pool, k_cache, plane);
1090 memcpy(pool + plane, v_cache, plane);
1091 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 */
1092 uint32_t tab[2] = { 0, seq_len }; /* table row {0}, then the context length at byte 4 */
1093 Launch L = {
1094 .q = q, .q_bytes = n_out * 4, .pool = pool, .pool_bytes = 2 * plane, .tab = tab, .tab_bytes = sizeof tab,
1095 .out = out, .out_bytes = n_out * 4, .grid_x = num_q_heads / heads_per_cta(HD, log2gqa), .grid_y = 1,
1096 .params = { 1, f2u(score_scale(HD)), (uint32_t)(2 * plane), num_kv_heads * HD * 4, (uint32_t)plane, HD * 4, num_q_heads, 4 }
1097 };
1098 rc = launch(ks, &L, info);
1099 omega_gpu_host_free(host_tmp);
1100 UNLOCK();
1101 if (info) info->call_ns = now_ns() - t0;
1102 return rc;
1103}
1104
1105/* Rows per launch of the rows path: the CTA bound, then (under a reservation) what the q buffer holds. Caller holds the lock. */
1106static uint32_t rows_per_launch(uint32_t num_rows, uint32_t num_q_heads, size_t row_bytes) {
1107 uint32_t per = OMEGA_GPU_ATTN_ROWS_MAX_CTAS / num_q_heads;
1108 if (per == 0) per = 1;
1109 if (per > num_rows) per = num_rows;
1110 if (!g_sim && g_q.reserved && g_q.cap >= row_bytes) {
1111 size_t fit = g_q.cap / row_bytes;
1112 if (fit < per) per = (uint32_t)fit;
1113 }
1114 return per;
1115}
1116
1117int omega_gpu_gqa_attention_rows_f32(const float *q, const float *k_cache, const float *v_cache,
1118 uint32_t base_len, uint32_t num_rows, uint32_t num_q_heads,
1119 uint32_t num_kv_heads, uint32_t head_dim, float *out, OmegaGpuAttnInfo *info) {
1120 uint64_t t0 = now_ns();
1121 if (!q || !k_cache || !v_cache || !out || num_rows == 0) return OMEGA_GPU_ATTN_BAD_ARGS;
1122 uint32_t log2gqa;
1123 int rc = check_heads(num_q_heads, num_kv_heads, head_dim, &log2gqa);
1124 if (rc != OMEGA_GPU_ATTN_OK) return rc;
1125 if ((uint64_t)base_len + num_rows > OMEGA_GPU_ATTN_MAX_GQA_CTX) return OMEGA_GPU_ATTN_TOO_LARGE;
1126 const uint32_t HD = head_dim, total = base_len + num_rows;
1127 const size_t row = (size_t)num_q_heads * HD;
1128 Slot *ks = NULL;
1129 const uint32_t log2bs = 12; /* one block of 4096 slots, as the single-row call */
1130 rc = begin(true, log2bs, log2gqa, HD, -1, &ks, info);
1131 if (rc != OMEGA_GPU_ATTN_OK) return rc;
1132 /* the whole context (every row's keys are a prefix of it) staged once */
1133 size_t plane = (size_t)total * num_kv_heads * HD * 4;
1134 void *host_tmp = NULL;
1135 int stage_rc;
1136 uint8_t *pool = stage_target(2 * plane, &host_tmp, &stage_rc);
1137 if (!pool) { UNLOCK(); return stage_rc; }
1138 memcpy(pool, k_cache, plane);
1139 memcpy(pool + plane, v_cache, plane);
1140 if (info) { info->kv_bytes_staged += 2 * plane; info->kv_bytes_naive += (uint64_t)num_rows * 2 * plane; info->kv_blocks_logical += num_rows; info->kv_blocks_unique += 1; }
1141 const uint32_t per = rows_per_launch(num_rows, num_q_heads, row * 4);
1142 /* table of one launch: per block ids (all 0: the one staged block), then per context lengths */
1143 uint32_t *tab = omega_gpu_host_calloc(2 * (size_t)per, sizeof *tab);
1144 if (!tab) { omega_gpu_host_free(host_tmp); UNLOCK(); return OMEGA_GPU_ATTN_CHIP_FAIL; }
1145 for (uint32_t r0 = 0; r0 < num_rows && rc == OMEGA_GPU_ATTN_OK; r0 += per) {
1146 const uint32_t nr = num_rows - r0 < per ? num_rows - r0 : per;
1147 for (uint32_t i = 0; i < nr; i++) { tab[i] = 0; tab[nr + i] = base_len + r0 + i + 1; }
1148 Launch L = {
1149 .q = q + (size_t)r0 * row, .q_bytes = (size_t)nr * row * 4, .pool = pool, .pool_bytes = 2 * plane,
1150 .tab = tab, .tab_bytes = (size_t)2 * nr * 4, .out = out + (size_t)r0 * row, .out_bytes = (size_t)nr * row * 4,
1151 .grid_x = num_q_heads / heads_per_cta(HD, log2gqa), .grid_y = nr,
1152 .params = { 1, f2u(score_scale(HD)), (uint32_t)(2 * plane), num_kv_heads * HD * 4, (uint32_t)plane, HD * 4, num_q_heads, nr * 4 }
1153 };
1154 rc = launch(ks, &L, info);
1155 }
1156 omega_gpu_host_free(tab);
1157 omega_gpu_host_free(host_tmp);
1158 UNLOCK();
1159 if (info) info->call_ns = now_ns() - t0;
1160 return rc;
1161}
1162
1163/* Paged path shared by the single and batched entries. tables[s] has n_blocks[s] entries
1164 * (already filtered of negatives), ctx[s] the context length. */
1165/* cut F: a sequence's own split count from its context alone (the kernel computes the same): log2 of the largest
1166 * power of two <= min(2^MAX_LOG2SPLIT, chunks), chunks = ceil(ctx / HD) (cut J: one whole chunk per split; cut F took two). */
1167static uint32_t own_log2split(uint32_t ctx, uint32_t HD) {
1168 uint32_t x = (ctx + HD - 1) / HD, l = 0;
1169 while (l < OMEGA_GPU_ATTN_MAX_LOG2SPLIT && (2u << l) <= x) l++;
1170 return l;
1171}
1172
1173/* 2^x in float without the math library (the engine archive also links where there is none): round x to the
1174 * nearest integer n, 2^f on f in [-0.5, 0.5] by the Cephes exp2f polynomial, scale by 2^n through the exponent
1175 * bits. x <= -127 (so also -inf, an empty split) is 0. The combine only passes x <= 0. */
1176static float host_exp2(float x) {
1177 if (x <= -127.0f) return 0.0f;
1178 if (x > 127.0f) x = 127.0f;
1179 int n = (int)(x + (x < 0.0f ? -0.5f : 0.5f));
1180 const float f = x - (float)n;
1181 float px = 1.535336188319500e-4f;
1182 px = px * f + 1.339887440266574e-3f;
1183 px = px * f + 9.618437357674640e-3f;
1184 px = px * f + 5.550332471162809e-2f;
1185 px = px * f + 2.402264791363012e-1f;
1186 px = px * f + 6.931472028550421e-1f;
1187 px = 1.0f + f * px;
1188 if (n < -126) { px *= 0.5f; n = -126; }
1189 union { uint32_t u; float f; } sc;
1190 sc.u = (uint32_t)(n + 127) << 23;
1191 return px * sc.f;
1192}
1193
1194/* cut F: fold the per-split partials of each (sequence, head) row into out. w_s = 2^(M_s - max M): the kernel's
1195 * running max and sum live in the log2 domain (scale carries log2 e, MUFU.EX2). A row whose every split is empty
1196 * (context 0) is 0. */
1197static void combine_splits(const float *part, float *out, size_t rows, uint32_t S, uint32_t HD) {
1198 const size_t pw = (size_t)HD + 2;
1199 for (size_t r = 0; r < rows; r++) {
1200 const float *p = part + r * S * pw;
1201 float *o = out + r * HD;
1202 float mx = -__builtin_inff();
1203 for (uint32_t s = 0; s < S; s++) if (p[s * pw + HD] > mx) mx = p[s * pw + HD];
1204 if (!(mx > -__builtin_inff())) { memset(o, 0, (size_t)HD * 4); continue; }
1205 float w[1u << OMEGA_GPU_ATTN_MAX_LOG2SPLIT], lsum = 0.0f;
1206 for (uint32_t s = 0; s < S; s++) { w[s] = host_exp2(p[s * pw + HD] - mx); lsum += w[s] * p[s * pw + HD + 1]; }
1207 const float inv = 1.0f / lsum;
1208 for (uint32_t d = 0; d < HD; d++) {
1209 float a = 0.0f;
1210 for (uint32_t s = 0; s < S; s++) a += w[s] * p[s * pw + d];
1211 o[d] = a * inv;
1212 }
1213 }
1214}
1215
1216static int paged_core(const float *q, const uint8_t *pool, const OmegaGpuKvLayout *ly,
1217 const uint32_t *const *tables, const uint32_t *n_blocks, const uint32_t *ctx,
1218 uint32_t num_seqs, uint32_t layer_idx, uint32_t num_q_heads, uint32_t num_kv_heads,
1219 uint32_t head_dim, float *out, OmegaGpuAttnInfo *info) {
1220 uint64_t t0 = now_ns();
1221 uint32_t log2gqa, log2bs;
1222 int rc = check_heads(num_q_heads, num_kv_heads, head_dim, &log2gqa);
1223 if (rc != OMEGA_GPU_ATTN_OK) return rc;
1224 const uint32_t HD = head_dim;
1225 if (!ly || layer_idx >= ly->num_layers || log2_exact(ly->block_size, &log2bs) != 0) return OMEGA_GPU_ATTN_BAD_ARGS;
1226 /* the oracle addresses heads as kv_head * head_dim * 2 inside a token: the layout must agree */
1227 if (ly->head_stride_bytes != HD * 2 || ly->token_stride_bytes != (uint64_t)num_kv_heads * HD * 2 ||
1228 ly->kv_plane_stride_bytes != (uint64_t)ly->block_size * ly->token_stride_bytes ||
1229 ly->layer_stride_bytes != 2 * ly->kv_plane_stride_bytes || ly->block_stride_bytes < (uint64_t)ly->num_layers * ly->layer_stride_bytes)
1230 return OMEGA_GPU_ATTN_BAD_ARGS;
1231 size_t row = (size_t)num_q_heads * HD;
1232 /* effective context per sequence and block id range check */
1233 uint32_t *eff = omega_gpu_host_calloc(num_seqs ? num_seqs : 1, sizeof *eff);
1234 if (!eff) return OMEGA_GPU_ATTN_CHIP_FAIL;
1235 for (uint32_t s = 0; s < num_seqs; s++) {
1236 uint64_t cap = (uint64_t)n_blocks[s] * ly->block_size;
1237 eff[s] = (uint32_t)(ctx[s] < cap ? ctx[s] : cap);
1238 for (uint32_t b = 0; b < n_blocks[s]; b++) {
1239 uint64_t id = tables[s][b];
1240 if (id >= ly->num_blocks || id * ly->block_stride_bytes + (uint64_t)(layer_idx + 1) * ly->layer_stride_bytes > ly->pool_bytes) { omega_gpu_host_free(eff); return OMEGA_GPU_ATTN_BAD_ARGS; }
1241 }
1242 }
1243 uint32_t seqs_per_launch = OMEGA_GPU_ATTN_MAX_CTAS / num_q_heads;
1244 if (seqs_per_launch == 0) seqs_per_launch = 1;
1245 /* cut F: split each (sequence, head) over 2^log2split CTAs along the context: at least one whole chunk per
1246 * split, from the longest context in the call, within the split launch bound (the test hook forces it). */
1247 uint32_t log2split = 0;
1248 if (g_split >= 0) log2split = (uint32_t)g_split;
1249 else for (uint32_t s = 0; s < num_seqs; s++) { uint32_t l = own_log2split(eff[s], HD); if (l > log2split) log2split = l; }
1250 while (log2split && ((uint64_t)num_q_heads * seqs_per_launch << log2split) > OMEGA_GPU_ATTN_SPLIT_MAX_CTAS) log2split--;
1251 const uint32_t S = 1u << log2split;
1252 float *part = omega_gpu_host_alloc((size_t)seqs_per_launch * num_q_heads * S * (HD + 2) * 4); /* the partials of one launch */
1253 if (!part) { omega_gpu_host_free(eff); return OMEGA_GPU_ATTN_CHIP_FAIL; }
1254 Slot *ks = NULL;
1255 rc = begin(false, log2bs, log2gqa, HD, (int)log2split, &ks, info);
1256 if (rc != OMEGA_GPU_ATTN_OK) { omega_gpu_host_free(eff); omega_gpu_host_free(part); return rc; }
1257 uint32_t maxb = 1;
1258 for (uint32_t s = 0; s < num_seqs; s++) if (n_blocks[s] > maxb) maxb = n_blocks[s];
1259 /* Resident pool (2026-10-12): the caller's pool IS omega's allocation. Read it in place when the
1260 * layout fits the allocation and every referenced block passes the 32-bit fit rule; else stage. */
1261 bool resident = g_resident.cpu && (const void *)pool == g_resident.cpu && ly->pool_bytes <= g_resident.size;
1262 for (uint32_t s = 0; resident && s < num_seqs; s++) {
1263 uint32_t need = eff[s] ? (eff[s] + ly->block_size - 1) / ly->block_size : 0;
1264 for (uint32_t b = 0; b < need; b++) if (!resident_fits(ly, tables[s][b])) { resident = false; break; }
1265 }
1266 /* Dedupe map: physical block id -> staged slot of the current launch (-1 = not staged yet),
1267 * plus the list of ids touched by the launch (in slot order) so the reset is O(unique). */
1268 int32_t *slot_of = NULL; uint32_t *touched = NULL;
1269 if (g_dedupe && !resident) {
1270 size_t nb = ly->num_blocks ? ly->num_blocks : 1;
1271 slot_of = omega_gpu_host_alloc(nb * sizeof *slot_of);
1272 touched = omega_gpu_host_alloc(nb * sizeof *touched);
1273 if (!slot_of || !touched) { omega_gpu_host_free(slot_of); omega_gpu_host_free(touched); omega_gpu_host_free(eff); UNLOCK(); return OMEGA_GPU_ATTN_CHIP_FAIL; }
1274 memset(slot_of, 0xff, nb * sizeof *slot_of); /* every entry -1 */
1275 }
1276 for (uint32_t s0 = 0; s0 < num_seqs && rc == OMEGA_GPU_ATTN_OK; s0 += seqs_per_launch) {
1277 uint32_t ns = num_seqs - s0 < seqs_per_launch ? num_seqs - s0 : seqs_per_launch;
1278 /* logical references: every sequence's blocks up to its (truncated) context */
1279 uint32_t total = 0;
1280 for (uint32_t s = 0; s < ns; s++) total += eff[s0 + s] ? (eff[s0 + s] + ly->block_size - 1) / ly->block_size : 0;
1281 uint32_t *tab = omega_gpu_host_calloc((size_t)ns * maxb + ns, sizeof *tab);
1282 if (!tab) { rc = OMEGA_GPU_ATTN_CHIP_FAIL; break; }
1283 if (resident) {
1284 /* the table carries the physical ids; the kernel's block stride is the pool's; the layer
1285 * base is the chip address of this layer's slice of block 0 */
1286 for (uint32_t s = 0; s < ns; s++) {
1287 uint32_t need = eff[s0 + s] ? (eff[s0 + s] + ly->block_size - 1) / ly->block_size : 0;
1288 for (uint32_t b = 0; b < need; b++) tab[(size_t)s * maxb + b] = tables[s0 + s][b];
1289 tab[(size_t)ns * maxb + s] = eff[s0 + s];
1290 }
1291 if (info) { info->kv_blocks_logical += total; info->kv_bytes_naive += (uint64_t)total * ly->layer_stride_bytes; }
1292 Launch L = {
1293 .q = q + (size_t)s0 * row, .q_bytes = (size_t)ns * row * 4,
1294 .pool = (const uint8_t *)pool + (size_t)layer_idx * ly->layer_stride_bytes, .pool_bytes = 0,
1295 .tab = tab, .tab_bytes = ((size_t)ns * maxb + ns) * 4,
1296 .out = part, .out_bytes = (size_t)ns * num_q_heads * S * (HD + 2) * 4,
1297 .grid_x = num_q_heads / heads_per_cta(HD, log2gqa), .grid_y = ns * S,
1298 .params = { maxb, f2u(score_scale(HD)), (uint32_t)ly->block_stride_bytes, (uint32_t)ly->token_stride_bytes,
1299 (uint32_t)ly->kv_plane_stride_bytes, (uint32_t)ly->head_stride_bytes, num_q_heads, ns * maxb * 4 },
1300 .pool_va = g_resident.va + (uint64_t)layer_idx * ly->layer_stride_bytes,
1301 };
1302 rc = launch(ks, &L, info);
1303 if (rc == OMEGA_GPU_ATTN_OK) combine_splits(part, out + (size_t)s0 * row, (size_t)ns * num_q_heads, S, HD);
1304 omega_gpu_host_free(tab);
1305 continue;
1306 }
1307 /* pass 1: assign staged slots. Dedupe keys on the PHYSICAL block id (not the table
1308 * position): a CoW prefix block shared by several branches gets one slot. Each
1309 * sequence's compact table keeps its own block order and truncated context. */
1310 uint32_t g = 0;
1311 for (uint32_t s = 0; s < ns; s++) {
1312 uint32_t need = eff[s0 + s] ? (eff[s0 + s] + ly->block_size - 1) / ly->block_size : 0;
1313 for (uint32_t b = 0; b < need; b++) {
1314 uint32_t id = tables[s0 + s][b];
1315 if (g_dedupe) {
1316 if (slot_of[id] < 0) { slot_of[id] = (int32_t)g; touched[g] = id; g++; }
1317 tab[(size_t)s * maxb + b] = (uint32_t)slot_of[id];
1318 } else {
1319 tab[(size_t)s * maxb + b] = g++; /* legacy: one slot per reference */
1320 }
1321 }
1322 tab[(size_t)ns * maxb + s] = eff[s0 + s];
1323 }
1324 uint64_t staged_bytes = (uint64_t)(g ? g : 1) * ly->layer_stride_bytes;
1325 if (staged_bytes > 0xffffffffull) { omega_gpu_host_free(tab); rc = OMEGA_GPU_ATTN_TOO_LARGE; break; }
1326 void *host_tmp = NULL;
1327 int stage_rc;
1328 uint8_t *staged = stage_target((size_t)staged_bytes, &host_tmp, &stage_rc);
1329 if (!staged) { omega_gpu_host_free(tab); rc = stage_rc; break; }
1330 /* pass 2: copy each staged slot's (physical block, layer) slice exactly once */
1331 if (g_dedupe) {
1332 for (uint32_t u = 0; u < g; u++) {
1333 const uint8_t *src = pool + (size_t)touched[u] * ly->block_stride_bytes + (size_t)layer_idx * ly->layer_stride_bytes;
1334 memcpy(staged + (size_t)u * ly->layer_stride_bytes, src, (size_t)ly->layer_stride_bytes);
1335 slot_of[touched[u]] = -1; /* reset for the next launch */
1336 }
1337 } else {
1338 uint32_t w = 0;
1339 for (uint32_t s = 0; s < ns; s++) {
1340 uint32_t need = eff[s0 + s] ? (eff[s0 + s] + ly->block_size - 1) / ly->block_size : 0;
1341 for (uint32_t b = 0; b < need; b++, w++) {
1342 const uint8_t *src = pool + (size_t)tables[s0 + s][b] * ly->block_stride_bytes + (size_t)layer_idx * ly->layer_stride_bytes;
1343 memcpy(staged + (size_t)w * ly->layer_stride_bytes, src, (size_t)ly->layer_stride_bytes);
1344 }
1345 }
1346 }
1347 if (info) {
1348 info->kv_blocks_logical += total; info->kv_blocks_unique += g;
1349 info->kv_bytes_staged += (uint64_t)g * ly->layer_stride_bytes;
1350 info->kv_bytes_naive += (uint64_t)total * ly->layer_stride_bytes;
1351 }
1352 Launch L = {
1353 .q = q + (size_t)s0 * row, .q_bytes = (size_t)ns * row * 4, .pool = staged, .pool_bytes = (size_t)staged_bytes,
1354 .tab = tab, .tab_bytes = ((size_t)ns * maxb + ns) * 4,
1355 .out = part, .out_bytes = (size_t)ns * num_q_heads * S * (HD + 2) * 4,
1356 .grid_x = num_q_heads / heads_per_cta(HD, log2gqa), .grid_y = ns * S,
1357 .params = { maxb, f2u(score_scale(HD)), (uint32_t)ly->layer_stride_bytes, (uint32_t)ly->token_stride_bytes,
1358 (uint32_t)ly->kv_plane_stride_bytes, (uint32_t)ly->head_stride_bytes, num_q_heads, ns * maxb * 4 }
1359 };
1360 rc = launch(ks, &L, info);
1361 if (rc == OMEGA_GPU_ATTN_OK) combine_splits(part, out + (size_t)s0 * row, (size_t)ns * num_q_heads, S, HD);
1362 omega_gpu_host_free(host_tmp); omega_gpu_host_free(tab);
1363 }
1364 UNLOCK();
1365 omega_gpu_host_free(eff); omega_gpu_host_free(slot_of); omega_gpu_host_free(touched); omega_gpu_host_free(part);
1366 if (info) info->call_ns = now_ns() - t0;
1367 return rc;
1368}
1369
1370int omega_gpu_paged_attention_bf16(const float *q, const void *pool, const OmegaGpuKvLayout *layout,
1371 const uint32_t *block_ids, uint32_t num_block_ids,
1372 uint32_t context_len, uint32_t layer_idx,
1373 uint32_t num_q_heads, uint32_t num_kv_heads, uint32_t head_dim,
1374 float *out, OmegaGpuAttnInfo *info) {
1375 if (!q || !pool || !layout || !out || (num_block_ids && !block_ids)) return OMEGA_GPU_ATTN_BAD_ARGS;
1376 const uint32_t *tables[1] = { block_ids };
1377 uint32_t nb[1] = { num_block_ids }, cx[1] = { context_len };
1378 return paged_core(q, pool, layout, tables, nb, cx, 1, layer_idx, num_q_heads, num_kv_heads, head_dim, out, info);
1379}
1380
1381int omega_gpu_paged_attention_batch_bf16(const float *q, const void *pool, const OmegaGpuKvLayout *layout,
1382 const int32_t *block_tables, const int32_t *context_lens,
1383 uint32_t max_blocks_per_seq, uint32_t num_seqs, uint32_t layer_idx,
1384 uint32_t num_q_heads, uint32_t num_kv_heads, uint32_t head_dim,
1385 float *out, OmegaGpuAttnInfo *info) {
1386 if (!q || !pool || !layout || !out || !block_tables || !context_lens || num_seqs == 0) return OMEGA_GPU_ATTN_BAD_ARGS;
1387 /* the oracle's rules: ctx <= 0 -> 0; a table row past the array -> empty; negatives removed */
1388 uint32_t **tables = omega_gpu_host_calloc(num_seqs, sizeof *tables);
1389 uint32_t *nb = omega_gpu_host_calloc(num_seqs, sizeof *nb), *cx = omega_gpu_host_calloc(num_seqs, sizeof *cx);
1390 if (!tables || !nb || !cx) { omega_gpu_host_free(tables); omega_gpu_host_free(nb); omega_gpu_host_free(cx); return OMEGA_GPU_ATTN_CHIP_FAIL; }
1391 int rc = OMEGA_GPU_ATTN_OK;
1392 for (uint32_t s = 0; s < num_seqs; s++) {
1393 cx[s] = context_lens[s] > 0 ? (uint32_t)context_lens[s] : 0;
1394 tables[s] = omega_gpu_host_calloc(max_blocks_per_seq ? max_blocks_per_seq : 1, sizeof **tables);
1395 if (!tables[s]) { rc = OMEGA_GPU_ATTN_CHIP_FAIL; break; }
1396 for (uint32_t b = 0; b < max_blocks_per_seq; b++) {
1397 int32_t v = block_tables[(size_t)s * max_blocks_per_seq + b];
1398 if (v >= 0) tables[s][nb[s]++] = (uint32_t)v;
1399 }
1400 }
1401 if (rc == OMEGA_GPU_ATTN_OK)
1402 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);
1403 for (uint32_t s = 0; s < num_seqs; s++) omega_gpu_host_free(tables[s]);
1404 omega_gpu_host_free(tables); omega_gpu_host_free(nb); omega_gpu_host_free(cx);
1405 return rc;
1406}
1407
1408static const char *const k_mutant_names[OMEGA_GPU_ATTN_MUTANT_COUNT] = {
1409 "none", "NO_MAX", "KV_HEAD", "SLOT", "NO_RESCALE", "Q_ROW", "OUT_ROW"
1410};
1411_Static_assert(sizeof k_mutant_names / sizeof k_mutant_names[0] == OMEGA_GPU_ATTN_MUTANT_COUNT, "mutant name table");
1412
1413const char *omega_gpu_attention_mutant_name(OmegaGpuAttnMutant m) {
1414 return (m >= 0 && m < OMEGA_GPU_ATTN_MUTANT_COUNT && k_mutant_names[m]) ? k_mutant_names[m] : "?";
1415}
1416
1417const char *omega_gpu_attention_rc_name(int rc) {
1418 switch (rc) {
1419 case OMEGA_GPU_ATTN_OK: return "OK";
1420 case OMEGA_GPU_ATTN_BAD_ARGS: return "BAD_ARGS";
1421 case OMEGA_GPU_ATTN_TOO_LARGE: return "TOO_LARGE";
1422 case OMEGA_GPU_ATTN_CODEGEN_FAIL: return "CODEGEN_FAIL";
1423 case OMEGA_GPU_ATTN_CHIP_FAIL: return "CHIP_FAIL";
1424 case OMEGA_GPU_ATTN_UNWRITTEN: return "UNWRITTEN";
1425 default: return "UNKNOWN";
1426 }
1427}
1428
1429/* omega #308 R2 test hook: 0 production, 1 lane-dependent branch inside a reconvergence
1430 * region, 2 the same with the BSYNC dropped (negative control). Clears the kernel cache. */
1431void omega_gpu_attention_test_set_divergent(int mode) {
1432 LOCK();
1433 g_divergent = (mode < 0 || mode > 2) ? 0 : mode;
1434 cache_clear_locked();
1435 UNLOCK();
1436}