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