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