interplane.Get Omega
Read in your language

CUDApp

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

Brought by drakestapleton

branch main Branches Tags History

CUDApp / src / omega_gpu_elementwise_api.c

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