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