interplane.Get Omega
Read in your language

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

branch main Branches Tags History

omega-mv / evidence / FB1-CUT4B-0396844 / omega_gpu_elementwise_api.c

615 lines · 30661 bytes Raw Blame History
1/* omega_gpu_elementwise_api.c: FB-1 cut 4 (2026-10-04). See the header.
2 *
3 * Layout of this file: (1) kernel codegen on top of the BlackwellIR, with a
4 * small scheduler that writes every control word; (2) one launcher cloned from
5 * the chip-proven tensor matmul path (omega_blackwell_execute_matmul_tensor);
6 * (3) the public entry points, which split work into <= OMEGA_GPU_EW_MAX_CTAS
7 * launches and run the host-side bookkeeping.
8 *
9 * Scheduling rules (chip-learned, src/omega_numeric.c omega_numeric_check_patch):
10 * - a variable-latency result (LDG, LDS, LDC, LDCU, S2R, SHFL, MUFU) arrives through
11 * a scoreboard; the producer stalls >= 2 and the consumer waits on that SB;
12 * - a fixed-latency result (FADD FMUL FFMA IMAD IADD3 MOV LOP3 SHF) has no
13 * scoreboard: the producer stalls >= 5 before its consumer (we use 6);
14 * - a predicate producer (ISETP) stalls 13 before @P0 use (the codegen default);
15 * - stores (STG, STS) set a read barrier so the next instruction cannot overwrite
16 * the source register early.
17 * The emitter below serialises: every instruction waits on everything still
18 * pending. Slow and safe; speed is a later cut.
19 */
20#include "omega_gpu_elementwise_api.h"
21#include "omega_blackwell_codegen.h"
22#include "omega_blackwell_qmd.h"
23#include "omega_blackwell_submit.h"
24#include "omega_gpu_session.h"
25#include "sha256.h"
26#include <stdio.h>
27#include <stdlib.h>
28#include <string.h>
29#include <time.h>
30
31/* ------------------------------------------------------------------ codegen */
32
33#define CW(stall, wbar, rbar, wait) \
34 (((uint32_t)(stall) << 9) | ((uint32_t)(wbar) << 14) | ((uint32_t)(rbar) << 17) | ((uint32_t)(wait) << 20))
35#define CW_YIELD 0x2000u
36#define SB_NONE 7u
37#define SB_GPR 0u /* variable-latency GPR results */
38#define SB_RD 1u /* store source-register read barrier */
39#define SB_UGPR 2u /* uniform-register results (LDCU) */
40
41enum { K_FIXED, K_PRED, K_VAR, K_UVAR, K_STORE, K_SYNC, K_EXIT, K_BRA };
42
43#define EW_MAX_LOOPS 4
44typedef struct {
45 BlackwellIRProgram *p;
46 uint32_t pending; /* scoreboards set and not yet waited on */
47 int err;
48 int loop_start[EW_MAX_LOOPS], loop_end[EW_MAX_LOOPS];
49 int n_loops;
50} Em;
51
52static void emit(Em *e, BlackwellIRInsn in, int kind) {
53 uint32_t wait = e->pending;
54 switch (kind) {
55 case K_FIXED: in.control = CW(6, SB_NONE, SB_NONE, wait); e->pending = 0; break;
56 case K_PRED: in.control = CW(13, SB_NONE, SB_NONE, wait); e->pending = 0; break;
57 case K_VAR: in.control = CW(4, SB_GPR, SB_NONE, wait) | CW_YIELD; e->pending = 1u << SB_GPR; break;
58 case K_UVAR: in.control = CW(4, SB_UGPR, SB_NONE, wait) | CW_YIELD; e->pending = 1u << SB_UGPR; break;
59 case K_STORE: in.control = CW(4, SB_NONE, SB_RD, wait) | CW_YIELD; e->pending = 1u << SB_RD; break;
60 case K_SYNC: in.control = CW(6, SB_NONE, SB_NONE, wait); e->pending = 0; break;
61 /* a predicated EXIT or BRA that falls through must not be the only waiter */
62 case K_EXIT: in.control = CW(5, SB_NONE, SB_NONE, wait); e->pending = in.predicate_p0 ? wait : 0; break;
63 case K_BRA: in.control = CW(5, SB_NONE, SB_NONE, wait); e->pending = in.predicate_p0 ? wait : 0; break;
64 default: e->err = -1; return;
65 }
66 if (omega_bw_ir_append(e->p, &in) < 0) e->err = -1; /* append returns the index */
67}
68
69static int V(Em *e) { int v = omega_bw_ir_alloc_vreg(e->p); if (v < 0) e->err = -1; return v; }
70static int V64(Em *e) { int v = omega_bw_ir_alloc_vreg64(e->p); if (v < 0) e->err = -1; return v; }
71static int UV64(Em *e) { int v = omega_bw_ir_alloc_uvreg64(e->p); if (v < 0) e->err = -1; return v; }
72static int here(const Em *e) { return (int)e->p->count; }
73
74#define NOREG -1
75static BlackwellIRInsn I0(BlackwellIROpcode op) {
76 BlackwellIRInsn in; memset(&in, 0, sizeof in);
77 in.op = op; in.dst_vreg = NOREG; in.src1_vreg = NOREG; in.src2_vreg = NOREG; in.src3_vreg = NOREG; in.ureg = NOREG;
78 return in;
79}
80static 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); }
81static 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); }
82static 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); }
83static 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); }
84static 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); }
85static void movf(Em *e, int dst, float f) { uint32_t u; memcpy(&u, &f, 4); movi(e, dst, u); }
86static void movrz(Em *e, int dst) { BlackwellIRInsn i = I0(BW_IR_MOV_RZ); i.dst_vreg = dst; emit(e, i, K_FIXED); }
87/* dst = a * imm + c (c may be NOREG for RZ) */
88static 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); }
89/* dst = a * b + c (registers) */
90static 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); }
91static 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); }
92static 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); }
93/* dst64 = idx * 4 + ptr64 (byte address of element idx) */
94static 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); }
95static 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); }
96static 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); }
97static 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); }
98static 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); }
99static 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); }
100static 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); }
101static 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); }
102static void shfl_down(Em *e, int d, int a, uint32_t off) { BlackwellIRInsn i = I0(BW_IR_SHFL_DOWN); i.dst_vreg = d; i.src1_vreg = a; i.imm = off; emit(e, i, K_VAR); }
103static 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); }
104static 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); }
105static void bar_sync(Em *e) { emit(e, I0(BW_IR_BAR_SYNC), K_SYNC); }
106static 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); }
107static void exit_if_p0(Em *e) { BlackwellIRInsn i = I0(BW_IR_EXIT); i.predicate_p0 = true; emit(e, i, K_EXIT); }
108static 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); }
109static void tail(Em *e) {
110 emit(e, I0(BW_IR_EXIT), K_EXIT);
111 BlackwellIRInsn self = I0(BW_IR_BRA); /* the self-branch every kernel here ends with */
112 self.control = 0x000fc000u;
113 if (omega_bw_ir_append(e->p, &self) < 0) e->err = -1;
114}
115static void loop_begin(Em *e) { if (e->n_loops < EW_MAX_LOOPS) e->loop_start[e->n_loops] = here(e); }
116/* Closing a loop: every value defined before the loop and read inside it stays
117 * live until the back-branch, otherwise the linear-scan allocator (which knows
118 * nothing about back-edges) would hand its register to a body temporary whose
119 * first definition comes after the value's last textual use (e.g. the scale y
120 * in rmsnorm pass 2), and the next iteration would read garbage. */
121static void loop_end(Em *e) {
122 if (e->n_loops >= EW_MAX_LOOPS) { e->err = -1; return; }
123 int start = e->loop_start[e->n_loops], end = here(e) - 1;
124 e->loop_end[e->n_loops] = end;
125 e->n_loops++;
126 OmegaRegAlloc *ra = &e->p->regalloc;
127 for (int v = 0; v < ra->num_vregs; v++) {
128 OmegaLiveInterval *iv = &ra->intervals[v];
129 if (iv->first_def >= 0 && iv->first_def < start && iv->last_use >= start && iv->last_use < end) iv->last_use = end;
130 }
131}
132
133/* Kernel argument words (constant bank 0, same slots as the matmul path):
134 * 0x380 a, 0x388 b, 0x390 c (64-bit each), then four 32-bit parameters. */
135#define ARG_A 0x380u
136#define ARG_B 0x388u
137#define ARG_C 0x390u
138#define ARG_P0 0x398u
139#define ARG_P1 0x39cu
140#define ARG_P2 0x3a0u
141#define ARG_P3 0x3a4u
142#define DESC_OFF 0x358u
143
144typedef struct { int udesc, pa, pb, pc, tid, cta; } Pro;
145static Pro prologue(Em *e) {
146 Pro r;
147 r.udesc = UV64(e); r.pa = V64(e); r.pb = V64(e); r.pc = V64(e); r.tid = V(e); r.cta = V(e);
148 ldcu64(e, r.udesc, DESC_OFF);
149 ldc64(e, r.pa, ARG_A); ldc64(e, r.pb, ARG_B); ldc64(e, r.pc, ARG_C);
150 s2r(e, r.tid, BW_SR_TID_X); s2r(e, r.cta, BW_SR_CTAID_X);
151 return r;
152}
153
154/* out[i] = 2^a[i] for i < n (n = P0). Threads 128, grid ceil(n/128). Mutant: 2^(a+1). */
155static void gen_ex2(Em *e, int mutant) {
156 Pro p = prologue(e);
157 int n = V(e), i = V(e), off = V64(e), x = V(e), y = V(e);
158 ldc32(e, n, ARG_P0);
159 imadi(e, i, p.cta, OMEGA_GPU_EW_THREADS, p.tid);
160 isetp_ge_u32(e, i, n);
161 exit_if_p0(e);
162 addr4(e, off, i, p.pa);
163 ldg(e, x, off, p.udesc);
164 if (mutant) { int one = V(e); movf(e, one, 1.0f); fadd(e, x, x, one); }
165 mufu(e, BW_IR_MUFU_EX2, y, x);
166 addr4(e, off, i, p.pc);
167 stg(e, off, y, p.udesc);
168 tail(e);
169}
170
171/* out[i] = a[i ^ 127] within each CTA of 128 (n % 128 == 0). STS own word, BAR.SYNC,
172 * LDS the partner word. Mutant: LDS own word (no exchange). */
173static void gen_xchg(Em *e, int mutant) {
174 Pro p = prologue(e);
175 int i = V(e), off = V64(e), x = V(e), saddr = V(e), paddr = V(e), mask = V(e), y = V(e);
176 imadi(e, i, p.cta, OMEGA_GPU_EW_THREADS, p.tid);
177 addr4(e, off, i, p.pa);
178 ldg(e, x, off, p.udesc);
179 imadi(e, saddr, p.tid, 4, NOREG);
180 sts32(e, saddr, x);
181 bar_sync(e);
182 if (mutant) {
183 lds32(e, y, saddr);
184 } else {
185 movi(e, mask, OMEGA_GPU_EW_THREADS - 1);
186 lop3xor(e, paddr, p.tid, mask);
187 imadi(e, paddr, paddr, 4, NOREG);
188 lds32(e, y, paddr);
189 }
190 addr4(e, off, i, p.pc);
191 stg(e, off, y, p.udesc);
192 tail(e);
193}
194
195/* One CTA of 128 threads per row. P0 = dim/128 (loop count), P1 = bits(1/dim),
196 * P2 = bits(eps), P3 = dim. Mutant: the warp tree drops the last SHFL step. */
197static void gen_rmsnorm(Em *e, int mutant) {
198 Pro p = prologue(e);
199 int nk = V(e), invd = V(e), eps = V(e), dim = V(e);
200 int rowbase = V(e), idx = V(e), col = V(e), k = V(e), acc = V(e), cT = V(e), c1 = V(e);
201 int off = V64(e), x = V(e), t = V(e);
202 ldc32(e, nk, ARG_P0); ldc32(e, invd, ARG_P1); ldc32(e, eps, ARG_P2); ldc32(e, dim, ARG_P3);
203 imadr(e, rowbase, p.cta, dim, NOREG);
204 iadd3(e, idx, rowbase, p.tid);
205 movrz(e, acc); movrz(e, k);
206 movi(e, cT, OMEGA_GPU_EW_THREADS); movi(e, c1, 1);
207 loop_begin(e);
208 int l1 = here(e);
209 addr4(e, off, idx, p.pa);
210 ldg(e, x, off, p.udesc);
211 ffma(e, acc, x, x, acc);
212 iadd3(e, idx, idx, cT);
213 iadd3(e, k, k, c1);
214 isetp_ge_u32(e, k, nk);
215 bra_back_if_not_p0(e, l1);
216 loop_end(e);
217 static const uint32_t steps[5] = { 16, 8, 4, 2, 1 };
218 for (int s = 0; s < (mutant ? 4 : 5); s++) { shfl_down(e, t, acc, steps[s]); fadd(e, acc, acc, t); }
219 int saddr = V(e);
220 imadi(e, saddr, p.tid, 4, NOREG);
221 sts32(e, saddr, acc);
222 bar_sync(e);
223 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);
224 movrz(e, a0); movi(e, a1, 128); movi(e, a2, 256); movi(e, a3, 384);
225 lds32(e, s0, a0); lds32(e, s1, a1); lds32(e, s2, a2); lds32(e, s3, a3);
226 fadd(e, sum, s0, s1); fadd(e, sum, sum, s2); fadd(e, sum, sum, s3);
227 int v = V(e), y = V(e), u = V(e), cmh = V(e), c15 = V(e);
228 fmul(e, v, sum, invd);
229 fadd(e, v, v, eps);
230 mufu(e, BW_IR_MUFU_RSQ, y, v);
231 movf(e, cmh, -0.5f); movf(e, c15, 1.5f);
232 fmul(e, u, v, y); fmul(e, u, u, y); ffma(e, u, u, cmh, c15); fmul(e, y, y, u);
233 int offw = V64(e), offc = V64(e), w = V(e), o = V(e);
234 iadd3(e, idx, rowbase, p.tid);
235 imadi(e, col, p.tid, 1, NOREG); /* col = tid (the encoder maps a missing src2 to R0, not RZ, so no IADD3 here) */
236 movrz(e, k);
237 loop_begin(e);
238 int l2 = here(e);
239 addr4(e, off, idx, p.pa);
240 ldg(e, x, off, p.udesc);
241 addr4(e, offw, col, p.pb);
242 ldg(e, w, offw, p.udesc);
243 fmul(e, o, x, y);
244 fmul(e, o, o, w);
245 addr4(e, offc, idx, p.pc);
246 stg(e, offc, o, p.udesc);
247 iadd3(e, idx, idx, cT);
248 iadd3(e, col, col, cT);
249 iadd3(e, k, k, c1);
250 isetp_ge_u32(e, k, nk);
251 bra_back_if_not_p0(e, l2);
252 loop_end(e);
253 tail(e);
254}
255
256/* One CTA of head_dim/2 threads per head. P0 = head_dim, P1 = head_dim/2.
257 * a = vector, b = table (cos in the first half of each head, sin in the second).
258 * Mutant: out0 = q0*cos + q1*sin. */
259static void gen_rope(Em *e, int mutant) {
260 Pro p = prologue(e);
261 int hd = V(e), half = V(e), i0 = V(e), i1 = V(e), off0 = V64(e), off1 = V64(e);
262 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);
263 ldc32(e, hd, ARG_P0); ldc32(e, half, ARG_P1);
264 imadr(e, i0, p.cta, hd, p.tid);
265 iadd3(e, i1, i0, half);
266 addr4(e, off0, i0, p.pa); ldg(e, q0, off0, p.udesc);
267 addr4(e, off1, i1, p.pa); ldg(e, q1, off1, p.udesc);
268 addr4(e, off0, i0, p.pb); ldg(e, c, off0, p.udesc);
269 addr4(e, off1, i1, p.pb); ldg(e, s, off1, p.udesc);
270 fmul(e, t0, q0, c); fmul(e, t1, q1, s);
271 if (mutant) fadd(e, o0, t0, t1); else fsub(e, o0, t0, t1);
272 fmul(e, t0, q0, s); fmul(e, t1, q1, c);
273 fadd(e, o1, t0, t1);
274 addr4(e, off0, i0, p.pc); stg(e, off0, o0, p.udesc);
275 addr4(e, off1, i1, p.pc); stg(e, off1, o1, p.udesc);
276 tail(e);
277}
278
279/* out[i] = g/(1+2^(g*-log2e)) * up for i < n (P0). Mutant: 2^(g*+log2e). */
280static void gen_swiglu(Em *e, int mutant) {
281 Pro p = prologue(e);
282 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);
283 ldc32(e, n, ARG_P0);
284 imadi(e, i, p.cta, OMEGA_GPU_EW_THREADS, p.tid);
285 isetp_ge_u32(e, i, n);
286 exit_if_p0(e);
287 addr4(e, off, i, p.pa); ldg(e, g, off, p.udesc);
288 addr4(e, off, i, p.pb); ldg(e, u, off, p.udesc);
289 movf(e, k, mutant ? 1.4426950408889634f : -1.4426950408889634f);
290 movf(e, one, 1.0f);
291 fmul(e, t, g, k);
292 mufu(e, BW_IR_MUFU_EX2, ex, t);
293 fadd(e, d, ex, one);
294 mufu(e, BW_IR_MUFU_RCP, r, d);
295 fmul(e, o, g, r);
296 fmul(e, o, o, u);
297 addr4(e, off, i, p.pc);
298 stg(e, off, o, p.udesc);
299 tail(e);
300}
301
302/* A value first defined inside a loop body may not be read after the loop
303 * before it is written again: the allocator could have let a later body
304 * temporary share its register, and the last iteration's value would be lost. */
305static int check_loop_invariant(const Em *e) {
306 const OmegaRegAlloc *ra = &e->p->regalloc;
307 for (int L = 0; L < e->n_loops; L++)
308 for (int v = 0; v < ra->num_vregs; v++) {
309 int fd = ra->intervals[v].first_def;
310 if (fd < e->loop_start[L] || fd > e->loop_end[L]) continue;
311 for (size_t i = (size_t)e->loop_end[L] + 1; i < e->p->count; i++) {
312 const BlackwellIRInsn *in = &e->p->insns[i];
313 if (in->src1_vreg == v || in->src2_vreg == v || in->src3_vreg == v) return -1;
314 if (in->dst_vreg == v && !in->is_uniform) break;
315 }
316 }
317 return 0;
318}
319
320#define EW_GPR_BUDGET 64u /* the QMD declares 64 registers, as the matmul launcher does */
321
322static int build_kernel(OmegaGpuEwOp op, int mutant, OmegaBlackwellKernel *kernel) {
323 BlackwellIRProgram *prog = calloc(1, sizeof *prog);
324 if (!prog) return OMEGA_GPU_EW_CODEGEN_FAIL;
325 omega_bw_ir_init(prog);
326 Em e; memset(&e, 0, sizeof e); e.p = prog;
327 switch (op) {
328 case OMEGA_GPU_EW_EX2: gen_ex2(&e, mutant); break;
329 case OMEGA_GPU_EW_XCHG: gen_xchg(&e, mutant); break;
330 case OMEGA_GPU_EW_RMSNORM: gen_rmsnorm(&e, mutant); break;
331 case OMEGA_GPU_EW_ROPE: gen_rope(&e, mutant); break;
332 case OMEGA_GPU_EW_SWIGLU: gen_swiglu(&e, mutant); break;
333 default: e.err = -1; break;
334 }
335 int rc = OMEGA_GPU_EW_CODEGEN_FAIL;
336 int ra_rc = (e.err == 0) ? omega_bw_regalloc_solve(prog) : -1;
337 int loop_rc = (ra_rc == 0) ? check_loop_invariant(&e) : -1;
338#ifdef OMEGA_EW_DEBUG
339 fprintf(stderr, "ew codegen op=%d mutant=%d emit_err=%d insns=%zu vregs=%d regalloc=%d loops=%d peak_gpr=%u\n",
340 (int)op, mutant, e.err, prog->count, prog->regalloc.num_vregs, ra_rc, loop_rc, prog->regalloc.peak_gpr_usage);
341#endif
342 if (e.err == 0 && ra_rc == 0 && loop_rc == 0 && prog->regalloc.peak_gpr_usage <= EW_GPR_BUDGET) {
343 size_t max_bytes = (size_t)BW_MAX_IR_INSNS * 16;
344 memset(kernel, 0, sizeof *kernel);
345 kernel->code = malloc(max_bytes);
346 size_t emitted = 0;
347 if (kernel->code && omega_bw_encode_program(prog, kernel->code, max_bytes, &emitted) == 0) {
348 kernel->code_size = emitted;
349 kernel->insn_count = emitted / 16;
350 kernel->gpr_count = prog->regalloc.peak_gpr_usage;
351 kernel->uniform_gpr_count = prog->regalloc.peak_ugpr_usage;
352 sha256_hash(kernel->code, kernel->code_size, kernel->code_digest);
353 rc = OMEGA_GPU_EW_OK;
354 } else {
355#ifdef OMEGA_EW_DEBUG
356 fprintf(stderr, "ew codegen op=%d: encode failed (an instruction form the encoder refuses)\n", (int)op);
357#endif
358 free(kernel->code); kernel->code = NULL;
359 }
360 }
361 free(prog);
362 return rc;
363}
364
365/* --------------------------------------------------------- kernel cache */
366
367/* One kernel per (op, mutant); the device copy is uploaded once and stays
368 * resident for the process (cut 4b: no per-call code page). */
369typedef struct { int used; int op; int mutant; OmegaBlackwellKernel kernel; NvrmMem code; } Slot;
370static int g_mutant_op; /* 0 = none */
371static Slot g_cache[8];
372static OmegaGpuScratch g_a, g_b, g_c; /* staging, grown to the high-water mark, reused per call */
373static bool g_hooked;
374#define LOCK() omega_gpu_session_lock()
375#define UNLOCK() omega_gpu_session_unlock()
376
377static void cache_clear_locked(void) {
378 for (size_t i = 0; i < sizeof g_cache / sizeof g_cache[0]; i++)
379 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]); }
380}
381
382void omega_gpu_elementwise_cache_clear(void) {
383 LOCK();
384 cache_clear_locked();
385 UNLOCK();
386}
387
388/* Called by the session (lock held, device still open) right before it closes. */
389static void on_session_close(void) {
390 cache_clear_locked();
391 omega_gpu_session_scratch_free(&g_a); omega_gpu_session_scratch_free(&g_b); omega_gpu_session_scratch_free(&g_c);
392}
393
394void omega_gpu_elementwise_test_set_mutant(int op) {
395 LOCK();
396 g_mutant_op = op;
397 cache_clear_locked();
398 UNLOCK();
399}
400
401/* Caller holds the lock. Builds the kernel if needed; uploads the device copy when a
402 * device is open (upload = false lets the host-only codegen path run without a chip). */
403static int kernel_for(OmegaGpuEwOp op, bool upload, Slot **out, bool *hit) {
404 int mutant = (g_mutant_op == (int)op);
405 Slot *s = NULL;
406 for (size_t i = 0; i < sizeof g_cache / sizeof g_cache[0]; i++)
407 if (g_cache[i].used && g_cache[i].op == (int)op && g_cache[i].mutant == mutant) { s = &g_cache[i]; *hit = true; break; }
408 if (!s) {
409 OmegaBlackwellKernel k;
410 int rc = build_kernel(op, mutant, &k);
411 if (rc != OMEGA_GPU_EW_OK) return rc;
412 size_t slot = 0;
413 for (size_t i = 0; i < sizeof g_cache / sizeof g_cache[0]; i++) if (!g_cache[i].used) { slot = i; break; }
414 s = &g_cache[slot];
415 if (s->used) { free(s->kernel.code); omega_gpu_session_free(&s->code); } /* full: evict slot 0 */
416 memset(s, 0, sizeof *s);
417 s->used = 1; s->op = (int)op; s->mutant = mutant; s->kernel = k;
418 *hit = false;
419 }
420 if (upload && !s->code.cpu) {
421 if (omega_gpu_session_alloc(s->kernel.code_size, &s->code) != 0) return OMEGA_GPU_EW_CHIP_FAIL;
422 memcpy(s->code.cpu, s->kernel.code, s->kernel.code_size);
423 __asm__ volatile("dsb sy" ::: "memory");
424 }
425 *out = s;
426 return OMEGA_GPU_EW_OK;
427}
428
429int omega_gpu_elementwise_codegen(OmegaGpuEwOp op, const uint32_t *dims, float eps, OmegaBlackwellKernel *kernel) {
430 (void)dims; (void)eps; /* kernels read their shape from the argument words */
431 if (!kernel) return OMEGA_GPU_EW_BAD_ARGS;
432 LOCK();
433 int mutant = (g_mutant_op == (int)op);
434 UNLOCK();
435 return build_kernel(op, mutant, kernel);
436}
437
438const char *omega_gpu_elementwise_last_error(void) { return omega_gpu_session_last_error(); }
439
440/* ------------------------------------------------------------ launcher */
441
442#define EW_POISON 0xffbadbadu /* a NaN pattern no kernel here produces on purpose */
443#define EW_WAIT_MS 600000ull /* like main's load/store launchers; a 5 s wait failed under contention (omega#198) */
444
445static uint64_t now_ns(void) {
446 struct timespec t; clock_gettime(CLOCK_MONOTONIC, &t);
447 return (uint64_t)t.tv_sec * 1000000000ULL + (uint64_t)t.tv_nsec;
448}
449
450/* Caller holds the lock. Opens the shared device on first use. */
451static int dev_open_locked(void) {
452 if (!g_hooked) { (void)omega_gpu_session_on_close(on_session_close); g_hooked = true; }
453 return omega_gpu_session_open() ? OMEGA_GPU_EW_OK : OMEGA_GPU_EW_CHIP_FAIL;
454}
455
456/* One launch: a and b staged in, c out (c_bytes/4 words, poison-filled first), through
457 * the shared session (omega_gpu_session_launch: shader-cache invalidate, constant bank,
458 * QMD0/QMD1, first marker, L2_FLUSH_DIRTY, second marker), then readback and the
459 * poison scan. b may be NULL when b_fill wrote the staging buffer already. */
460static int run_abc(const Slot *ks, const void *a, size_t a_bytes, const void *b, size_t b_bytes,
461 void *c, size_t c_bytes, uint32_t threads_x, uint32_t grid_x,
462 const uint32_t params[4], OmegaGpuEwInfo *info) {
463 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))
464 return OMEGA_GPU_EW_CHIP_FAIL;
465 memcpy(g_a.mem.cpu, a, a_bytes);
466 if (b) memcpy(g_b.mem.cpu, b, b_bytes);
467 size_t c_words = c_bytes / 4;
468 uint32_t *c_dev = (uint32_t *)g_c.mem.cpu;
469 for (size_t i = 0; i < c_words; i++) c_dev[i] = EW_POISON;
470 __asm__ volatile("dsb sy" ::: "memory");
471
472 uint32_t args[OMEGA_BW_CBANK_MATMUL_ARGS_WORDS];
473 args[0] = (uint32_t)g_a.mem.va; args[1] = (uint32_t)(g_a.mem.va >> 32);
474 args[2] = (uint32_t)g_b.mem.va; args[3] = (uint32_t)(g_b.mem.va >> 32);
475 args[4] = (uint32_t)g_c.mem.va; args[5] = (uint32_t)(g_c.mem.va >> 32);
476 args[6] = params[0]; args[7] = params[1]; args[8] = params[2]; args[9] = params[3];
477 OmegaGpuLaunch L = {
478 .code_va = ks->code.va, .gpr_count = EW_GPR_BUDGET, .threads_x = threads_x, .threads_y = 1,
479 .grid_x = grid_x, .grid_y = 1, .num_elements = c_words,
480 .args = args, .n_args = OMEGA_BW_CBANK_MATMUL_ARGS_WORDS, .timeout_ms = EW_WAIT_MS,
481 };
482 uint64_t elapsed = 0; uint32_t marker = 0;
483 if (omega_gpu_session_launch(&L, &elapsed, &marker) != 0) return OMEGA_GPU_EW_CHIP_FAIL;
484
485 memcpy(c, g_c.mem.cpu, c_bytes);
486 uint32_t unwritten = 0;
487 for (size_t i = 0; i < c_words; i++) if (((uint32_t *)c)[i] == EW_POISON) unwritten++;
488 if (info) {
489 info->chip_calls++;
490 info->elapsed_ns += elapsed;
491 info->completion_marker = marker;
492 info->unwritten_words += unwritten;
493 info->threads_per_cta = threads_x;
494 info->ctas_last_launch = grid_x;
495 }
496 return unwritten ? OMEGA_GPU_EW_UNWRITTEN : OMEGA_GPU_EW_OK;
497}
498
499/* ------------------------------------------------------- public entries */
500
501static void info_begin(OmegaGpuEwInfo *info, const OmegaBlackwellKernel *k, bool hit) {
502 if (!info) return;
503 memset(info, 0, sizeof *info);
504 info->kernel_cache_hit = hit;
505 info->gpr_count = k->gpr_count;
506 info->insn_count = (uint32_t)k->insn_count;
507 snprintf(info->target_chip, sizeof info->target_chip, "NVIDIA DGX Spark (Grace Blackwell GB10)");
508 info->sm_architecture = 121;
509}
510static uint32_t f2u(float f) { uint32_t u; memcpy(&u, &f, 4); return u; }
511static void info_end(OmegaGpuEwInfo *info, uint64_t t0) { if (info) info->call_ns = now_ns() - t0; }
512
513/* Common prologue of every chip entry: lock, open, kernel (resident), info. */
514static int begin(OmegaGpuEwOp op, Slot **ks, OmegaGpuEwInfo *info) {
515 LOCK();
516 int rc = dev_open_locked();
517 bool hit = false;
518 if (rc == OMEGA_GPU_EW_OK) rc = kernel_for(op, true, ks, &hit);
519 if (rc != OMEGA_GPU_EW_OK) { UNLOCK(); return rc; }
520 info_begin(info, &(*ks)->kernel, hit);
521 return OMEGA_GPU_EW_OK;
522}
523
524int omega_gpu_rmsnorm_f32(uint32_t rows, uint32_t dim, const float *x, const float *weight,
525 float eps, float *out, OmegaGpuEwInfo *info) {
526 uint64_t t0 = now_ns();
527 if (!x || !weight || !out || rows == 0 || dim == 0 || dim % OMEGA_GPU_EW_THREADS != 0) return OMEGA_GPU_EW_BAD_ARGS;
528 if (dim > OMEGA_GPU_EW_MAX_DIM) return OMEGA_GPU_EW_TOO_LARGE;
529 Slot *k = NULL;
530 int rc = begin(OMEGA_GPU_EW_RMSNORM, &k, info);
531 if (rc != OMEGA_GPU_EW_OK) return rc;
532 uint32_t params[4] = { dim / OMEGA_GPU_EW_THREADS, f2u(1.0f / (float)dim), f2u(eps), dim };
533 for (uint32_t r0 = 0; r0 < rows && rc == OMEGA_GPU_EW_OK; r0 += OMEGA_GPU_EW_MAX_CTAS) {
534 uint32_t nr = rows - r0 < OMEGA_GPU_EW_MAX_CTAS ? rows - r0 : OMEGA_GPU_EW_MAX_CTAS;
535 size_t bytes = (size_t)nr * dim * 4;
536 rc = run_abc(k, x + (size_t)r0 * dim, bytes, weight, (size_t)dim * 4, out + (size_t)r0 * dim, bytes,
537 OMEGA_GPU_EW_THREADS, nr, params, info);
538 }
539 UNLOCK();
540 info_end(info, t0);
541 return rc;
542}
543
544int omega_gpu_rope_f32(uint32_t heads, uint32_t head_dim, const float *v,
545 const float *cos_half, const float *sin_half, float *out, OmegaGpuEwInfo *info) {
546 uint64_t t0 = now_ns();
547 if (!v || !cos_half || !sin_half || !out || heads == 0 || head_dim < 2 || (head_dim & 1)) return OMEGA_GPU_EW_BAD_ARGS;
548 if (head_dim > 2048) return OMEGA_GPU_EW_TOO_LARGE;
549 Slot *k = NULL;
550 int rc = begin(OMEGA_GPU_EW_ROPE, &k, info);
551 if (rc != OMEGA_GPU_EW_OK) return rc;
552 uint32_t half = head_dim / 2;
553 uint32_t params[4] = { head_dim, half, 0, 0 };
554 for (uint32_t h0 = 0; h0 < heads && rc == OMEGA_GPU_EW_OK; h0 += OMEGA_GPU_EW_MAX_CTAS) {
555 uint32_t nh = heads - h0 < OMEGA_GPU_EW_MAX_CTAS ? heads - h0 : OMEGA_GPU_EW_MAX_CTAS;
556 size_t bytes = (size_t)nh * head_dim * 4;
557 /* table: cos in the first half of each head, sin in the second, written straight into
558 * the staging buffer (one copy per head of this launch) */
559 if (omega_gpu_session_scratch(&g_b, bytes) != 0) { rc = OMEGA_GPU_EW_CHIP_FAIL; break; }
560 float *table = g_b.mem.cpu;
561 for (uint32_t h = 0; h < nh; h++) {
562 memcpy(table + (size_t)h * head_dim, cos_half, half * sizeof *table);
563 memcpy(table + (size_t)h * head_dim + half, sin_half, half * sizeof *table);
564 }
565 /* out may alias v: v is copied into the staging buffer before the result lands in out */
566 rc = run_abc(k, v + (size_t)h0 * head_dim, bytes, NULL, bytes, out + (size_t)h0 * head_dim, bytes, half, nh, params, info);
567 }
568 UNLOCK();
569 info_end(info, t0);
570 return rc;
571}
572
573static int run_1d(OmegaGpuEwOp op, uint32_t n, const void *a, const void *b, void *c, OmegaGpuEwInfo *info) {
574 uint64_t t0 = now_ns();
575 Slot *k = NULL;
576 int rc = begin(op, &k, info);
577 if (rc != OMEGA_GPU_EW_OK) return rc;
578 const uint32_t chunk = OMEGA_GPU_EW_MAX_CTAS * OMEGA_GPU_EW_THREADS;
579 for (uint32_t i0 = 0; i0 < n && rc == OMEGA_GPU_EW_OK; i0 += chunk) {
580 uint32_t ni = n - i0 < chunk ? n - i0 : chunk;
581 uint32_t grid = (ni + OMEGA_GPU_EW_THREADS - 1) / OMEGA_GPU_EW_THREADS;
582 uint32_t params[4] = { ni, 0, 0, 0 };
583 size_t bytes = (size_t)ni * 4;
584 rc = run_abc(k, (const uint8_t *)a + (size_t)i0 * 4, bytes, b ? (const uint8_t *)b + (size_t)i0 * 4 : a, bytes,
585 (uint8_t *)c + (size_t)i0 * 4, bytes, OMEGA_GPU_EW_THREADS, grid, params, info);
586 }
587 UNLOCK();
588 info_end(info, t0);
589 return rc;
590}
591
592int omega_gpu_swiglu_f32(uint32_t n, const float *gate, const float *up, float *out, OmegaGpuEwInfo *info) {
593 if (!gate || !up || !out || n == 0) return OMEGA_GPU_EW_BAD_ARGS;
594 return run_1d(OMEGA_GPU_EW_SWIGLU, n, gate, up, out, info);
595}
596int omega_gpu_ex2_f32(uint32_t n, const float *x, float *out, OmegaGpuEwInfo *info) {
597 if (!x || !out || n == 0) return OMEGA_GPU_EW_BAD_ARGS;
598 return run_1d(OMEGA_GPU_EW_EX2, n, x, NULL, out, info);
599}
600int omega_gpu_shared_xchg_u32(uint32_t n, const uint32_t *x, uint32_t *out, OmegaGpuEwInfo *info) {
601 if (!x || !out || n == 0 || n % OMEGA_GPU_EW_THREADS != 0) return OMEGA_GPU_EW_BAD_ARGS;
602 return run_1d(OMEGA_GPU_EW_XCHG, n, x, NULL, out, info);
603}
604
605const char *omega_gpu_elementwise_rc_name(int rc) {
606 switch (rc) {
607 case OMEGA_GPU_EW_OK: return "OK";
608 case OMEGA_GPU_EW_BAD_ARGS: return "BAD_ARGS";
609 case OMEGA_GPU_EW_TOO_LARGE: return "TOO_LARGE";
610 case OMEGA_GPU_EW_CODEGEN_FAIL: return "CODEGEN_FAIL";
611 case OMEGA_GPU_EW_CHIP_FAIL: return "CHIP_FAIL";
612 case OMEGA_GPU_EW_UNWRITTEN: return "UNWRITTEN";
613 default: return "UNKNOWN";
614 }
615}