interplane.Get Omega
Read in your language

CUDApp

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

Brought by drakestapleton

branch main Branches Tags History

CUDApp / src / omega_gpu_attention_api.c

1796 lines · 107286 bytes Raw Blame History
1/* SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception */
2#include "omega_attn_tables.h"
3/* omega_gpu_attention_api.c: FB-1 cut 5 (2026-10-04). See the header.
4 *
5 * Layout: (1) kernel codegen on the BlackwellIR with the serialising scheduler
6 * of cut 4 (every instruction waits on everything still pending; slow and safe),
7 * extended with forward branches and more loops; (2) the launcher, cloned from
8 * cut 4's run_abc with a fourth buffer (block tables and context lengths), 16
9 * argument words, and cut 1b's shader-cache invalidate; (3) the public entry
10 * points, which stage the referenced KV blocks per launch and apply the oracle's
11 * argument rules (dropped tokens past the table, negative table entries, zero
12 * context) on the host.
13 *
14 * One CTA per (query head, sequence), head_dim threads (64 or 128; the text below says 64, the
15 * constants scale with KSpec.hd). The context is walked in chunks of head_dim tokens:
16 * phase A thread t owns token base+t: block lookup, K dot q (f32 FFMA), s = dot * scale
17 * (scale folds 1/sqrt(d) and log2 e), s and the token's byte offset go to shared;
18 * reduce chunk max (SHFL.DOWN tree per warp, lane partials to shared, BAR.SYNC, 2 LDS),
19 * m_new = max(m, chunk max), alpha = EX2(m - m_new), p = EX2(s - m_new) to shared,
20 * chunk sum the same way, l = l * alpha + chunk sum;
21 * phase B thread d owns dimension d: acc = acc * alpha + sum over the chunk of p_t * V[t][d].
22 * Then out[d] = acc * RCP(l). The first chunk sees m = -inf, so alpha = EX2(-inf) = 0 and
23 * the initial l and acc drop out (PTX ISA ex2.approx: ex2(-Inf) = +0).
24 *
25 * Shared memory (16 * head_dim bytes; hd 64: 1024 bytes, the QMD default): [0,4hd) q, [4hd,8hd) s then p,
26 * [8hd,12hd) token byte offsets, [12hd,16hd) warp partials for the reductions (hd 64: 0, 256, 512,
27 * 768; hd 128: 0, 512, 1024, 1536; the partials of warp w are read at 12hd + 128w).
28 */
29#include "omega_gpu_attention_api.h"
30#include "omega_host_policy.h"
31#include "omega_api_plan.h"
32#include "omega_blackwell_codegen.h"
33#include "omega_gpu_om_ir.h"
34#include "cudapp_native.h"
35#include "omega_attn_host_policy.h"
36#include "omega_bw_reconv.h"
37#include "omega_blackwell_qmd.h"
38#include "omega_blackwell_submit.h"
39#include "omega_gpu_session.h"
40#include "omega_gpu_fmt.h"
41#include "sha256.h"
42#ifdef OMEGA_ATTN_DEBUG
43#include <stdio.h> /* the debug trace only; never in the freestanding build */
44#endif
45#include <string.h>
46
47/* ------------------------------------------------------------------ codegen */
48#ifndef CUDAPP_MIGRATION_PENDING_C_API_KGEN
49#define CUDAPP_MIGRATION_PENDING_C_API_KGEN 0
50#endif
51#if CUDAPP_MIGRATION_PENDING_C_API_KGEN
52/* Differential oracle only. Production kernel computation is om/kgen/attention*.om. */
53
54#define CW(stall, wbar, rbar, wait) \
55 (((uint32_t)(stall) << 9) | ((uint32_t)(wbar) << 14) | ((uint32_t)(rbar) << 17) | ((uint32_t)(wait) << 20))
56#define CW_YIELD 0x2000u
57#define SB_NONE 7u
58#define SB_GPR 0u
59#define SB_RD 1u
60#define SB_UGPR 2u
61#define SB_LD2 4u /* second scoreboard for batched loads (the matmul kernel's B-load word, omega #328) */
62#define SB_LD3 3u /* third: phase B keeps shared loads and the two halves of the V loads on separate scoreboards */
63#define AT_BATCH_MAX 4 /* loads in flight per scoreboard: 4 complete on the chip, 8 never did (omega #328) */
64
65enum { K_FIXED, K_PRED, K_VAR, K_UVAR, K_STORE, K_SYNC, K_EXIT, K_BRA, K_BSSY, K_BSYNC };
66
67#define AT_MAX_LOOPS 8
68typedef struct {
69 BlackwellIRProgram *p;
70 uint32_t pending;
71 uint32_t batch; /* scoreboards the open load batch is filling (no wait on them inside the batch) */
72 int batch_n[8]; /* loads issued per scoreboard in the open batch */
73 int err;
74 int loop_start[AT_MAX_LOOPS], loop_end[AT_MAX_LOOPS];
75 int n_loops, depth, stack[AT_MAX_LOOPS];
76 BwRegions rg; /* structured reconvergence regions (omega #308) */
77 int rg_mutant; /* test only: 1 = drop the BSYNC at join (the 2026-10-04 bug shape; host sim must catch it) */
78} Em;
79
80static void emit(Em *e, BlackwellIRInsn in, int kind) {
81 uint32_t wait = e->pending;
82 e->batch = 0; av_memset(e->batch_n, 0, sizeof e->batch_n); /* an ordinary instruction waits on the whole batch */
83 switch (kind) {
84 case K_FIXED: in.control = CW(6, SB_NONE, SB_NONE, wait); e->pending = 0; break;
85 case K_PRED: in.control = CW(13, SB_NONE, SB_NONE, wait); e->pending = 0; break;
86 case K_VAR: in.control = CW(4, SB_GPR, SB_NONE, wait) | CW_YIELD; e->pending = 1u << SB_GPR; break;
87 case K_UVAR: in.control = CW(4, SB_UGPR, SB_NONE, wait) | CW_YIELD; e->pending = 1u << SB_UGPR; break;
88 case K_STORE: in.control = CW(4, SB_NONE, SB_RD, wait) | CW_YIELD; e->pending = 1u << SB_RD; break;
89 case K_SYNC: in.control = CW(6, SB_NONE, SB_NONE, wait); e->pending = 0; break;
90 case K_EXIT: in.control = CW(5, SB_NONE, SB_NONE, wait); e->pending = in.predicate_p0 ? wait : 0; break;
91 case K_BRA: in.control = CW(5, SB_NONE, SB_NONE, wait); e->pending = in.predicate_p0 ? wait : 0; break;
92 /* stall counts as nvcc 13.0.88 writes them for sm_121 (see src/omega_gpu_elementwise_api.c) */
93 case K_BSSY: in.control = CW(1, SB_NONE, SB_NONE, wait) | CW_YIELD; e->pending = 0; break;
94 case K_BSYNC: in.control = CW(5, SB_NONE, SB_NONE, wait) | CW_YIELD; e->pending = 0; break;
95 default: e->err = -1; return;
96 }
97 if (omega_bw_ir_append(e->p, &in) < 0) e->err = -1;
98}
99
100static int V(Em *e) { int v = omega_bw_ir_alloc_vreg(e->p); if (v < 0) e->err = -1; return v; }
101static int V64(Em *e) { int v = omega_bw_ir_alloc_vreg64(e->p); if (v < 0) e->err = -1; return v; }
102static int V128(Em *e) { int v = omega_bw_ir_alloc_vreg128(e->p); if (v < 0) e->err = -1; return v; }
103static int UV64(Em *e) { int v = omega_bw_ir_alloc_uvreg64(e->p); if (v < 0) e->err = -1; return v; }
104static int here(const Em *e) { return (int)e->p->count; }
105
106#define NOREG -1
107static BlackwellIRInsn I0(BlackwellIROpcode op) {
108 BlackwellIRInsn in; av_memset(&in, 0, sizeof in);
109 in.op = op; in.dst_vreg = NOREG; in.src1_vreg = NOREG; in.src2_vreg = NOREG; in.src3_vreg = NOREG; in.ureg = NOREG;
110 return in;
111}
112static 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); }
113static 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); }
114static 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); }
115static 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); }
116static 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); }
117static void movf(Em *e, int dst, float f) { uint32_t u; av_memcpy(&u, &f, 4); movi(e, dst, u); }
118static void movrz(Em *e, int dst) { BlackwellIRInsn i = I0(BW_IR_MOV_RZ); i.dst_vreg = dst; emit(e, i, K_FIXED); }
119/* dst = a * imm + c (c may be NOREG for RZ) */
120static 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); }
121/* dst = a * b + c (registers; c may be NOREG) */
122static 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); }
123static 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); }
124static 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); }
125static 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); }
126static 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); }
127/* dst64 = idx * imm + base64 (byte address) */
128static 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); }
129static 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); }
130/* Batched loads (2026-10-12, long-context finding): every load above waits on the previous one, so
131 * phase A paid one global latency per dim pair and phase B one per token (~6 GB/s at 1268 ctx). A
132 * batched load sets `sb` and waits on every pending scoreboard except the ones the open batch is
133 * filling (and SB_RD, its read barrier), so up to AT_BATCH_MAX loads per scoreboard are in flight.
134 * The next ordinary instruction (emit) waits on all of them. SB_RD covers the address register: the
135 * allocator may hand that register to a later load's data before this load has read it. */
136static void emit_batched(Em *e, BlackwellIRInsn in, uint32_t sb) {
137 if (sb >= 8 || e->batch_n[sb] >= AT_BATCH_MAX) { e->err = -1; return; }
138 in.control = CW(4, sb, SB_RD, e->pending & ~e->batch) | CW_YIELD;
139 e->batch |= (1u << sb) | (1u << SB_RD); e->batch_n[sb]++;
140 e->pending |= (1u << sb) | (1u << SB_RD);
141 if (omega_bw_ir_append(e->p, &in) < 0) e->err = -1;
142}
143/* A fixed-latency instruction inside an open load batch: it waits on the batch's read barrier (its
144 * destination may be a load's address register, which the load may read late) but not on the loads'
145 * data, so the address of the next load is computed while the earlier loads are in flight. Only for
146 * instructions that read no result of the open batch. */
147static void emit_fixed_in_batch(Em *e, BlackwellIRInsn in) {
148 uint32_t wait = (e->pending & ~e->batch) | (e->batch ? (1u << SB_RD) : 0u);
149 in.control = CW(6, SB_NONE, SB_NONE, wait);
150 if (omega_bw_ir_append(e->p, &in) < 0) e->err = -1;
151}
152static 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); }
153static 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); }
154static 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); }
155static 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); }
156/* sub-register operands of a quad */
157static 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); }
158static 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); }
159static 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); }
160static 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); }
161static 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); }
162static 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); }
163static 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); }
164static 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); }
165static 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); }
166static 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); }
167static 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); }
168static 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); }
169/* SHFL and BAR.SYNC are refused inside an open reconvergence region (omega #308): on a split
170 * warp they read inactive lanes / count a partial warp, which is what produced wrong dims on
171 * the chip on 2026-10-04. The build fails closed instead. */
172static int in_region(Em *e) { if (e->rg.depth > 0) { e->err = -1; return 1; } return 0; }
173static 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); }
174static 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); }
175static 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); }
176static void bar_sync(Em *e) { if (in_region(e)) return; emit(e, I0(BW_IR_BAR_SYNC), K_SYNC); }
177static 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); }
178static 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); }
179/* @P0 BRA forward; the target is patched in when known */
180static 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; }
181static 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; }
182
183/* ---- structured reconvergence regions (omega #308); same API as the elementwise emitter ---- */
184enum { RX_ALWAYS, RX_IF_P0, RX_IF_NOT_P0 };
185static int region_begin(Em *e) {
186 int bar = bw_regions_next_bar(&e->rg);
187 if (bar < 0) { e->err = -1; return -1; }
188 int at = here(e);
189 BlackwellIRInsn i = I0(BW_IR_BSSY); i.bar_reg = (uint8_t)bar; i.imm = 2; emit(e, i, K_BSSY);
190 if (bw_regions_begin(&e->rg, at) < 0) e->err = -1;
191 return bar;
192}
193static void region_exit(Em *e, int cond) {
194 int at = here(e);
195 BlackwellIRInsn i = I0(BW_IR_BRA); i.imm = 1;
196 if (cond != RX_ALWAYS) { i.predicate_p0 = true; i.predicate_not = (cond == RX_IF_NOT_P0); }
197 emit(e, i, K_BRA);
198 if (bw_regions_exit(&e->rg, at) < 0) e->err = -1;
199}
200static void region_join(Em *e) {
201 if (e->rg.depth <= 0) { e->err = -1; return; }
202 int d = e->rg.depth - 1, bsync = here(e);
203 BlackwellIRInsn i = I0(e->rg_mutant == 1 ? BW_IR_NOP : BW_IR_BSYNC); i.bar_reg = (uint8_t)d; emit(e, i, K_BSYNC);
204 if (e->rg_mutant == 1) {
205 BwRegions *r = &e->rg; r->depth--;
206 e->p->insns[r->bssy_at[d]].imm = (uint32_t)(bsync + 1 - r->bssy_at[d]);
207 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]);
208 return;
209 }
210 if (bw_regions_join(&e->rg, e->p, bsync) != d) e->err = -1;
211}
212static void tail(Em *e) {
213 emit(e, I0(BW_IR_EXIT), K_EXIT);
214 BlackwellIRInsn self = I0(BW_IR_BRA);
215 self.control = 0x000fc000u;
216 if (omega_bw_ir_append(e->p, &self) < 0) e->err = -1;
217}
218/* Loops nest; loop_end() extends every value defined before the loop and read inside
219 * it to the back-branch (the linear-scan allocator knows nothing about back-edges). */
220static void loop_begin(Em *e) {
221 if (e->depth >= AT_MAX_LOOPS || e->n_loops >= AT_MAX_LOOPS) { e->err = -1; return; }
222 e->stack[e->depth++] = here(e);
223}
224static void loop_end(Em *e) {
225 if (e->depth == 0 || e->n_loops >= AT_MAX_LOOPS) { e->err = -1; return; }
226 int start = e->stack[--e->depth], end = here(e) - 1;
227 e->loop_start[e->n_loops] = start; e->loop_end[e->n_loops] = end; e->n_loops++;
228 OmegaRegAlloc *ra = &e->p->regalloc;
229 for (int v = 0; v < ra->num_vregs; v++) {
230 OmegaLiveInterval *iv = &ra->intervals[v];
231 if (iv->first_def >= 0 && iv->first_def < start && iv->last_use >= start && iv->last_use < end) iv->last_use = end;
232 }
233}
234/* A value first defined inside a loop may not be read after it before being redefined. */
235static int check_loop_invariant(const Em *e) {
236 const OmegaRegAlloc *ra = &e->p->regalloc;
237 for (int L = 0; L < e->n_loops; L++)
238 for (int v = 0; v < ra->num_vregs; v++) {
239 int fd = ra->intervals[v].first_def;
240 if (fd < e->loop_start[L] || fd > e->loop_end[L]) continue;
241 for (size_t i = (size_t)e->loop_end[L] + 1; i < e->p->count; i++) {
242 const BlackwellIRInsn *in = &e->p->insns[i];
243 if (in->src1_vreg == v || in->src2_vreg == v || in->src3_vreg == v) return -1;
244 /* only LDCU/LDCU64 write a uniform register; any other dst (also a uniform-source IMAD) is GPR v */
245 if (in->dst_vreg == v && in->op != BW_IR_LDCU && in->op != BW_IR_LDCU64) break;
246 }
247 }
248 return 0;
249}
250#endif /* CUDAPP_MIGRATION_PENDING_C_API_KGEN */
251
252/* Kernel argument words (constant bank 0 at 0x380; the bank is 1024 bytes, so 32 words fit). */
253#define ARG_Q 0x380u
254#define ARG_POOL 0x388u
255#define ARG_OUT 0x390u
256#define ARG_TAB 0x398u
257#define ARG_MAXB 0x3a0u /* words per block-table row */
258#define ARG_SCALE 0x3a4u /* bits of log2(e) / sqrt(head_dim) */
259#define ARG_BSTRIDE 0x3a8u /* bytes between staged blocks */
260#define ARG_TSTRIDE 0x3acu /* bytes between tokens */
261#define ARG_KVP 0x3b0u /* bytes from the K plane to the V plane */
262#define ARG_HSTRIDE 0x3b4u /* bytes between kv heads */
263#define ARG_NQH 0x3b8u /* query heads (q and out row count per sequence) */
264#define ARG_CTXOFF 0x3bcu /* byte offset of the context-length array inside the table buffer */
265#define ARG_WORDS 16u
266#define DESC_OFF 0x358u
267
268/* Head dimension is a kernel parameter (64 or 128, see KSpec.hd). Shared memory is four arrays of hd words:
269 * 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,
270 * the layout of every cut before head_dim 128). */
271#define SH_Q 0u
272#define F32_NEG_INF 0xff800000u
273
274/* divergent (omega #308 regression R2): 0 = production branch-free chunk loop; 1 = the
275 * lane-dependent "j >= ctx" branch restored inside a reconvergence region (BSSY/BSYNC) so
276 * the SHFL reductions run on a joined warp; 2 = the same with the BSYNC dropped (the
277 * 2026-10-04 bug shape, a negative control the host simulator must catch). */
278typedef struct { bool f32; uint32_t log2bs, log2gqa; int mutant; int divergent; uint32_t hd; int split; bool general; } KSpec;
279/* split (cut F, 2026-10-12): -1 = direct output (the gqa f32 and rows callers; byte for byte the kernel before).
280 * 0..MAX_LOG2SPLIT = the paged path: 2^split CTAs share one (sequence, head). Each sequence derives its own split
281 * count from its own context (so its result never depends on the other sequences in the launch), every CTA writes
282 * an unnormalised partial (acc[hd], running max, running sum; an empty slice writes acc 0, max -inf) and the host
283 * combines them, also when split == 0. */
284
285/* cut K (2026-10-12, GQA group): at head_dim 128 one CTA serves the GC query heads of one kv head, GC =
286 * min(2^log2gqa, 4), so every K and V byte of a launch is read once instead of once per query head. The KV
287 * pool is GPU-uncached (host-written), so the four CTAs of a GQA group were four DRAM reads of the same
288 * bytes: 21 MB per call at 1268 tokens, the memory ceiling (sc leg smoke-ctx-chunk: 152 us per call).
289 * Grid x is the head group (num_q_heads / GC CTAs per sequence and split). Shared memory: q, scores and
290 * warp partials per head, token offsets once. GC = 1 (every hd 64 kernel, hd 128 with gqa 1) emits exactly
291 * the program before this cut (digest fixtures). */
292static uint32_t heads_per_cta(uint32_t hd, uint32_t log2gqa) { uint64_t p[16]={hd,log2gqa};(void)ap_plan(AP_AT,21,p);return p[8]; }
293static uint32_t shared_bytes_for(uint32_t hd, uint32_t log2gqa) { uint64_t p[16]={hd,log2gqa};(void)ap_plan(AP_AT,21,p);return p[9]; }
294uint32_t omega_gpu_attention_heads_per_cta(uint32_t head_dim, uint32_t log2_gqa) { return heads_per_cta(head_dim, log2_gqa); }
295
296#if CUDAPP_MIGRATION_PENDING_C_API_KGEN
297static void gen_attention(Em *e, const KSpec *k) {
298 const uint32_t elem = k->f32 ? 4u : 2u;
299 const uint32_t HD = k->hd, GC = heads_per_cta(HD, k->log2gqa), log2gc = GC == 4u ? 2u : GC == 2u ? 1u : 0u;
300 const uint32_t HB = HD * 4u; /* bytes of one per-head shared array */
301 const uint32_t SH_S = GC * HB, SH_O = 2u * GC * HB, SH_R = SH_O + HB; /* warps per CTA: HD / 32 */
302 int udesc = UV64(e), A = V64(e), B = V64(e), C = V64(e), D = V64(e);
303 int tid = V(e), h = V(e), seq = V(e);
304 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);
305 ldcu64(e, udesc, DESC_OFF);
306 ldc64(e, A, ARG_Q); ldc64(e, B, ARG_POOL); ldc64(e, C, ARG_OUT); ldc64(e, D, ARG_TAB);
307 ldc32(e, p_maxb, ARG_MAXB); ldc32(e, scale, ARG_SCALE); ldc32(e, p_bstride, ARG_BSTRIDE); ldc32(e, p_tstride, ARG_TSTRIDE);
308 ldc32(e, p_kvp, ARG_KVP); ldc32(e, p_hstride, ARG_HSTRIDE); ldc32(e, p_nqh, ARG_NQH); ldc32(e, p_ctxoff, ARG_CTXOFF);
309 s2r(e, tid, BW_SR_TID_X); s2r(e, h, BW_SR_CTAID_X); s2r(e, seq, BW_SR_CTAID_Y);
310
311 /* cut F, partial mode: grid y = sequence * S + split; the split index picks this CTA's slice of the context (below) */
312 const bool part = k->split >= 0;
313 const uint32_t LS = part ? (uint32_t)k->split : 0u, S = 1u << LS, log2hd = (HD == 128u) ? 7u : 6u;
314 int split = -1, kb = -1, kend = -1;
315 if (part) { split = V(e); if (LS) { lop3andi(e, split, seq, S - 1u); shri(e, seq, seq, LS); } else movrz(e, split); }
316
317 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);
318 /* c32 / c64 keep their hd 64 names: the inner (dim pair) loop trip count HD / 2 and the chunk size HD */
319 movi(e, c1, 1); movi(e, c4, 4); movi(e, c32, HD / 2); movi(e, c64, HD);
320 movi(e, c256, SH_S); movi(e, c512, SH_O); movi(e, c768, SH_R); movi(e, c896, SH_R + 128); movrz(e, zero);
321 /* warp partials 2 and 3 (lane 0 of warps 2 and 3): only a 128-thread CTA has them. Created and emitted only
322 * when HD == 128, so the hd 64 program (vreg numbering, instruction sequence) is exactly the one before. */
323 int c1024 = -1, c1152 = -1, rc_ = -1, rd_ = -1;
324 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); }
325
326 /* q[tid] -> shared; out address kept for the end. Row = seq * num_q_heads + head for
327 * both q and out (flattened head-major, the oracle's layout). The head-wiring mutants
328 * swap the row of head h with h ^ 1 on one side only. GC > 1: head g of the group is
329 * h * GC + g; q goes to SH_Q + g * HB; the output rows are derived in the epilogue. */
330 int tid4 = V(e), qrow = V(e), qoff = V(e), qaddr = V64(e), qv = V(e), oaddr = GC == 1 ? V64(e) : -1;
331 int hq = h, ho = h;
332 if (GC == 1 && k->mutant == OMEGA_GPU_ATTN_MUTANT_Q_ROW) { hq = V(e); lop3xor(e, hq, h, c1); }
333 if (GC == 1 && k->mutant == OMEGA_GPU_ATTN_MUTANT_OUT_ROW) { ho = V(e); lop3xor(e, ho, h, c1); }
334 imadi(e, tid4, tid, 4, NOREG);
335 if (GC == 1) {
336 imadr(e, qrow, seq, p_nqh, hq);
337 imadi(e, qoff, qrow, HD * 4, tid4);
338 wide(e, qaddr, qoff, 1, A);
339 ldg(e, qv, qaddr, udesc);
340 sts32(e, tid4, qv); /* SH_Q + tid*4 */
341 if (!part) { /* direct output address; partial mode derives its row in the epilogue */
342 if (ho == hq) wide(e, oaddr, qoff, 1, C);
343 else {
344 int orow = V(e), ooff = V(e);
345 imadr(e, orow, seq, p_nqh, ho);
346 imadi(e, ooff, orow, HD * 4, tid4);
347 wide(e, oaddr, ooff, 1, C);
348 }
349 }
350 } else {
351 int h0 = V(e), hg = V(e), qsh = V(e);
352 imadi(e, h0, h, GC, NOREG);
353 for (uint32_t g = 0; g < GC; g++) {
354 imadi(e, hg, c1, g, h0);
355 if (k->mutant == OMEGA_GPU_ATTN_MUTANT_Q_ROW) lop3xor(e, hg, hg, c1);
356 imadr(e, qrow, seq, p_nqh, hg);
357 imadi(e, qoff, qrow, HD * 4, tid4);
358 wide(e, qaddr, qoff, 1, A);
359 ldg(e, qv, qaddr, udesc);
360 imadi(e, qsh, c1, g * HB, tid4);
361 sts32(e, qsh, qv);
362 }
363 }
364
365 /* kv head offset, this sequence's table row and context length */
366 int kvh = V(e), kvoff = V(e), t1 = V(e), tab = V64(e), ca = V64(e), ctx = V(e), vb = V64(e);
367 shri(e, kvh, h, k->log2gqa - log2gc); /* GC heads per CTA: kv head = (h * GC) >> log2gqa */
368 if (k->mutant == OMEGA_GPU_ATTN_MUTANT_KV_HEAD) lop3xor(e, kvh, kvh, c1);
369 imadr(e, kvoff, kvh, p_hstride, NOREG);
370 imadr(e, t1, seq, p_maxb, NOREG);
371 imadi(e, t1, t1, 4, NOREG);
372 wide(e, tab, t1, 1, D);
373 imadi(e, t1, seq, 4, p_ctxoff);
374 wide(e, ca, t1, 1, D);
375 ldg(e, ctx, ca, udesc);
376 if (part) {
377 /* This sequence's own split count s_own = min(S, pow2floor(chunks)), chunks = ceil(ctx / HD), from its own
378 * context alone (the host picks the launch S the same way over the batch); per = roundup(ceil(ctx / s_own), HD)
379 * whole chunks per split; this CTA's slice is [kb, kend), kend = min(ctx, kb + per) through the sign bit of
380 * ctx - (kb + per). Splits past s_own get kb >= kend: an empty partial. Branch-free: candidate 2^c replaces
381 * per when chunks >= 2^c; the candidates nest, so the largest that fits wins. */
382 int per = V(e), x = V(e), cand = V(e), dd = V(e), lt = V(e), cH1 = V(e), cK = V(e);
383 kb = V(e); kend = V(e);
384 movi(e, cH1, HD - 1u);
385 iadd3(e, per, ctx, cH1); lop3andi(e, per, per, ~(HD - 1u)); /* roundup(ctx, HD): one split takes it all */
386 shri(e, x, per, log2hd); /* chunks (cut J: one whole chunk per split) */
387 for (uint32_t c = 1; c <= LS; c++) {
388 movi(e, cK, (1u << c) - 1u); iadd3(e, cand, ctx, cK); shri(e, cand, cand, c);
389 iadd3(e, cand, cand, cH1); lop3andi(e, cand, cand, ~(HD - 1u)); /* roundup(ceil(ctx / 2^c), HD) */
390 movi(e, cK, 0u - (1u << c)); iadd3(e, dd, x, cK); shri(e, lt, dd, 31); /* lt = (x < 2^c) */
391 imadi(e, dd, cand, 0xFFFFFFFFu, per); /* per - cand */
392 imadr(e, per, lt, dd, cand); /* lt ? per : cand */
393 }
394 imadr(e, kb, split, per, NOREG);
395 iadd3(e, kend, kb, per);
396 imadi(e, dd, kend, 0xFFFFFFFFu, ctx);
397 shri(e, lt, dd, 31);
398 imadr(e, kend, lt, dd, kend);
399 }
400 const int lim = part ? kend : ctx; /* the end of this CTA's token range */
401 /* V column base for dimension tid: pool + kv plane + tid * elem. The kv head offset is
402 * already inside the per-token offset phase A leaves in shared memory (found by the host
403 * simulator: adding it here too read V from the wrong head for every kv head but 0). */
404 wide(e, vb, tid, elem, B);
405 wide(e, vb, p_kvp, 1, vb);
406
407 /* running max, sum and accumulator per head of the group (GC = 1: one of each, as before) */
408 int M[4], L[4], acc[4];
409 for (uint32_t g = 0; g < GC; g++) M[g] = V(e);
410 for (uint32_t g = 0; g < GC; g++) L[g] = V(e);
411 for (uint32_t g = 0; g < GC; g++) acc[g] = V(e);
412 int base = V(e), sOff = V(e), oOff = V(e), rOff = V(e);
413 for (uint32_t g = 0; g < GC; g++) movi(e, M[g], F32_NEG_INF);
414 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 */
415 for (uint32_t g = 0; g < GC; g++) movrz(e, acc[g]);
416 if (part) iadd3(e, base, kb, zero); else movrz(e, base);
417 iadd3(e, sOff, tid4, c256); iadd3(e, oOff, tid4, c512); iadd3(e, rOff, tid4, c768);
418 bar_sync(e); /* q visible to every thread */
419 if (part) isetp_ge_u32(e, kb, kend); else isetp_ge_u32(e, zero, ctx); /* empty range: out = 0 (an empty partial) */
420 int bZ = bra_fwd_if_p0(e);
421
422 /* ---------------- chunk loop ---------------- */
423 int j = V(e), s[4], koff;
424 for (uint32_t g = 0; g < GC; g++) s[g] = V(e);
425 koff = V(e);
426 int bi = V(e), sl = V(e), ta = V64(e), blk = V(e), ka = V64(e), dot[4], d;
427 for (uint32_t g = 0; g < GC; g++) dot[g] = V(e);
428 d = V(e);
429 int lo = V(e), hi = V(e), qa = V(e), j1 = V(e);
430 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);
431 int tsh = GC > 1 ? V(e) : -1; /* per-head shared address temporary (GC > 1 only) */
432 movi(e, cm1, 0xFFFFFFFFu); iadd3(e, ctxm1, lim, cm1); movi(e, cninf, F32_NEG_INF);
433 loop_begin(e);
434 int Lout = here(e);
435 /* No branch here: a warp split by "j >= ctx" without a BSSY/BSYNC region stays split, and
436 * the SHFL reductions below then read inactive lanes, which is undefined (wrong dims
437 * tid >= tail on the chip, 2026-10-04). The IR has BSSY/BSYNC regions since omega #310
438 * (omega_bw_reconv.h); this kernel stays branchless and does not use them.
439 * over = (j >= ctx) as 0/1 from the sign of ctx-1-j; out-of-range lanes read token `base`
440 * (always < ctx here) and their score is forced to -inf after the dot product with s = -max(-s, nb), nb = -inf or +inf. */
441 iadd3(e, j, base, tid);
442 for (uint32_t g = 0; g < GC; g++) movi(e, s[g], F32_NEG_INF);
443 movrz(e, koff);
444 if (k->divergent) {
445 /* omega #308 R2: the lane-dependent branch, inside a reconvergence region. Lanes with
446 * j >= ctx skip phase A (s stays -inf, koff 0); the BSYNC at region_join rejoins them
447 * before the SHFL reductions below. divergent == 2 drops that BSYNC (negative control). */
448 region_begin(e);
449 isetp_ge_u32(e, j, lim);
450 region_exit(e, RX_IF_P0);
451 } else {
452 imadi(e, dneg, j, 0xFFFFFFFFu, ctxm1); /* ctx - 1 - j */
453 shri(e, over, dneg, 31);
454 imadr(e, ot, over, tid, NOREG);
455 imadi(e, j, ot, 0xFFFFFFFFu, j); /* j - over*tid */
456 }
457 /* phase A: token j */
458 shri(e, bi, j, k->log2bs);
459 lop3andi(e, sl, j, (1u << k->log2bs) - 1u);
460 wide(e, ta, bi, 4, tab);
461 ldg(e, blk, ta, udesc);
462 imadr(e, koff, blk, p_bstride, NOREG);
463 if (k->mutant == OMEGA_GPU_ATTN_MUTANT_SLOT) {
464 /* K read from slot (t + 1) % block_size, V from the right slot: a K/V mismatch.
465 * (Shifting both only permutes matched pairs inside a full block, which softmax cannot see.) */
466 int sl1 = V(e);
467 iadd3(e, j1, j, c1); lop3andi(e, sl1, j1, (1u << k->log2bs) - 1u);
468 imadr(e, sl1, sl1, p_tstride, koff);
469 iadd3(e, sl1, sl1, kvoff);
470 wide(e, ka, sl1, 1, B);
471 imadr(e, koff, sl, p_tstride, koff);
472 iadd3(e, koff, koff, kvoff);
473 } else {
474 imadr(e, koff, sl, p_tstride, koff);
475 iadd3(e, koff, koff, kvoff);
476 wide(e, ka, koff, 1, B);
477 }
478 /* phase A inner loop (batched, 2026-10-12): two 128-bit global loads of K per pass on SB_GPR (16 dims
479 * bf16, 8 dims f32) with the first half of the matching q slice as 128-bit shared loads on SB_LD2, one
480 * wait; then the second half of q, one more (short) wait. The serial loop before paid one global
481 * latency per dim pair. Two halves keep the pass inside AT_GPR_BUDGET (the whole slice at once is
482 * 65 to 76 registers). qa = d * 4 is the shared byte offset of q[d]. GC > 1: the same K pass feeds
483 * every head of the group, each from its own q slice at SH_Q + g * HB (cut K). */
484 const uint32_t dims = k->f32 ? 8u : 16u; /* dims per pass: 32 bytes of K either way */
485 const uint32_t nq = dims / 4u; /* q quads per pass, loaded in two halves */
486 int kx[2], qq[4];
487 kx[0] = V128(e); kx[1] = V128(e);
488 for (uint32_t i = 0; i < nq; i++) qq[i] = V128(e);
489 for (uint32_t g = 0; g < GC; g++) movrz(e, dot[g]);
490 movrz(e, d);
491 loop_begin(e);
492 int Lin = here(e);
493 imadi(e, qa, d, 4, NOREG);
494 ldg128_b(e, kx[0], ka, 0u, udesc, SB_GPR);
495 ldg128_b(e, kx[1], ka, 16u, udesc, SB_GPR);
496 for (uint32_t g = 0; g < GC; g++) {
497 for (int hh = 0; hh < 2; hh++) {
498 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); }
499 if (k->f32) {
500 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 */
501 } else {
502 for (int s4 = 0; s4 < 4; s4++) {
503 int pi = hh * 4 + s4; /* bf16 pair: dims 2*pi (low half) and 2*pi+1 (high half) */
504 imadi_s(e, lo, kx[hh], s4, 0x10000u, NOREG); /* low bf16 -> f32: bits << 16 */
505 lop3andi_s(e, hi, kx[hh], s4, 0xffff0000u); /* high bf16 -> f32: keep the top half */
506 e_ffma_s(e, dot[g], qq[pi / 2], (pi % 2) * 2, lo, 0, dot[g]);
507 e_ffma_s(e, dot[g], qq[pi / 2], (pi % 2) * 2 + 1, hi, 0, dot[g]);
508 }
509 }
510 }
511 }
512 wide(e, ka, c1, 32u, ka);
513 imadi(e, d, c1, dims, d);
514 isetp_ge_u32(e, d, c64);
515 bra_back_if_not_p0(e, Lin);
516 loop_end(e);
517 for (uint32_t g = 0; g < GC; g++) e_fmul(e, s[g], dot[g], scale);
518 if (k->divergent) {
519 region_join(e); /* every lane back before the cross-lane reductions */
520 } else {
521 imadi(e, nb, over, 0x80000000u, cninf); /* over ? +inf : -inf (bits) */
522 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); }
523 }
524 for (uint32_t g = 0; g < GC; g++) {
525 if (g == 0) sts32(e, sOff, s[0]);
526 else { imadi(e, tsh, c1, g * HB, sOff); sts32(e, tsh, s[g]); }
527 }
528 sts32(e, oOff, koff);
529
530 /* chunk max, per head */
531 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;
532 alpha[0] = V(e); parg = V(e); p = V(e); sw = V(e); lc = V(e);
533 for (uint32_t g = 1; g < GC; g++) alpha[g] = V(e);
534 static const uint32_t steps[5] = { 16, 8, 4, 2, 1 };
535 for (uint32_t g = 0; g < GC; g++) {
536 shfl_down(e, t, s[g], steps[0]); e_fmax(e, mw, s[g], t);
537 for (int i = 1; i < 5; i++) { shfl_down(e, t, mw, steps[i]); e_fmax(e, mw, mw, t); }
538 if (g == 0) sts32(e, rOff, mw);
539 else { imadi(e, tsh, c1, g * HB, rOff); sts32(e, tsh, mw); }
540 }
541 bar_sync(e);
542 for (uint32_t g = 0; g < GC; g++) {
543 const int pg = GC == 1 ? p : s[g]; /* GC > 1: p overwrites the score register of its head */
544 if (g == 0) { lds32(e, ra, c768); lds32(e, rb, c896); }
545 else { imadi(e, tsh, c1, g * HB, c768); lds32(e, ra, tsh); imadi(e, tsh, c1, g * HB, c896); lds32(e, rb, tsh); }
546 e_fmax(e, mc, ra, rb);
547 if (HD == 128) {
548 if (g == 0) { lds32(e, rc_, c1024); lds32(e, rd_, c1152); }
549 else { imadi(e, tsh, c1, g * HB, c1024); lds32(e, rc_, tsh); imadi(e, tsh, c1, g * HB, c1152); lds32(e, rd_, tsh); }
550 e_fmax(e, mc, mc, rc_); e_fmax(e, mc, mc, rd_);
551 }
552 e_fmax(e, Mn, M[g], mc);
553 if (k->mutant == OMEGA_GPU_ATTN_MUTANT_NO_MAX) {
554 movf(e, alpha[g], 1.0f);
555 mufu(e, BW_IR_MUFU_EX2, pg, s[g]);
556 e_fmax(e, M[g], Mn, mc);
557 } else {
558 e_fsub(e, diff, M[g], Mn);
559 mufu(e, BW_IR_MUFU_EX2, alpha[g], diff);
560 e_fmax(e, M[g], Mn, mc); /* M = Mn */
561 e_fsub(e, parg, s[g], Mn);
562 mufu(e, BW_IR_MUFU_EX2, pg, parg);
563 }
564 }
565 bar_sync(e); /* everyone has read the max partials before they are overwritten */
566 for (uint32_t g = 0; g < GC; g++) {
567 const int pg = GC == 1 ? p : s[g];
568 if (g == 0) sts32(e, sOff, pg);
569 else { imadi(e, tsh, c1, g * HB, sOff); sts32(e, tsh, pg); }
570 shfl_down(e, t, pg, steps[0]); e_fadd(e, sw, pg, t);
571 for (int i = 1; i < 5; i++) { shfl_down(e, t, sw, steps[i]); e_fadd(e, sw, sw, t); }
572 if (g == 0) sts32(e, rOff, sw);
573 else { imadi(e, tsh, c1, g * HB, rOff); sts32(e, tsh, sw); }
574 }
575 bar_sync(e);
576 for (uint32_t g = 0; g < GC; g++) {
577 if (g == 0) { lds32(e, ra, c768); lds32(e, rb, c896); }
578 else { imadi(e, tsh, c1, g * HB, c768); lds32(e, ra, tsh); imadi(e, tsh, c1, g * HB, c896); lds32(e, rb, tsh); }
579 e_fadd(e, lc, ra, rb);
580 if (HD == 128) {
581 if (g == 0) { lds32(e, rc_, c1024); lds32(e, rd_, c1152); }
582 else { imadi(e, tsh, c1, g * HB, c1024); lds32(e, rc_, tsh); imadi(e, tsh, c1, g * HB, c1152); lds32(e, rd_, tsh); }
583 e_fadd(e, lc, lc, rc_); e_fadd(e, lc, lc, rd_);
584 }
585 e_ffma(e, L[g], L[g], alpha[g], lc);
586 if (k->mutant != OMEGA_GPU_ATTN_MUTANT_NO_RESCALE) e_fmul(e, acc[g], acc[g], alpha[g]);
587 }
588
589 /* phase B (batched, 2026-10-12): dimension tid over the chunk's tokens, AT_TOK tokens per pass. The
590 * token offsets of a pass come in two 128-bit shared loads (SB_LD2, one wait), then each V address is
591 * computed into one register pair while the earlier V loads are in flight (emit_fixed_in_batch: the
592 * read barrier orders the overwrite after the load has read it) and its load issued on SB_GPR or
593 * SB_LD3; the p values follow as two more shared loads on SB_LD2; one wait for all of it. A token past
594 * ctx inside a pass has p = 0 and the offset of a real token (phase A), so it adds exactly 0.
595 * GC > 1: one V load per token feeds every head's accumulator from that head's p slice (cut K). */
596 enum { AT_TOK = 8 };
597 int kk = V(e), tt = V(e), oa = V(e), pa = V(e), ko4[2], pv4[2], va = V64(e), v[AT_TOK];
598 for (int i = 0; i < 2; i++) { ko4[i] = V128(e); pv4[i] = V128(e); }
599 for (int i = 0; i < AT_TOK; i++) v[i] = V(e);
600 movrz(e, kk);
601 loop_begin(e);
602 int LB = here(e);
603 iadd3(e, tt, base, kk);
604 isetp_ge_u32(e, tt, lim);
605 int bB = bra_fwd_if_p0(e);
606 imadi(e, oa, kk, 4, c512);
607 imadi(e, pa, kk, 4, c256);
608 for (int i = 0; i < 2; i++) lds128_b(e, ko4[i], oa, (uint32_t)i * 16u, SB_LD2);
609 for (int i = 0; i < AT_TOK; i++) {
610 if (i == 0) wide_s(e, va, ko4[0], 0, 1, vb); /* ordinary: waits for the offsets */
611 else wide_s_b(e, va, ko4[i / 4], i % 4, 1, vb);
612 uint32_t sb = (i < AT_TOK / 2) ? SB_GPR : SB_LD3;
613 if (k->f32) ldg_b(e, v[i], va, udesc, sb); else ldg16_b(e, v[i], va, udesc, sb);
614 }
615 if (GC == 1) {
616 for (int i = 0; i < 2; i++) lds128_b(e, pv4[i], pa, (uint32_t)i * 16u, SB_LD2);
617 for (int i = 0; i < AT_TOK; i++) {
618 if (!k->f32) imadi(e, v[i], v[i], 0x10000u, NOREG);
619 e_ffma_s(e, acc[0], pv4[i / 4], i % 4, v[i], 0, acc[0]);
620 }
621 } else {
622 if (!k->f32) for (int i = 0; i < AT_TOK; i++) imadi(e, v[i], v[i], 0x10000u, NOREG);
623 for (uint32_t g = 0; g < GC; g++) {
624 for (int i = 0; i < 2; i++) lds128_b(e, pv4[i], pa, g * HB + (uint32_t)i * 16u, SB_LD2);
625 for (int i = 0; i < AT_TOK; i++) e_ffma_s(e, acc[g], pv4[i / 4], i % 4, v[i], 0, acc[g]);
626 }
627 }
628 imadi(e, kk, c1, AT_TOK, kk);
629 isetp_ge_u32(e, kk, c64);
630 bra_back_if_not_p0(e, LB);
631 loop_end(e);
632 patch_fwd(e, bB);
633 bar_sync(e); /* phase B reads of s/p and offsets finish before the next chunk writes them */
634 iadd3(e, base, base, c64);
635 isetp_ge_u32(e, base, lim);
636 bra_back_if_not_p0(e, Lout);
637 loop_end(e);
638
639 patch_fwd(e, bZ);
640 if (part && GC == 1) {
641 /* partial row (seq * nqh + out head) * S + split: acc[HD] unnormalised, then M and L at words HD and HD + 1
642 * (every lane stores the same CTA-wide M and L). Everything is re-derived here from the CTA ids and the
643 * constant bank so no extra value lives across the chunk loop (the hd 128 kernel sits at the register budget). */
644 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);
645 int paddr = V64(e), maddr = V64(e), laddr = V64(e), Cp = V64(e);
646 s2r(e, cy, BW_SR_CTAID_Y); s2r(e, hh, BW_SR_CTAID_X); ldc32(e, nq_, ARG_NQH); ldc64(e, Cp, ARG_OUT);
647 if (k->mutant == OMEGA_GPU_ATTN_MUTANT_OUT_ROW) lop3xor(e, hh, hh, c1);
648 if (LS) { lop3andi(e, sp, cy, S - 1u); shri(e, sq, cy, LS); } else { movrz(e, sp); iadd3(e, sq, cy, zero); }
649 imadr(e, prow, sq, nq_, hh);
650 imadi(e, prow, prow, S, sp);
651 imadi(e, t4, tid, 4, NOREG);
652 imadi(e, poff, prow, (HD + 2u) * 4u, t4);
653 wide(e, paddr, poff, 1, Cp);
654 stg(e, paddr, acc[0], udesc);
655 imadi(e, poff, prow, (HD + 2u) * 4u, NOREG);
656 wide(e, maddr, poff, 1, Cp);
657 wide(e, maddr, c64, 4, maddr);
658 stg(e, maddr, M[0], udesc);
659 wide(e, laddr, c1, 4, maddr);
660 stg(e, laddr, L[0], udesc);
661 } else if (part) {
662 /* GC heads: row (seq * nqh + h * GC + g) * S + split for head g (OUT_ROW: g ^ 1 on the output side) */
663 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);
664 int paddr = V64(e), maddr = V64(e), laddr = V64(e), Cp = V64(e);
665 s2r(e, cy, BW_SR_CTAID_Y); s2r(e, h0, BW_SR_CTAID_X); ldc32(e, nq_, ARG_NQH); ldc64(e, Cp, ARG_OUT);
666 imadi(e, h0, h0, GC, NOREG);
667 if (LS) { lop3andi(e, sp, cy, S - 1u); shri(e, sq, cy, LS); } else { movrz(e, sp); iadd3(e, sq, cy, zero); }
668 imadi(e, t4, tid, 4, NOREG);
669 for (uint32_t g = 0; g < GC; g++) {
670 imadi(e, hg, c1, g, h0);
671 if (k->mutant == OMEGA_GPU_ATTN_MUTANT_OUT_ROW) lop3xor(e, hg, hg, c1);
672 imadr(e, prow, sq, nq_, hg);
673 imadi(e, prow, prow, S, sp);
674 imadi(e, poff, prow, (HD + 2u) * 4u, t4);
675 wide(e, paddr, poff, 1, Cp);
676 stg(e, paddr, acc[g], udesc);
677 imadi(e, poff, prow, (HD + 2u) * 4u, NOREG);
678 wide(e, maddr, poff, 1, Cp);
679 wide(e, maddr, c64, 4, maddr);
680 stg(e, maddr, M[g], udesc);
681 wide(e, laddr, c1, 4, maddr);
682 stg(e, laddr, L[g], udesc);
683 }
684 } else if (GC == 1) {
685 int inv = V(e), o = V(e);
686 mufu(e, BW_IR_MUFU_RCP, inv, L[0]);
687 e_fmul(e, o, acc[0], inv);
688 stg(e, oaddr, o, udesc);
689 } else {
690 /* direct output, GC heads: row seq * nqh + h * GC + g (OUT_ROW: g ^ 1), re-derived from the CTA ids */
691 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);
692 int oa64 = V64(e), Cp = V64(e);
693 s2r(e, cy, BW_SR_CTAID_Y); s2r(e, h0, BW_SR_CTAID_X); ldc32(e, nq_, ARG_NQH); ldc64(e, Cp, ARG_OUT);
694 imadi(e, h0, h0, GC, NOREG);
695 imadi(e, t4, tid, 4, NOREG);
696 for (uint32_t g = 0; g < GC; g++) {
697 imadi(e, hg, c1, g, h0);
698 if (k->mutant == OMEGA_GPU_ATTN_MUTANT_OUT_ROW) lop3xor(e, hg, hg, c1);
699 imadr(e, orow, cy, nq_, hg);
700 imadi(e, ooff, orow, HD * 4, t4);
701 wide(e, oa64, ooff, 1, Cp);
702 mufu(e, BW_IR_MUFU_RCP, inv, L[g]);
703 e_fmul(e, o, acc[g], inv);
704 stg(e, oa64, o, udesc);
705 }
706 }
707 tail(e);
708}
709#endif /* CUDAPP_MIGRATION_PENDING_C_API_KGEN */
710
711/* ---------------------------------------------------------- general kernel
712 * AttnGeneral (2026-10-27, runtime API 0.6.0): the fallback for every shape the tuned kernel above does not take.
713 * head_dim D is any of 1..256 (compile-time per kernel, built on first use like every other KSpec field);
714 * T = roundup(D, 32) threads, chunk = T tokens, NW = T / 32 warps. Query heads, kv heads and the GQA / MQA map
715 * are runtime: the host writes one kv-head byte offset per query head (the head map), so any kv head count that
716 * divides the query head count works. CTA (x = query head, y = row) reads its key range [lo, hi) from a host-built
717 * row record {lo, hi, table word offset, 0}: causal masking, sliding windows and per-sequence paged contexts are
718 * all just ranges. Same online softmax as gen_attention (log2 domain, EX2 / RCP, fp32 throughout) and the same
719 * branch-free over-clamp (no lane-dependent branch around the SHFL reductions).
720 * phase A thread t owns token base + t: K . q over D dims, four dims per pass (scalar K loads batched on
721 * SB_GPR, the q quad from shared on SB_LD2), then a static tail of D % 4 dims;
722 * phase B thread t owns dimension min(t, D - 1): threads t >= D recompute dimension D - 1 bit for bit and
723 * store the same word.
724 * Shared: q [0, 4T), s then p [4T, 8T), token byte offsets [8T, 12T), warp partials [12T, 16T) (warp w at 12T + 128w).
725 * Contiguous KV is one block of 2^31 slots (log2bs 31, block table {0}). */
726#define ARG_G_RECOFF ARG_MAXB /* general kernel: byte offset of the row records inside the table buffer */
727#define ARG_G_HMAPOFF ARG_HSTRIDE /* general kernel: byte offset of the head map (kv byte offset per query head) */
728static uint32_t gen_threads(uint32_t hd) { uint64_t p[32]={0,0,hd};(void)ah_policy(p,0);return (uint32_t)p[8]; }
729static uint32_t gen_shared_bytes(uint32_t hd) { uint64_t p[32]={0,0,hd};(void)ah_policy(p,0);return (uint32_t)p[9]; }
730
731#if CUDAPP_MIGRATION_PENDING_C_API_KGEN
732static void gen_attention_general(Em *e, const KSpec *k) {
733 const uint32_t elem = k->f32 ? 4u : 2u, D = k->hd, T = gen_threads(D), NW = T / 32u;
734 const uint32_t SH_S_ = 4u * T, SH_O_ = 8u * T, SH_R_ = 12u * T, D4 = D / 4u, DT = D % 4u;
735 const uint32_t mask = k->log2bs >= 31u ? 0x7fffffffu : (1u << k->log2bs) - 1u;
736 int udesc = UV64(e), A = V64(e), B = V64(e), C = V64(e), TB = V64(e);
737 int tid = V(e), h = V(e), row = V(e);
738 int recoff = V(e), scale = V(e), p_bstride = V(e), p_tstride = V(e), p_kvp = V(e), hmapoff = V(e), p_nqh = V(e);
739 ldcu64(e, udesc, DESC_OFF);
740 ldc64(e, A, ARG_Q); ldc64(e, B, ARG_POOL); ldc64(e, C, ARG_OUT); ldc64(e, TB, ARG_TAB);
741 ldc32(e, recoff, ARG_G_RECOFF); ldc32(e, scale, ARG_SCALE); ldc32(e, p_bstride, ARG_BSTRIDE); ldc32(e, p_tstride, ARG_TSTRIDE);
742 ldc32(e, p_kvp, ARG_KVP); ldc32(e, hmapoff, ARG_G_HMAPOFF); ldc32(e, p_nqh, ARG_NQH);
743 s2r(e, tid, BW_SR_TID_X); s2r(e, h, BW_SR_CTAID_X); s2r(e, row, BW_SR_CTAID_Y);
744
745 int c1 = V(e), zero = V(e), cm1 = V(e), cninf = V(e), cT = V(e), cS = V(e), cO = V(e), cR = V(e), tmp = V(e);
746 movi(e, c1, 1); movrz(e, zero); movi(e, cm1, 0xFFFFFFFFu); movi(e, cninf, F32_NEG_INF); movi(e, cT, T);
747 movi(e, cS, SH_S_); movi(e, cO, SH_O_); movi(e, cR, SH_R_);
748 /* dq = min(tid, D - 1), branch-free through the sign of D - 1 - tid */
749 int dq = V(e), dd = V(e), sg = V(e), dq4 = V(e);
750 movi(e, tmp, D - 1u);
751 imadi(e, dd, tid, 0xFFFFFFFFu, tmp);
752 shri(e, sg, dd, 31);
753 imadr(e, dq, sg, dd, tid);
754 imadi(e, dq4, dq, 4, NOREG);
755 /* q[row][h][dq] -> shared q[dq]; the out address of the same element (row-major [row][q head][D]) */
756 int qrow = V(e), qoff = V(e), qaddr = V64(e), qv = V(e), oaddr = V64(e);
757 imadr(e, qrow, row, p_nqh, h);
758 imadi(e, qoff, qrow, D * 4u, dq4);
759 wide(e, qaddr, qoff, 1, A);
760 ldg(e, qv, qaddr, udesc);
761 sts32(e, dq4, qv);
762 wide(e, oaddr, qoff, 1, C);
763 /* the row record {lo, hi, table word offset} and this head's kv byte offset */
764 int ra = V64(e), lo = V(e), hi = V(e), toff = V(e), tab = V64(e), kvoff = V(e);
765 imadi(e, tmp, row, 16u, recoff);
766 wide(e, ra, tmp, 1, TB);
767 ldg(e, lo, ra, udesc);
768 wide(e, ra, c1, 4u, ra);
769 ldg(e, hi, ra, udesc);
770 wide(e, ra, c1, 4u, ra);
771 ldg(e, toff, ra, udesc);
772 wide(e, tab, toff, 4u, TB);
773 imadi(e, tmp, h, 4u, hmapoff);
774 wide(e, ra, tmp, 1, TB);
775 ldg(e, kvoff, ra, udesc);
776 if (k->mutant == OMEGA_GPU_ATTN_GMUT_CAUSAL) { /* planted: the range ends one key early (hi - 1 when lo < hi) */
777 int x = V(e), s1 = V(e);
778 imadi(e, x, hi, 0xFFFFFFFFu, lo);
779 shri(e, s1, x, 31);
780 imadi(e, hi, s1, 0xFFFFFFFFu, hi);
781 }
782 /* V column base for dimension dq; the token's offset (kv head included) comes from shared */
783 int vb = V64(e);
784 wide(e, vb, dq, elem, B);
785 wide(e, vb, p_kvp, 1, vb);
786
787 int M = V(e), L = V(e), acc = V(e), base = V(e), sOff = V(e), oOff = V(e), rOff = V(e), tid4 = V(e), him1 = V(e);
788 movi(e, M, F32_NEG_INF); movf(e, L, 1.0f); movrz(e, acc); /* alpha = EX2(-inf) = 0 on the first chunk clears L and acc */
789 iadd3(e, base, lo, zero);
790 imadi(e, tid4, tid, 4, NOREG);
791 iadd3(e, sOff, tid4, cS); iadd3(e, oOff, tid4, cO); iadd3(e, rOff, tid4, cR);
792 iadd3(e, him1, hi, cm1);
793 bar_sync(e); /* q visible to every thread */
794 isetp_ge_u32(e, lo, hi); /* empty range: out = 0 */
795 int bZ = bra_fwd_if_p0(e);
796
797 /* ---------------- chunk loop ---------------- */
798 int j = V(e), dneg = V(e), over = V(e), ot = V(e), bi = V(e), sl = V(e), ta = V64(e), blk = V(e), koff = V(e), ka = V64(e);
799 int dot = V(e), s = V(e), nb = V(e), ns = V(e), va = V64(e), kv4[4];
800 for (int i = 0; i < 4; i++) kv4[i] = V(e);
801 int qa = -1, d = -1, cD4 = -1, qq = -1, qt = -1;
802 if (D4) { qa = V(e); d = V(e); cD4 = V(e); qq = V128(e); movi(e, cD4, D4 * 4u); }
803 if (DT) qt = V(e);
804 loop_begin(e);
805 int Lout = here(e);
806 iadd3(e, j, base, tid);
807 imadi(e, dneg, j, 0xFFFFFFFFu, him1); /* hi - 1 - j */
808 shri(e, over, dneg, 31);
809 imadr(e, ot, over, tid, NOREG);
810 imadi(e, j, ot, 0xFFFFFFFFu, j); /* past the range: token base (always < hi here) */
811 shri(e, bi, j, k->log2bs);
812 lop3andi(e, sl, j, mask);
813 wide(e, ta, bi, 4u, tab);
814 ldg(e, blk, ta, udesc);
815 imadr(e, koff, blk, p_bstride, NOREG);
816 imadr(e, koff, sl, p_tstride, koff);
817 iadd3(e, koff, koff, kvoff);
818 wide(e, ka, koff, 1, B);
819 movrz(e, dot);
820 if (D4) {
821 movrz(e, d); movrz(e, qa);
822 loop_begin(e);
823 int Lin = here(e);
824 for (uint32_t i = 0; i < 4u; i++) {
825 if (i) { BlackwellIRInsn w = I0(BW_IR_IMAD_WIDE); w.dst_vreg = va; w.src1_vreg = c1; w.imm = i * elem; w.src3_vreg = ka; emit_fixed_in_batch(e, w); }
826 if (k->f32) ldg_b(e, kv4[i], i ? va : ka, udesc, SB_GPR); else ldg16_b(e, kv4[i], i ? va : ka, udesc, SB_GPR);
827 }
828 lds128_b(e, qq, qa, 0u, SB_LD2);
829 for (int i = 0; i < 4; i++) {
830 if (!k->f32) imadi(e, kv4[i], kv4[i], 0x10000u, NOREG); /* bf16 -> f32: bits << 16 */
831 e_ffma_s(e, dot, qq, i, kv4[i], 0, dot);
832 }
833 wide(e, ka, c1, 4u * elem, ka);
834 imadi(e, qa, c1, 16u, qa);
835 imadi(e, d, c1, 4u, d);
836 isetp_ge_u32(e, d, cD4);
837 bra_back_if_not_p0(e, Lin);
838 loop_end(e);
839 }
840 if (k->mutant != OMEGA_GPU_ATTN_GMUT_TAIL_DIMS) { /* planted: the last D % 4 dims dropped from the dot product */
841 for (uint32_t t = 0; t < DT; t++) {
842 if (t) { BlackwellIRInsn w = I0(BW_IR_IMAD_WIDE); w.dst_vreg = va; w.src1_vreg = c1; w.imm = t * elem; w.src3_vreg = ka; emit_fixed_in_batch(e, w); }
843 if (k->f32) ldg_b(e, kv4[t], t ? va : ka, udesc, SB_GPR); else ldg16_b(e, kv4[t], t ? va : ka, udesc, SB_GPR);
844 }
845 for (uint32_t t = 0; t < DT; t++) {
846 movi(e, tmp, (D4 * 4u + t) * 4u);
847 lds32(e, qt, tmp);
848 if (!k->f32) imadi(e, kv4[t], kv4[t], 0x10000u, NOREG);
849 e_ffma(e, dot, qt, kv4[t], dot);
850 }
851 }
852 e_fmul(e, s, dot, scale);
853 imadi(e, nb, over, 0x80000000u, cninf); /* over ? +inf : -inf (bits) */
854 e_fsub(e, ns, zero, s); e_fmax(e, ns, ns, nb); e_fsub(e, s, zero, ns);
855 sts32(e, sOff, s);
856 sts32(e, oOff, koff);
857
858 /* chunk max and sum: SHFL tree per warp, lane partials to shared, NW partials read back */
859 int t_ = V(e), mw = V(e), rr = 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);
860 static const uint32_t steps[5] = { 16, 8, 4, 2, 1 };
861 shfl_down(e, t_, s, steps[0]); e_fmax(e, mw, s, t_);
862 for (int i = 1; i < 5; i++) { shfl_down(e, t_, mw, steps[i]); e_fmax(e, mw, mw, t_); }
863 sts32(e, rOff, mw);
864 bar_sync(e);
865 lds32(e, mc, cR);
866 for (uint32_t w = 1; w < NW; w++) { movi(e, tmp, SH_R_ + 128u * w); lds32(e, rr, tmp); e_fmax(e, mc, mc, rr); }
867 e_fmax(e, Mn, M, mc);
868 e_fsub(e, diff, M, Mn);
869 mufu(e, BW_IR_MUFU_EX2, alpha, diff);
870 e_fmax(e, M, Mn, mc); /* M = Mn */
871 e_fsub(e, parg, s, Mn);
872 mufu(e, BW_IR_MUFU_EX2, p, parg);
873 bar_sync(e); /* every max partial read before the sums overwrite them */
874 sts32(e, sOff, p);
875 shfl_down(e, t_, p, steps[0]); e_fadd(e, sw, p, t_);
876 for (int i = 1; i < 5; i++) { shfl_down(e, t_, sw, steps[i]); e_fadd(e, sw, sw, t_); }
877 sts32(e, rOff, sw);
878 bar_sync(e);
879 lds32(e, lc, cR);
880 for (uint32_t w = 1; w < NW; w++) { movi(e, tmp, SH_R_ + 128u * w); lds32(e, rr, tmp); e_fadd(e, lc, lc, rr); }
881 e_ffma(e, L, L, alpha, lc);
882 e_fmul(e, acc, acc, alpha);
883
884 /* phase B: dimension dq over the chunk's tokens, AT_TOK per pass (the gen_attention batching) */
885 enum { AT_TOK = 8 };
886 int kk = V(e), tt = V(e), oa = V(e), pa = V(e), ko4[2], pv4[2], v[AT_TOK];
887 for (int i = 0; i < 2; i++) { ko4[i] = V128(e); pv4[i] = V128(e); }
888 for (int i = 0; i < AT_TOK; i++) v[i] = V(e);
889 movrz(e, kk);
890 loop_begin(e);
891 int LB = here(e);
892 iadd3(e, tt, base, kk);
893 isetp_ge_u32(e, tt, hi);
894 int bB = bra_fwd_if_p0(e);
895 imadi(e, oa, kk, 4, cO);
896 imadi(e, pa, kk, 4, cS);
897 for (int i = 0; i < 2; i++) lds128_b(e, ko4[i], oa, (uint32_t)i * 16u, SB_LD2);
898 for (int i = 0; i < AT_TOK; i++) {
899 if (i == 0) wide_s(e, va, ko4[0], 0, 1, vb);
900 else wide_s_b(e, va, ko4[i / 4], i % 4, 1, vb);
901 uint32_t sb = (i < AT_TOK / 2) ? SB_GPR : SB_LD3;
902 if (k->f32) ldg_b(e, v[i], va, udesc, sb); else ldg16_b(e, v[i], va, udesc, sb);
903 }
904 for (int i = 0; i < 2; i++) lds128_b(e, pv4[i], pa, (uint32_t)i * 16u, SB_LD2);
905 for (int i = 0; i < AT_TOK; i++) {
906 if (!k->f32) imadi(e, v[i], v[i], 0x10000u, NOREG);
907 e_ffma_s(e, acc, pv4[i / 4], i % 4, v[i], 0, acc);
908 }
909 imadi(e, kk, c1, AT_TOK, kk);
910 isetp_ge_u32(e, kk, cT);
911 bra_back_if_not_p0(e, LB);
912 loop_end(e);
913 patch_fwd(e, bB);
914 bar_sync(e); /* phase B reads of p and offsets finish before the next chunk writes them */
915 iadd3(e, base, base, cT);
916 if (k->mutant == OMEGA_GPU_ATTN_GMUT_TAIL_CHUNK) { /* planted: stop before a partial last chunk */
917 int last = V(e);
918 iadd3(e, last, base, cT);
919 iadd3(e, last, last, cm1);
920 isetp_ge_u32(e, last, hi);
921 } else {
922 isetp_ge_u32(e, base, hi);
923 }
924 bra_back_if_not_p0(e, Lout);
925 loop_end(e);
926
927 patch_fwd(e, bZ);
928 int inv = V(e), o = V(e);
929 mufu(e, BW_IR_MUFU_RCP, inv, L);
930 e_fmul(e, o, acc, inv);
931 stg(e, oaddr, o, udesc);
932 tail(e);
933}
934#endif /* CUDAPP_MIGRATION_PENDING_C_API_KGEN */
935
936#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) */
937
938static int build_kernel(const KSpec *k, OmegaBlackwellKernel *kernel, BlackwellIRProgram **keep) {
939 BlackwellIRProgram *prog = omega_gpu_host_calloc(1, sizeof *prog);
940 if (!prog) return OMEGA_GPU_ATTN_CODEGEN_FAIL;
941 int rc = OMEGA_GPU_ATTN_CODEGEN_FAIL;
942#if CUDAPP_MIGRATION_PENDING_C_API_KGEN
943 omega_bw_ir_init(prog);
944 Em e; av_memset(&e, 0, sizeof e); e.p = prog;
945 e.rg_mutant = (k->divergent == 2) ? 1 : 0;
946 if (k->general) gen_attention_general(&e, k); else gen_attention(&e, k);
947 if (e.depth != 0) e.err = -1;
948 if (e.rg.depth != 0) e.err = -1; /* a region left open has no join: refuse the build */
949 int ra_rc = (e.err == 0) ? omega_bw_regalloc_solve(prog) : -1;
950 int loop_rc = (ra_rc == 0) ? check_loop_invariant(&e) : -1;
951 int emit_rc = e.err;
952#else
953 uint64_t emit_err = 0;
954 uint64_t kind = (uint64_t)k->f32 | ((uint64_t)k->general << 1) |
955 ((uint64_t)k->divergent << 2) | ((uint64_t)k->mutant << 8) |
956 ((uint64_t)(k->split + 1) << 40);
957 int emit_rc = omega_gpu_om_ir_replay(omega_attention_ir, kind, k->hd, k->log2bs,
958 k->log2gqa, prog, &emit_err);
959 /* The single replay entry already solves allocation and checks closed loops. */
960 int ra_rc = emit_rc == OMEGA_OM_IR_OK ? 0 : -1;
961 int loop_rc = ra_rc;
962#endif
963#ifdef OMEGA_ATTN_DEBUG
964 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",
965 (int)k->f32, k->log2bs, k->log2gqa, k->mutant, emit_rc, prog->count, prog->regalloc.num_vregs, ra_rc, loop_rc, prog->regalloc.peak_gpr_usage);
966#endif
967 if (emit_rc == 0 && ra_rc == 0 && loop_rc == 0 && prog->regalloc.peak_gpr_usage <= AT_GPR_BUDGET) {
968 size_t max_bytes = (size_t)BW_MAX_IR_INSNS * 16;
969 av_memset(kernel, 0, sizeof *kernel);
970 kernel->code = omega_gpu_host_alloc(max_bytes);
971 size_t emitted = 0;
972 if (kernel->code && omega_bw_encode_program(prog, kernel->code, max_bytes, &emitted) == 0) {
973 kernel->code_size = emitted;
974 kernel->insn_count = emitted / 16;
975 kernel->gpr_count = prog->regalloc.peak_gpr_usage;
976 kernel->uniform_gpr_count = prog->regalloc.peak_ugpr_usage;
977 sha256_hash(kernel->code, kernel->code_size, kernel->code_digest);
978 rc = OMEGA_GPU_ATTN_OK;
979 } else {
980 omega_gpu_host_free(kernel->code); kernel->code = NULL;
981 }
982 }
983 if (keep && rc == OMEGA_GPU_ATTN_OK) *keep = prog; else omega_gpu_host_free(prog);
984 return rc;
985}
986
987/* --------------------------------------------------------- kernel cache */
988
989/* One kernel per KSpec; the device copy is uploaded once and stays resident for
990 * the process (cut 4b). The IR program is kept for the host simulator. */
991static int g_mutant;
992static int g_divergent; /* omega #308 R2 test hook: see KSpec.divergent */
993static bool g_dedupe = true; /* shared-prefix staging dedupe; false = legacy per-sequence staging (test hook) */
994typedef struct { int used; KSpec k; OmegaBlackwellKernel kernel; BlackwellIRProgram *prog; OmegaGpuMem code; } Slot;
995static OmegaGpuAttnSim g_sim;
996static Slot g_cache[16]; /* split variants (cut F) multiply the shapes in flight */
997static int g_split = -1; /* test hook: forced log2split (0..OMEGA_GPU_ATTN_MAX_LOG2SPLIT), -1 = chosen per launch from the context */
998static OmegaGpuScratch g_q, g_pool, g_tab, g_out; /* staging, grown to the high-water mark, reused per call */
999static OmegaGpuMem g_resident; /* the resident KV pool (omega_gpu_attention_pool_alloc); cpu NULL = none */
1000static bool g_hooked;
1001#define LOCK() omega_gpu_session_lock()
1002#define UNLOCK() omega_gpu_session_unlock()
1003
1004void omega_gpu_attention_test_set_simulator(OmegaGpuAttnSim sim) { LOCK(); g_sim = sim; UNLOCK(); }
1005static uint32_t g_sim_shared_bytes; /* shared bytes the launcher would declare for the kernel the simulator is running */
1006uint32_t omega_gpu_attention_test_shared_bytes(void) { return g_sim_shared_bytes; }
1007void omega_gpu_attention_test_set_dedupe(bool on) { LOCK(); g_dedupe = on; UNLOCK(); }
1008void omega_gpu_attention_test_set_split(int log2split) {
1009 uint64_t p[16]={(uint64_t)(int64_t)log2split};(void)ap_plan(AP_AT,27,p);
1010 LOCK();g_split=(int32_t)(uint32_t)p[8];UNLOCK();
1011}
1012/* AttnGeneral (0.6.0) test hooks. g_gmutant: planted defects of the general path (kernel ones are KSpec.mutant of the
1013 * general kernels; GQA_MAP and SCALE are host-side). g_force_general: route shapes the tuned kernel takes through the
1014 * general kernel too (sweep coverage at head_dim 64 / 128). g_sim_threads: threads per CTA of the simulated launch. */
1015static int g_gmutant;
1016static bool g_force_general;
1017static uint32_t g_sim_threads;
1018uint32_t omega_gpu_attention_test_threads(void) { return g_sim_threads; }
1019void omega_gpu_attention_test_force_general(bool on) { LOCK(); g_force_general = on; UNLOCK(); }
1020static int gmutant_kernel(void) {
1021 return (g_gmutant == OMEGA_GPU_ATTN_GMUT_TAIL_CHUNK || g_gmutant == OMEGA_GPU_ATTN_GMUT_TAIL_DIMS || g_gmutant == OMEGA_GPU_ATTN_GMUT_CAUSAL) ? g_gmutant : 0;
1022}
1023
1024/* ---- resident KV pool (see the header) ---- */
1025
1026static int dev_open_locked(void);
1027
1028/* The kernel computes block_id * block_stride + slot * token_stride + head offset in 32 bits before
1029 * widening onto the 64-bit layer base: one layer slice (both planes, every token and head of the
1030 * block) past the block's start must stay inside 32 bits. */
1031static bool resident_fits(const OmegaGpuKvLayout *ly, uint32_t block_id) {
1032 uint64_t p[16]={ly->block_stride_bytes,block_id,ly->layer_stride_bytes};
1033 (void)ap_plan(AP_AT,24,p);return p[8];
1034}
1035bool omega_gpu_attention_test_resident_fits(const OmegaGpuKvLayout *layout, uint32_t block_id) {
1036 return layout && resident_fits(layout, block_id);
1037}
1038
1039int omega_gpu_attention_pool_alloc(size_t bytes, void **cpu) {
1040 if (!cpu) return OMEGA_GPU_ATTN_BAD_ARGS;
1041 uint64_t p[16]={bytes,1};int pr=ap_plan(AP_AT,19,p);if(pr)return pr;
1042 *cpu = NULL;
1043 LOCK();
1044 if (g_resident.cpu) { omega_gpu_session_set_error("attention pool: already allocated"); UNLOCK(); return OMEGA_GPU_ATTN_BAD_ARGS; }
1045 if (g_sim) {
1046 g_resident.cpu = omega_gpu_host_calloc(1, bytes);
1047 if (!g_resident.cpu) { UNLOCK(); return OMEGA_GPU_ATTN_CHIP_FAIL; }
1048 g_resident.va = (uintptr_t)g_resident.cpu; g_resident.size = bytes;
1049 } else {
1050 int rc = dev_open_locked();
1051 if (rc != OMEGA_GPU_ATTN_OK) { UNLOCK(); return rc; }
1052 if (omega_gpu_session_alloc(bytes, &g_resident) != 0) { av_memset(&g_resident, 0, sizeof g_resident); UNLOCK(); return OMEGA_GPU_ATTN_CHIP_FAIL; }
1053 }
1054 *cpu = g_resident.cpu;
1055 UNLOCK();
1056 return OMEGA_GPU_ATTN_OK;
1057}
1058
1059void omega_gpu_attention_pool_free(void) {
1060 LOCK();
1061 if (g_resident.cpu) { if (g_sim) omega_gpu_host_free(g_resident.cpu); else omega_gpu_session_free(&g_resident); }
1062 av_memset(&g_resident, 0, sizeof g_resident);
1063 UNLOCK();
1064}
1065
1066static void cache_clear_locked(void) {
1067 for (size_t i = 0; i < sizeof g_cache / sizeof g_cache[0]; i++)
1068 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); av_memset(&g_cache[i], 0, sizeof g_cache[i]); }
1069}
1070
1071void omega_gpu_attention_cache_clear(void) {
1072 LOCK();
1073 cache_clear_locked();
1074 UNLOCK();
1075}
1076
1077/* Called by the session (lock held, device still open) right before it closes. */
1078static void on_session_close(void) {
1079 cache_clear_locked();
1080 av_memset(&g_resident, 0, sizeof g_resident); /* the session's memory goes with it; the caller's mapping is dead */
1081 omega_gpu_session_scratch_free(&g_q); omega_gpu_session_scratch_free(&g_pool);
1082 omega_gpu_session_scratch_free(&g_tab); omega_gpu_session_scratch_free(&g_out);
1083}
1084
1085void omega_gpu_attention_test_set_mutant(OmegaGpuAttnMutant m) {
1086 LOCK();
1087 g_mutant = (int)m;
1088 cache_clear_locked();
1089 UNLOCK();
1090}
1091
1092/* Caller holds the lock. Builds the kernel if needed; uploads the device copy when
1093 * `upload` (the chip path; the simulator never needs one). */
1094static int kernel_for(bool f32, uint32_t log2bs, uint32_t log2gqa, uint32_t hd, int split, bool general, bool upload, Slot **out, bool *hit) {
1095 KSpec k = { .f32 = f32, .log2bs = log2bs, .log2gqa = log2gqa, .mutant = general ? gmutant_kernel() : g_mutant, .divergent = general ? 0 : g_divergent, .hd = hd, .split = split, .general = general };
1096 Slot *s = NULL;
1097 for (size_t i = 0; i < sizeof g_cache / sizeof g_cache[0]; i++)
1098 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 && g_cache[i].k.general == k.general) { /* field compare: memcmp would read struct padding */
1099 s = &g_cache[i]; *hit = true; break;
1100 }
1101 if (!s) {
1102 OmegaBlackwellKernel kern; BlackwellIRProgram *kp = NULL;
1103 int rc = build_kernel(&k, &kern, &kp);
1104 if (rc != OMEGA_GPU_ATTN_OK) return rc;
1105 size_t slot = 0;
1106 for (size_t i = 0; i < sizeof g_cache / sizeof g_cache[0]; i++) if (!g_cache[i].used) { slot = i; break; }
1107 s = &g_cache[slot];
1108 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 */
1109 av_memset(s, 0, sizeof *s);
1110 s->used = 1; s->k = k; s->kernel = kern; s->prog = kp;
1111 *hit = false;
1112 }
1113 if (upload && !s->code.cpu) {
1114 if (omega_gpu_session_alloc_code(s->kernel.code_size, &s->code) != 0) return OMEGA_GPU_ATTN_CHIP_FAIL;
1115 av_memcpy(s->code.cpu, s->kernel.code, s->kernel.code_size);
1116 if (omega_gpu_session_sync_to_gpu(&s->code) != 0) { omega_gpu_session_free(&s->code); return OMEGA_GPU_ATTN_CHIP_FAIL; }
1117 }
1118 *out = s;
1119 return OMEGA_GPU_ATTN_OK;
1120}
1121
1122int omega_gpu_attention_codegen_hd(bool kv_f32, uint32_t log2_block_size, uint32_t log2_gqa, uint32_t head_dim, OmegaBlackwellKernel *kernel) {
1123 if (!kernel) return OMEGA_GPU_ATTN_BAD_ARGS;
1124 uint64_t p[16]={0,log2_block_size,log2_gqa,head_dim};
1125 int pr=ap_plan(AP_AT,26,p);if(pr)return pr;
1126 LOCK();
1127 KSpec k = { .f32 = kv_f32, .log2bs = log2_block_size, .log2gqa = log2_gqa, .mutant = g_mutant, .divergent = g_divergent, .hd = head_dim, .split = -1 };
1128 UNLOCK();
1129 return build_kernel(&k, kernel, NULL);
1130}
1131
1132int omega_gpu_attention_codegen(bool kv_f32, uint32_t log2_block_size, uint32_t log2_gqa, OmegaBlackwellKernel *kernel) {
1133 return omega_gpu_attention_codegen_hd(kv_f32, log2_block_size, log2_gqa, OMEGA_GPU_ATTN_HEAD_DIM, kernel);
1134}
1135
1136int omega_gpu_attention_codegen_general(bool kv_f32, uint32_t log2_block_size, uint32_t head_dim, OmegaBlackwellKernel *kernel) {
1137 if (!kernel) return OMEGA_GPU_ATTN_BAD_ARGS;
1138 uint64_t p[16]={1,log2_block_size,0,head_dim};
1139 int pr=ap_plan(AP_AT,26,p);if(pr)return pr;
1140 LOCK();
1141 KSpec k = { .f32 = kv_f32, .log2bs = log2_block_size, .log2gqa = 0, .mutant = gmutant_kernel(), .divergent = 0, .hd = head_dim, .split = -1, .general = true };
1142 UNLOCK();
1143 return build_kernel(&k, kernel, NULL);
1144}
1145
1146const char *omega_gpu_attention_last_error(void) { return omega_gpu_session_last_error(); }
1147
1148/* ------------------------------------------------------------ launcher */
1149
1150#define AT_POISON 0xffbadbadu
1151#define AT_WAIT_MS 600000ull
1152
1153static uint64_t now_ns(void) { return omega_gpu_session_now_ns(); } /* the platform clock (CLOCK_NS) */
1154
1155typedef OmegaGpuAttnLaunch Launch;
1156
1157/* Caller holds the lock. Chip path: open the shared device on first use. */
1158static int dev_open_locked(void) {
1159 if (!g_hooked) { (void)omega_gpu_session_on_close(on_session_close); g_hooked = true; }
1160 return omega_gpu_session_open() ? OMEGA_GPU_ATTN_OK : OMEGA_GPU_ATTN_CHIP_FAIL;
1161}
1162
1163/* Where a call stages the KV slice it is about to hand the kernel: straight into the
1164 * device staging buffer on the chip path (one copy), a host buffer under the simulator.
1165 * Caller holds the lock; the result is valid until the next staging call. */
1166static void *stage_target(size_t bytes, void **host_tmp, int *fail_rc) {
1167 *host_tmp = NULL;
1168 *fail_rc = OMEGA_GPU_ATTN_CHIP_FAIL;
1169 if (g_sim) { *host_tmp = omega_gpu_host_alloc(bytes ? bytes : 1); return *host_tmp; }
1170 int r = omega_gpu_session_scratch(&g_pool, bytes);
1171 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 */
1172 return g_pool.mem.cpu;
1173}
1174
1175/* Threads and shared bytes the launcher declares: the tuned kernel runs head_dim threads, the general one
1176 * roundup(head_dim, 32) (gen_attention_general). */
1177static uint32_t kspec_threads(const KSpec *k) { return k->general ? gen_threads(k->hd) : k->hd; }
1178static uint32_t kspec_shared(const KSpec *k) { return k->general ? gen_shared_bytes(k->hd) : shared_bytes_for(k->hd, k->log2gqa); }
1179
1180/* One launch through the shared session (omega_gpu_session_launch: shader-cache
1181 * invalidate, constant bank, QMD0/QMD1, first marker, L2_FLUSH_DIRTY, second marker),
1182 * then readback and the poison scan. L->pool may already be the pool staging buffer. */
1183static int run_launch(const Slot *ks, const Launch *L, OmegaGpuAttnInfo *info) {
1184 int sr = omega_gpu_session_scratch(&g_q, L->q_bytes);
1185 if (!sr) sr = omega_gpu_session_scratch(&g_tab, L->tab_bytes);
1186 if (!sr) sr = omega_gpu_session_scratch(&g_out, L->out_bytes);
1187 if (!sr && !L->pool_va && L->pool != g_pool.mem.cpu) sr = omega_gpu_session_scratch(&g_pool, L->pool_bytes);
1188 if (sr) return sr == OMEGA_GPU_SESSION_SCRATCH_RESERVED ? OMEGA_GPU_ATTN_TOO_LARGE : OMEGA_GPU_ATTN_CHIP_FAIL;
1189 av_memcpy(g_q.mem.cpu, L->q, L->q_bytes);
1190 if (!L->pool_va && L->pool != g_pool.mem.cpu) av_memcpy(g_pool.mem.cpu, L->pool, L->pool_bytes);
1191 const uint64_t pool_va = L->pool_va ? L->pool_va : g_pool.mem.va; /* resident: the caller's KV, read in place */
1192 av_memcpy(g_tab.mem.cpu, L->tab, L->tab_bytes);
1193 size_t out_words = L->out_bytes / 4;
1194 uint32_t *out_dev = (uint32_t *)g_out.mem.cpu;
1195 av_fill32(out_dev, out_words, AT_POISON);
1196 /* the KV this launch reads: the staged pool, or the resident pool the caller wrote in place */
1197 if (omega_gpu_session_sync_to_gpu(&g_q.mem) != 0 || omega_gpu_session_sync_to_gpu(&g_tab.mem) != 0 ||
1198 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)
1199 return OMEGA_GPU_ATTN_CHIP_FAIL;
1200
1201 uint32_t args[32];
1202 const uint64_t pack[32] = { g_q.mem.va, pool_va, g_out.mem.va, g_tab.mem.va,
1203 L->params[0], L->params[1], L->params[2], L->params[3],
1204 L->params[4], L->params[5], L->params[6], L->params[7] };
1205 if (av_args(args, pack, 4, ARG_WORDS)) return OMEGA_GPU_ATTN_CHIP_FAIL;
1206 OmegaGpuLaunch GL = {
1207 .code_va = ks->code.va, .gpr_count = AT_GPR_BUDGET, .threads_x = kspec_threads(&ks->k), .threads_y = 1, .shared_bytes = kspec_shared(&ks->k), /* tuned: (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; general: 16 * roundup(hd, 32) */
1208 .grid_x = L->grid_x, .grid_y = L->grid_y, .num_elements = out_words,
1209 .args = args, .n_args = ARG_WORDS, .timeout_ms = AT_WAIT_MS,
1210 };
1211 uint64_t elapsed = 0; uint32_t marker = 0;
1212 if (omega_gpu_session_launch(&GL, &elapsed, &marker) != 0) return OMEGA_GPU_ATTN_CHIP_FAIL;
1213 if (omega_gpu_session_sync_to_cpu(&g_out.mem) != 0) return OMEGA_GPU_ATTN_CHIP_FAIL;
1214
1215 av_memcpy(L->out, g_out.mem.cpu, L->out_bytes);
1216 uint32_t unwritten = 0;
1217 unwritten = (uint32_t)av_count32((const uint32_t *)L->out, out_words, AT_POISON);
1218 if (info) {
1219 info->chip_calls++;
1220 info->elapsed_ns += elapsed;
1221 info->completion_marker = marker;
1222 info->unwritten_words += unwritten;
1223 info->threads_per_cta = kspec_threads(&ks->k);
1224 info->ctas_last_launch = L->grid_x * L->grid_y;
1225 }
1226 return unwritten ? OMEGA_GPU_ATTN_UNWRITTEN : OMEGA_GPU_ATTN_OK;
1227}
1228
1229/* Caller holds the lock. Accounts the launch's q / table / output traffic (the KV
1230 * staging bytes are accounted where the slices are copied). */
1231static int launch(const Slot *ks, const Launch *L, OmegaGpuAttnInfo *info) {
1232 if (info) {
1233 info->q_bytes += L->q_bytes; info->tab_bytes += L->tab_bytes; info->out_bytes += L->out_bytes;
1234 info->kv_source = L->pool_va ? OMEGA_GPU_ATTN_KV_RESIDENT : OMEGA_GPU_ATTN_KV_STAGED;
1235 }
1236 if (g_sim) { g_sim_shared_bytes = kspec_shared(&ks->k); g_sim_threads = kspec_threads(&ks->k); return g_sim(ks->prog, L, info); }
1237 return run_launch(ks, L, info);
1238}
1239
1240/* ---- opt-in serving reservation (see the header) ---- */
1241
1242static int check_heads(uint32_t num_q_heads, uint32_t num_kv_heads, uint32_t head_dim, uint32_t *log2gqa, bool *legacy);
1243static int log2_exact(uint32_t v, uint32_t *out);
1244
1245int 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) {
1246 uint32_t log2gqa, log2bs; bool legacy;
1247 uint64_t p[16]={max_context,max_seqs,num_kv_heads,head_dim,kv_block_size,num_q_heads,0};
1248 if (ap_plan(AP_AT,19,p)) { omega_gpu_session_set_error("attention reserve: zero bound"); return OMEGA_GPU_ATTN_BAD_ARGS; }
1249 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; }
1250 int rc = check_heads(num_q_heads, num_kv_heads, head_dim, &log2gqa, &legacy);
1251 if (rc != OMEGA_GPU_ATTN_OK) { omega_gpu_session_set_error("attention reserve: bad head shape"); return rc; }
1252 /* KV staging, worst case over the two paths, per sequence: contiguous f32 holds both planes for max_context tokens
1253 * (2 * ctx * kvh * hd * 4); paged bf16 stages whole blocks of both planes (round_up(ctx, block) * kvh * hd * 4), which
1254 * is the larger one when max_context is under half a block. */
1255 p[6]=legacy;rc=ap_plan(AP_AT,5,p);if(rc)return rc;
1256 LOCK();
1257 rc = OMEGA_GPU_ATTN_OK;
1258 if (g_sim) rc = OMEGA_GPU_ATTN_OK; /* the simulator stages in host memory: nothing to reserve */
1259 else if (dev_open_locked() != OMEGA_GPU_ATTN_OK) rc = OMEGA_GPU_ATTN_CHIP_FAIL;
1260 else if (omega_gpu_session_scratch_reserve(&g_pool, p[8]) || omega_gpu_session_scratch_reserve(&g_q, p[9]) ||
1261 omega_gpu_session_scratch_reserve(&g_out, p[10]) || omega_gpu_session_scratch_reserve(&g_tab, p[11])) {
1262 /* roll back this API's own buffers: a failed reserve leaves nothing flagged (growth allowed as before) */
1263 omega_gpu_session_scratch_unreserve(&g_pool); omega_gpu_session_scratch_unreserve(&g_q);
1264 omega_gpu_session_scratch_unreserve(&g_out); omega_gpu_session_scratch_unreserve(&g_tab);
1265 rc = OMEGA_GPU_ATTN_CHIP_FAIL;
1266 }
1267 UNLOCK();
1268 return rc;
1269}
1270
1271int omega_gpu_attention_reserve_rows(uint32_t max_rows, uint32_t num_q_heads, uint32_t head_dim) {
1272 uint64_t valid[16]={max_rows,num_q_heads,head_dim};
1273 if (ap_plan(AP_AT,6,valid)) {
1274 omega_gpu_session_set_error("attention reserve rows: bad bound");
1275 return OMEGA_GPU_ATTN_BAD_ARGS;
1276 }
1277 uint64_t p[16]={max_rows,num_q_heads,0,0,0,head_dim};
1278 (void)ap_plan(AP_AT,2,p);
1279 const size_t qo=p[9],tab=p[10];
1280 LOCK();
1281 int rc = OMEGA_GPU_ATTN_OK;
1282 if (g_sim) rc = OMEGA_GPU_ATTN_OK;
1283 else if (dev_open_locked() != OMEGA_GPU_ATTN_OK) rc = OMEGA_GPU_ATTN_CHIP_FAIL;
1284 else if ((qo > g_q.cap && omega_gpu_session_scratch_reserve(&g_q, qo)) ||
1285 (qo > g_out.cap && omega_gpu_session_scratch_reserve(&g_out, qo)) ||
1286 (tab > g_tab.cap && omega_gpu_session_scratch_reserve(&g_tab, tab)))
1287 rc = OMEGA_GPU_ATTN_CHIP_FAIL; /* growth failed; whatever grew stays reserved at its larger size */
1288 UNLOCK();
1289 return rc;
1290}
1291void omega_gpu_attention_unreserve(void) {
1292 LOCK();
1293 omega_gpu_session_scratch_unreserve(&g_pool); omega_gpu_session_scratch_unreserve(&g_q);
1294 omega_gpu_session_scratch_unreserve(&g_out); omega_gpu_session_scratch_unreserve(&g_tab);
1295 UNLOCK();
1296}
1297
1298/* ------------------------------------------------------- public entries */
1299
1300static void info_begin(OmegaGpuAttnInfo *info, const OmegaBlackwellKernel *k, bool hit) {
1301 if (!info) return;
1302 av_memset(info, 0, sizeof *info);
1303 info->kernel_cache_hit = hit;
1304 info->gpr_count = k->gpr_count;
1305 info->insn_count = (uint32_t)k->insn_count;
1306 omega_gpu_fmt(info->target_chip, sizeof info->target_chip, "NVIDIA DGX Spark (Grace Blackwell GB10)");
1307 info->sm_architecture = 121;
1308}
1309static uint32_t f2u(float f) { uint32_t u; av_memcpy(&u, &f, 4); return u; }
1310static int log2_exact(uint32_t v, uint32_t *out) {
1311 uint64_t p[16]={v};int rc=ap_plan(AP_AT,1,p);
1312 if (!rc) *out=p[8];
1313 return rc;
1314}
1315/* log2(e) / sqrt(head_dim) with the square roots as literals (8 and 11.313708498984761 = sqrt(128), both exactly what sqrt() returns):
1316 * the library must not need libm (omegatool links without -lm; a constant head_dim folded sqrt away, a runtime one does not). */
1317static float score_scale(uint32_t hd) {
1318 uint64_t p[16]={hd};(void)ap_plan(AP_AT,23,p);
1319 uint32_t bits=p[8];float out;av_memcpy(&out,&bits,4);return out;
1320}
1321/* The general path's score scale in the log2 domain: log2(e) * (user scale, or 1 / sqrt(head_dim) when 0). The SCALE
1322 * mutant restores the pre-0.6 defect of the tuned path's helper: 1 / 8 for every head_dim. */
1323static float general_scale(uint32_t hd, float user) {
1324 uint32_t bits;av_memcpy(&bits,&user,4);uint64_t p[16]={hd,bits,g_gmutant==OMEGA_GPU_ATTN_GMUT_SCALE};
1325 (void)ap_plan(AP_AT,22,p);bits=p[8];float out;av_memcpy(&out,&bits,4);return out;
1326}
1327
1328/* Common head-shape checks. OK for every shape some kernel takes; *legacy says whether the tuned kernel does
1329 * (head_dim 64 / 128, at most MAX_Q_HEADS query heads, a power-of-two GQA ratio; *log2gqa is then its log2).
1330 * Everything else valid runs on the general kernel. */
1331static int check_heads(uint32_t num_q_heads, uint32_t num_kv_heads, uint32_t head_dim, uint32_t *log2gqa, bool *legacy) {
1332 uint64_t p[16]={num_q_heads,num_kv_heads,head_dim,g_force_general};
1333 int rc=ap_plan(AP_AT,0,p);if(rc)return rc;
1334 *log2gqa=p[8];*legacy=p[9]!=0;
1335 return OMEGA_GPU_ATTN_OK;
1336}
1337
1338/* Common prologue of every chip entry (lock held on success): device, kernel, info. */
1339static int begin(bool f32, uint32_t log2bs, uint32_t log2gqa, uint32_t hd, int split, bool general, Slot **ks, OmegaGpuAttnInfo *info) {
1340 LOCK();
1341 int rc = g_sim ? OMEGA_GPU_ATTN_OK : dev_open_locked();
1342 bool hit = false;
1343 if (rc == OMEGA_GPU_ATTN_OK) rc = kernel_for(f32, log2bs, log2gqa, hd, split, general, !g_sim, ks, &hit);
1344 if (rc != OMEGA_GPU_ATTN_OK) { UNLOCK(); return rc; }
1345 info_begin(info, &(*ks)->kernel, hit);
1346 return OMEGA_GPU_ATTN_OK;
1347}
1348
1349/* kv byte offset of each query head's kv head (the general kernel's head map). GQA_MAP plants the classic
1350 * interleaving bug: h % num_kv_heads instead of h / (num_q_heads / num_kv_heads). */
1351static void head_map(uint32_t *hmap, uint32_t nqh, uint32_t nkv, uint32_t head_bytes) {
1352 av_headmap(hmap, nqh, nkv, head_bytes, g_gmutant==OMEGA_GPU_ATTN_GMUT_GQA_MAP);
1353}
1354
1355/* One general-kernel call: rows r of [0, nrows) attend to keys [lo[r], hi[r]) of their table (ids + r * maxb, or
1356 * the one contiguous block when ids is NULL); per rows per launch. Caller holds the lock with ks a general kernel. */
1357typedef struct {
1358 const float *q; float *out; uint32_t nrows, nqh, hd;
1359 const uint32_t *lo, *hi, *ids; uint32_t maxb; const uint32_t *hmap;
1360 const uint8_t *pool; size_t pool_bytes; uint64_t pool_va;
1361 uint32_t bstride, tstride, kvp; float scale;
1362} GenCall;
1363static int general_run(const Slot *ks, const GenCall *g, uint32_t per, OmegaGpuAttnInfo *info) {
1364 uint64_t p[32]={g->nrows,g->nqh,g->hd,per,g->maxb,g->ids!=NULL};
1365 (void)ah_policy(p,1);
1366 uint32_t *tab = omega_gpu_host_calloc(p[9], sizeof *tab);
1367 if (!tab) return OMEGA_GPU_ATTN_CHIP_FAIL;
1368 int rc = OMEGA_GPU_ATTN_OK;
1369 for (; rc == OMEGA_GPU_ATTN_OK && ah_policy(p,2); (void)ah_policy(p,3)) {
1370 const uint64_t r0=p[10];const uint32_t nr=p[11],hoff=p[12],ioff=p[13];
1371 av_gentab(g->lo+r0,g->hi+r0,tab,nr,ioff,g->ids?g->maxb:0);
1372 av_memcpy(tab + hoff, g->hmap, p[20]);
1373 if (g->ids) av_memcpy(tab + ioff, g->ids + p[18], p[19]); else tab[ioff] = 0;
1374 Launch L = {
1375 .q = g->q + p[15], .q_bytes = p[16], .pool = g->pool, .pool_bytes = g->pool_bytes,
1376 .tab = tab, .tab_bytes = p[17], .out = g->out + p[15], .out_bytes = p[16],
1377 .grid_x = g->nqh, .grid_y = nr,
1378 .params = { 0, f2u(g->scale), g->bstride, g->tstride, g->kvp, p[21], g->nqh, 0 },
1379 .pool_va = g->pool_va,
1380 };
1381 rc = launch(ks, &L, info);
1382 }
1383 omega_gpu_host_free(tab);
1384 return rc;
1385}
1386
1387static uint32_t rows_per_launch(uint32_t num_rows, uint32_t num_q_heads, size_t row_bytes);
1388
1389int omega_gpu_attention_general(const OmegaGpuAttnGeneralDesc *d, const float *q, const void *k, const void *v,
1390 float *out, OmegaGpuAttnInfo *info) {
1391 uint64_t t0 = now_ns();
1392 if (!d || !q || !out || (d->kv_len && (!k || !v))) return OMEGA_GPU_ATTN_BAD_ARGS; /* k / v may be NULL only with kv_len 0 */
1393 uint64_t valid[16]={d->num_rows,1};
1394 if(ap_plan(AP_AT,19,valid))return OMEGA_GPU_ATTN_BAD_ARGS;
1395 const uint32_t nqh = d->num_q_heads, nkv = d->num_kv_heads, HD = d->head_dim, R = d->num_rows;
1396 uint32_t log2gqa; bool legacy;
1397 int rc = check_heads(nqh, nkv, HD, &log2gqa, &legacy);
1398 if (rc != OMEGA_GPU_ATTN_OK) return rc;
1399 valid[1]=(uint64_t)(int64_t)d->window_left;valid[2]=(uint64_t)(int64_t)d->window_right;valid[3]=f2u(d->scale);
1400 if(ap_plan(AP_AT,7,valid))return OMEGA_GPU_ATTN_BAD_ARGS;
1401 uint64_t shape[16]={d->kv_len,nkv,HD,d->kv_bf16?2:4,d->kv_token_stride,d->kv_head_stride};
1402 rc=ap_plan(AP_AT,11,shape);if(rc)return rc;
1403 const size_t row = (size_t)nqh * HD;
1404 if (d->kv_len == 0) { av_memset(out, 0, (size_t)R * row * 4); if (info) { av_memset(info, 0, sizeof *info); info->call_ns = now_ns() - t0; } return OMEGA_GPU_ATTN_OK; }
1405 const uint32_t elem = d->kv_bf16 ? 2u : 4u;
1406 const uint64_t ts=shape[9],hs=shape[10],plane=shape[8];
1407 uint32_t *lo = omega_gpu_host_calloc(2u * (size_t)R + nqh, sizeof *lo);
1408 if (!lo) return OMEGA_GPU_ATTN_CHIP_FAIL;
1409 uint32_t *hi = lo + R, *hmap = hi + R;
1410 uint64_t range[16]={d->q_pos0,d->kv_len,d->causal,(uint64_t)(int64_t)d->window_left,(uint64_t)(int64_t)d->window_right};
1411 av_ranges(lo,R,range);
1412 head_map(hmap, nqh, nkv, HD * elem);
1413 Slot *ks = NULL;
1414 rc = begin(!d->kv_bf16, 31u, 0u, HD, -1, true, &ks, info);
1415 if (rc != OMEGA_GPU_ATTN_OK) { omega_gpu_host_free(lo); return rc; }
1416 void *host_tmp = NULL;
1417 int stage_rc;
1418 uint8_t *pool = stage_target((size_t)(2u * plane), &host_tmp, &stage_rc);
1419 if (!pool) { omega_gpu_host_free(lo); UNLOCK(); return stage_rc; }
1420 /* gather both planes densely as [token][kv head][head_dim] (any caller strides, in elements) */
1421 const size_t hb = (size_t)HD * elem;
1422 uint64_t gather[16]={d->kv_len,nkv,hb,ts,hs,elem};
1423 const size_t source_bytes=((size_t)(d->kv_len-1)*ts+(size_t)(nkv-1)*hs)*elem+hb;
1424 av_gather(k,source_bytes,pool,(size_t)plane,gather);
1425 av_gather(v,source_bytes,pool+(size_t)plane,(size_t)plane,gather);
1426 if (info) { info->kv_bytes_staged += 2u * plane; info->kv_bytes_naive += 2u * plane; info->kv_blocks_logical += 1; info->kv_blocks_unique += 1; }
1427 GenCall g = {
1428 .q = q, .out = out, .nrows = R, .nqh = nqh, .hd = HD, .lo = lo, .hi = hi, .ids = NULL, .maxb = 1, .hmap = hmap,
1429 .pool = pool, .pool_bytes = (size_t)(2u * plane), .pool_va = 0, .bstride = 0, .tstride = nkv * HD * elem,
1430 .kvp = (uint32_t)plane, .scale = general_scale(HD, d->scale),
1431 };
1432 rc = general_run(ks, &g, rows_per_launch(R, nqh, row * 4), info);
1433 omega_gpu_host_free(host_tmp);
1434 omega_gpu_host_free(lo);
1435 UNLOCK();
1436 if (info) info->call_ns = now_ns() - t0;
1437 return rc;
1438}
1439
1440int omega_gpu_gqa_attention_f32(const float *q, const float *k_cache, const float *v_cache,
1441 uint32_t seq_len, uint32_t num_q_heads, uint32_t num_kv_heads,
1442 uint32_t head_dim, float *out, OmegaGpuAttnInfo *info) {
1443 uint64_t t0 = now_ns();
1444 if (!q || !k_cache || !v_cache || !out) return OMEGA_GPU_ATTN_BAD_ARGS;
1445 uint32_t log2gqa; bool legacy;
1446 int rc = check_heads(num_q_heads, num_kv_heads, head_dim, &log2gqa, &legacy);
1447 if (rc != OMEGA_GPU_ATTN_OK) return rc;
1448 uint64_t select[16]={seq_len,legacy};(void)ap_plan(AP_AT,9,select);
1449 if (select[8]) { /* outside the tuned kernel: the general one */
1450 const OmegaGpuAttnGeneralDesc d = { .num_rows = 1, .num_q_heads = num_q_heads, .num_kv_heads = num_kv_heads, .head_dim = head_dim,
1451 .kv_len = seq_len, .q_pos0 = seq_len - 1u, .causal = 1, .window_left = -1, .window_right = -1 };
1452 return omega_gpu_attention_general(&d, q, k_cache, v_cache, out, info);
1453 }
1454 const uint32_t HD = head_dim;
1455 size_t n_out = (size_t)num_q_heads * HD;
1456 if (seq_len == 0) { av_memset(out, 0, n_out * 4); if (info) { av_memset(info, 0, sizeof *info); info->call_ns = now_ns() - t0; } return OMEGA_GPU_ATTN_OK; }
1457 Slot *ks = NULL;
1458 const uint32_t log2bs = 12; /* one block of 4096 slots */
1459 rc = begin(true, log2bs, log2gqa, HD, -1, false, &ks, info);
1460 if (rc != OMEGA_GPU_ATTN_OK) return rc;
1461 size_t plane = (size_t)seq_len * num_kv_heads * HD * 4;
1462 void *host_tmp = NULL;
1463 int stage_rc;
1464 uint8_t *pool = stage_target(2 * plane, &host_tmp, &stage_rc);
1465 if (!pool) { UNLOCK(); return stage_rc; }
1466 av_memcpy(pool, k_cache, plane);
1467 av_memcpy(pool + plane, v_cache, plane);
1468 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 */
1469 uint32_t tab[2] = { 0, seq_len }; /* table row {0}, then the context length at byte 4 */
1470 Launch L = {
1471 .q = q, .q_bytes = n_out * 4, .pool = pool, .pool_bytes = 2 * plane, .tab = tab, .tab_bytes = sizeof tab,
1472 .out = out, .out_bytes = n_out * 4, .grid_x = num_q_heads / heads_per_cta(HD, log2gqa), .grid_y = 1,
1473 .params = { 1, f2u(score_scale(HD)), (uint32_t)(2 * plane), num_kv_heads * HD * 4, (uint32_t)plane, HD * 4, num_q_heads, 4 }
1474 };
1475 rc = launch(ks, &L, info);
1476 omega_gpu_host_free(host_tmp);
1477 UNLOCK();
1478 if (info) info->call_ns = now_ns() - t0;
1479 return rc;
1480}
1481
1482/* Rows per launch of the rows path: the CTA bound, then (under a reservation) what the q buffer holds. Caller holds the lock. */
1483static uint32_t rows_per_launch(uint32_t num_rows, uint32_t num_q_heads, size_t row_bytes) {
1484 uint64_t p[16]={num_rows,num_q_heads,row_bytes,g_q.cap,!g_sim&&g_q.reserved,0};
1485 (void)ap_plan(AP_AT,2,p);return p[8];
1486}
1487
1488int omega_gpu_gqa_attention_rows_f32(const float *q, const float *k_cache, const float *v_cache,
1489 uint32_t base_len, uint32_t num_rows, uint32_t num_q_heads,
1490 uint32_t num_kv_heads, uint32_t head_dim, float *out, OmegaGpuAttnInfo *info) {
1491 uint64_t t0 = now_ns();
1492 if (!q || !k_cache || !v_cache || !out) return OMEGA_GPU_ATTN_BAD_ARGS;
1493 uint64_t shape[16]={num_rows,1};
1494 int shape_rc=ap_plan(AP_AT,19,shape);if(shape_rc)return shape_rc;
1495 uint32_t log2gqa; bool legacy;
1496 int rc = check_heads(num_q_heads, num_kv_heads, head_dim, &log2gqa, &legacy);
1497 if (rc != OMEGA_GPU_ATTN_OK) return rc;
1498 shape[0]=base_len;shape[1]=num_rows;shape[2]=legacy;shape_rc=ap_plan(AP_AT,8,shape);if(shape_rc)return shape_rc;
1499 if (shape[9]) { /* outside the tuned kernel: the general one */
1500 const OmegaGpuAttnGeneralDesc d = { .num_rows = num_rows, .num_q_heads = num_q_heads, .num_kv_heads = num_kv_heads, .head_dim = head_dim,
1501 .kv_len = base_len + num_rows, .q_pos0 = base_len, .causal = 1, .window_left = -1, .window_right = -1 };
1502 return omega_gpu_attention_general(&d, q, k_cache, v_cache, out, info);
1503 }
1504 const uint32_t HD=head_dim,total=shape[8];
1505 const size_t row = (size_t)num_q_heads * HD;
1506 Slot *ks = NULL;
1507 const uint32_t log2bs = 12; /* one block of 4096 slots, as the single-row call */
1508 rc = begin(true, log2bs, log2gqa, HD, -1, false, &ks, info);
1509 if (rc != OMEGA_GPU_ATTN_OK) return rc;
1510 /* the whole context (every row's keys are a prefix of it) staged once */
1511 size_t plane = (size_t)total * num_kv_heads * HD * 4;
1512 void *host_tmp = NULL;
1513 int stage_rc;
1514 uint8_t *pool = stage_target(2 * plane, &host_tmp, &stage_rc);
1515 if (!pool) { UNLOCK(); return stage_rc; }
1516 av_memcpy(pool, k_cache, plane);
1517 av_memcpy(pool + plane, v_cache, plane);
1518 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; }
1519 const uint32_t per = rows_per_launch(num_rows, num_q_heads, row * 4);
1520 /* table of one launch: per block ids (all 0: the one staged block), then per context lengths */
1521 uint32_t *tab = omega_gpu_host_calloc(2 * (size_t)per, sizeof *tab);
1522 if (!tab) { omega_gpu_host_free(host_tmp); UNLOCK(); return OMEGA_GPU_ATTN_CHIP_FAIL; }
1523 for (uint64_t r0 = 0; r0 < num_rows && rc == OMEGA_GPU_ATTN_OK; r0 += per) {
1524 uint64_t chunk[16]={num_rows-r0,per,0};(void)ap_plan(AP_AT,12,chunk);
1525 const uint32_t nr=chunk[8];
1526 av_rowtab(tab, nr, base_len + r0);
1527 Launch L = {
1528 .q = q + (size_t)r0 * row, .q_bytes = (size_t)nr * row * 4, .pool = pool, .pool_bytes = 2 * plane,
1529 .tab = tab, .tab_bytes = (size_t)2 * nr * 4, .out = out + (size_t)r0 * row, .out_bytes = (size_t)nr * row * 4,
1530 .grid_x = num_q_heads / heads_per_cta(HD, log2gqa), .grid_y = nr,
1531 .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 }
1532 };
1533 rc = launch(ks, &L, info);
1534 }
1535 omega_gpu_host_free(tab);
1536 omega_gpu_host_free(host_tmp);
1537 UNLOCK();
1538 if (info) info->call_ns = now_ns() - t0;
1539 return rc;
1540}
1541
1542/* Paged path shared by the single and batched entries. tables[s] has n_blocks[s] entries
1543 * (already filtered of negatives), ctx[s] the context length. */
1544
1545/* cut F: fold the per-split partials of each (sequence, head) row into out. w_s = 2^(M_s - max M): the kernel's
1546 * running max and sum live in the log2 domain (scale carries log2 e, MUFU.EX2). A row whose every split is empty
1547 * (context 0) is 0. */
1548static void combine_splits(const float *part, float *out, size_t rows, uint32_t S, uint32_t HD) {
1549 av_fold(part,out,rows,S,HD);
1550}
1551
1552static int paged_core(const float *q, const uint8_t *pool, const OmegaGpuKvLayout *ly,
1553 const uint32_t *const *tables, const uint32_t *n_blocks, const uint32_t *ctx,
1554 uint32_t num_seqs, uint32_t layer_idx, uint32_t num_q_heads, uint32_t num_kv_heads,
1555 uint32_t head_dim, float *out, OmegaGpuAttnInfo *info) {
1556 uint64_t t0 = now_ns();
1557 uint32_t log2gqa, log2bs; bool legacy;
1558 int rc = check_heads(num_q_heads, num_kv_heads, head_dim, &log2gqa, &legacy);
1559 if (rc != OMEGA_GPU_ATTN_OK) return rc;
1560 const uint32_t HD = head_dim;
1561 if (!ly || log2_exact(ly->block_size, &log2bs) != 0) return OMEGA_GPU_ATTN_BAD_ARGS;
1562 uint64_t layout[16]={HD,num_kv_heads,ly->block_size,ly->head_stride_bytes,ly->token_stride_bytes,ly->kv_plane_stride_bytes,ly->layer_stride_bytes};
1563 rc=ap_plan(AP_AT,13,layout);if(rc)return rc;
1564 uint64_t span[16]={layer_idx,ly->num_layers,ly->block_stride_bytes,ly->layer_stride_bytes};
1565 rc=ap_plan(AP_AT,14,span);if(rc)return rc;
1566 size_t row = (size_t)num_q_heads * HD;
1567 /* effective context per sequence and block id range check */
1568 uint32_t *eff = omega_gpu_host_calloc(num_seqs ? num_seqs : 1, sizeof *eff);
1569 if (!eff) return OMEGA_GPU_ATTN_CHIP_FAIL;
1570 av_eff(eff,ctx,n_blocks,num_seqs,ly->block_size);
1571 for (uint32_t s = 0; s < num_seqs; s++) {
1572 uint64_t block[16]={0,ly->num_blocks,ly->block_stride_bytes,layer_idx,ly->layer_stride_bytes,ly->pool_bytes};
1573 if(av_blocks(tables[s],n_blocks[s],block)){omega_gpu_host_free(eff);return OMEGA_GPU_ATTN_BAD_ARGS;}
1574 }
1575 uint64_t plan[16]={0,num_q_heads};(void)ap_plan(AP_AT,4,plan);
1576 uint32_t seqs_per_launch=plan[9];
1577 /* cut F: split each (sequence, head) over 2^log2split CTAs along the context: at least one whole chunk per
1578 * split, from the longest context in the call, within the split launch bound (the test hook forces it). */
1579 /* general kernel (shapes the tuned one does not take): one CTA per (sequence, head), no split, direct output */
1580 uint32_t log2split = 0;
1581 if (legacy) {
1582 if (g_split >= 0) log2split = (uint32_t)g_split;
1583 else log2split=av_best(eff,num_seqs,HD);
1584 plan[0]=log2split;(void)ap_plan(AP_AT,4,plan);log2split=plan[8];
1585 }
1586 const uint32_t S=plan[10];
1587 uint64_t allocation[16]={seqs_per_launch,num_q_heads,S,HD,legacy};(void)ap_plan(AP_AT,17,allocation);
1588 float *part=omega_gpu_host_alloc(allocation[8]);
1589 uint32_t *gz=legacy?NULL:omega_gpu_host_calloc(allocation[9],sizeof *gz);
1590 if (!part || (!legacy && !gz)) { omega_gpu_host_free(eff); omega_gpu_host_free(part); omega_gpu_host_free(gz); return OMEGA_GPU_ATTN_CHIP_FAIL; }
1591 if (gz) head_map(gz + seqs_per_launch, num_q_heads, num_kv_heads, (uint32_t)ly->head_stride_bytes);
1592 Slot *ks = NULL;
1593 rc = begin(false, log2bs, log2gqa, HD, legacy ? (int)log2split : -1, !legacy, &ks, info);
1594 if (rc != OMEGA_GPU_ATTN_OK) { omega_gpu_host_free(eff); omega_gpu_host_free(part); omega_gpu_host_free(gz); return rc; }
1595 uint32_t maxb = 1;
1596 maxb=av_max(n_blocks,num_seqs);
1597 const GenCall gbase = {
1598 .nqh = num_q_heads, .hd = HD, .lo = gz, .maxb = maxb, .hmap = gz ? gz + seqs_per_launch : NULL,
1599 .tstride = (uint32_t)ly->token_stride_bytes, .kvp = (uint32_t)ly->kv_plane_stride_bytes, .scale = general_scale(HD, 0.0f),
1600 };
1601 /* Resident pool (2026-10-12): the caller's pool IS omega's allocation. Read it in place when the
1602 * layout fits the allocation and every referenced block passes the 32-bit fit rule; else stage. */
1603 bool resident = g_resident.cpu && (const void *)pool == g_resident.cpu && ly->pool_bytes <= g_resident.size;
1604 for (uint32_t s = 0; resident && s < num_seqs; s++) {
1605 uint64_t ctxplan[16]={eff[s],n_blocks[s],ly->block_size};(void)ap_plan(AP_AT,15,ctxplan);uint32_t need=ctxplan[9];
1606 if (!av_resfit(tables[s],need,ly->block_stride_bytes,ly->layer_stride_bytes)) resident=false;
1607 }
1608 /* Dedupe map: physical block id -> staged slot of the current launch (-1 = not staged yet),
1609 * plus the list of ids touched by the launch (in slot order) so the reset is O(unique). */
1610 int32_t *slot_of = NULL; uint32_t *touched = NULL;
1611 if (g_dedupe && !resident) {
1612 size_t nb = ly->num_blocks ? ly->num_blocks : 1;
1613 slot_of = omega_gpu_host_alloc(nb * sizeof *slot_of);
1614 touched = omega_gpu_host_alloc(nb * sizeof *touched);
1615 if (!slot_of || !touched) { omega_gpu_host_free(slot_of); omega_gpu_host_free(touched); omega_gpu_host_free(eff); omega_gpu_host_free(part); omega_gpu_host_free(gz); UNLOCK(); return OMEGA_GPU_ATTN_CHIP_FAIL; }
1616 av_memset(slot_of, 0xff, nb * sizeof *slot_of); /* every entry -1 */
1617 }
1618 for (uint64_t s0 = 0; s0 < num_seqs && rc == OMEGA_GPU_ATTN_OK; s0 += seqs_per_launch) {
1619 uint64_t chunk[16]={num_seqs-s0,seqs_per_launch,0};(void)ap_plan(AP_AT,12,chunk);
1620 uint32_t ns=chunk[8];
1621 /* logical references: every sequence's blocks up to its (truncated) context */
1622 uint32_t total=av_total(eff+s0,ns,ly->block_size);
1623 uint32_t *tab = omega_gpu_host_calloc((size_t)ns * maxb + ns, sizeof *tab);
1624 if (!tab) { rc = OMEGA_GPU_ATTN_CHIP_FAIL; break; }
1625 if (resident) {
1626 /* the table carries the physical ids; the kernel's block stride is the pool's; the layer
1627 * base is the chip address of this layer's slice of block 0 */
1628 for (uint32_t s = 0; s < ns; s++) {
1629 uint64_t ctxplan[16]={eff[s0+s],n_blocks[s0+s],ly->block_size};(void)ap_plan(AP_AT,15,ctxplan);uint32_t need=ctxplan[9];
1630 uint64_t tq[16]={need,2,(size_t)s*maxb,(size_t)ns*maxb+s,eff[s0+s]};
1631 (void)av_table(tables[s0+s],tab,(size_t)ns*maxb+ns,NULL,NULL,0,tq,0);
1632 }
1633 if (info) { info->kv_blocks_logical += total; info->kv_bytes_naive += (uint64_t)total * ly->layer_stride_bytes; }
1634 if (!legacy) {
1635 GenCall gc = gbase;
1636 gc.q = q + (size_t)s0 * row; gc.out = out + (size_t)s0 * row; gc.nrows = ns; gc.hi = tab + (size_t)ns * maxb; gc.ids = tab;
1637 gc.pool = (const uint8_t *)pool + (size_t)layer_idx * ly->layer_stride_bytes; gc.pool_bytes = 0;
1638 gc.pool_va = g_resident.va + (uint64_t)layer_idx * ly->layer_stride_bytes; gc.bstride = (uint32_t)ly->block_stride_bytes;
1639 rc = general_run(ks, &gc, ns, info);
1640 omega_gpu_host_free(tab);
1641 continue;
1642 }
1643 Launch L = {
1644 .q = q + (size_t)s0 * row, .q_bytes = (size_t)ns * row * 4,
1645 .pool = (const uint8_t *)pool + (size_t)layer_idx * ly->layer_stride_bytes, .pool_bytes = 0,
1646 .tab = tab, .tab_bytes = ((size_t)ns * maxb + ns) * 4,
1647 .out = part, .out_bytes = (size_t)ns * num_q_heads * S * (HD + 2) * 4,
1648 .grid_x = num_q_heads / heads_per_cta(HD, log2gqa), .grid_y = ns * S,
1649 .params = { maxb, f2u(score_scale(HD)), (uint32_t)ly->block_stride_bytes, (uint32_t)ly->token_stride_bytes,
1650 (uint32_t)ly->kv_plane_stride_bytes, (uint32_t)ly->head_stride_bytes, num_q_heads, ns * maxb * 4 },
1651 .pool_va = g_resident.va + (uint64_t)layer_idx * ly->layer_stride_bytes,
1652 };
1653 rc = launch(ks, &L, info);
1654 if (rc == OMEGA_GPU_ATTN_OK) combine_splits(part, out + (size_t)s0 * row, (size_t)ns * num_q_heads, S, HD);
1655 omega_gpu_host_free(tab);
1656 continue;
1657 }
1658 /* pass 1: assign staged slots. Dedupe keys on the PHYSICAL block id (not the table
1659 * position): a CoW prefix block shared by several branches gets one slot. Each
1660 * sequence's compact table keeps its own block order and truncated context. */
1661 uint32_t g = 0;
1662 for (uint32_t s = 0; s < ns; s++) {
1663 uint64_t ctxplan[16]={eff[s0+s],n_blocks[s0+s],ly->block_size};(void)ap_plan(AP_AT,15,ctxplan);uint32_t need=ctxplan[9];
1664 uint64_t tq[16]={need,g_dedupe!=0,(size_t)s*maxb,(size_t)ns*maxb+s,eff[s0+s]};
1665 g=av_table(tables[s0+s],tab,(size_t)ns*maxb+ns,slot_of,touched,g_dedupe?ly->num_blocks:0,tq,g);
1666 }
1667 uint64_t staging[16]={g,ly->layer_stride_bytes};rc=ap_plan(AP_AT,18,staging);
1668 if(rc){omega_gpu_host_free(tab);break;}
1669 uint64_t staged_bytes=staging[8];
1670 void *host_tmp = NULL;
1671 int stage_rc;
1672 uint8_t *staged = stage_target((size_t)staged_bytes, &host_tmp, &stage_rc);
1673 if (!staged) { omega_gpu_host_free(tab); rc = stage_rc; break; }
1674 /* pass 2: copy each staged slot's (physical block, layer) slice exactly once */
1675 if (g_dedupe) {
1676 uint64_t sq[16]={g,ly->block_stride_bytes,(size_t)layer_idx*ly->layer_stride_bytes,ly->layer_stride_bytes,0};
1677 av_stage(pool,ly->pool_bytes,staged,(size_t)staged_bytes,touched,sq);
1678 av_reset(slot_of,ly->num_blocks,touched,g);
1679 } else {
1680 uint32_t w = 0;
1681 for (uint32_t s = 0; s < ns; s++) {
1682 uint64_t ctxplan[16]={eff[s0+s],n_blocks[s0+s],ly->block_size};(void)ap_plan(AP_AT,15,ctxplan);uint32_t need=ctxplan[9];
1683 uint64_t sq[16]={need,ly->block_stride_bytes,(size_t)layer_idx*ly->layer_stride_bytes,ly->layer_stride_bytes,w};
1684 av_stage(pool,ly->pool_bytes,staged,(size_t)staged_bytes,tables[s0+s],sq);
1685 w+=need;
1686 }
1687 }
1688 if (info) {
1689 info->kv_blocks_logical += total; info->kv_blocks_unique += g;
1690 info->kv_bytes_staged += (uint64_t)g * ly->layer_stride_bytes;
1691 info->kv_bytes_naive += (uint64_t)total * ly->layer_stride_bytes;
1692 }
1693 if (!legacy) {
1694 GenCall gc = gbase;
1695 gc.q = q + (size_t)s0 * row; gc.out = out + (size_t)s0 * row; gc.nrows = ns; gc.hi = tab + (size_t)ns * maxb; gc.ids = tab;
1696 gc.pool = staged; gc.pool_bytes = (size_t)staged_bytes; gc.pool_va = 0; gc.bstride = (uint32_t)ly->layer_stride_bytes;
1697 rc = general_run(ks, &gc, ns, info);
1698 } else {
1699 Launch L = {
1700 .q = q + (size_t)s0 * row, .q_bytes = (size_t)ns * row * 4, .pool = staged, .pool_bytes = (size_t)staged_bytes,
1701 .tab = tab, .tab_bytes = ((size_t)ns * maxb + ns) * 4,
1702 .out = part, .out_bytes = (size_t)ns * num_q_heads * S * (HD + 2) * 4,
1703 .grid_x = num_q_heads / heads_per_cta(HD, log2gqa), .grid_y = ns * S,
1704 .params = { maxb, f2u(score_scale(HD)), (uint32_t)ly->layer_stride_bytes, (uint32_t)ly->token_stride_bytes,
1705 (uint32_t)ly->kv_plane_stride_bytes, (uint32_t)ly->head_stride_bytes, num_q_heads, ns * maxb * 4 }
1706 };
1707 rc = launch(ks, &L, info);
1708 if (rc == OMEGA_GPU_ATTN_OK) combine_splits(part, out + (size_t)s0 * row, (size_t)ns * num_q_heads, S, HD);
1709 }
1710 omega_gpu_host_free(host_tmp); omega_gpu_host_free(tab);
1711 }
1712 UNLOCK();
1713 omega_gpu_host_free(eff); omega_gpu_host_free(slot_of); omega_gpu_host_free(touched); omega_gpu_host_free(part); omega_gpu_host_free(gz);
1714 if (info) info->call_ns = now_ns() - t0;
1715 return rc;
1716}
1717
1718int omega_gpu_paged_attention_bf16(const float *q, const void *pool, const OmegaGpuKvLayout *layout,
1719 const uint32_t *block_ids, uint32_t num_block_ids,
1720 uint32_t context_len, uint32_t layer_idx,
1721 uint32_t num_q_heads, uint32_t num_kv_heads, uint32_t head_dim,
1722 float *out, OmegaGpuAttnInfo *info) {
1723 if (!q || !pool || !layout || !out || (num_block_ids && !block_ids)) return OMEGA_GPU_ATTN_BAD_ARGS;
1724 const uint32_t *tables[1] = { block_ids };
1725 uint32_t nb[1] = { num_block_ids }, cx[1] = { context_len };
1726 return paged_core(q, pool, layout, tables, nb, cx, 1, layer_idx, num_q_heads, num_kv_heads, head_dim, out, info);
1727}
1728
1729int omega_gpu_paged_attention_batch_bf16(const float *q, const void *pool, const OmegaGpuKvLayout *layout,
1730 const int32_t *block_tables, const int32_t *context_lens,
1731 uint32_t max_blocks_per_seq, uint32_t num_seqs, uint32_t layer_idx,
1732 uint32_t num_q_heads, uint32_t num_kv_heads, uint32_t head_dim,
1733 float *out, OmegaGpuAttnInfo *info) {
1734 if (!q || !pool || !layout || !out || !block_tables || !context_lens) return OMEGA_GPU_ATTN_BAD_ARGS;
1735 uint64_t p[16]={num_seqs,1};int pr=ap_plan(AP_AT,19,p);if(pr)return pr;
1736 /* the oracle's rules: ctx <= 0 -> 0; a table row past the array -> empty; negatives removed */
1737 uint32_t **tables = omega_gpu_host_calloc(num_seqs, sizeof *tables);
1738 uint32_t *nb = omega_gpu_host_calloc(num_seqs, sizeof *nb), *cx = omega_gpu_host_calloc(num_seqs, sizeof *cx);
1739 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; }
1740 int rc = OMEGA_GPU_ATTN_OK;
1741 av_context(cx, context_lens, num_seqs);
1742 for (uint32_t s = 0; s < num_seqs; s++) {
1743 tables[s] = omega_gpu_host_calloc(max_blocks_per_seq ? max_blocks_per_seq : 1, sizeof **tables);
1744 if (!tables[s]) { rc = OMEGA_GPU_ATTN_CHIP_FAIL; break; }
1745 nb[s] = (uint32_t)av_compact32(tables[s], block_tables + (size_t)s * max_blocks_per_seq, max_blocks_per_seq);
1746 }
1747 if (rc == OMEGA_GPU_ATTN_OK)
1748 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);
1749 for (uint32_t s = 0; s < num_seqs; s++) omega_gpu_host_free(tables[s]);
1750 omega_gpu_host_free(tables); omega_gpu_host_free(nb); omega_gpu_host_free(cx);
1751 return rc;
1752}
1753
1754static const char *const k_mutant_names[OMEGA_GPU_ATTN_MUTANT_COUNT] = {
1755 "none", "NO_MAX", "KV_HEAD", "SLOT", "NO_RESCALE", "Q_ROW", "OUT_ROW"
1756};
1757_Static_assert(sizeof k_mutant_names / sizeof k_mutant_names[0] == OMEGA_GPU_ATTN_MUTANT_COUNT, "mutant name table");
1758
1759const char *omega_gpu_attention_mutant_name(OmegaGpuAttnMutant m) {
1760 return (m >= 0 && m < OMEGA_GPU_ATTN_MUTANT_COUNT && k_mutant_names[m]) ? k_mutant_names[m] : "?";
1761}
1762
1763void omega_gpu_attention_test_set_general_mutant(OmegaGpuAttnGeneralMutant m) {
1764 LOCK();
1765 g_gmutant = (m > 0 && m < OMEGA_GPU_ATTN_GMUT_COUNT) ? (int)m : 0;
1766 cache_clear_locked();
1767 UNLOCK();
1768}
1769static const char *const k_gmutant_names[OMEGA_GPU_ATTN_GMUT_COUNT] = {
1770 "none", "GQA_MAP", "TAIL_CHUNK", "TAIL_DIMS", "CAUSAL", "SCALE"
1771};
1772_Static_assert(sizeof k_gmutant_names / sizeof k_gmutant_names[0] == OMEGA_GPU_ATTN_GMUT_COUNT, "general mutant name table");
1773const char *omega_gpu_attention_general_mutant_name(OmegaGpuAttnGeneralMutant m) {
1774 return (m >= 0 && m < OMEGA_GPU_ATTN_GMUT_COUNT) ? k_gmutant_names[m] : "?";
1775}
1776
1777const char *omega_gpu_attention_rc_name(int rc) {
1778 switch (rc) {
1779 case OMEGA_GPU_ATTN_OK: return "OK";
1780 case OMEGA_GPU_ATTN_BAD_ARGS: return "BAD_ARGS";
1781 case OMEGA_GPU_ATTN_TOO_LARGE: return "TOO_LARGE";
1782 case OMEGA_GPU_ATTN_CODEGEN_FAIL: return "CODEGEN_FAIL";
1783 case OMEGA_GPU_ATTN_CHIP_FAIL: return "CHIP_FAIL";
1784 case OMEGA_GPU_ATTN_UNWRITTEN: return "UNWRITTEN";
1785 default: return "UNKNOWN";
1786 }
1787}
1788
1789/* omega #308 R2 test hook: 0 production, 1 lane-dependent branch inside a reconvergence
1790 * region, 2 the same with the BSYNC dropped (negative control). Clears the kernel cache. */
1791void omega_gpu_attention_test_set_divergent(int mode) {
1792 LOCK();
1793 g_divergent = (mode < 0 || mode > 2) ? 0 : mode;
1794 cache_clear_locked();
1795 UNLOCK();
1796}