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/gpu-reconv-308/T1a-GPU-RECONV-0a1812f/omega_gpu_elementwise_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 / gpu-reconv-308 / T1a-GPU-RECONV-0a1812f / omega_gpu_elementwise_api.c` 1139 lines ยท 59968 bytes Raw Blame History 1 /* omega_gpu_elementwise_api.c: FB-1 cut 4 (2026-10-04). See the header. 2 * 3 * Layout of this file: (1) kernel codegen on top of the BlackwellIR, with a 4 * small scheduler that writes every control word; (2) one launcher cloned from 5 * the chip-proven tensor matmul path (omega_blackwell_execute_matmul_tensor); 6 * (3) the public entry points, which split work into <= OMEGA_GPU_EW_MAX_CTAS 7 * launches and run the host-side bookkeeping. 8 * 9 * Scheduling rules (chip-learned, src/omega_numeric.c omega_numeric_check_patch): 10 * - a variable-latency result (LDG, LDS, LDC, LDCU, S2R, SHFL, MUFU) arrives through 11 * a scoreboard; the producer stalls >= 2 and the consumer waits on that SB; 12 * - a fixed-latency result (FADD FMUL FFMA IMAD IADD3 MOV LOP3 SHF) has no 13 * scoreboard: the producer stalls >= 5 before its consumer (we use 6); 14 * - a predicate producer (ISETP) stalls 14 before @P0 use (NAK SM120 padding); 15 * - stores (STG, STS) set a read barrier so the next instruction cannot overwrite 16 * the source register early. 17 * The emitter below serialises: every instruction waits on everything still 18 * pending. A final local pass tightens supported adjacent ALU pairs to 5 cycles. 19 */ 20 #include "omega_gpu_elementwise_api.h" 21 #include "omega_blackwell_codegen.h" 22 #include "omega_bw_reconv.h" 23 #include "omega_blackwell_qmd.h" 24 #include "omega_blackwell_submit.h" 25 #include "omega_gpu_session.h" 26 #include "sha256.h" 27 #include 28 #include 29 #include 30 #include 31 32 /* ------------------------------------------------------------------ codegen */ 33 34 #define CW(stall, wbar, rbar, wait) \ 35 (((uint32_t)(stall) << 9) | ((uint32_t)(wbar) << 14) | ((uint32_t)(rbar) << 17) | ((uint32_t)(wait) << 20)) 36 #define CW_YIELD 0x2000u 37 #define SB_NONE 7u 38 #define SB_GPR 0u /* variable-latency GPR results */ 39 #define SB_RD 1u /* store source-register read barrier */ 40 #define SB_UGPR 2u /* uniform-register results (LDCU) */ 41 42 enum { K_FIXED, K_PRED, K_VAR, K_UVAR, K_STORE, K_SYNC, K_EXIT, K_BRA, K_BSSY, K_BSYNC }; 43 44 #define EW_MAX_LOOPS 4 45 typedef struct { 46 BlackwellIRProgram *p; 47 uint32_t pending; /* scoreboards set and not yet waited on */ 48 int err; 49 int loop_start[EW_MAX_LOOPS], loop_end[EW_MAX_LOOPS]; 50 int n_loops; 51 int open_start[EW_MAX_LOOPS]; /* starts of loops begun and not yet ended (nesting stack) */ 52 int depth; 53 BwRegions rg; /* structured reconvergence regions (omega #308) */ 54 int rg_mutant; /* test only: 1 = drop the BSYNC at join, 2 = corrupt the BSSY target (host sim must catch both) */ 55 int exited; /* a predicated EXIT was emitted: some lanes of a warp may be gone */ 56 int exit_sync_ok; /* test only: lets a kernel put SHFL/BAR after a predicated EXIT (the negative control R6) */ 57 int test_path; /* building for omega_gpu_elementwise_codegen_ir (host tests), never for a launch */ 58 } Em; 59 60 static void emit(Em *e, BlackwellIRInsn in, int kind) { 61 uint32_t wait = e->pending; 62 switch (kind) { 63 case K_FIXED: in.control = CW(6, SB_NONE, SB_NONE, wait); e->pending = 0; break; 64 case K_PRED: in.control = CW(14, SB_NONE, SB_NONE, wait); e->pending = 0; break; 65 case K_VAR: in.control = CW(4, SB_GPR, SB_NONE, wait) | CW_YIELD; e->pending = 1u << SB_GPR; break; 66 case K_UVAR: in.control = CW(4, SB_UGPR, SB_NONE, wait) | CW_YIELD; e->pending = 1u << SB_UGPR; break; 67 case K_STORE: in.control = CW(4, SB_NONE, SB_RD, wait) | CW_YIELD; e->pending = 1u << SB_RD; break; 68 case K_SYNC: in.control = CW(6, SB_NONE, SB_NONE, wait); e->pending = 0; break; 69 /* a predicated EXIT or BRA that falls through must not be the only waiter */ 70 case K_EXIT: in.control = CW(5, SB_NONE, SB_NONE, wait); e->pending = in.predicate_p0 ? wait : 0; break; 71 case K_BRA: in.control = CW(5, SB_NONE, SB_NONE, wait); e->pending = in.predicate_p0 ? wait : 0; break; 72 /* BSSY / BSYNC read no registers; the stall counts (1 and 5, both with yield) are the ones 73 * nvcc 13.0.88 writes for sm_121 (docs/gpu-reconvergence-308.md). They wait on everything 74 * pending so that, as for every branch here, nothing is in flight across a control edge 75 * and the straight-line scoreboard walk in the tests stays valid. */ 76 case K_BSSY: in.control = CW(1, SB_NONE, SB_NONE, wait) | CW_YIELD; e->pending = 0; break; 77 case K_BSYNC: in.control = CW(5, SB_NONE, SB_NONE, wait) | CW_YIELD; e->pending = 0; break; 78 default: e->err = -1; return; 79 } 80 if (omega_bw_ir_append(e->p, &in) < 0) e->err = -1; /* append returns the index */ 81 } 82 83 static int V(Em *e) { int v = omega_bw_ir_alloc_vreg(e->p); if (v < 0) e->err = -1; return v; } 84 static int V64(Em *e) { int v = omega_bw_ir_alloc_vreg64(e->p); if (v < 0) e->err = -1; return v; } 85 static int UV64(Em *e) { int v = omega_bw_ir_alloc_uvreg64(e->p); if (v < 0) e->err = -1; return v; } 86 static int here(const Em *e) { return (int)e->p->count; } 87 88 #define NOREG -1 89 static BlackwellIRInsn I0(BlackwellIROpcode op) { 90 BlackwellIRInsn in; memset(&in, 0, sizeof in); 91 in.op = op; in.dst_vreg = NOREG; in.src1_vreg = NOREG; in.src2_vreg = NOREG; in.src3_vreg = NOREG; in.ureg = NOREG; 92 return in; 93 } 94 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); } 95 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); } 96 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); } 97 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); } 98 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); } 99 static void movf(Em *e, int dst, float f) { uint32_t u; memcpy(&u, &f, 4); movi(e, dst, u); } 100 static void movrz(Em *e, int dst) { BlackwellIRInsn i = I0(BW_IR_MOV_RZ); i.dst_vreg = dst; emit(e, i, K_FIXED); } 101 /* dst = a * imm + c (c may be NOREG for RZ) */ 102 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); } 103 /* dst = a * b + c (registers) */ 104 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); } 105 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); } 106 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); } 107 /* dst64 = idx * 4 + ptr64 (byte address of element idx) */ 108 static void addr4(Em *e, int dst64, int idx, int ptr64) { BlackwellIRInsn i = I0(BW_IR_IMAD_WIDE); i.dst_vreg = dst64; i.src1_vreg = idx; i.imm = 4; i.src3_vreg = ptr64; 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 /* Independent loads (LDG_E from global, or LDS32 from shared memory with ureg NOREG) issued 111 * back to back (campaign C2a, 2026-10-05). The first load 112 * waits on whatever is pending; the others wait on nothing, so all n are in flight together. 113 * Every load sets SB_GPR (a counting scoreboard), so the next instruction waits once for all 114 * of them instead of once per load. Fails the build if a load address is a destination of the 115 * group or a destination repeats (the later loads would read an operand still in flight). */ 116 static void ld_group(Em *e, BlackwellIROpcode op, int n, const int *dst, const int *addr, int ureg) { 117 for (int i = 0; i < n; i++) 118 for (int k = 0; k < n; k++) 119 if (addr[i] == dst[k] || (k != i && dst[i] == dst[k])) { e->err = -1; return; } 120 for (int i = 0; i < n; i++) { 121 if (op != BW_IR_LDG_E && op != BW_IR_LDS32) { e->err = -1; return; } 122 BlackwellIRInsn in = I0(op); in.dst_vreg = dst[i]; in.src1_vreg = addr[i]; in.ureg = ureg; 123 if (i == 0) { emit(e, in, K_VAR); continue; } 124 in.control = CW(4, SB_GPR, SB_NONE, 0) | CW_YIELD; /* nonzero, so the encoder keeps it */ 125 if (omega_bw_ir_append(e->p, &in) < 0) e->err = -1; 126 } 127 } 128 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); } 129 static void 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); } 130 static void 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); } 131 static void 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); } 132 static void 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); } 133 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); } 134 /* Cross-lane and warp-ending ops are refused inside an open reconvergence region (omega #308): 135 * a SHFL or BAR.SYNC reached by a split warp reads inactive lanes / counts a partial warp 136 * (undefined; the 2026-10-04 attention bug), and a lane that EXITs inside a region can no 137 * longer be joined. The build fails closed instead of emitting such code. */ 138 /* Cross-lane instructions (SHFL, BAR.SYNC) need the whole warp present. The emitter refuses 139 * them (fails the build) inside an open reconvergence region, where lanes may be on different 140 * paths, and after a predicated EXIT, where lanes may be gone for good: a SHFL then reads 141 * inactive lanes (undefined on the chip, the attention failure of 2026-10-04). A kernel that 142 * must drop lanes before a cross-lane step clamps them instead and exits them afterwards. */ 143 static int warp_split(Em *e) { if (e->rg.depth > 0 || (e->exited && !e->exit_sync_ok)) { e->err = -1; return 1; } return 0; } 144 static void shfl_down(Em *e, int d, int a, uint32_t off) { if (warp_split(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); } 145 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); } 146 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); } 147 static void bar_sync(Em *e) { if (warp_split(e)) return; emit(e, I0(BW_IR_BAR_SYNC), K_SYNC); } 148 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); } 149 /* An EXIT inside a region would leave the barrier waiting for a lane that never comes: refused. */ 150 static void exit_if_p0(Em *e) { if (e->rg.depth > 0) { e->err = -1; return; } e->exited = 1; BlackwellIRInsn i = I0(BW_IR_EXIT); i.predicate_p0 = true; emit(e, i, K_EXIT); } 151 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); } 152 static void tail(Em *e) { 153 emit(e, I0(BW_IR_EXIT), K_EXIT); 154 BlackwellIRInsn self = I0(BW_IR_BRA); /* the self-branch every kernel here ends with */ 155 self.control = 0x000fc000u; 156 if (omega_bw_ir_append(e->p, &self) < 0) e->err = -1; 157 } 158 /* Loops may nest (prime race cut): begin pushes the start, end pops it, so the inner 159 * loop is closed (and its liveness fixed) first. For the single-level loops above this 160 * is exactly the old behaviour. */ 161 static void loop_begin(Em *e) { if (e->depth >= EW_MAX_LOOPS) { e->err = -1; return; } e->open_start[e->depth++] = here(e); } 162 /* Closing a loop: every value defined before the loop and read inside it stays 163 * live until the back-branch, otherwise the linear-scan allocator (which knows 164 * nothing about back-edges) would hand its register to a body temporary whose 165 * first definition comes after the value's last textual use (e.g. the scale y 166 * in rmsnorm pass 2), and the next iteration would read garbage. */ 167 static void loop_end(Em *e) { 168 if (e->n_loops >= EW_MAX_LOOPS || e->depth <= 0) { e->err = -1; return; } 169 int start = e->open_start[--e->depth], end = here(e) - 1; 170 e->loop_start[e->n_loops] = start; 171 e->loop_end[e->n_loops] = end; 172 e->n_loops++; 173 OmegaRegAlloc *ra = &e->p->regalloc; 174 for (int v = 0; v < ra->num_vregs; v++) { 175 OmegaLiveInterval *iv = &ra->intervals[v]; 176 if (iv->first_def >= 0 && iv->first_def < start && iv->last_use >= start && iv->last_use < end) iv->last_use = end; 177 } 178 } 179 180 /* Kernel argument words (constant bank 0, same slots as the matmul path): 181 * 0x380 a, 0x388 b, 0x390 c (64-bit each), then four 32-bit parameters. */ 182 #define ARG_A 0x380u 183 #define ARG_B 0x388u 184 #define ARG_C 0x390u 185 #define ARG_P0 0x398u 186 #define ARG_P1 0x39cu 187 #define ARG_P2 0x3a0u 188 #define ARG_P3 0x3a4u 189 #define ARG_P4 0x3a8u 190 #define DESC_OFF 0x358u 191 192 typedef struct { int udesc, pa, pb, pc, tid, cta; } Pro; 193 static Pro prologue(Em *e) { 194 Pro r; 195 r.udesc = UV64(e); r.pa = V64(e); r.pb = V64(e); r.pc = V64(e); r.tid = V(e); r.cta = V(e); 196 ldcu64(e, r.udesc, DESC_OFF); 197 ldc64(e, r.pa, ARG_A); ldc64(e, r.pb, ARG_B); ldc64(e, r.pc, ARG_C); 198 s2r(e, r.tid, BW_SR_TID_X); s2r(e, r.cta, BW_SR_CTAID_X); 199 return r; 200 } 201 202 /* out[i] = 2^a[i] for i < n (n = P0). Threads 128, grid ceil(n/128). Mutant: 2^(a+1). */ 203 static void gen_ex2(Em *e, int mutant) { 204 Pro p = prologue(e); 205 int n = V(e), i = V(e), off = V64(e), x = V(e), y = V(e); 206 ldc32(e, n, ARG_P0); 207 imadi(e, i, p.cta, OMEGA_GPU_EW_THREADS, p.tid); 208 isetp_ge_u32(e, i, n); 209 exit_if_p0(e); 210 addr4(e, off, i, p.pa); 211 ldg(e, x, off, p.udesc); 212 if (mutant) { int one = V(e); movf(e, one, 1.0f); fadd(e, x, x, one); } 213 mufu(e, BW_IR_MUFU_EX2, y, x); 214 addr4(e, off, i, p.pc); 215 stg(e, off, y, p.udesc); 216 tail(e); 217 } 218 219 /* out[i] = a[i ^ 127] within each CTA of 128 (n % 128 == 0). STS own word, BAR.SYNC, 220 * LDS the partner word. Mutant: LDS own word (no exchange). */ 221 static void gen_xchg(Em *e, int mutant) { 222 Pro p = prologue(e); 223 int i = V(e), off = V64(e), x = V(e), saddr = V(e), paddr = V(e), mask = V(e), y = V(e); 224 imadi(e, i, p.cta, OMEGA_GPU_EW_THREADS, p.tid); 225 addr4(e, off, i, p.pa); 226 ldg(e, x, off, p.udesc); 227 imadi(e, saddr, p.tid, 4, NOREG); 228 sts32(e, saddr, x); 229 bar_sync(e); 230 if (mutant) { 231 lds32(e, y, saddr); 232 } else { 233 movi(e, mask, OMEGA_GPU_EW_THREADS - 1); 234 lop3xor(e, paddr, p.tid, mask); 235 imadi(e, paddr, paddr, 4, NOREG); 236 lds32(e, y, paddr); 237 } 238 addr4(e, off, i, p.pc); 239 stg(e, off, y, p.udesc); 240 tail(e); 241 } 242 243 /* One CTA of 128 threads per row. P0 = dim/128 (loop count), P1 = bits(1/dim), 244 * P2 = bits(eps), P3 = dim. Mutant: the warp tree drops the last SHFL step. */ 245 static void gen_rmsnorm(Em *e, int mutant) { 246 Pro p = prologue(e); 247 int nk = V(e), invd = V(e), eps = V(e), dim = V(e); 248 int rowbase = V(e), idx = V(e), col = V(e), k = V(e), acc = V(e), cT = V(e), c1 = V(e); 249 int off = V64(e), x = V(e), t = V(e); 250 ldc32(e, nk, ARG_P0); ldc32(e, invd, ARG_P1); ldc32(e, eps, ARG_P2); ldc32(e, dim, ARG_P3); 251 imadr(e, rowbase, p.cta, dim, NOREG); 252 iadd3(e, idx, rowbase, p.tid); 253 movrz(e, acc); movrz(e, k); 254 movi(e, cT, OMEGA_GPU_EW_THREADS); movi(e, c1, 1); 255 loop_begin(e); 256 int l1 = here(e); 257 addr4(e, off, idx, p.pa); 258 ldg(e, x, off, p.udesc); 259 ffma(e, acc, x, x, acc); 260 iadd3(e, idx, idx, cT); 261 iadd3(e, k, k, c1); 262 isetp_ge_u32(e, k, nk); 263 bra_back_if_not_p0(e, l1); 264 loop_end(e); 265 static const uint32_t steps[5] = { 16, 8, 4, 2, 1 }; 266 for (int s = 0; s < (mutant ? 4 : 5); s++) { shfl_down(e, t, acc, steps[s]); fadd(e, acc, acc, t); } 267 int saddr = V(e); 268 imadi(e, saddr, p.tid, 4, NOREG); 269 sts32(e, saddr, acc); 270 bar_sync(e); 271 int a0 = V(e), a1 = V(e), a2 = V(e), a3 = V(e), s0 = V(e), s1 = V(e), s2 = V(e), s3 = V(e), sum = V(e); 272 movrz(e, a0); movi(e, a1, 128); movi(e, a2, 256); movi(e, a3, 384); 273 lds32(e, s0, a0); lds32(e, s1, a1); lds32(e, s2, a2); lds32(e, s3, a3); 274 fadd(e, sum, s0, s1); fadd(e, sum, sum, s2); fadd(e, sum, sum, s3); 275 int v = V(e), y = V(e), u = V(e), cmh = V(e), c15 = V(e); 276 fmul(e, v, sum, invd); 277 fadd(e, v, v, eps); 278 mufu(e, BW_IR_MUFU_RSQ, y, v); 279 movf(e, cmh, -0.5f); movf(e, c15, 1.5f); 280 fmul(e, u, v, y); fmul(e, u, u, y); ffma(e, u, u, cmh, c15); fmul(e, y, y, u); 281 int offw = V64(e), offc = V64(e), w = V(e), o = V(e); 282 iadd3(e, idx, rowbase, p.tid); 283 imadi(e, col, p.tid, 1, NOREG); /* col = tid (the encoder maps a missing src2 to R0, not RZ, so no IADD3 here) */ 284 movrz(e, k); 285 loop_begin(e); 286 int l2 = here(e); 287 addr4(e, off, idx, p.pa); 288 ldg(e, x, off, p.udesc); 289 addr4(e, offw, col, p.pb); 290 ldg(e, w, offw, p.udesc); 291 fmul(e, o, x, y); 292 fmul(e, o, o, w); 293 addr4(e, offc, idx, p.pc); 294 stg(e, offc, o, p.udesc); 295 iadd3(e, idx, idx, cT); 296 iadd3(e, col, col, cT); 297 iadd3(e, k, k, c1); 298 isetp_ge_u32(e, k, nk); 299 bra_back_if_not_p0(e, l2); 300 loop_end(e); 301 tail(e); 302 } 303 304 /* One CTA of head_dim/2 threads per head. P0 = head_dim, P1 = head_dim/2. 305 * a = vector, b = table (cos in the first half of each head, sin in the second). 306 * Mutant: out0 = q0*cos + q1*sin. */ 307 static void gen_rope(Em *e, int mutant) { 308 Pro p = prologue(e); 309 int hd = V(e), half = V(e), i0 = V(e), i1 = V(e), off0 = V64(e), off1 = V64(e); 310 int q0 = V(e), q1 = V(e), c = V(e), s = V(e), t0 = V(e), t1 = V(e), o0 = V(e), o1 = V(e); 311 ldc32(e, hd, ARG_P0); ldc32(e, half, ARG_P1); 312 imadr(e, i0, p.cta, hd, p.tid); 313 iadd3(e, i1, i0, half); 314 addr4(e, off0, i0, p.pa); ldg(e, q0, off0, p.udesc); 315 addr4(e, off1, i1, p.pa); ldg(e, q1, off1, p.udesc); 316 addr4(e, off0, i0, p.pb); ldg(e, c, off0, p.udesc); 317 addr4(e, off1, i1, p.pb); ldg(e, s, off1, p.udesc); 318 fmul(e, t0, q0, c); fmul(e, t1, q1, s); 319 if (mutant) fadd(e, o0, t0, t1); else fsub(e, o0, t0, t1); 320 fmul(e, t0, q0, s); fmul(e, t1, q1, c); 321 fadd(e, o1, t0, t1); 322 addr4(e, off0, i0, p.pc); stg(e, off0, o0, p.udesc); 323 addr4(e, off1, i1, p.pc); stg(e, off1, o1, p.udesc); 324 tail(e); 325 } 326 327 /* out[i] = g/(1+2^(g*-log2e)) * up for i < n (P0). Mutant: 2^(g*+log2e). */ 328 static void gen_swiglu(Em *e, int mutant) { 329 Pro p = prologue(e); 330 int n = V(e), i = V(e), off = V64(e), g = V(e), u = V(e), k = V(e), t = V(e), ex = V(e), d = V(e), r = V(e), one = V(e), o = V(e); 331 ldc32(e, n, ARG_P0); 332 imadi(e, i, p.cta, OMEGA_GPU_EW_THREADS, p.tid); 333 isetp_ge_u32(e, i, n); 334 exit_if_p0(e); 335 addr4(e, off, i, p.pa); ldg(e, g, off, p.udesc); 336 addr4(e, off, i, p.pb); ldg(e, u, off, p.udesc); 337 movf(e, k, mutant ? 1.`4426950408889634f` : -1.`4426950408889634f`); 338 movf(e, one, 1.0f); 339 fmul(e, t, g, k); 340 mufu(e, BW_IR_MUFU_EX2, ex, t); 341 fadd(e, d, ex, one); 342 mufu(e, BW_IR_MUFU_RCP, r, d); 343 fmul(e, o, g, r); 344 fmul(e, o, o, u); 345 addr4(e, off, i, p.pc); 346 stg(e, off, o, p.udesc); 347 tail(e); 348 } 349 350 /* ------------------------------------------- prime race sieve (2026-10-05) */ 351 static void lop3lut(Em *e, int d, int a, int b, int c, uint32_t lut) { BlackwellIRInsn i = I0(BW_IR_LOP3_LUT); i.dst_vreg = d; i.src1_vreg = a; i.src2_vreg = b; i.src3_vreg = c; i.imm = lut & 0xffu; emit(e, i, K_FIXED); } 352 static void shl_r(Em *e, int d, int a, int n) { BlackwellIRInsn i = I0(BW_IR_SHF_L_U32); i.dst_vreg = d; i.src1_vreg = a; i.src2_vreg = n; emit(e, i, K_FIXED); } 353 static void shr_i(Em *e, int d, int a, uint32_t n) { BlackwellIRInsn i = I0(BW_IR_SHF_R); i.dst_vreg = d; i.src1_vreg = a; i.imm = n; emit(e, i, K_FIXED); } 354 static void imadhi(Em *e, int d, int a, int b) { BlackwellIRInsn i = I0(BW_IR_IMAD_HI_U32); i.dst_vreg = d; i.src1_vreg = a; i.src2_vreg = b; emit(e, i, K_FIXED); } 355 /* dst64 = a * imm + c64 (IMAD.WIDE.U32 immediate form) */ 356 static void widei(Em *e, int dst64, int a, uint32_t imm, int c64) { BlackwellIRInsn i = I0(BW_IR_IMAD_WIDE); i.dst_vreg = dst64; i.src1_vreg = a; i.imm = imm; i.src3_vreg = c64; emit(e, i, K_FIXED); } 357 /* @P0 BRA forward; returns the instruction index for bra_patch_here */ 358 static int bra_fwd_if_p0(Em *e) { int at = here(e); BlackwellIRInsn i = I0(BW_IR_BRA); i.predicate_p0 = true; i.imm = 1; emit(e, i, K_BRA); return at; } 359 static void bra_patch_here(Em *e, int at) { if (e->err == 0 && at >= 0 && at < here(e)) e->p->insns[at].imm = (uint32_t)(here(e) - at); else e->err = -1; } 360 static void bra_always(Em *e, int target) { BlackwellIRInsn i = I0(BW_IR_BRA); i.imm = (uint32_t)(target - here(e)); emit(e, i, K_BRA); } 361 362 /* ---- structured reconvergence regions (omega #308; bookkeeping in omega_bw_reconv.h) ---- 363 * region_begin: BSSY Bd (d = nesting depth), fails closed when no barrier register is left. 364 * region_exit: a forward branch out of the innermost region, patched to its BSYNC at join 365 * (RX_ALWAYS, RX_IF_P0, RX_IF_NOT_P0). 366 * region_join: BSYNC Bd; patches the BSSY to the instruction after it and every exit to it. 367 * Usage: divergent loop = region_begin; L: isetp; region_exit(RX_IF_P0); body; bra_always(L); region_join. 368 * if/else diamond = region_begin; isetp; t = bra_fwd_if_p0; then; region_exit(RX_ALWAYS); 369 * bra_patch_here(t); else; region_join. */ 370 enum { RX_ALWAYS, RX_IF_P0, RX_IF_NOT_P0 }; 371 static int region_begin(Em *e) { 372 int bar = bw_regions_next_bar(&e->rg); 373 if (bar < 0) { e->err = -1; return -1; } 374 int at = here(e); 375 BlackwellIRInsn i = I0(BW_IR_BSSY); i.bar_reg = (uint8_t)bar; i.imm = 2; emit(e, i, K_BSSY); 376 if (bw_regions_begin(&e->rg, at) < 0) e->err = -1; 377 return bar; 378 } 379 static void region_exit(Em *e, int cond) { 380 int at = here(e); 381 BlackwellIRInsn i = I0(BW_IR_BRA); i.imm = 1; 382 if (cond != RX_ALWAYS) { i.predicate_p0 = true; i.predicate_not = (cond == RX_IF_NOT_P0); } 383 emit(e, i, K_BRA); 384 if (bw_regions_exit(&e->rg, at) < 0) e->err = -1; 385 } 386 static void region_join(Em *e) { 387 if (e->rg.depth <= 0) { e->err = -1; return; } 388 int d = e->rg.depth - 1, bsync = here(e); 389 BlackwellIRInsn i = I0(e->rg_mutant == 1 ? BW_IR_NOP : BW_IR_BSYNC); i.bar_reg = (uint8_t)d; emit(e, i, K_BSYNC); 390 if (e->rg_mutant == 1) { 391 /* negative control (host sim only): the join is a NOP; patch as the real join would */ 392 BwRegions *r = &e->rg; r->depth--; 393 e->p->insns[r->bssy_at[d]].imm = (uint32_t)(bsync + 1 - r->bssy_at[d]); 394 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]); 395 return; 396 } 397 if (bw_regions_join(&e->rg, e->p, bsync) != d) e->err = -1; 398 if (e->rg_mutant == 2) e->p->insns[e->rg.bssy_at[d]].imm += 1; /* negative control: BSSY names the wrong join */ 399 } 400 401 /* Word-parallel odd-only sieve (docs: handoff 2026-10-05 DESIGN "GPU kernel (native)"). 402 * Thread t owns 32-bit output words w = t, t + S, t + 2S, ... (S = P1 = threads launched; 403 * the I42 envelope caps a launch at OMEGA_GPU_EW_MAX_CTAS CTAs, so a grid-stride loop 404 * replaces one thread per word). Every word has exactly one writer; no atomics. 405 * Bit j of word w is the odd number 2(32w + j) + 1. 406 * Arguments: a (0x380) = prime table, entries {p, magic = ceil(2^32 / p), k0 = (p*p - 1)/2} 407 * (12 bytes, ascending p, odd primes <= isqrt(limit)) followed by ONE sentinel entry with 408 * k0 = 0xffffffff that ends every scan; c (0x390) = output words; 409 * P0 = nwords, P1 = S, P2 = last word index, P3 = ~tailmask (bits past the last odd). 410 * Range: limit < 2^32 (so base, k0 < 2^31 and the sign-bit tricks below hold). 411 * Per word: base = 32w; for each prime while k0 < base + 32: 412 * d = base - k0; neg = d >> 31 (k0 > base); dpos = neg ? 0 : d; jadd = neg ? k0 - base : 0 413 * q = hi32(dpos * magic) (= floor(dpos/p) or one more: magic is rounded up) 414 * r = dpos - q*p (q one too big -> r = (dpos mod p) - p, wrapped) 415 * j = p - r; j -= p * ((r - 1) >> 31) (r == 0 -> 0; wrapped r -> p - (dpos mod p)) 416 * One fix covers both cases: with q one too big, dpos mod p >= p - dpos*e/2^32 > p/2 > 0 417 * (e = magic*p - 2^32 < p, dpos < 2^31), so the true remainder is never 0 there and 418 * p - r - p = p - (dpos mod p) is the right offset. A separate "r += p if wrapped" step was 419 * removed after a negative control showed it changes no output (host sim, limit 1e7, where 420 * the overshoot occurs 268 times; bench/prime_race/tests magic_model). 421 * j += jadd; while j < 32 { acc |= 1 << j; j += p } 422 * then acc |= (w == 0) (the number 1), word = ~(acc | (w == last ? ~tailmask : 0)). 423 * Branch-free except the loop branches. Mutant: drops the j fix (j = p - r unreduced), so words where 424 * base - k0 is a multiple of p (or q overshot) mark the wrong bits. 425 * 426 * staged = 1 (OMEGA_GPU_EW_PRIME_SIEVE_SHARED, campaign C3): P4 = table words, sentinel included 427 * (3 per entry). The CTA first copies the table into shared memory at offset 0 (thread t copies 428 * words t, t + 128, ...), BAR_SYNC, then the prime loop reads shared memory (LDS) instead of 429 * uncached global memory. Every thread reaches the barrier: the w >= nwords exit comes after 430 * it. The launch must declare at least 4 * P4 bytes of shared memory. 431 * 432 * divergent (omega #308, regression R1): 0 = the warp-uniform mark loop above (campaign C5). 433 * 1 = the original lane-dependent mark loop (omega `888a011`: `while j < 32 { acc |= 1 << j; j += p }`) 434 * wrapped in a reconvergence region. 2 = as 1, and the prime loop (whose break `k0 >= base + 32` 435 * is also lane-dependent: every lane sieves a different word) wrapped in an outer region, so the 436 * mark loop's region nests inside it (B0 outer, B1 inner). */ 437 static void gen_prime_sieve(Em *e, int mutant, int staged, int divergent) { 438 Pro pr = prologue(e); 439 int nwords = V(e), stride = V(e), lastw = V(e), tailinv = V(e); 440 int one = V(e), c32 = V(e), cm1 = V(e), w = V(e); 441 ldc32(e, nwords, ARG_P0); ldc32(e, stride, ARG_P1); ldc32(e, lastw, ARG_P2); ldc32(e, tailinv, ARG_P3); 442 movi(e, one, 1); movi(e, c32, 32); movi(e, cm1, 0xffffffffu); 443 int c4 = -1, c8 = -1, c12 = -1; 444 if (staged) { 445 int twords = V(e), i = V(e), ga = V64(e), val = V(e), sa = V(e); 446 c4 = V(e); c8 = V(e); c12 = V(e); 447 ldc32(e, twords, ARG_P4); 448 movi(e, c4, 4); movi(e, c8, 8); movi(e, c12, 12); 449 imadi(e, i, pr.tid, 1, NOREG); 450 /* The staging loop's trip count differs per thread (thread t copies words t, t+128, ...), 451 * so its exit splits the warp. The divergent variants rejoin the warp before BAR.SYNC 452 * (a barrier is not a reconvergence point: the fragments would stay split for the rest 453 * of the kernel). The production kernel keeps the 2026-10-05 C3 form unchanged. */ 454 if (divergent) region_begin(e); 455 loop_begin(e); /* staging loop */ 456 int ls = here(e); 457 isetp_ge_u32(e, i, twords); 458 int sdone = -1; 459 if (divergent) region_exit(e, RX_IF_P0); else sdone = bra_fwd_if_p0(e); 460 addr4(e, ga, i, pr.pa); 461 ldg(e, val, ga, pr.udesc); 462 imadi(e, sa, i, 4, NOREG); 463 sts32(e, sa, val); 464 imadi(e, i, one, OMEGA_GPU_EW_THREADS, i); 465 bra_always(e, ls); 466 loop_end(e); 467 if (divergent) region_join(e); else bra_patch_here(e, sdone); 468 bar_sync(e); 469 } 470 imadi(e, w, pr.cta, OMEGA_GPU_EW_THREADS, pr.tid); 471 isetp_ge_u32(e, w, nwords); 472 exit_if_p0(e); 473 474 /* ptr, a64, a64m: global addresses, or (staged) 32-bit shared offsets */ 475 int base = V(e), basep32 = V(e), acc = V(e); 476 int ptr = staged ? V(e) : V64(e), a64 = staged ? V(e) : V64(e), a64m = staged ? V(e) : V64(e); 477 int p = V(e), magic = V(e), k0 = V(e), negp = V(e), d = V(e), neg = V(e), nd = V(e), dpos = V(e), jadd = V(e); 478 int q = V(e), r = V(e), j = V(e), t = V(e), z = V(e), bit = V(e); 479 int e1 = V(e), m = V(e), word = V(e), oaddr = V64(e); 480 int tt = V(e), jj = V(e), sh = V(e), c31 = V(e), cm32 = V(e); 481 movi(e, c31, 31); movi(e, cm32, 0xffffffe0u); 482 483 loop_begin(e); /* word loop */ 484 int lw = here(e); 485 imadi(e, base, w, 32, NOREG); 486 iadd3(e, basep32, base, c32); 487 movrz(e, acc); 488 if (staged) movrz(e, ptr); else widei(e, ptr, one, 0, pr.pa); 489 490 if (divergent >= 2) region_begin(e); /* outer region: the prime loop's break is lane-dependent */ 491 loop_begin(e); /* prime loop */ 492 int lp = here(e); 493 /* one memory round trip per prime: all three entry words load together (C2a). The 494 * sentinel entry is a whole entry, so loading p and magic before the k0 test is in bounds. */ 495 if (staged) { iadd3(e, a64, ptr, c8); iadd3(e, a64m, ptr, c4); } 496 else { widei(e, a64, one, 8, ptr); widei(e, a64m, one, 4, ptr); } 497 { 498 const int dsts[3] = { k0, p, magic }, adrs[3] = { a64, ptr, a64m }; 499 if (staged) ld_group(e, BW_IR_LDS32, 3, dsts, adrs, NOREG); 500 else ld_group(e, BW_IR_LDG_E, 3, dsts, adrs, pr.udesc); 501 } 502 isetp_ge_u32(e, k0, basep32); 503 int brk = -1; 504 if (divergent >= 2) region_exit(e, RX_IF_P0); else brk = bra_fwd_if_p0(e); 505 imadi(e, negp, p, 0xffffffffu, NOREG); /* -p */ 506 imadi(e, d, k0, 0xffffffffu, base); /* base - k0 */ 507 shr_i(e, neg, d, 31); 508 imadi(e, nd, d, 0xffffffffu, NOREG); /* -d */ 509 imadr(e, dpos, neg, nd, d); /* d - neg*d */ 510 imadr(e, jadd, neg, nd, NOREG); /* neg * (k0 - base) */ 511 imadhi(e, q, dpos, magic); 512 imadr(e, r, q, negp, dpos); /* dpos - q*p */ 513 imadi(e, j, r, 0xffffffffu, p); /* p - r */ 514 if (!mutant) { 515 iadd3(e, t, r, cm1); 516 shr_i(e, z, t, 31); /* r == 0, or r wrapped (q one too big) */ 517 imadr(e, j, z, negp, j); /* j - p */ 518 } 519 iadd3(e, j, j, jadd); 520 521 /* mark loop (campaign C5): the trip count depends only on p, so every active lane runs the 522 * same ceil(32/p) steps and the warp never splits here (all active lanes are on the same 523 * prime). Bits past this word are masked out instead of branched around. The old loop ran 524 * "while j < 32", a lane-dependent branch with no reconvergence point. */ 525 if (divergent) { 526 /* R1: the `888a011` mark loop, lane-dependent trip count, inside a region. Each lane 527 * leaves at its own iteration (the exit jumps to the BSYNC) and the warp reunites there. */ 528 region_begin(e); 529 loop_begin(e); 530 int li = here(e); 531 isetp_ge_u32(e, j, c32); 532 region_exit(e, RX_IF_P0); 533 shl_r(e, bit, one, j); 534 lop3lut(e, acc, acc, bit, NOREG, 0xfc); /* acc | bit */ 535 iadd3(e, j, j, p); 536 bra_always(e, li); 537 loop_end(e); 538 region_join(e); 539 } else { 540 movrz(e, tt); 541 loop_begin(e); 542 int li = here(e); 543 isetp_ge_u32(e, tt, c32); 544 int done = bra_fwd_if_p0(e); 545 iadd3(e, jj, j, tt); 546 lop3lut(e, sh, jj, c31, NOREG, 0xc0); /* jj & 31 */ 547 shl_r(e, bit, one, sh); 548 iadd3(e, t, jj, cm32); 549 shr_i(e, z, t, 31); /* jj < 32 (j <= p + 31, far below 2^31) */ 550 imadi(e, m, z, 0xffffffffu, NOREG); /* all ones when jj < 32, else 0 */ 551 lop3lut(e, acc, acc, bit, m, 0xf8); /* acc | (bit & m) */ 552 iadd3(e, tt, tt, p); 553 bra_always(e, li); 554 loop_end(e); 555 bra_patch_here(e, done); 556 } 557 558 if (staged) iadd3(e, ptr, ptr, c12); else widei(e, ptr, one, 12, ptr); 559 bra_always(e, lp); 560 loop_end(e); 561 if (divergent >= 2) region_join(e); else bra_patch_here(e, brk); 562 563 iadd3(e, t, w, cm1); 564 shr_i(e, z, t, 31); /* w == 0: the number 1 is not prime */ 565 lop3lut(e, acc, acc, z, NOREG, 0xfc); 566 lop3xor(e, e1, w, lastw); 567 iadd3(e, t, e1, cm1); 568 shr_i(e, z, t, 31); /* w == last word */ 569 imadr(e, m, z, tailinv, NOREG); 570 lop3lut(e, word, acc, m, NOREG, 0x03); /* ~(acc | m) */ 571 addr4(e, oaddr, w, pr.pc); 572 stg(e, oaddr, word, pr.udesc); 573 /* IMAD, not IADD3: the IADD3 encoder ignores the scheduler control word (fixed 574 * 0x010fca00), so right after a store it would not wait on the read barrier */ 575 imadr(e, w, stride, one, w); 576 isetp_ge_u32(e, w, nwords); 577 bra_back_if_not_p0(e, lw); 578 loop_end(e); 579 tail(e); 580 } 581 582 /* ---- reconvergence probes (omega #308, regressions R3..R6 and the resource bound) ---- 583 * All: a, b = u32 inputs, out = u32, P0 = n; 128 threads, grid ceil(n/128); launched by 584 * omega_gpu_reconv_probe_u32. A lane past n clamps its index to n-1 so that it loads valid 585 * data and takes part in the warp-wide SHFL; it exits only after the SHFL, before its store. 586 * Each probe computes a per-lane r on divergent paths, joins, then 587 * out[i] = r + 4099 * s, s = r of lane (lane+1) in the same warp (SHFL.DOWN 1; lane 31: own r) 588 * so a lane that joined late, never, or with the wrong value shows in the neighbour's word too. 589 * The host oracle is rc_oracle in tests/gpu_reconv_test.c. */ 590 typedef struct { Pro pr; int n, i, idx, x, y, r, s, one, cm1; } Rp; 591 static Rp rp_begin(Em *e) { 592 Rp k; memset(&k, 0, sizeof k); 593 k.pr = prologue(e); 594 k.n = V(e); k.i = V(e); k.idx = V(e); k.x = V(e); k.y = V(e); k.r = V(e); k.s = V(e); k.one = V(e); k.cm1 = V(e); 595 int nm1 = V(e), d = V(e), neg = V(e), off = V64(e); 596 ldc32(e, k.n, ARG_P0); 597 movi(e, k.one, 1); movi(e, k.cm1, 0xffffffffu); 598 imadi(e, k.i, k.pr.cta, OMEGA_GPU_EW_THREADS, k.pr.tid); 599 iadd3(e, nm1, k.n, k.cm1); /* n - 1 */ 600 imadi(e, d, k.i, 0xffffffffu, nm1); /* (n - 1) - i, top bit set when i > n - 1 */ 601 shr_i(e, neg, d, 31); 602 imadr(e, k.idx, neg, d, k.i); /* i, or n - 1 when past the end */ 603 addr4(e, off, k.idx, k.pr.pa); ldg(e, k.x, off, k.pr.udesc); 604 addr4(e, off, k.idx, k.pr.pb); ldg(e, k.y, off, k.pr.udesc); 605 return k; 606 } 607 static void rp_end(Em *e, const Rp *k) { 608 int out = V(e), off = V64(e); 609 shfl_down(e, k->s, k->r, 1); 610 imadi(e, out, k->s, 4099, k->r); 611 isetp_ge_u32(e, k->i, k->n); 612 exit_if_p0(e); 613 addr4(e, off, k->i, k->pr.pc); 614 stg(e, off, out, k->pr.udesc); 615 tail(e); 616 } 617 /* R3: if/else with sides of different length. x >= y: r = f(x, y) (5 steps); else r = x + 1. 618 * Math mutant: the long side is one too big. */ 619 static void gen_rc_diamond(Em *e, int mutant) { 620 Rp k = rp_begin(e); 621 int t = V(e), u = V(e); 622 region_begin(e); 623 isetp_ge_u32(e, k.x, k.y); 624 int els = bra_fwd_if_p0(e); 625 iadd3(e, k.r, k.x, k.one); /* short side */ 626 region_exit(e, RX_ALWAYS); 627 bra_patch_here(e, els); 628 imadi(e, t, k.x, 3, k.y); /* long side: t = 3x + y */ 629 lop3xor(e, u, t, k.x); /* u = t ^ x */ 630 imadi(e, k.r, u, 5, k.one); /* r = 5u + 1 */ 631 shr_i(e, t, k.r, 3); 632 iadd3(e, k.r, k.r, t); /* r += r >> 3 */ 633 if (mutant) iadd3(e, k.r, k.r, k.one); 634 region_join(e); 635 rp_end(e, &k); 636 } 637 /* The lane-dependent loop shared by R4 and R5: v = x & 255, step = (y & 15) + 1, 638 * while v < 256 { v += step; cnt += 1 }. Math mutant: the bound is 255. Emits the region. */ 639 static void rc_count_loop(Em *e, const Rp *k, int mutant, int v, int cnt) { 640 int st = V(e), bound = V(e), c255 = V(e), c15 = V(e); 641 movi(e, c255, 255); movi(e, c15, 15); movi(e, bound, mutant ? 255 : 256); 642 lop3lut(e, v, k->x, c255, NOREG, 0xc0); 643 lop3lut(e, st, k->y, c15, NOREG, 0xc0); 644 iadd3(e, st, st, k->one); 645 movrz(e, cnt); 646 region_begin(e); 647 loop_begin(e); 648 int L = here(e); 649 isetp_ge_u32(e, v, bound); 650 region_exit(e, RX_IF_P0); 651 iadd3(e, v, v, st); 652 iadd3(e, cnt, cnt, k->one); 653 bra_always(e, L); 654 loop_end(e); 655 region_join(e); 656 } 657 /* R4: lane-dependent loop exit (break). r = 256 * cnt + v. */ 658 static void gen_rc_loopbreak(Em *e, int mutant) { 659 Rp k = rp_begin(e); 660 int v = V(e), cnt = V(e); 661 rc_count_loop(e, &k, mutant, v, cnt); 662 imadi(e, k.r, cnt, 256, v); 663 rp_end(e, &k); 664 } 665 /* R5: nested divergence. Odd x: r = 7 (skips the inner region). Even x: the R4 loop inside the 666 * outer region, r = 256 * cnt + v + 100. */ 667 static void gen_rc_nested(Em *e, int mutant) { 668 Rp k = rp_begin(e); 669 int v = V(e), cnt = V(e), low = V(e), c100 = V(e); 670 movi(e, k.r, 7); movi(e, c100, 100); 671 lop3lut(e, low, k.x, k.one, NOREG, 0xc0); /* x & 1 */ 672 region_begin(e); 673 isetp_ge_u32(e, low, k.one); 674 region_exit(e, RX_IF_P0); 675 rc_count_loop(e, &k, mutant, v, cnt); 676 imadi(e, k.r, cnt, 256, v); 677 iadd3(e, k.r, k.r, c100); 678 region_join(e); 679 rp_end(e, &k); 680 } 681 /* R6: lanes past the end, a divergent region, then a CTA-wide exchange and the warp SHFL. 682 * xv = x | 1 computed on divergent paths (even lanes take the branch), every thread stores xv 683 * to its shared slot, BAR.SYNC, reads its partner's (tid ^ 1), r = 3x + partner_xv. 684 * Production form: lanes past n are clamped and exit after the SHFL (correct). early_exit 685 * (mutant 1): lanes past n EXIT first, as a naive kernel would; the emitter refuses that 686 * (BAR/SHFL after a predicated EXIT). Only the host-test build path (codegen_ir) may bypass the 687 * refusal, so the simulator can show what the kernel would do (SHFL_EXITED); a launch never can. */ 688 static void gen_rc_exit_bar(Em *e, int early_exit) { 689 Rp k = rp_begin(e); 690 int saddr = V(e), paddr = V(e), yv = V(e), xv = V(e), low = V(e); 691 if (early_exit) { 692 e->exit_sync_ok = early_exit == 1 && e->test_path; 693 isetp_ge_u32(e, k.i, k.n); 694 exit_if_p0(e); 695 } 696 imadi(e, xv, k.x, 1, NOREG); 697 lop3lut(e, low, k.x, k.one, NOREG, 0xc0); /* x & 1 */ 698 region_begin(e); 699 isetp_ge_u32(e, low, k.one); 700 region_exit(e, RX_IF_P0); /* odd lanes leave */ 701 iadd3(e, xv, xv, k.one); /* even lanes: xv = x + 1 */ 702 region_join(e); 703 imadi(e, saddr, k.pr.tid, 4, NOREG); 704 sts32(e, saddr, xv); 705 bar_sync(e); 706 lop3xor(e, paddr, k.pr.tid, k.one); 707 imadi(e, paddr, paddr, 4, NOREG); 708 lds32(e, yv, paddr); 709 imadi(e, k.r, k.x, 3, yv); 710 rp_end(e, &k); 711 } 712 /* Barrier-register bound: `levels` nested regions, each leaving lanes with x >= y out and adding 1 713 * for the others: r = x + levels * (x < y). 16 levels must build (B0..B15); 17 must be refused. */ 714 static void gen_rc_depth(Em *e, int levels) { 715 Rp k = rp_begin(e); 716 imadi(e, k.r, k.x, 1, NOREG); 717 for (int d = 0; d < levels; d++) { 718 region_begin(e); 719 isetp_ge_u32(e, k.x, k.y); 720 region_exit(e, RX_IF_P0); 721 iadd3(e, k.r, k.r, k.one); 722 } 723 for (int d = 0; d < levels; d++) region_join(e); 724 rp_end(e, &k); 725 } 726 /* Codegen refusals (each must come back CODEGEN_FAIL; a kernel with a split warp at a 727 * cross-lane step must never reach the chip). */ 728 static void gen_rc_refuse(Em *e, OmegaGpuEwOp which) { 729 Rp k = rp_begin(e); 730 switch (which) { 731 case OMEGA_GPU_EW_RC_REFUSE_EXIT_IN_REGION: region_begin(e); isetp_ge_u32(e, k.i, k.n); exit_if_p0(e); region_join(e); break; 732 case OMEGA_GPU_EW_RC_REFUSE_BAR_IN_REGION: region_begin(e); bar_sync(e); region_join(e); break; 733 case OMEGA_GPU_EW_RC_REFUSE_SHFL_IN_REGION: region_begin(e); shfl_down(e, k.s, k.x, 1); region_join(e); break; 734 case OMEGA_GPU_EW_RC_REFUSE_UNCLOSED: region_begin(e); isetp_ge_u32(e, k.x, k.y); region_exit(e, RX_IF_P0); break; /* no join */ 735 case OMEGA_GPU_EW_RC_REFUSE_JOIN_ONLY: region_join(e); break; /* BSYNC without BSSY */ 736 default: e->err = -1; break; 737 } 738 imadi(e, k.r, k.x, 1, NOREG); 739 rp_end(e, &k); 740 } 741 742 /* A value first defined inside a loop body may not be read after the loop 743 * before it is written again: the allocator could have let a later body 744 * temporary share its register, and the last iteration's value would be lost. */ 745 static int check_loop_invariant(const Em *e) { 746 const OmegaRegAlloc *ra = &e->p->regalloc; 747 for (int L = 0; L < e->n_loops; L++) 748 for (int v = 0; v < ra->num_vregs; v++) { 749 int fd = ra->intervals[v].first_def; 750 if (fd < e->loop_start[L] || fd > e->loop_end[L]) continue; 751 for (size_t i = (size_t)e->loop_end[L] + 1; i < e->p->count; i++) { 752 const BlackwellIRInsn *in = &e->p->insns[i]; 753 if (in->src1_vreg == v || in->src2_vreg == v || in->src3_vreg == v) return -1; 754 if (in->dst_vreg == v && !in->is_uniform) break; 755 } 756 } 757 return 0; 758 } 759 760 #define EW_GPR_BUDGET 64u /* the QMD declares 64 registers, as the matmul launcher does */ 761 762 /* Mesa NAK sm120_instr_latencies.rs + sm100/reg_raw.csv: ALU/dual-ALU pairs 763 * and FMA/FMA pairs need 4 + 1 cycles; mixed pairs need 5 + 1. CSV rows are 764 * READERS, columns WRITERS (see lat_rs_gen.py), not the reverse. IMAD.WIDE 765 * has operand-specific latencies and is deliberately excluded here. 766 * 767 * Retain at least 5 cycles after every fixed producer. Thus the next reader 768 * uses the pair-specific bound and later readers are >= 9 cycles away (the 769 * next instruction in a tightened pair is itself fixed). No instruction, 770 * branch target, wait, barrier assignment or register allocation is changed. 771 * IADD3's encoder still supplies its historical control word; do not pretend 772 * to schedule that producer here. Its existing 5-cycle delay is unchanged. 773 * 774 * Predicate-to-guard uses NAK paw_latency -> raw(write, None): reader 775 * RedirectedFp64, writer Dualalu = 13, plus SM120's 1 = 14, in emit above. 776 * NVIDIA's public ISA docs are silent about SASS control-word semantics. 777 */ 778 static int fixed_pair_class(BlackwellIROpcode op) { 779 switch (op) { 780 case BW_IR_MOV_RZ: case BW_IR_MOV_IMM: case BW_IR_IADD3: 781 case BW_IR_LOP3_XOR: case BW_IR_LOP3_LUT: 782 case BW_IR_SHF_R: case BW_IR_SHF_L_U32: return 1; 783 case BW_IR_IMAD: case BW_IR_IMAD_HI_U32: 784 case BW_IR_FADD: case BW_IR_FSUB: case BW_IR_FMUL: case BW_IR_FFMA: return 2; 785 default: return 0; 786 } 787 } 788 789 static void schedule_fixed_pairs(BlackwellIRProgram *p) { 790 for (size_t i = 0; i + 1 < p->count; i++) { 791 BlackwellIRInsn *a = &p->insns[i]; 792 const BlackwellIRInsn *b = &p->insns[i + 1]; 793 int cls = fixed_pair_class(a->op); 794 if (!cls || cls != fixed_pair_class(b->op) || a->op == BW_IR_IADD3 || 795 a->predicate_p0 || b->predicate_p0 || ((a->control >> 9) & 15u) != 6) 796 continue; 797 a->control = (a->control & ~(15u << 9)) | (5u << 9); 798 } 799 } 800 801 static int build_kernel(OmegaGpuEwOp op, int mutant, OmegaBlackwellKernel *kernel, BlackwellIRProgram *prog_out, int test_path) { 802 BlackwellIRProgram *prog = calloc(1, sizeof *prog); 803 if (!prog) return OMEGA_GPU_EW_CODEGEN_FAIL; 804 omega_bw_ir_init(prog); 805 Em e; memset(&e, 0, sizeof e); e.p = prog; e.test_path = test_path; 806 /* mutant 1 = the op's math mutant (as before); 2 = the join (BSYNC) dropped; 3 = the BSSY 807 * names the wrong join. 2 and 3 only change kernels that open a region. */ 808 e.rg_mutant = mutant == 2 ? 1 : mutant == 3 ? 2 : 0; 809 int math = mutant == 1; 810 switch (op) { 811 case OMEGA_GPU_EW_EX2: gen_ex2(&e, math); break; 812 case OMEGA_GPU_EW_XCHG: gen_xchg(&e, math); break; 813 case OMEGA_GPU_EW_RMSNORM: gen_rmsnorm(&e, math); break; 814 case OMEGA_GPU_EW_ROPE: gen_rope(&e, math); break; 815 case OMEGA_GPU_EW_SWIGLU: gen_swiglu(&e, math); break; 816 case OMEGA_GPU_EW_PRIME_SIEVE: gen_prime_sieve(&e, math, 0, 0); break; 817 case OMEGA_GPU_EW_PRIME_SIEVE_SHARED: gen_prime_sieve(&e, math, 1, 0); break; 818 case OMEGA_GPU_EW_PRIME_SIEVE_DIV1: gen_prime_sieve(&e, math, 0, 1); break; 819 case OMEGA_GPU_EW_PRIME_SIEVE_SHARED_DIV1: gen_prime_sieve(&e, math, 1, 1); break; 820 case OMEGA_GPU_EW_PRIME_SIEVE_DIV2: gen_prime_sieve(&e, math, 0, 2); break; 821 case OMEGA_GPU_EW_PRIME_SIEVE_SHARED_DIV2: gen_prime_sieve(&e, math, 1, 2); break; 822 case OMEGA_GPU_EW_RC_DIAMOND: gen_rc_diamond(&e, math); break; 823 case OMEGA_GPU_EW_RC_LOOPBREAK: gen_rc_loopbreak(&e, math); break; 824 case OMEGA_GPU_EW_RC_NESTED: gen_rc_nested(&e, math); break; 825 case OMEGA_GPU_EW_RC_EXIT_BAR: gen_rc_exit_bar(&e, math); break; 826 case OMEGA_GPU_EW_RC_REFUSE_EXIT_SHFL: gen_rc_exit_bar(&e, 2); break; 827 case OMEGA_GPU_EW_RC_DEPTH16: gen_rc_depth(&e, BW_RECONV_MAX_BAR); break; 828 case OMEGA_GPU_EW_RC_REFUSE_DEPTH17: gen_rc_depth(&e, BW_RECONV_MAX_BAR + 1); break; 829 case OMEGA_GPU_EW_RC_REFUSE_EXIT_IN_REGION: case OMEGA_GPU_EW_RC_REFUSE_BAR_IN_REGION: 830 case OMEGA_GPU_EW_RC_REFUSE_SHFL_IN_REGION: case OMEGA_GPU_EW_RC_REFUSE_UNCLOSED: 831 case OMEGA_GPU_EW_RC_REFUSE_JOIN_ONLY: gen_rc_refuse(&e, op); break; 832 default: e.err = -1; break; 833 } 834 if (e.rg.depth != 0) e.err = -1; /* a region left open has no join: refuse the build */ 835 schedule_fixed_pairs(prog); 836 int rc = OMEGA_GPU_EW_CODEGEN_FAIL; 837 int ra_rc = (e.err == 0) ? omega_bw_regalloc_solve(prog) : -1; 838 int loop_rc = (ra_rc == 0) ? check_loop_invariant(&e) : -1; 839 #ifdef OMEGA_EW_DEBUG 840 fprintf(stderr, "ew codegen op=%d mutant=%d emit_err=%d insns=%zu vregs=%d regalloc=%d loops=%d peak_gpr=%u\n", 841 (int)op, mutant, e.err, prog->count, prog->regalloc.num_vregs, ra_rc, loop_rc, prog->regalloc.peak_gpr_usage); 842 #endif 843 if (e.err == 0 && ra_rc == 0 && loop_rc == 0 && prog->regalloc.peak_gpr_usage <= EW_GPR_BUDGET) { 844 size_t max_bytes = (size_t)BW_MAX_IR_INSNS * 16; 845 memset(kernel, 0, sizeof *kernel); 846 kernel->code = malloc(max_bytes); 847 size_t emitted = 0; 848 if (kernel->code && omega_bw_encode_program(prog, kernel->code, max_bytes, &emitted) == 0) { 849 kernel->code_size = emitted; 850 kernel->insn_count = emitted / 16; 851 kernel->gpr_count = prog->regalloc.peak_gpr_usage; 852 kernel->uniform_gpr_count = prog->regalloc.peak_ugpr_usage; 853 sha256_hash(kernel->code, kernel->code_size, kernel->code_digest); 854 if (prog_out) *prog_out = *prog; 855 rc = OMEGA_GPU_EW_OK; 856 } else { 857 #ifdef OMEGA_EW_DEBUG 858 fprintf(stderr, "ew codegen op=%d: encode failed (an instruction form the encoder refuses)\n", (int)op); 859 #endif 860 free(kernel->code); kernel->code = NULL; 861 } 862 } 863 free(prog); 864 return rc; 865 } 866 867 /* --------------------------------------------------------- kernel cache */ 868 869 /* One kernel per (op, mutant); the device copy is uploaded once and stays 870 * resident for the process (cut 4b: no per-call code page). */ 871 typedef struct { int used; int op; int mutant; OmegaBlackwellKernel kernel; NvrmMem code; } Slot; 872 static int g_mutant_op; /* 0 = none */ 873 static int g_mutant_level = 1; /* the mutant number built for g_mutant_op (1 math, 2 join dropped, 3 join corrupted) */ 874 static Slot g_cache[8]; 875 static OmegaGpuScratch g_a, g_b, g_c; /* staging, grown to the high-water mark, reused per call */ 876 static bool g_hooked; 877 #define LOCK() omega_gpu_session_lock() 878 #define UNLOCK() omega_gpu_session_unlock() 879 880 static void cache_clear_locked(void) { 881 for (size_t i = 0; i < sizeof g_cache / sizeof g_cache[0]; i++) 882 if (g_cache[i].used) { free(g_cache[i].kernel.code); omega_gpu_session_free(&g_cache[i].code); memset(&g_cache[i], 0, sizeof g_cache[i]); } 883 } 884 885 void omega_gpu_elementwise_cache_clear(void) { 886 LOCK(); 887 cache_clear_locked(); 888 UNLOCK(); 889 } 890 891 /* Called by the session (lock held, device still open) right before it closes. */ 892 static void on_session_close(void) { 893 cache_clear_locked(); 894 omega_gpu_session_scratch_free(&g_a); omega_gpu_session_scratch_free(&g_b); omega_gpu_session_scratch_free(&g_c); 895 } 896 897 void omega_gpu_elementwise_test_set_mutant(int op) { 898 LOCK(); 899 g_mutant_op = op; g_mutant_level = 1; 900 cache_clear_locked(); 901 UNLOCK(); 902 } 903 void omega_gpu_elementwise_test_set_mutant_level(int op, int level) { 904 LOCK(); 905 g_mutant_op = op; g_mutant_level = level < 1 ? 1 : level > 3 ? 3 : level; 906 cache_clear_locked(); 907 UNLOCK(); 908 } 909 910 /* Caller holds the lock. Builds the kernel if needed; uploads the device copy when a 911 * device is open (upload = false lets the host-only codegen path run without a chip). */ 912 static int kernel_for(OmegaGpuEwOp op, bool upload, Slot **out, bool *hit) { 913 int mutant = (g_mutant_op == (int)op) ? g_mutant_level : 0; 914 Slot *s = NULL; 915 for (size_t i = 0; i < sizeof g_cache / sizeof g_cache[0]; i++) 916 if (g_cache[i].used && g_cache[i].op == (int)op && g_cache[i].mutant == mutant) { s = &g_cache[i]; *hit = true; break; } 917 if (!s) { 918 OmegaBlackwellKernel k; 919 int rc = build_kernel(op, mutant, &k, NULL, 0); 920 if (rc != OMEGA_GPU_EW_OK) return rc; 921 size_t slot = 0; 922 for (size_t i = 0; i < sizeof g_cache / sizeof g_cache[0]; i++) if (!g_cache[i].used) { slot = i; break; } 923 s = &g_cache[slot]; 924 if (s->used) { free(s->kernel.code); omega_gpu_session_free(&s->code); } /* full: evict slot 0 */ 925 memset(s, 0, sizeof *s); 926 s->used = 1; s->op = (int)op; s->mutant = mutant; s->kernel = k; 927 *hit = false; 928 } 929 if (upload && !s->code.cpu) { 930 if (omega_gpu_session_alloc(s->kernel.code_size, &s->code) != 0) return OMEGA_GPU_EW_CHIP_FAIL; 931 memcpy(s->code.cpu, s->kernel.code, s->kernel.code_size); 932 __asm__ volatile("dsb sy" ::: "memory"); 933 } 934 *out = s; 935 return OMEGA_GPU_EW_OK; 936 } 937 938 int omega_gpu_elementwise_codegen(OmegaGpuEwOp op, const uint32_t *dims, float eps, OmegaBlackwellKernel *kernel) { 939 (void)dims; (void)eps; /* kernels read their shape from the argument words */ 940 if (!kernel) return OMEGA_GPU_EW_BAD_ARGS; 941 LOCK(); 942 int mutant = (g_mutant_op == (int)op) ? g_mutant_level : 0; 943 UNLOCK(); 944 return build_kernel(op, mutant, kernel, NULL, 0); 945 } 946 947 int omega_gpu_elementwise_codegen_ir(OmegaGpuEwOp op, int mutant, void *prog, OmegaBlackwellKernel *kernel) { 948 if (!kernel) return OMEGA_GPU_EW_BAD_ARGS; 949 if (mutant < 0 || mutant > 3) return OMEGA_GPU_EW_BAD_ARGS; 950 return build_kernel(op, mutant, kernel, (BlackwellIRProgram *)prog, 1); 951 } 952 953 const char *omega_gpu_elementwise_last_error(void) { return omega_gpu_session_last_error(); } 954 955 /* ------------------------------------------------------------ launcher */ 956 957 #define EW_POISON 0xffbadbadu /* a NaN pattern no kernel here produces on purpose */ 958 #define EW_WAIT_MS 600000ull /* like main's load/store launchers; a 5 s wait failed under contention (omega#198) */ 959 960 static uint64_t now_ns(void) { 961 struct timespec t; clock_gettime(CLOCK_MONOTONIC, &t); 962 return (uint64_t)t.tv_sec * 1000000000ULL + (uint64_t)t.tv_nsec; 963 } 964 965 /* Caller holds the lock. Opens the shared device on first use. */ 966 static int dev_open_locked(void) { 967 if (!g_hooked) { (void)omega_gpu_session_on_close(on_session_close); g_hooked = true; } 968 return omega_gpu_session_open() ? OMEGA_GPU_EW_OK : OMEGA_GPU_EW_CHIP_FAIL; 969 } 970 971 /* One launch: a and b staged in, c out (c_bytes/4 words, poison-filled first), through 972 * the shared session (omega_gpu_session_launch: shader-cache invalidate, constant bank, 973 * QMD0/QMD1, first marker, L2_FLUSH_DIRTY, second marker), then readback and the 974 * poison scan. b may be NULL when b_fill wrote the staging buffer already. */ 975 static int run_abc(const Slot *ks, const void *a, size_t a_bytes, const void *b, size_t b_bytes, 976 void *c, size_t c_bytes, uint32_t threads_x, uint32_t grid_x, 977 const uint32_t params[4], OmegaGpuEwInfo *info) { 978 if (omega_gpu_session_scratch(&g_a, a_bytes) || omega_gpu_session_scratch(&g_b, b_bytes) || omega_gpu_session_scratch(&g_c, c_bytes)) 979 return OMEGA_GPU_EW_CHIP_FAIL; 980 memcpy(g_a.mem.cpu, a, a_bytes); 981 if (b) memcpy(g_b.mem.cpu, b, b_bytes); 982 size_t c_words = c_bytes / 4; 983 uint32_t *c_dev = (uint32_t *)g_c.mem.cpu; 984 for (size_t i = 0; i < c_words; i++) c_dev[i] = EW_POISON; 985 __asm__ volatile("dsb sy" ::: "memory"); 986 987 uint32_t args[OMEGA_BW_CBANK_MATMUL_ARGS_WORDS]; 988 args[0] = (uint32_t)g_a.mem.va; args[1] = (uint32_t)(g_a.mem.va >> 32); 989 args[2] = (uint32_t)g_b.mem.va; args[3] = (uint32_t)(g_b.mem.va >> 32); 990 args[4] = (uint32_t)g_c.mem.va; args[5] = (uint32_t)(g_c.mem.va >> 32); 991 args[6] = params[0]; args[7] = params[1]; args[8] = params[2]; args[9] = params[3]; 992 OmegaGpuLaunch L = { 993 .code_va = ks->code.va, .gpr_count = EW_GPR_BUDGET, .threads_x = threads_x, .threads_y = 1, 994 .grid_x = grid_x, .grid_y = 1, .num_elements = c_words, 995 .args = args, .n_args = OMEGA_BW_CBANK_MATMUL_ARGS_WORDS, .timeout_ms = EW_WAIT_MS, 996 }; 997 uint64_t elapsed = 0; uint32_t marker = 0; 998 if (omega_gpu_session_launch(&L, &elapsed, &marker) != 0) return OMEGA_GPU_EW_CHIP_FAIL; 999 1000 memcpy(c, g_c.mem.cpu, c_bytes); 1001 uint32_t unwritten = 0; 1002 for (size_t i = 0; i < c_words; i++) if (((uint32_t *)c)[i] == EW_POISON) unwritten++; 1003 if (info) { 1004 info->chip_calls++; 1005 info->elapsed_ns += elapsed; 1006 info->completion_marker = marker; 1007 info->unwritten_words += unwritten; 1008 info->threads_per_cta = threads_x; 1009 info->ctas_last_launch = grid_x; 1010 } 1011 return unwritten ? OMEGA_GPU_EW_UNWRITTEN : OMEGA_GPU_EW_OK; 1012 } 1013 1014 /* ------------------------------------------------------- public entries */ 1015 1016 static void info_begin(OmegaGpuEwInfo *info, const OmegaBlackwellKernel *k, bool hit) { 1017 if (!info) return; 1018 memset(info, 0, sizeof *info); 1019 info->kernel_cache_hit = hit; 1020 info->gpr_count = k->gpr_count; 1021 info->insn_count = (uint32_t)k->insn_count; 1022 snprintf(info->target_chip, sizeof info->target_chip, "NVIDIA DGX Spark (Grace Blackwell GB10)"); 1023 info->sm_architecture = 121; 1024 } 1025 static uint32_t f2u(float f) { uint32_t u; memcpy(&u, &f, 4); return u; } 1026 static void info_end(OmegaGpuEwInfo *info, uint64_t t0) { if (info) info->call_ns = now_ns() - t0; } 1027 1028 /* Common prologue of every chip entry: lock, open, kernel (resident), info. */ 1029 static int begin(OmegaGpuEwOp op, Slot **ks, OmegaGpuEwInfo *info) { 1030 LOCK(); 1031 int rc = dev_open_locked(); 1032 bool hit = false; 1033 if (rc == OMEGA_GPU_EW_OK) rc = kernel_for(op, true, ks, &hit); 1034 if (rc != OMEGA_GPU_EW_OK) { UNLOCK(); return rc; } 1035 info_begin(info, &(*ks)->kernel, hit); 1036 return OMEGA_GPU_EW_OK; 1037 } 1038 1039 int omega_gpu_rmsnorm_f32(uint32_t rows, uint32_t dim, const float *x, const float *weight, 1040 float eps, float *out, OmegaGpuEwInfo *info) { 1041 uint64_t t0 = now_ns(); 1042 if (!x || !weight || !out || rows == 0 || dim == 0 || dim % OMEGA_GPU_EW_THREADS != 0) return OMEGA_GPU_EW_BAD_ARGS; 1043 if (dim > OMEGA_GPU_EW_MAX_DIM) return OMEGA_GPU_EW_TOO_LARGE; 1044 Slot *k = NULL; 1045 int rc = begin(OMEGA_GPU_EW_RMSNORM, &k, info); 1046 if (rc != OMEGA_GPU_EW_OK) return rc; 1047 uint32_t params[4] = { dim / OMEGA_GPU_EW_THREADS, f2u(1.0f / (float)dim), f2u(eps), dim }; 1048 for (uint32_t r0 = 0; r0 < rows && rc == OMEGA_GPU_EW_OK; r0 += OMEGA_GPU_EW_MAX_CTAS) { 1049 uint32_t nr = rows - r0 < OMEGA_GPU_EW_MAX_CTAS ? rows - r0 : OMEGA_GPU_EW_MAX_CTAS; 1050 size_t bytes = (size_t)nr * dim * 4; 1051 rc = run_abc(k, x + (size_t)r0 * dim, bytes, weight, (size_t)dim * 4, out + (size_t)r0 * dim, bytes, 1052 OMEGA_GPU_EW_THREADS, nr, params, info); 1053 } 1054 UNLOCK(); 1055 info_end(info, t0); 1056 return rc; 1057 } 1058 1059 int omega_gpu_rope_f32(uint32_t heads, uint32_t head_dim, const float *v, 1060 const float *cos_half, const float *sin_half, float *out, OmegaGpuEwInfo *info) { 1061 uint64_t t0 = now_ns(); 1062 if (!v || !cos_half || !sin_half || !out || heads == 0 || head_dim < 2 || (head_dim & 1)) return OMEGA_GPU_EW_BAD_ARGS; 1063 if (head_dim > 2048) return OMEGA_GPU_EW_TOO_LARGE; 1064 Slot *k = NULL; 1065 int rc = begin(OMEGA_GPU_EW_ROPE, &k, info); 1066 if (rc != OMEGA_GPU_EW_OK) return rc; 1067 uint32_t half = head_dim / 2; 1068 uint32_t params[4] = { head_dim, half, 0, 0 }; 1069 for (uint32_t h0 = 0; h0 < heads && rc == OMEGA_GPU_EW_OK; h0 += OMEGA_GPU_EW_MAX_CTAS) { 1070 uint32_t nh = heads - h0 < OMEGA_GPU_EW_MAX_CTAS ? heads - h0 : OMEGA_GPU_EW_MAX_CTAS; 1071 size_t bytes = (size_t)nh * head_dim * 4; 1072 /* table: cos in the first half of each head, sin in the second, written straight into 1073 * the staging buffer (one copy per head of this launch) */ 1074 if (omega_gpu_session_scratch(&g_b, bytes) != 0) { rc = OMEGA_GPU_EW_CHIP_FAIL; break; } 1075 float *table = g_b.mem.cpu; 1076 for (uint32_t h = 0; h < nh; h++) { 1077 memcpy(table + (size_t)h * head_dim, cos_half, half * sizeof *table); 1078 memcpy(table + (size_t)h * head_dim + half, sin_half, half * sizeof *table); 1079 } 1080 /* out may alias v: v is copied into the staging buffer before the result lands in out */ 1081 rc = run_abc(k, v + (size_t)h0 * head_dim, bytes, NULL, bytes, out + (size_t)h0 * head_dim, bytes, half, nh, params, info); 1082 } 1083 UNLOCK(); 1084 info_end(info, t0); 1085 return rc; 1086 } 1087 1088 static int run_1d(OmegaGpuEwOp op, uint32_t n, const void *a, const void *b, void *c, OmegaGpuEwInfo *info) { 1089 uint64_t t0 = now_ns(); 1090 Slot *k = NULL; 1091 int rc = begin(op, &k, info); 1092 if (rc != OMEGA_GPU_EW_OK) return rc; 1093 const uint32_t chunk = OMEGA_GPU_EW_MAX_CTAS * OMEGA_GPU_EW_THREADS; 1094 for (uint32_t i0 = 0; i0 < n && rc == OMEGA_GPU_EW_OK; i0 += chunk) { 1095 uint32_t ni = n - i0 < chunk ? n - i0 : chunk; 1096 uint32_t grid = (ni + OMEGA_GPU_EW_THREADS - 1) / OMEGA_GPU_EW_THREADS; 1097 uint32_t params[4] = { ni, 0, 0, 0 }; 1098 size_t bytes = (size_t)ni * 4; 1099 rc = run_abc(k, (const uint8_t *)a + (size_t)i0 * 4, bytes, b ? (const uint8_t *)b + (size_t)i0 * 4 : a, bytes, 1100 (uint8_t *)c + (size_t)i0 * 4, bytes, OMEGA_GPU_EW_THREADS, grid, params, info); 1101 } 1102 UNLOCK(); 1103 info_end(info, t0); 1104 return rc; 1105 } 1106 1107 int omega_gpu_swiglu_f32(uint32_t n, const float *gate, const float *up, float *out, OmegaGpuEwInfo *info) { 1108 if (!gate || !up || !out || n == 0) return OMEGA_GPU_EW_BAD_ARGS; 1109 return run_1d(OMEGA_GPU_EW_SWIGLU, n, gate, up, out, info); 1110 } 1111 int omega_gpu_ex2_f32(uint32_t n, const float *x, float *out, OmegaGpuEwInfo *info) { 1112 if (!x || !out || n == 0) return OMEGA_GPU_EW_BAD_ARGS; 1113 return run_1d(OMEGA_GPU_EW_EX2, n, x, NULL, out, info); 1114 } 1115 int omega_gpu_shared_xchg_u32(uint32_t n, const uint32_t *x, uint32_t *out, OmegaGpuEwInfo *info) { 1116 if (!x || !out || n == 0 || n % OMEGA_GPU_EW_THREADS != 0) return OMEGA_GPU_EW_BAD_ARGS; 1117 return run_1d(OMEGA_GPU_EW_XCHG, n, x, NULL, out, info); 1118 } 1119 int omega_gpu_reconv_probe_u32(OmegaGpuEwOp op, uint32_t n, const uint32_t *a, const uint32_t *b, uint32_t *out, OmegaGpuEwInfo *info) { 1120 if (!a || !b || !out || n == 0) return OMEGA_GPU_EW_BAD_ARGS; 1121 switch (op) { 1122 case OMEGA_GPU_EW_RC_DIAMOND: case OMEGA_GPU_EW_RC_LOOPBREAK: case OMEGA_GPU_EW_RC_NESTED: 1123 case OMEGA_GPU_EW_RC_EXIT_BAR: case OMEGA_GPU_EW_RC_DEPTH16: break; 1124 default: return OMEGA_GPU_EW_BAD_ARGS; 1125 } 1126 return run_1d(op, n, a, b, out, info); 1127 } 1128 1129 const char *omega_gpu_elementwise_rc_name(int rc) { 1130 switch (rc) { 1131 case OMEGA_GPU_EW_OK: return "OK"; 1132 case OMEGA_GPU_EW_BAD_ARGS: return "BAD_ARGS"; 1133 case OMEGA_GPU_EW_TOO_LARGE: return "TOO_LARGE"; 1134 case OMEGA_GPU_EW_CODEGEN_FAIL: return "CODEGEN_FAIL"; 1135 case OMEGA_GPU_EW_CHIP_FAIL: return "CHIP_FAIL"; 1136 case OMEGA_GPU_EW_UNWRITTEN: return "UNWRITTEN"; 1137 default: return "UNKNOWN"; 1138 } 1139 }