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
GitHub aien-dev/omega-mv#255 (code only)
Apply it
git checkout -b patch-493cfb87be280c09 fc96141e3da05019247b39f9db75c3fe548b8e99 curl -fsSL https://interplane.io/drakestapleton/omega-mv/patches/493cfb87be280c09.patch | git am
Provenance
github-import 1
aien-dev/omega-mv
255
1528fa6b58697dc2295fb2192caa27ec3ec388b2
{"kind":"github-import","owner":"aien-dev","repo":"omega-mv","number":255,"url":"https://github.com/aien-dev/omega-mv/pull/255","export_sha256":"967c79e26a893657b5cdaa45efd442be5dbd2ecfe68e25f9a8c1b5da4d60d452","imported_utc":"2026-11-18T16:36:59Z","metadata":"unavailable","state_derived":true}
Changes
diff --git a/Makefile b/Makefile index a629086f6..876240429 100644 --- a/Makefile +++ b/Makefile @@ -19,7 +19,7 @@ SRCS = src/sha256.c src/omega_canonical.c src/omega_validate.c src/omega_core.c src/omega_library.c src/omega_discovery.c src/omega_machine.c src/omega_realize_synth.c \ src/omega_matvec.c src/omega_accelerator.c src/omega_accelerator_world.c \ src/omega_vector.c src/omega_blackwell_encoder.c src/omega_blackwell_qmd.c \ - src/omega_blackwell_realize.c src/omega_blackwell_submit.c src/omega_blackwell_engine.c src/omega_gpu_engine.c src/omega_blackwell_gates.c src/omega_blackwell_matmul.c src/omega_blackwell_codegen.c src/omega_gpu_matmul_api.c src/omega_world_gates.c src/omega_gpu_wait.c \ + src/omega_blackwell_realize.c src/omega_blackwell_submit.c src/omega_blackwell_engine.c src/omega_gpu_engine.c src/omega_blackwell_gates.c src/omega_blackwell_matmul.c src/omega_blackwell_codegen.c src/omega_gpu_matmul_api.c src/omega_gpu_elementwise_api.c src/omega_world_gates.c src/omega_gpu_wait.c \ src/omega_evidence.c \ $(PHYSICS_DIR)/m16/m16_native.c $(PHYSICS_DIR)/nvrm/nvrm.c \ tools/omegatool.c @@ -2143,3 +2143,14 @@ $(GPU_API_TEST): tests/gpu_matmul_api_test.c src/omega_gpu_matmul_api.h $(OUT_DI $(CC) $(CFLAGS) -o $@ tests/gpu_matmul_api_test.c $(OUT_DIR)/libomega_gpu.a -lpthread -lm test-gpu-matmul-api: $(GPU_API_TEST) ./$(GPU_API_TEST) --host-only + +# FB-1 cut 4: native rmsnorm / rope / swiglu (+ EX2 and shared-exchange probes). +# test-gpu-elementwise is host-only (refusals, codegen, word fixtures, nvdisasm +# listing); the chip gate is `./build/gpu_elementwise_test --out receipt.json` +# through the heavy queue. -ffp-contract=off keeps the f32 oracle free of FMA. +.PHONY: test-gpu-elementwise +GPU_EW_TEST = $(OUT_DIR)/gpu_elementwise_test +$(GPU_EW_TEST): tests/gpu_elementwise_test.c src/omega_gpu_elementwise_api.h $(OUT_DIR)/libomega_gpu.a + $(CC) $(CFLAGS) -ffp-contract=off -o $@ tests/gpu_elementwise_test.c $(OUT_DIR)/libomega_gpu.a -lpthread -lm +test-gpu-elementwise: $(GPU_EW_TEST) + ./$(GPU_EW_TEST) --host-only diff --git a/docs/numeric/FB1_CUT4_ELEMENTWISE.md b/docs/numeric/FB1_CUT4_ELEMENTWISE.md new file mode 100644 index 000000000..800046274 --- /dev/null +++ b/docs/numeric/FB1_CUT4_ELEMENTWISE.md @@ -0,0 +1,65 @@ +# FB-1 cut 4: native rmsnorm, rope, swiglu (own codegen, no CUDA) + +Written 2026-10-04. Program: `~/handoffs/2026-10-04-fb1-cuts-2-6-plan.md` section 4. +Code: `src/omega_gpu_elementwise_api.{h,c}`, `tests/gpu_elementwise_test.c`, +`tools/run_gpu_elementwise_chip.sh`; four additive IR ops in `src/omega_blackwell_codegen.{h,c}`. + +## DOCS READ (gate record `docs-read omega`, 2026-10-04) +- nvdisasm 13.0 `-b SM121` decode of every instruction form the kernels use (the method of + `tools/divsqrt_nvdisasm_check.sh`). The new words: + - `0x7308 / w2 0x00000800` decodes `MUFU.EX2 R2, R4` (RCP is `0x1000`, RSQ `0x1400`). + - `0x7b1d / 0 / 0x00010000 / 0x000fec00` decodes `BAR.SYNC.DEFER_BLOCKING 0x0`; the same words + `src/omega_numeric.c:885` runs on the chip (LDS_STS op, 148/148 specs). + - `0x7984 / 0xff / 0x08000800` decodes `LDS R9, [R10+URZ]` and `0x7988 / Rb / 0x080008ff` + decodes `STS [R8+URZ], R2` (`src/omega_numeric.c:884-886`). The codegen's older `BW_IR_LDS` and + `BW_IR_STS` decode as `LDS.U8` / `STS.U8` (byte wide); they are left untouched and the 32-bit + forms are new ops `BW_IR_LDS32` / `BW_IR_STS32`. +- DOCS SILENT on the SASS-level error bound of MUFU.EX2; the PTX ISA bound for `ex2.approx.f32` + (maximum relative error 2^-22.5 in the primary range) is used, with 2x margin. +- `nvos.h:1112` (nvidia-open-580.173.02): GPU-cached system memory is not coherent with CPU + mappings. Every buffer in the launcher is `nvrm_alloc_gpu_uncached`, as in the matmul path. +- Scheduling rules come from the chip-learned checks in `src/omega_numeric.c` + (`omega_numeric_check_patch`): scoreboard producers stall >= 2 and are waited on; fixed-latency + producers stall >= 5 (we use 6); ISETP stalls 13 before a predicated consumer (codegen default). + The emitter serialises every dependency (slow, safe); speed is a later cut. + +## Kernels (one per op; shape read from the four argument words c[0x0][0x398..0x3a4]) +| op | CTA | grid | math on the chip | oracle (tensor.rs, sovereign-core 5fdab70) | tolerance | +|---|---|---|---|---|---| +| ex2 probe | 128 | ceil(n/128) | `MUFU.EX2` | `exp2` in f64 | 1e-6 rel | +| xchg probe | 128 | n/128 | `STS`, `BAR.SYNC`, `LDS` partner word | `a[i ^ 127]` | exact | +| rmsnorm | 128 (4 warps) per row | rows | f32 `FFMA` strided sum of squares, `SHFL.DOWN` 16..1 tree, lane partials to shared, `BAR.SYNC`, 4 `LDS`, `MUFU.RSQ` + one Newton step, `(x*scale)*w` | f64 sum, `(1/sqrt(mean+eps)) as f32`, `x*scale*weight` | 1e-5 rel + 1e-6 abs | +| rope | head_dim/2 per head | heads | `FMUL, FMUL, FADD/FSUB` on (q0,q1) with host cos/sin | same f32 ops, same order (rotate_half, cos/sin cast from f64) | exact (bitwise) | +| swiglu | 128 | ceil(n/128) | `t=g*-log2e; e=EX2(t); d=e+1; r=RCP(d); (g*r)*up` | f64 `g/(1+exp(-g))*up` | 1e-5 rel + 1e-6 abs | + +Rope note: the trait is in-place on q and k; the API takes a vector of heads and writes `out` +(which may alias the input). The host builds the per-head cos|sin table once per call. + +Launch envelope: at most 64 CTAs per launch (matmul sweep 2026-10-03 lost tiles at 128, +investigation I42, cause UNKNOWN); the API splits rows / heads / elements on the host. + +## Mutants (the same parity check must fail against them, in the same chip run) +EX2: `2^(x+1)`. XCHG: reads its own word. RMSNORM: warp tree drops the last `SHFL` step. +ROPE: `out0 = q0*cos + q1*sin`. SWIGLU: `exp(+g)`. + +## Register-allocation rule the loops rely on +The IR allocator is a linear scan over textual intervals and knows nothing about back-edges. +`loop_end()` extends every value defined before a loop and read inside it to the back-branch; +`check_loop_invariant()` refuses a kernel that reads, after a loop, a value first defined inside +it without redefining it first. Both are in `omega_gpu_elementwise_api.c`. + +## Status +Shader-cache invalidate: every launch emits `INVALIDATE_SHADER_CACHES` (instruction, data, constant) right after the channel setup words, shared constants `OMEGA_BW_MTHD_INVALIDATE_SHADER_CACHES` / `OMEGA_BW_INVALIDATE_SHADER_CACHES_ALL` in `omega_blackwell_submit.h` used by the matmul launcher too (cut 1b finding: stale SM instruction cache after code-address reuse; local driver clcec0.h is a stub, bits from NVIDIA open-gpu-doc, chip-proven FB1-CUT1B-4345406). Test case `icache_reuse_rotation` cycles 10 distinct kernels twice as a guard (red seen by cut 1b on matmul, not re-observed here: one chip run rule). + +Host: `make test-gpu-elementwise` (fixtures, refusals, codegen, register budget, nvdisasm listing of +all five kernels) PASS at this head. Chip: see the PR title tags and the receipt folder +`~/workspace/evidence-out/FB1-CUT4-<sha>/` (receipt.json, device.txt, run.log, SHA256SUMS). + +## Limits (what this does not prove) +- One chip run per op is a correctness receipt, not a rate; no load test, no repeat statistics. +- The xchg mutant proves the check can say no; it does not prove the barrier is necessary (a + no-barrier variant might pass by timing luck and would be a flaky negative control). +- rmsnorm's f32 sum differs from the f64 oracle by design; the 1e-5 tolerance covers dims up to + 16384 on data of unit scale. Inputs with huge dynamic range would need an f64 or Kahan sum. +- Speed is not measured beyond `elapsed_ns`; the serialised schedule and one device open per + launch are the known price until the resident-device work of cut 1b lands. diff --git a/src/omega_blackwell_codegen.c b/src/omega_blackwell_codegen.c index 070a1181a..560f8ef45 100644 --- a/src/omega_blackwell_codegen.c +++ b/src/omega_blackwell_codegen.c @@ -667,12 +667,77 @@ static int encode_single_insn(const BlackwellIRInsn *insn, const OmegaRegAlloc * break; } + case BW_IR_MUFU_EX2: + /* MUFU.EX2 Rd, Ra. nvdisasm 13.0 -b SM121: 0x7308 with sub-op 0x0800 decodes + * "MUFU.EX2 R2, R4" (RCP is 0x1000, RSQ 0x1400 above). */ + w[0] = 0x7308U | ((uint32_t)(dst & 0xff) << 16); + w[1] = (uint32_t)(src1 & 0xff); + w[2] = 0x00000800; + w[3] = insn->control ? insn->control : 0x000e2400; + break; + + case BW_IR_BAR_SYNC: + /* BAR.SYNC.DEFER_BLOCKING 0x0: the exact words src/omega_numeric.c:885 runs on + * the chip (nvdisasm: "BAR.SYNC.DEFER_BLOCKING 0x0"). No registers. */ + w[0] = 0x00007b1dU; + w[1] = 0x00000000; + w[2] = 0x00010000; + w[3] = insn->control ? insn->control : 0x000fec00; + break; + + case BW_IR_LDS32: + /* LDS Rd, [Ra+URZ] (32-bit), the src/omega_numeric.c:886 form. */ + w[0] = 0x7984U | ((uint32_t)(dst & 0xff) << 16) | ((uint32_t)(src1 & 0xff) << 24); + w[1] = 0x000000ff; + w[2] = 0x08000800; + w[3] = insn->control ? insn->control : 0x000e2800; + break; + + case BW_IR_STS32: + /* STS [Ra+URZ], Rb (32-bit), the src/omega_numeric.c:884 form. */ + w[0] = 0x7988U | ((uint32_t)(src1 & 0xff) << 24); + w[1] = (uint32_t)(src2 & 0xff); + w[2] = 0x080008ffU; + w[3] = insn->control ? insn->control : 0x000fe200; + break; + default: return -1; } return 0; } +/* FB-1 cut 4: word-level fixtures for the four additive ops (checked against the + * nvdisasm decodes recorded in docs/numeric/FB1_CUT4_ELEMENTWISE.md). 0 = all good. */ +int omega_blackwell_verify_codegen_fixtures_fb1cut4(void) { + OmegaRegAlloc ra; + memset(&ra, 0, sizeof(ra)); + ra.vreg_to_phys[0] = 2; /* R2 */ + ra.vreg_to_phys[1] = 4; /* R4 */ + ra.vreg_to_phys[2] = 9; /* R9 */ + ra.vreg_to_phys[3] = 10; /* R10 */ + ra.vreg_to_phys[4] = 8; /* R8 */ + uint32_t w[4]; + + /* MUFU.EX2 R2, R4 */ + BlackwellIRInsn ex2 = { .op = BW_IR_MUFU_EX2, .dst_vreg = 0, .src1_vreg = 1 }; + if (encode_single_insn(&ex2, &ra, w) != 0) return -1; + if (w[0] != 0x00027308U || w[1] != 4 || w[2] != 0x00000800U) return -2; + /* BAR.SYNC.DEFER_BLOCKING 0x0 */ + BlackwellIRInsn bar = { .op = BW_IR_BAR_SYNC }; + if (encode_single_insn(&bar, &ra, w) != 0) return -3; + if (w[0] != 0x00007b1dU || w[1] != 0 || w[2] != 0x00010000U || w[3] != 0x000fec00U) return -4; + /* LDS R9, [R10+URZ] */ + BlackwellIRInsn lds = { .op = BW_IR_LDS32, .dst_vreg = 2, .src1_vreg = 3 }; + if (encode_single_insn(&lds, &ra, w) != 0) return -5; + if (w[0] != 0x0a097984U || w[1] != 0xff || w[2] != 0x08000800U) return -6; + /* STS [R8+URZ], R2 */ + BlackwellIRInsn sts = { .op = BW_IR_STS32, .src1_vreg = 4, .src2_vreg = 0 }; + if (encode_single_insn(&sts, &ra, w) != 0) return -7; + if (w[0] != 0x08007988U || w[1] != 2 || w[2] != 0x080008ffU) return -8; + return 0; +} + int omega_bw_encode_program(const BlackwellIRProgram *prog, uint8_t *code_buf, size_t max_len, size_t *out_len) { if (!prog || !code_buf || !out_len) return -1; diff --git a/src/omega_blackwell_codegen.h b/src/omega_blackwell_codegen.h index 69500b48b..b0828b26d 100644 --- a/src/omega_blackwell_codegen.h +++ b/src/omega_blackwell_codegen.h @@ -64,7 +64,14 @@ typedef enum { BW_IR_LDS, /* LDS Rd, [Ra] */ BW_IR_STS, /* STS [Ra], Rb */ BW_IR_EXIT, /* EXIT */ - BW_IR_BRA /* BRA. imm = signed instruction delta; predicate_p0 / predicate_not select @P0 or @!P0 */ + BW_IR_BRA, /* BRA. imm = signed instruction delta; predicate_p0 / predicate_not select @P0 or @!P0 */ + /* FB-1 cut 4 (2026-10-04), additive. Encodings decoded with nvdisasm 13.0 -b SM121 + * (tools/divsqrt_nvdisasm_check.sh method); the BAR/LDS/STS words are the ones + * src/omega_numeric.c:884-886 runs on the chip (LDS_STS op, 148/148 specs PASS). */ + BW_IR_MUFU_EX2, /* MUFU.EX2 Rd, Ra (2^x, approximate: PTX ex2.approx.f32 bound 2^-22.5 rel) */ + BW_IR_BAR_SYNC, /* BAR.SYNC.DEFER_BLOCKING 0x0 (CTA barrier 0; the QMD declares 1 barrier) */ + BW_IR_LDS32, /* LDS Rd, [Ra+URZ] 32-bit shared load (BW_IR_LDS encodes LDS.U8: byte) */ + BW_IR_STS32 /* STS [Ra+URZ], Rb 32-bit shared store (BW_IR_STS encodes STS.U8: byte) */ } BlackwellIROpcode; /* Special Register Identifiers */ @@ -179,6 +186,9 @@ int omega_blackwell_codegen_matmul_tensor_loop(const OmegaMatMulSpec *spec, uint /* Unit test for instruction encoding bitfield fixtures (Gate 3) */ int omega_blackwell_verify_codegen_fixtures(void); +/* FB-1 cut 4: fixtures for MUFU_EX2, BAR_SYNC, LDS32, STS32 (0 = pass) */ +int omega_blackwell_verify_codegen_fixtures_fb1cut4(void); + /* Unit test for bounded register allocation live intervals and bounds enforcement (Gate 4) */ int omega_blackwell_test_regalloc_bounds(void); diff --git a/src/omega_blackwell_submit.h b/src/omega_blackwell_submit.h index a4357c5d0..e9d330717 100644 --- a/src/omega_blackwell_submit.h +++ b/src/omega_blackwell_submit.h @@ -11,6 +11,16 @@ #define OMEGA_BW_MARKER_COMPLETION_PAYLOAD 0x44444444U #define OMEGA_BW_MARKER2_PAYLOAD 0x46464646u /* C3 second release, after the L2 flush */ +/* Shader-cache invalidate, emitted as the first compute method of every launch that + * uploads kernel code (cut 1b finding: the SM instruction cache is not coherent with + * host writes; after a kernel-cache slot was evicted and its code address reused, the + * chip ran stale instructions). Method and bits from NVIDIA open-gpu-doc + * classes/compute/clcec0.h (BLACKWELL_COMPUTE_B): NVCEC0_INVALIDATE_SHADER_CACHES 0x021c, + * _INSTRUCTION 0:0, _DATA 4:4, _CONSTANT 12:12. The shipped driver tree's clcec0.h is a + * 30-line class-id stub and does not list the method; chip-proven by receipt + * FB1-CUT1B-4345406 (18/18 parity after the fix). Emit: nvrm_mthd(1, MTHD, 1), ALL. */ +#define OMEGA_BW_MTHD_INVALIDATE_SHADER_CACHES 0x021cu +#define OMEGA_BW_INVALIDATE_SHADER_CACHES_ALL ((1u << 0) | (1u << 4) | (1u << 12)) #define OMEGA_BW_SEMAPHORE_INTERMEDIATE_INIT 5U #define OMEGA_BW_SEMAPHORE_INTERMEDIATE_DONE 6U diff --git a/src/omega_gpu_elementwise_api.c b/src/omega_gpu_elementwise_api.c new file mode 100644 index 000000000..f6ef2aa09 --- /dev/null +++ b/src/omega_gpu_elementwise_api.c @@ -0,0 +1,657 @@ +/* omega_gpu_elementwise_api.c: FB-1 cut 4 (2026-10-04). See the header. + * + * Layout of this file: (1) kernel codegen on top of the BlackwellIR, with a + * small scheduler that writes every control word; (2) one launcher cloned from + * the chip-proven tensor matmul path (omega_blackwell_execute_matmul_tensor); + * (3) the public entry points, which split work into <= OMEGA_GPU_EW_MAX_CTAS + * launches and run the host-side bookkeeping. + * + * Scheduling rules (chip-learned, src/omega_numeric.c omega_numeric_check_patch): + * - a variable-latency result (LDG, LDS, LDC, LDCU, S2R, SHFL, MUFU) arrives through + * a scoreboard; the producer stalls >= 2 and the consumer waits on that SB; + * - a fixed-latency result (FADD FMUL FFMA IMAD IADD3 MOV LOP3 SHF) has no + * scoreboard: the producer stalls >= 5 before its consumer (we use 6); + * - a predicate producer (ISETP) stalls 13 before @P0 use (the codegen default); + * - stores (STG, STS) set a read barrier so the next instruction cannot overwrite + * the source register early. + * The emitter below serialises: every instruction waits on everything still + * pending. Slow and safe; speed is a later cut. + */ +#include "omega_gpu_elementwise_api.h" +#include "omega_blackwell_codegen.h" +#include "omega_blackwell_qmd.h" +#include "omega_blackwell_submit.h" +#include "m16_native.h" +#include "sha256.h" +#include <pthread.h> +#include <stdio.h> +#include <stdlib.h> +#include <string.h> +#include <time.h> + +/* ------------------------------------------------------------------ codegen */ + +#define CW(stall, wbar, rbar, wait) \ + (((uint32_t)(stall) << 9) | ((uint32_t)(wbar) << 14) | ((uint32_t)(rbar) << 17) | ((uint32_t)(wait) << 20)) +#define CW_YIELD 0x2000u +#define SB_NONE 7u +#define SB_GPR 0u /* variable-latency GPR results */ +#define SB_RD 1u /* store source-register read barrier */ +#define SB_UGPR 2u /* uniform-register results (LDCU) */ + +enum { K_FIXED, K_PRED, K_VAR, K_UVAR, K_STORE, K_SYNC, K_EXIT, K_BRA }; + +#define EW_MAX_LOOPS 4 +typedef struct { + BlackwellIRProgram *p; + uint32_t pending; /* scoreboards set and not yet waited on */ + int err; + int loop_start[EW_MAX_LOOPS], loop_end[EW_MAX_LOOPS]; + int n_loops; +} Em; + +static void emit(Em *e, BlackwellIRInsn in, int kind) { + uint32_t wait = e->pending; + switch (kind) { + case K_FIXED: in.control = CW(6, SB_NONE, SB_NONE, wait); e->pending = 0; break; + case K_PRED: in.control = CW(13, SB_NONE, SB_NONE, wait); e->pending = 0; break; + case K_VAR: in.control = CW(4, SB_GPR, SB_NONE, wait) | CW_YIELD; e->pending = 1u << SB_GPR; break; + case K_UVAR: in.control = CW(4, SB_UGPR, SB_NONE, wait) | CW_YIELD; e->pending = 1u << SB_UGPR; break; + case K_STORE: in.control = CW(4, SB_NONE, SB_RD, wait) | CW_YIELD; e->pending = 1u << SB_RD; break; + case K_SYNC: in.control = CW(6, SB_NONE, SB_NONE, wait); e->pending = 0; break; + /* a predicated EXIT or BRA that falls through must not be the only waiter */ + case K_EXIT: in.control = CW(5, SB_NONE, SB_NONE, wait); e->pending = in.predicate_p0 ? wait : 0; break; + case K_BRA: in.control = CW(5, SB_NONE, SB_NONE, wait); e->pending = in.predicate_p0 ? wait : 0; break; + default: e->err = -1; return; + } + if (omega_bw_ir_append(e->p, &in) < 0) e->err = -1; /* append returns the index */ +} + +static int V(Em *e) { int v = omega_bw_ir_alloc_vreg(e->p); if (v < 0) e->err = -1; return v; } +static int V64(Em *e) { int v = omega_bw_ir_alloc_vreg64(e->p); if (v < 0) e->err = -1; return v; } +static int UV64(Em *e) { int v = omega_bw_ir_alloc_uvreg64(e->p); if (v < 0) e->err = -1; return v; } +static int here(const Em *e) { return (int)e->p->count; } + +#define NOREG -1 +static BlackwellIRInsn I0(BlackwellIROpcode op) { + BlackwellIRInsn in; memset(&in, 0, sizeof in); + in.op = op; in.dst_vreg = NOREG; in.src1_vreg = NOREG; in.src2_vreg = NOREG; in.src3_vreg = NOREG; in.ureg = NOREG; + return in; +} +static void ldcu64(Em *e, int udst, uint32_t off) { BlackwellIRInsn i = I0(BW_IR_LDCU64); i.dst_vreg = udst; i.imm = off; i.is_uniform = true; emit(e, i, K_UVAR); } +static void ldc64(Em *e, int dst64, uint32_t off) { BlackwellIRInsn i = I0(BW_IR_LDC64); i.dst_vreg = dst64; i.imm = off; emit(e, i, K_VAR); } +static void ldc32(Em *e, int dst, uint32_t off) { BlackwellIRInsn i = I0(BW_IR_LDC); i.dst_vreg = dst; i.imm = off; emit(e, i, K_VAR); } +static void s2r(Em *e, int dst, uint32_t sr) { BlackwellIRInsn i = I0(BW_IR_S2R); i.dst_vreg = dst; i.imm = sr; emit(e, i, K_VAR); } +static void movi(Em *e, int dst, uint32_t imm) { BlackwellIRInsn i = I0(BW_IR_MOV_IMM); i.dst_vreg = dst; i.imm = imm; emit(e, i, K_FIXED); } +static void movf(Em *e, int dst, float f) { uint32_t u; memcpy(&u, &f, 4); movi(e, dst, u); } +static void movrz(Em *e, int dst) { BlackwellIRInsn i = I0(BW_IR_MOV_RZ); i.dst_vreg = dst; emit(e, i, K_FIXED); } +/* dst = a * imm + c (c may be NOREG for RZ) */ +static void imadi(Em *e, int dst, int a, uint32_t imm, int c) { BlackwellIRInsn i = I0(BW_IR_IMAD); i.dst_vreg = dst; i.src1_vreg = a; i.imm = imm; i.src3_vreg = c; emit(e, i, K_FIXED); } +/* dst = a * b + c (registers) */ +static void imadr(Em *e, int dst, int a, int b, int c) { BlackwellIRInsn i = I0(BW_IR_IMAD); i.dst_vreg = dst; i.src1_vreg = a; i.src2_vreg = b; i.src3_vreg = c; emit(e, i, K_FIXED); } +static void iadd3(Em *e, int dst, int a, int b) { BlackwellIRInsn i = I0(BW_IR_IADD3); i.dst_vreg = dst; i.src1_vreg = a; i.src2_vreg = b; emit(e, i, K_FIXED); } +static void lop3xor(Em *e, int dst, int a, int b) { BlackwellIRInsn i = I0(BW_IR_LOP3_XOR); i.dst_vreg = dst; i.src1_vreg = a; i.src2_vreg = b; emit(e, i, K_FIXED); } +/* dst64 = idx * 4 + ptr64 (byte address of element idx) */ +static void addr4(Em *e, int dst64, int idx, int ptr64) { BlackwellIRInsn i = I0(BW_IR_IMAD_WIDE); i.dst_vreg = dst64; i.src1_vreg = idx; i.imm = 4; i.src3_vreg = ptr64; emit(e, i, K_FIXED); } +static void ldg(Em *e, int dst, int addr64, int udesc) { BlackwellIRInsn i = I0(BW_IR_LDG_E); i.dst_vreg = dst; i.src1_vreg = addr64; i.ureg = udesc; emit(e, i, K_VAR); } +static void stg(Em *e, int addr64, int val, int udesc) { BlackwellIRInsn i = I0(BW_IR_STG_E); i.src1_vreg = addr64; i.src2_vreg = val; i.ureg = udesc; emit(e, i, K_STORE); } +static void fadd(Em *e, int d, int a, int b) { BlackwellIRInsn i = I0(BW_IR_FADD); i.dst_vreg = d; i.src1_vreg = a; i.src2_vreg = b; emit(e, i, K_FIXED); } +static void fsub(Em *e, int d, int a, int b) { BlackwellIRInsn i = I0(BW_IR_FSUB); i.dst_vreg = d; i.src1_vreg = a; i.src2_vreg = b; emit(e, i, K_FIXED); } +static void fmul(Em *e, int d, int a, int b) { BlackwellIRInsn i = I0(BW_IR_FMUL); i.dst_vreg = d; i.src1_vreg = a; i.src2_vreg = b; emit(e, i, K_FIXED); } +static void ffma(Em *e, int d, int a, int b, int c) { BlackwellIRInsn i = I0(BW_IR_FFMA); i.dst_vreg = d; i.src1_vreg = a; i.src2_vreg = b; i.src3_vreg = c; emit(e, i, K_FIXED); } +static void mufu(Em *e, BlackwellIROpcode op, int d, int a) { BlackwellIRInsn i = I0(op); i.dst_vreg = d; i.src1_vreg = a; emit(e, i, K_VAR); } +static 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); } +static void sts32(Em *e, int addr, int val) { BlackwellIRInsn i = I0(BW_IR_STS32); i.src1_vreg = addr; i.src2_vreg = val; emit(e, i, K_STORE); } +static void lds32(Em *e, int d, int addr) { BlackwellIRInsn i = I0(BW_IR_LDS32); i.dst_vreg = d; i.src1_vreg = addr; emit(e, i, K_VAR); } +static void bar_sync(Em *e) { emit(e, I0(BW_IR_BAR_SYNC), K_SYNC); } +static void isetp_ge_u32(Em *e, int a, int b) { BlackwellIRInsn i = I0(BW_IR_ISETP_GE_U32); i.src1_vreg = a; i.src2_vreg = b; emit(e, i, K_PRED); } +static void exit_if_p0(Em *e) { BlackwellIRInsn i = I0(BW_IR_EXIT); i.predicate_p0 = true; emit(e, i, K_EXIT); } +static void bra_back_if_not_p0(Em *e, int target) { BlackwellIRInsn i = I0(BW_IR_BRA); i.predicate_p0 = true; i.predicate_not = true; i.imm = (uint32_t)(target - here(e)); emit(e, i, K_BRA); } +static void tail(Em *e) { + emit(e, I0(BW_IR_EXIT), K_EXIT); + BlackwellIRInsn self = I0(BW_IR_BRA); /* the self-branch every kernel here ends with */ + self.control = 0x000fc000u; + if (omega_bw_ir_append(e->p, &self) < 0) e->err = -1; +} +static void loop_begin(Em *e) { if (e->n_loops < EW_MAX_LOOPS) e->loop_start[e->n_loops] = here(e); } +/* Closing a loop: every value defined before the loop and read inside it stays + * live until the back-branch, otherwise the linear-scan allocator (which knows + * nothing about back-edges) would hand its register to a body temporary whose + * first definition comes after the value's last textual use (e.g. the scale y + * in rmsnorm pass 2), and the next iteration would read garbage. */ +static void loop_end(Em *e) { + if (e->n_loops >= EW_MAX_LOOPS) { e->err = -1; return; } + int start = e->loop_start[e->n_loops], end = here(e) - 1; + e->loop_end[e->n_loops] = end; + e->n_loops++; + OmegaRegAlloc *ra = &e->p->regalloc; + for (int v = 0; v < ra->num_vregs; v++) { + OmegaLiveInterval *iv = &ra->intervals[v]; + if (iv->first_def >= 0 && iv->first_def < start && iv->last_use >= start && iv->last_use < end) iv->last_use = end; + } +} + +/* Kernel argument words (constant bank 0, same slots as the matmul path): + * 0x380 a, 0x388 b, 0x390 c (64-bit each), then four 32-bit parameters. */ +#define ARG_A 0x380u +#define ARG_B 0x388u +#define ARG_C 0x390u +#define ARG_P0 0x398u +#define ARG_P1 0x39cu +#define ARG_P2 0x3a0u +#define ARG_P3 0x3a4u +#define DESC_OFF 0x358u + +typedef struct { int udesc, pa, pb, pc, tid, cta; } Pro; +static Pro prologue(Em *e) { + Pro r; + r.udesc = UV64(e); r.pa = V64(e); r.pb = V64(e); r.pc = V64(e); r.tid = V(e); r.cta = V(e); + ldcu64(e, r.udesc, DESC_OFF); + ldc64(e, r.pa, ARG_A); ldc64(e, r.pb, ARG_B); ldc64(e, r.pc, ARG_C); + s2r(e, r.tid, BW_SR_TID_X); s2r(e, r.cta, BW_SR_CTAID_X); + return r; +} + +/* out[i] = 2^a[i] for i < n (n = P0). Threads 128, grid ceil(n/128). Mutant: 2^(a+1). */ +static void gen_ex2(Em *e, int mutant) { + Pro p = prologue(e); + int n = V(e), i = V(e), off = V64(e), x = V(e), y = V(e); + ldc32(e, n, ARG_P0); + imadi(e, i, p.cta, OMEGA_GPU_EW_THREADS, p.tid); + isetp_ge_u32(e, i, n); + exit_if_p0(e); + addr4(e, off, i, p.pa); + ldg(e, x, off, p.udesc); + if (mutant) { int one = V(e); movf(e, one, 1.0f); fadd(e, x, x, one); } + mufu(e, BW_IR_MUFU_EX2, y, x); + addr4(e, off, i, p.pc); + stg(e, off, y, p.udesc); + tail(e); +} + +/* out[i] = a[i ^ 127] within each CTA of 128 (n % 128 == 0). STS own word, BAR.SYNC, + * LDS the partner word. Mutant: LDS own word (no exchange). */ +static void gen_xchg(Em *e, int mutant) { + Pro p = prologue(e); + int i = V(e), off = V64(e), x = V(e), saddr = V(e), paddr = V(e), mask = V(e), y = V(e); + imadi(e, i, p.cta, OMEGA_GPU_EW_THREADS, p.tid); + addr4(e, off, i, p.pa); + ldg(e, x, off, p.udesc); + imadi(e, saddr, p.tid, 4, NOREG); + sts32(e, saddr, x); + bar_sync(e); + if (mutant) { + lds32(e, y, saddr); + } else { + movi(e, mask, OMEGA_GPU_EW_THREADS - 1); + lop3xor(e, paddr, p.tid, mask); + imadi(e, paddr, paddr, 4, NOREG); + lds32(e, y, paddr); + } + addr4(e, off, i, p.pc); + stg(e, off, y, p.udesc); + tail(e); +} + +/* One CTA of 128 threads per row. P0 = dim/128 (loop count), P1 = bits(1/dim), + * P2 = bits(eps), P3 = dim. Mutant: the warp tree drops the last SHFL step. */ +static void gen_rmsnorm(Em *e, int mutant) { + Pro p = prologue(e); + int nk = V(e), invd = V(e), eps = V(e), dim = V(e); + int rowbase = V(e), idx = V(e), col = V(e), k = V(e), acc = V(e), cT = V(e), c1 = V(e); + int off = V64(e), x = V(e), t = V(e); + ldc32(e, nk, ARG_P0); ldc32(e, invd, ARG_P1); ldc32(e, eps, ARG_P2); ldc32(e, dim, ARG_P3); + imadr(e, rowbase, p.cta, dim, NOREG); + iadd3(e, idx, rowbase, p.tid); + movrz(e, acc); movrz(e, k); + movi(e, cT, OMEGA_GPU_EW_THREADS); movi(e, c1, 1); + loop_begin(e); + int l1 = here(e); + addr4(e, off, idx, p.pa); + ldg(e, x, off, p.udesc); + ffma(e, acc, x, x, acc); + iadd3(e, idx, idx, cT); + iadd3(e, k, k, c1); + isetp_ge_u32(e, k, nk); + bra_back_if_not_p0(e, l1); + loop_end(e); + static const uint32_t steps[5] = { 16, 8, 4, 2, 1 }; + for (int s = 0; s < (mutant ? 4 : 5); s++) { shfl_down(e, t, acc, steps[s]); fadd(e, acc, acc, t); } + int saddr = V(e); + imadi(e, saddr, p.tid, 4, NOREG); + sts32(e, saddr, acc); + bar_sync(e); + 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); + movrz(e, a0); movi(e, a1, 128); movi(e, a2, 256); movi(e, a3, 384); + lds32(e, s0, a0); lds32(e, s1, a1); lds32(e, s2, a2); lds32(e, s3, a3); + fadd(e, sum, s0, s1); fadd(e, sum, sum, s2); fadd(e, sum, sum, s3); + int v = V(e), y = V(e), u = V(e), cmh = V(e), c15 = V(e); + fmul(e, v, sum, invd); + fadd(e, v, v, eps); + mufu(e, BW_IR_MUFU_RSQ, y, v); + movf(e, cmh, -0.5f); movf(e, c15, 1.5f); + fmul(e, u, v, y); fmul(e, u, u, y); ffma(e, u, u, cmh, c15); fmul(e, y, y, u); + int offw = V64(e), offc = V64(e), w = V(e), o = V(e); + iadd3(e, idx, rowbase, p.tid); + imadi(e, col, p.tid, 1, NOREG); /* col = tid (the encoder maps a missing src2 to R0, not RZ, so no IADD3 here) */ + movrz(e, k); + loop_begin(e); + int l2 = here(e); + addr4(e, off, idx, p.pa); + ldg(e, x, off, p.udesc); + addr4(e, offw, col, p.pb); + ldg(e, w, offw, p.udesc); + fmul(e, o, x, y); + fmul(e, o, o, w); + addr4(e, offc, idx, p.pc); + stg(e, offc, o, p.udesc); + iadd3(e, idx, idx, cT); + iadd3(e, col, col, cT); + iadd3(e, k, k, c1); + isetp_ge_u32(e, k, nk); + bra_back_if_not_p0(e, l2); + loop_end(e); + tail(e); +} + +/* One CTA of head_dim/2 threads per head. P0 = head_dim, P1 = head_dim/2. + * a = vector, b = table (cos in the first half of each head, sin in the second). + * Mutant: out0 = q0*cos + q1*sin. */ +static void gen_rope(Em *e, int mutant) { + Pro p = prologue(e); + int hd = V(e), half = V(e), i0 = V(e), i1 = V(e), off0 = V64(e), off1 = V64(e); + 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); + ldc32(e, hd, ARG_P0); ldc32(e, half, ARG_P1); + imadr(e, i0, p.cta, hd, p.tid); + iadd3(e, i1, i0, half); + addr4(e, off0, i0, p.pa); ldg(e, q0, off0, p.udesc); + addr4(e, off1, i1, p.pa); ldg(e, q1, off1, p.udesc); + addr4(e, off0, i0, p.pb); ldg(e, c, off0, p.udesc); + addr4(e, off1, i1, p.pb); ldg(e, s, off1, p.udesc); + fmul(e, t0, q0, c); fmul(e, t1, q1, s); + if (mutant) fadd(e, o0, t0, t1); else fsub(e, o0, t0, t1); + fmul(e, t0, q0, s); fmul(e, t1, q1, c); + fadd(e, o1, t0, t1); + addr4(e, off0, i0, p.pc); stg(e, off0, o0, p.udesc); + addr4(e, off1, i1, p.pc); stg(e, off1, o1, p.udesc); + tail(e); +} + +/* out[i] = g/(1+2^(g*-log2e)) * up for i < n (P0). Mutant: 2^(g*+log2e). */ +static void gen_swiglu(Em *e, int mutant) { + Pro p = prologue(e); + 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); + ldc32(e, n, ARG_P0); + imadi(e, i, p.cta, OMEGA_GPU_EW_THREADS, p.tid); + isetp_ge_u32(e, i, n); + exit_if_p0(e); + addr4(e, off, i, p.pa); ldg(e, g, off, p.udesc); + addr4(e, off, i, p.pb); ldg(e, u, off, p.udesc); + movf(e, k, mutant ? 1.4426950408889634f : -1.4426950408889634f); + movf(e, one, 1.0f); + fmul(e, t, g, k); + mufu(e, BW_IR_MUFU_EX2, ex, t); + fadd(e, d, ex, one); + mufu(e, BW_IR_MUFU_RCP, r, d); + fmul(e, o, g, r); + fmul(e, o, o, u); + addr4(e, off, i, p.pc); + stg(e, off, o, p.udesc); + tail(e); +} + +/* A value first defined inside a loop body may not be read after the loop + * before it is written again: the allocator could have let a later body + * temporary share its register, and the last iteration's value would be lost. */ +static int check_loop_invariant(const Em *e) { + const OmegaRegAlloc *ra = &e->p->regalloc; + for (int L = 0; L < e->n_loops; L++) + for (int v = 0; v < ra->num_vregs; v++) { + int fd = ra->intervals[v].first_def; + if (fd < e->loop_start[L] || fd > e->loop_end[L]) continue; + for (size_t i = (size_t)e->loop_end[L] + 1; i < e->p->count; i++) { + const BlackwellIRInsn *in = &e->p->insns[i]; + if (in->src1_vreg == v || in->src2_vreg == v || in->src3_vreg == v) return -1; + if (in->dst_vreg == v && !in->is_uniform) break; + } + } + return 0; +} + +#define EW_GPR_BUDGET 64u /* the QMD declares 64 registers, as the matmul launcher does */ + +static int build_kernel(OmegaGpuEwOp op, int mutant, OmegaBlackwellKernel *kernel) { + BlackwellIRProgram *prog = calloc(1, sizeof *prog); + if (!prog) return OMEGA_GPU_EW_CODEGEN_FAIL; + omega_bw_ir_init(prog); + Em e; memset(&e, 0, sizeof e); e.p = prog; + switch (op) { + case OMEGA_GPU_EW_EX2: gen_ex2(&e, mutant); break; + case OMEGA_GPU_EW_XCHG: gen_xchg(&e, mutant); break; + case OMEGA_GPU_EW_RMSNORM: gen_rmsnorm(&e, mutant); break; + case OMEGA_GPU_EW_ROPE: gen_rope(&e, mutant); break; + case OMEGA_GPU_EW_SWIGLU: gen_swiglu(&e, mutant); break; + default: e.err = -1; break; + } + int rc = OMEGA_GPU_EW_CODEGEN_FAIL; + int ra_rc = (e.err == 0) ? omega_bw_regalloc_solve(prog) : -1; + int loop_rc = (ra_rc == 0) ? check_loop_invariant(&e) : -1; +#ifdef OMEGA_EW_DEBUG + fprintf(stderr, "ew codegen op=%d mutant=%d emit_err=%d insns=%zu vregs=%d regalloc=%d loops=%d peak_gpr=%u\n", + (int)op, mutant, e.err, prog->count, prog->regalloc.num_vregs, ra_rc, loop_rc, prog->regalloc.peak_gpr_usage); +#endif + if (e.err == 0 && ra_rc == 0 && loop_rc == 0 && prog->regalloc.peak_gpr_usage <= EW_GPR_BUDGET) { + size_t max_bytes = (size_t)BW_MAX_IR_INSNS * 16; + memset(kernel, 0, sizeof *kernel); + kernel->code = malloc(max_bytes); + size_t emitted = 0; + if (kernel->code && omega_bw_encode_program(prog, kernel->code, max_bytes, &emitted) == 0) { + kernel->code_size = emitted; + kernel->insn_count = emitted / 16; + kernel->gpr_count = prog->regalloc.peak_gpr_usage; + kernel->uniform_gpr_count = prog->regalloc.peak_ugpr_usage; + sha256_hash(kernel->code, kernel->code_size, kernel->code_digest); + rc = OMEGA_GPU_EW_OK; + } else { +#ifdef OMEGA_EW_DEBUG + fprintf(stderr, "ew codegen op=%d: encode failed (an instruction form the encoder refuses)\n", (int)op); +#endif + free(kernel->code); kernel->code = NULL; + } + } + free(prog); + return rc; +} + +/* --------------------------------------------------------- kernel cache */ + +static int g_mutant_op; /* 0 = none */ +typedef struct { int used; int op; int mutant; OmegaBlackwellKernel kernel; } Slot; +static Slot g_cache[8]; +static pthread_mutex_t g_mu = PTHREAD_MUTEX_INITIALIZER; + +void omega_gpu_elementwise_cache_clear(void) { + pthread_mutex_lock(&g_mu); + for (size_t i = 0; i < sizeof g_cache / sizeof g_cache[0]; i++) + if (g_cache[i].used) { free(g_cache[i].kernel.code); memset(&g_cache[i], 0, sizeof g_cache[i]); } + pthread_mutex_unlock(&g_mu); +} + +void omega_gpu_elementwise_test_set_mutant(int op) { + pthread_mutex_lock(&g_mu); + g_mutant_op = op; + pthread_mutex_unlock(&g_mu); + omega_gpu_elementwise_cache_clear(); +} + +static int kernel_for(OmegaGpuEwOp op, OmegaBlackwellKernel *out, bool *hit) { + pthread_mutex_lock(&g_mu); + int mutant = (g_mutant_op == (int)op); + for (size_t i = 0; i < sizeof g_cache / sizeof g_cache[0]; i++) + if (g_cache[i].used && g_cache[i].op == (int)op && g_cache[i].mutant == mutant) { + *out = g_cache[i].kernel; *hit = true; pthread_mutex_unlock(&g_mu); return OMEGA_GPU_EW_OK; + } + OmegaBlackwellKernel k; + int rc = build_kernel(op, mutant, &k); + if (rc == OMEGA_GPU_EW_OK) { + for (size_t i = 0; i < sizeof g_cache / sizeof g_cache[0]; i++) + if (!g_cache[i].used) { g_cache[i].used = 1; g_cache[i].op = (int)op; g_cache[i].mutant = mutant; g_cache[i].kernel = k; break; } + *out = k; *hit = false; + } + pthread_mutex_unlock(&g_mu); + return rc; +} + +int omega_gpu_elementwise_codegen(OmegaGpuEwOp op, const uint32_t *dims, float eps, OmegaBlackwellKernel *kernel) { + (void)dims; (void)eps; /* kernels read their shape from the argument words */ + if (!kernel) return OMEGA_GPU_EW_BAD_ARGS; + pthread_mutex_lock(&g_mu); + int mutant = (g_mutant_op == (int)op); + pthread_mutex_unlock(&g_mu); + return build_kernel(op, mutant, kernel); +} + +/* ------------------------------------------------------------ launcher */ + +#define EW_POISON 0xffbadbadu /* a NaN pattern no kernel here produces on purpose */ +#define EW_MARKER2_PAYLOAD 0x46464646u /* same value as omega_blackwell_submit.c and the engine */ +#define EW_WAIT_MS 600000ull /* like main's load/store launchers; a 5 s wait failed under contention (omega#198) */ + +static const uint32_t SETUP_WORDS[18] = { + 0x20012061, 0x0000cec0, 0x20012092, 0x00000001, 0x200120a8, 0x0000000f, 0x2001255d, 0x00000003, + 0x2001255e, 0x20000000, 0x2001255f, 0x000fffff, 0x20012557, 0x00000003, 0x20012558, 0x22000000, + 0x20012559, 0x00000000, +}; + +static uint64_t now_ns(void) { + struct timespec t; clock_gettime(CLOCK_MONOTONIC, &t); + return (uint64_t)t.tv_sec * 1000000000ULL + (uint64_t)t.tv_nsec; +} +static size_t page_round(size_t b) { b = (b + 0xFFFULL) & ~0xFFFULL; return b < 0x1000 ? 0x1000 : b; } + +/* One launch: a and b in, c out (c_bytes/4 words, poison-filled first). Cloned + * from omega_blackwell_execute_matmul_tensor: every buffer GPU-uncached, first + * marker, L2_FLUSH_DIRTY, second marker, then readback and the poison scan. */ +static int run_abc(const OmegaBlackwellKernel *kernel, + const void *a, size_t a_bytes, const void *b, size_t b_bytes, + void *c, size_t c_bytes, uint32_t threads_x, uint32_t grid_x, + const uint32_t params[4], OmegaGpuEwInfo *info) { + M16NativeContext ctx; + if (m16_native_open(&ctx) != 0) return OMEGA_GPU_EW_CHIP_FAIL; + if (m16_native_create_channel(&ctx) != 0) { m16_native_close(&ctx); return OMEGA_GPU_EW_CHIP_FAIL; } + NvrmMem large_pb; + if (nvrm_alloc_gpu_uncached(&ctx.rm, 0x10000, &large_pb) != 0) { m16_native_close(&ctx); return OMEGA_GPU_EW_CHIP_FAIL; } + ctx.pb_mem = large_pb; + + NvrmMem code_mem, cbank_mem, a_mem, b_mem, c_mem, marker_mem, qmd_mem; +#define EW_ALLOC(mem, bytes) if (nvrm_alloc_gpu_uncached(&ctx.rm, (bytes), &(mem)) != 0) { m16_native_close(&ctx); return OMEGA_GPU_EW_CHIP_FAIL; } + EW_ALLOC(code_mem, page_round(kernel->code_size)); + EW_ALLOC(cbank_mem, 0x1000); + EW_ALLOC(a_mem, page_round(a_bytes)); + EW_ALLOC(b_mem, page_round(b_bytes)); + EW_ALLOC(c_mem, page_round(c_bytes)); + EW_ALLOC(marker_mem, 0x1000); + EW_ALLOC(qmd_mem, 0x10000); +#undef EW_ALLOC + memcpy(code_mem.cpu, kernel->code, kernel->code_size); + memcpy(a_mem.cpu, a, a_bytes); + memcpy(b_mem.cpu, b, b_bytes); + size_t c_words = c_bytes / 4; + uint32_t *c_dev = (uint32_t *)c_mem.cpu; + for (size_t i = 0; i < c_words; i++) c_dev[i] = EW_POISON; + + uint32_t cbank_data[OMEGA_BW_CBANK_DRIVER_WORDS]; + omega_blackwell_build_cbank_driver_2d(cbank_data, cbank_mem.va, threads_x, 1, grid_x, 1); + uint32_t cbank_args[OMEGA_BW_CBANK_MATMUL_ARGS_WORDS]; + cbank_args[0] = (uint32_t)a_mem.va; cbank_args[1] = (uint32_t)(a_mem.va >> 32); + cbank_args[2] = (uint32_t)b_mem.va; cbank_args[3] = (uint32_t)(b_mem.va >> 32); + cbank_args[4] = (uint32_t)c_mem.va; cbank_args[5] = (uint32_t)(c_mem.va >> 32); + cbank_args[6] = params[0]; cbank_args[7] = params[1]; cbank_args[8] = params[2]; cbank_args[9] = params[3]; + memcpy(cbank_mem.cpu, cbank_data, sizeof(cbank_data)); + memcpy((uint8_t *)cbank_mem.cpu + 0x380, cbank_args, sizeof(cbank_args)); + + uint64_t qmd0_va = qmd_mem.va, qmd1_va = qmd_mem.va + 0x1000, sem_va = qmd_mem.va + 0x2000, scratch_va = qmd_mem.va + 0x4000; + OmegaBlackwellQmdConfig qmd_cfg = { + .code_va = code_mem.va, .cbank_va = cbank_mem.va, .scratch_va = scratch_va, .sem_va = sem_va, + .qmd0_va = qmd0_va, .qmd1_va = qmd1_va, .num_elements = c_words, .threads_per_block = threads_x, + .grid_width = grid_x, .threads_x = threads_x, .threads_y = 1, .grid_x = grid_x, .grid_y = 1, + .gpr_count = EW_GPR_BUDGET + }; + uint32_t qmd0_words[OMEGA_BW_QMD_WORDS], qmd1_words[OMEGA_BW_QMD_WORDS]; + omega_blackwell_build_qmd0(qmd0_words, qmd0_va, qmd1_va); + omega_blackwell_build_qmd1(qmd1_words, &qmd_cfg); + if (omega_blackwell_verify_qmd_invariants(qmd1_words) != 0) { m16_native_close(&ctx); return OMEGA_GPU_EW_CHIP_FAIL; } + memcpy(qmd_mem.cpu, qmd0_words, sizeof(qmd0_words)); + memcpy((uint8_t *)qmd_mem.cpu + 0x1000, qmd1_words, sizeof(qmd1_words)); + + volatile uint32_t *hsem = (volatile uint32_t *)((uint8_t *)qmd_mem.cpu + 0x2000); + volatile uint32_t *hmarker = (volatile uint32_t *)marker_mem.cpu; + volatile uint32_t *hmarker2 = (volatile uint32_t *)((uint8_t *)marker_mem.cpu + 0x10); + *hsem = 0; *hmarker = 0; *hmarker2 = 0; + __asm__ volatile("dsb sy" ::: "memory"); + + uint32_t pb[1024]; + size_t n = 0; + memcpy(&pb[n], SETUP_WORDS, sizeof(SETUP_WORDS)); n += sizeof(SETUP_WORDS) / 4; + /* Every launch uploads fresh code into a freshly allocated page, so the code address + * of the previous (different) kernel is routinely reused: exactly the stale-SM-icache + * case cut 1b hit. Invalidate before the kernel (constants in omega_blackwell_submit.h). */ + pb[n++] = nvrm_mthd(1, OMEGA_BW_MTHD_INVALIDATE_SHADER_CACHES, 1); pb[n++] = OMEGA_BW_INVALIDATE_SHADER_CACHES_ALL; + pb[n++] = nvrm_mthd(1, 0x0188, 2); pb[n++] = (uint32_t)(cbank_mem.va >> 32); pb[n++] = (uint32_t)cbank_mem.va; + pb[n++] = nvrm_mthd(1, 0x0180, 2); pb[n++] = 0x00000380; pb[n++] = 0x00000001; + pb[n++] = nvrm_mthd(1, 0x01b0, 1); pb[n++] = 0x00000041; + pb[n++] = (224 << 16) | (1 << 13) | (0x01b4 >> 2) | (6u << 28); + memcpy(&pb[n], cbank_data, 224 * 4); n += 224; + pb[n++] = nvrm_mthd(1, 0x0188, 2); pb[n++] = (uint32_t)((cbank_mem.va + 0x380) >> 32); pb[n++] = (uint32_t)(cbank_mem.va + 0x380); + pb[n++] = nvrm_mthd(1, 0x0180, 2); pb[n++] = 0x00000028; pb[n++] = 0x00000001; + pb[n++] = nvrm_mthd(1, 0x01b0, 1); pb[n++] = 0x00000041; + pb[n++] = (10 << 16) | (1 << 13) | (0x01b4 >> 2) | (6u << 28); + memcpy(&pb[n], cbank_args, 10 * 4); n += 10; + pb[n++] = (98 << 16) | (1 << 13) | (0x0318 >> 2) | (2u << 28); + pb[n++] = (1u << 30) | (uint32_t)((qmd0_va >> 40) & 0x1ff); pb[n++] = (uint32_t)(qmd0_va >> 8); + memcpy(&pb[n], qmd0_words, 96 * 4); n += 96; + pb[n++] = nvrm_mthd(1, 0x0188, 2); pb[n++] = (uint32_t)(sem_va >> 32); pb[n++] = (uint32_t)sem_va; + pb[n++] = nvrm_mthd(1, 0x0180, 2); pb[n++] = 0x00000004; pb[n++] = 0x00000001; + pb[n++] = nvrm_mthd(1, 0x01b0, 1); pb[n++] = 0x00000041; + pb[n++] = (1 << 16) | (1 << 13) | (0x01b4 >> 2) | (6u << 28); + pb[n++] = OMEGA_BW_SEMAPHORE_INTERMEDIATE_INIT; + pb[n++] = (98 << 16) | (1 << 13) | (0x0318 >> 2) | (2u << 28); + pb[n++] = (1u << 30) | (uint32_t)((qmd1_va >> 40) & 0x1ff); pb[n++] = (uint32_t)(qmd1_va >> 8); + memcpy(&pb[n], qmd1_words, 96 * 4); n += 96; + pb[n++] = nvrm_mthd(0, 0x005c, 5); + pb[n++] = (uint32_t)marker_mem.va; pb[n++] = (uint32_t)(marker_mem.va >> 32); + pb[n++] = OMEGA_BW_MARKER_COMPLETION_PAYLOAD; pb[n++] = 0; pb[n++] = 0x1 | (1u << 20); + /* C3 tail: L2_FLUSH_DIRTY, then the second release the host waits for before reading */ + pb[n++] = nvrm_mthd(0, 0x0028, 4); pb[n++] = 0; pb[n++] = 0; pb[n++] = 0; pb[n++] = (0x10u << 27); + pb[n++] = nvrm_mthd(0, 0x005c, 5); + pb[n++] = (uint32_t)(marker_mem.va + 0x10); pb[n++] = (uint32_t)((marker_mem.va + 0x10) >> 32); + pb[n++] = EW_MARKER2_PAYLOAD; pb[n++] = 0; pb[n++] = 0x1 | (1u << 20); + + uint64_t t0 = now_ns(); + if (m16_native_submit_methods(&ctx, pb, n) != 0) { m16_native_close(&ctx); return OMEGA_GPU_EW_CHIP_FAIL; } + if (m16_native_wait_marker(hmarker, OMEGA_BW_MARKER_COMPLETION_PAYLOAD, EW_WAIT_MS) != 0) { m16_native_close(&ctx); return OMEGA_GPU_EW_CHIP_FAIL; } + if (m16_native_wait_marker(hmarker2, EW_MARKER2_PAYLOAD, EW_WAIT_MS) != 0) { m16_native_close(&ctx); return OMEGA_GPU_EW_CHIP_FAIL; } + __asm__ volatile("dsb sy" ::: "memory"); + uint64_t t1 = now_ns(); + if (*hsem != OMEGA_BW_SEMAPHORE_INTERMEDIATE_DONE) { m16_native_close(&ctx); return OMEGA_GPU_EW_CHIP_FAIL; } + + memcpy(c, c_mem.cpu, c_bytes); + uint32_t unwritten = 0; + for (size_t i = 0; i < c_words; i++) if (((uint32_t *)c)[i] == EW_POISON) unwritten++; + if (info) { + info->chip_calls++; + info->elapsed_ns += (t1 > t0) ? (t1 - t0) : 0; + info->completion_marker = *hmarker; + info->unwritten_words += unwritten; + info->threads_per_cta = threads_x; + info->ctas_last_launch = grid_x; + } + m16_native_close(&ctx); + return unwritten ? OMEGA_GPU_EW_UNWRITTEN : OMEGA_GPU_EW_OK; +} + +/* ------------------------------------------------------- public entries */ + +static void info_begin(OmegaGpuEwInfo *info, const OmegaBlackwellKernel *k, bool hit) { + if (!info) return; + memset(info, 0, sizeof *info); + info->kernel_cache_hit = hit; + info->gpr_count = k->gpr_count; + info->insn_count = (uint32_t)k->insn_count; + snprintf(info->target_chip, sizeof info->target_chip, "NVIDIA DGX Spark (Grace Blackwell GB10)"); + info->sm_architecture = 121; +} +static uint32_t f2u(float f) { uint32_t u; memcpy(&u, &f, 4); return u; } + +int omega_gpu_rmsnorm_f32(uint32_t rows, uint32_t dim, const float *x, const float *weight, + float eps, float *out, OmegaGpuEwInfo *info) { + if (!x || !weight || !out || rows == 0 || dim == 0 || dim % OMEGA_GPU_EW_THREADS != 0) return OMEGA_GPU_EW_BAD_ARGS; + if (dim > OMEGA_GPU_EW_MAX_DIM) return OMEGA_GPU_EW_TOO_LARGE; + OmegaBlackwellKernel k; bool hit = false; + int rc = kernel_for(OMEGA_GPU_EW_RMSNORM, &k, &hit); + if (rc != OMEGA_GPU_EW_OK) return rc; + info_begin(info, &k, hit); + uint32_t params[4] = { dim / OMEGA_GPU_EW_THREADS, f2u(1.0f / (float)dim), f2u(eps), dim }; + for (uint32_t r0 = 0; r0 < rows; r0 += OMEGA_GPU_EW_MAX_CTAS) { + uint32_t nr = rows - r0 < OMEGA_GPU_EW_MAX_CTAS ? rows - r0 : OMEGA_GPU_EW_MAX_CTAS; + size_t bytes = (size_t)nr * dim * 4; + rc = run_abc(&k, x + (size_t)r0 * dim, bytes, weight, (size_t)dim * 4, out + (size_t)r0 * dim, bytes, + OMEGA_GPU_EW_THREADS, nr, params, info); + if (rc != OMEGA_GPU_EW_OK) return rc; + } + return OMEGA_GPU_EW_OK; +} + +int omega_gpu_rope_f32(uint32_t heads, uint32_t head_dim, const float *v, + const float *cos_half, const float *sin_half, float *out, OmegaGpuEwInfo *info) { + if (!v || !cos_half || !sin_half || !out || heads == 0 || head_dim < 2 || (head_dim & 1)) return OMEGA_GPU_EW_BAD_ARGS; + if (head_dim > 2048) return OMEGA_GPU_EW_TOO_LARGE; + OmegaBlackwellKernel k; bool hit = false; + int rc = kernel_for(OMEGA_GPU_EW_ROPE, &k, &hit); + if (rc != OMEGA_GPU_EW_OK) return rc; + info_begin(info, &k, hit); + uint32_t half = head_dim / 2; + uint32_t hchunk = OMEGA_GPU_EW_MAX_CTAS; + size_t chunk_elems = (size_t)hchunk * head_dim; + float *table = malloc(chunk_elems * sizeof *table); + float *tmp = malloc(chunk_elems * sizeof *tmp); + if (!table || !tmp) { free(table); free(tmp); return OMEGA_GPU_EW_CHIP_FAIL; } + for (uint32_t h = 0; h < hchunk; h++) { + memcpy(table + (size_t)h * head_dim, cos_half, half * sizeof *table); + memcpy(table + (size_t)h * head_dim + half, sin_half, half * sizeof *table); + } + uint32_t params[4] = { head_dim, half, 0, 0 }; + for (uint32_t h0 = 0; h0 < heads; h0 += hchunk) { + uint32_t nh = heads - h0 < hchunk ? heads - h0 : hchunk; + size_t bytes = (size_t)nh * head_dim * 4; + /* through tmp so out may alias v */ + rc = run_abc(&k, v + (size_t)h0 * head_dim, bytes, table, bytes, tmp, bytes, half, nh, params, info); + if (rc != OMEGA_GPU_EW_OK) break; + memcpy(out + (size_t)h0 * head_dim, tmp, bytes); + } + free(table); free(tmp); + return rc; +} + +static int run_1d(OmegaGpuEwOp op, uint32_t n, const void *a, const void *b, void *c, OmegaGpuEwInfo *info) { + OmegaBlackwellKernel k; bool hit = false; + int rc = kernel_for(op, &k, &hit); + if (rc != OMEGA_GPU_EW_OK) return rc; + info_begin(info, &k, hit); + const uint32_t chunk = OMEGA_GPU_EW_MAX_CTAS * OMEGA_GPU_EW_THREADS; + for (uint32_t i0 = 0; i0 < n; i0 += chunk) { + uint32_t ni = n - i0 < chunk ? n - i0 : chunk; + uint32_t grid = (ni + OMEGA_GPU_EW_THREADS - 1) / OMEGA_GPU_EW_THREADS; + uint32_t params[4] = { ni, 0, 0, 0 }; + size_t bytes = (size_t)ni * 4; + rc = run_abc(&k, (const uint8_t *)a + (size_t)i0 * 4, bytes, b ? (const uint8_t *)b + (size_t)i0 * 4 : a, bytes, + (uint8_t *)c + (size_t)i0 * 4, bytes, OMEGA_GPU_EW_THREADS, grid, params, info); + if (rc != OMEGA_GPU_EW_OK) return rc; + } + return OMEGA_GPU_EW_OK; +} + +int omega_gpu_swiglu_f32(uint32_t n, const float *gate, const float *up, float *out, OmegaGpuEwInfo *info) { + if (!gate || !up || !out || n == 0) return OMEGA_GPU_EW_BAD_ARGS; + return run_1d(OMEGA_GPU_EW_SWIGLU, n, gate, up, out, info); +} +int omega_gpu_ex2_f32(uint32_t n, const float *x, float *out, OmegaGpuEwInfo *info) { + if (!x || !out || n == 0) return OMEGA_GPU_EW_BAD_ARGS; + return run_1d(OMEGA_GPU_EW_EX2, n, x, NULL, out, info); +} +int omega_gpu_shared_xchg_u32(uint32_t n, const uint32_t *x, uint32_t *out, OmegaGpuEwInfo *info) { + if (!x || !out || n == 0 || n % OMEGA_GPU_EW_THREADS != 0) return OMEGA_GPU_EW_BAD_ARGS; + return run_1d(OMEGA_GPU_EW_XCHG, n, x, NULL, out, info); +} + +const char *omega_gpu_elementwise_rc_name(int rc) { + switch (rc) { + case OMEGA_GPU_EW_OK: return "OK"; + case OMEGA_GPU_EW_BAD_ARGS: return "BAD_ARGS"; + case OMEGA_GPU_EW_TOO_LARGE: return "TOO_LARGE"; + case OMEGA_GPU_EW_CODEGEN_FAIL: return "CODEGEN_FAIL"; + case OMEGA_GPU_EW_CHIP_FAIL: return "CHIP_FAIL"; + case OMEGA_GPU_EW_UNWRITTEN: return "UNWRITTEN"; + default: return "UNKNOWN"; + } +} diff --git a/src/omega_gpu_elementwise_api.h b/src/omega_gpu_elementwise_api.h new file mode 100644 index 000000000..051c40d71 --- /dev/null +++ b/src/omega_gpu_elementwise_api.h @@ -0,0 +1,124 @@ +#ifndef OMEGA_GPU_ELEMENTWISE_API_H +#define OMEGA_GPU_ELEMENTWISE_API_H +/* + * omega_gpu_elementwise_api: native (no CUDA) elementwise and row-reduction + * kernels for the AIEN inference stack (FB-1 cut 4, 2026-10-04). + * + * Three inference ops plus two probe ops, every kernel generated by our own + * codegen (src/omega_blackwell_codegen.c IR) and launched through the same + * chip-proven sequence as the tensor matmul path: all buffers GPU-uncached + * (nvos.h NVOS32_ATTR2_GPU_CACHEABLE: system memory cached by the GPU is not + * coherent with CPU mappings), first marker, L2_FLUSH_DIRTY, second marker + * (C3 tail), poison-filled output scanned for unwritten words after readback. + * + * The math follows aien-sovereign-core crates/aien-inference-abi/src/tensor.rs + * (ReferenceCpuBackend), read 2026-10-04 at main 5fdab70: + * rmsnorm: scale = 1/sqrt(mean(x^2) + eps) (oracle sums in f64; the chip + * sums in f32 and uses MUFU.RSQ refined by one Newton step), + * out[i] = (x[i] * scale) * weight[i] in that order. + * rope: rotate_half pairs (i, i + head_dim/2) per head, cos/sin tables + * supplied by the host as f32 (the oracle casts f64 cos/sin to f32 + * before the f32 math): out0 = q0*cos - q1*sin, out1 = q0*sin + q1*cos, + * emitted as FMUL, FMUL, FADD (no fused multiply-add), so the chip + * result is bit-identical to the f32 oracle. + * swiglu: out = silu(gate) * up, silu(g) = g / (1 + exp(-g)); the chip uses + * MUFU.EX2(g * -log2(e)) and MUFU.RCP (approximate units), the + * oracle computes in f64. Tolerance is stated per op in the test. + * + * Launch envelope: at most OMEGA_GPU_EW_MAX_CTAS CTAs per launch (the matmul + * sweep of 2026-10-03 lost whole tiles at 128 CTAs, investigation I42); the + * API splits larger work on the host and makes several launches. + */ +#include <stdbool.h> +#include <stddef.h> +#include <stdint.h> +#include "omega_blackwell_matmul.h" /* OmegaBlackwellKernel */ + +#ifdef __cplusplus +extern "C" { +#endif + +enum { + OMEGA_GPU_EW_OK = 0, + OMEGA_GPU_EW_BAD_ARGS = -1, /* NULL pointer, zero dimension, or a shape rule below broken */ + OMEGA_GPU_EW_TOO_LARGE = -2, /* dimension outside the codegen limits */ + OMEGA_GPU_EW_CODEGEN_FAIL = -3, /* our codegen refused or exceeded the register budget */ + OMEGA_GPU_EW_CHIP_FAIL = -4, /* device open, submit, marker or release failed */ + OMEGA_GPU_EW_UNWRITTEN = -5 /* output words still equal to their poison after the run */ +}; + +/* Kernel families. The two probes exist to prove the new instructions on the + * chip with the smallest possible kernels (and are kept for regression). */ +typedef enum { + OMEGA_GPU_EW_EX2 = 1, /* out[i] = 2^a[i] (probe for MUFU.EX2) */ + OMEGA_GPU_EW_XCHG, /* out[i] = a[i ^ (T-1)] inside each CTA (probe for STS/BAR.SYNC/LDS) */ + OMEGA_GPU_EW_RMSNORM, + OMEGA_GPU_EW_ROPE, + OMEGA_GPU_EW_SWIGLU +} OmegaGpuEwOp; + +/* Shape rules (checked, refused with BAD_ARGS / TOO_LARGE): + * rmsnorm: dim % OMEGA_GPU_EW_THREADS == 0, dim <= OMEGA_GPU_EW_MAX_DIM, rows >= 1 + * rope: head_dim even, 2 <= head_dim <= 2048 (head_dim/2 threads per CTA), heads >= 1 + * swiglu: n >= 1 (the kernel guards the tail with a predicated EXIT) + * ex2: n >= 1; xchg: n % OMEGA_GPU_EW_THREADS == 0 */ +#define OMEGA_GPU_EW_THREADS 128u +#define OMEGA_GPU_EW_MAX_DIM 16384u +#define OMEGA_GPU_EW_MAX_CTAS 64u + +typedef struct { + uint32_t chip_calls; /* launches made */ + uint64_t elapsed_ns; /* sum of launch-to-second-marker over the launches */ + uint32_t completion_marker; /* observed first marker word of the last launch */ + uint32_t unwritten_words; /* output words still equal to poison (0 on success) */ + bool kernel_cache_hit; /* the shape's kernel was already generated in this process */ + uint32_t gpr_count; /* registers the generated kernel uses */ + uint32_t insn_count; + uint32_t threads_per_cta; + uint32_t ctas_last_launch; + char target_chip[64]; + uint32_t sm_architecture; +} OmegaGpuEwInfo; + +/* out[r*dim + i] = x[r*dim + i] * scale_r * weight[i]; scale_r = 1/sqrt(mean_i(x^2) + eps). */ +int omega_gpu_rmsnorm_f32(uint32_t rows, uint32_t dim, const float *x, const float *weight, + float eps, float *out, OmegaGpuEwInfo *info); + +/* v holds `heads` heads of head_dim values back to back; cos_half and sin_half + * hold head_dim/2 values each (cos(pos*freq_i), sin(pos*freq_i)); out gets the + * rotated heads (may alias v: the API copies through its own buffers). */ +int omega_gpu_rope_f32(uint32_t heads, uint32_t head_dim, const float *v, + const float *cos_half, const float *sin_half, float *out, + OmegaGpuEwInfo *info); + +/* out[i] = silu(gate[i]) * up[i] for i < n. */ +int omega_gpu_swiglu_f32(uint32_t n, const float *gate, const float *up, float *out, + OmegaGpuEwInfo *info); + +/* Probes. ex2: out[i] = 2^x[i]. xchg: out[i] = x[i ^ (OMEGA_GPU_EW_THREADS-1)] within each CTA. */ +int omega_gpu_ex2_f32(uint32_t n, const float *x, float *out, OmegaGpuEwInfo *info); +int omega_gpu_shared_xchg_u32(uint32_t n, const uint32_t *x, uint32_t *out, OmegaGpuEwInfo *info); + +/* Generate (without launching) the kernel for one op. Kernels read their shape + * from the argument words, so one kernel per op serves every shape; dims and eps + * are accepted for forward compatibility and ignored today (may be NULL / 0). + * Lets tests disassemble the bytes offline (nvdisasm) and check the register + * budget. Caller frees kernel->code. */ +int omega_gpu_elementwise_codegen(OmegaGpuEwOp op, const uint32_t *dims, float eps, + OmegaBlackwellKernel *kernel); + +/* TEST ONLY. Selects a deliberately wrong kernel for one op (0 clears). Each + * mutant changes the math by far more than the op's tolerance, so a parity + * check that still passes against it proves nothing. Clears the kernel cache. + * EX2: computes 2^(x+1). XCHG: reads its own shared word (no exchange). + * RMSNORM: the warp tree drops its last SHFL step (half the lanes go missing). + * ROPE: out0 = q0*cos + q1*sin. SWIGLU: exp(+g) instead of exp(-g). */ +void omega_gpu_elementwise_test_set_mutant(int op); + +const char *omega_gpu_elementwise_rc_name(int rc); +void omega_gpu_elementwise_cache_clear(void); + +#ifdef __cplusplus +} +#endif +#endif diff --git a/src/omega_gpu_matmul_api.c b/src/omega_gpu_matmul_api.c index 9c3478151..4abe6afe2 100644 --- a/src/omega_gpu_matmul_api.c +++ b/src/omega_gpu_matmul_api.c @@ -251,8 +251,9 @@ static int launch(const CacheSlot *ks, uint64_t a_va, uint64_t b_va, uint64_t c_ * 128x16x512 hung, all after the eighth distinct kernel). Method and bits * from NVIDIA open-gpu-doc classes/compute/clcec0.h (BLACKWELL_COMPUTE_B): * NVCEC0_INVALIDATE_SHADER_CACHES 0x021c, INSTRUCTION 0:0, DATA 4:4, - * CONSTANT 12:12 (the 0x021c form waits for idle first). */ - pb[n++] = nvrm_mthd(1, 0x021c, 1); pb[n++] = (1u << 0) | (1u << 4) | (1u << 12); + * CONSTANT 12:12 (the 0x021c form waits for idle first). Shared constants in + * omega_blackwell_submit.h so every launcher emits the same words. */ + pb[n++] = nvrm_mthd(1, OMEGA_BW_MTHD_INVALIDATE_SHADER_CACHES, 1); pb[n++] = OMEGA_BW_INVALIDATE_SHADER_CACHES_ALL; /* constant bank 0: driver words then our arguments at 0x380 (inline upload, same as cut 1) */ pb[n++] = nvrm_mthd(1, 0x0188, 2); pb[n++] = (uint32_t)(g.cbank.va >> 32); pb[n++] = (uint32_t)g.cbank.va; pb[n++] = nvrm_mthd(1, 0x0180, 2); pb[n++] = 0x00000380; pb[n++] = 0x00000001; diff --git a/tests/gpu_elementwise_test.c b/tests/gpu_elementwise_test.c new file mode 100644 index 000000000..c7be98eaf --- /dev/null +++ b/tests/gpu_elementwise_test.c @@ -0,0 +1,329 @@ +/* gpu_elementwise_test: FB-1 cut 4 gate for omega_gpu_elementwise_api. + * + * ./gpu_elementwise_test --host-only refusals, codegen, word fixtures, register budget, + * nvdisasm listing check when /usr/local/cuda/bin/nvdisasm exists + * ./gpu_elementwise_test --out receipt.json chip gate: every op against the host oracle, then its mutant + * (a deliberately wrong kernel) which the same check must catch + * + * Oracles re-state aien-sovereign-core crates/aien-inference-abi/src/tensor.rs (main 5fdab70) in C: + * rmsnorm sums in f64, rope computes cos/sin in f64 and casts to f32 before f32 math, swiglu is f64. + * This file is compiled with -ffp-contract=off so the f32 oracle math has no hidden fused multiply-add. + * + * Tolerances (why): EX2 1e-6 rel (PTX ex2.approx.f32: 2^-22.5 rel, we allow 2x). XCHG exact. + * RMSNORM 1e-5 rel + 1e-6 abs (f32 sum of up to 16384 squares against an f64 sum, plus RSQ seed with one + * Newton step; the mutant moves the scale by about 40 percent). ROPE exact (same f32 ops, same order). + * SWIGLU 1e-5 rel + 1e-6 abs (EX2 and RCP approximations, each about 2^-22 rel; the mutant flips the sign + * of the exponent, which is wrong by a factor of e^(2g)). + */ +#include "omega_gpu_elementwise_api.h" +#include "omega_blackwell_codegen.h" +#include <inttypes.h> +#include <math.h> +#include <stdio.h> +#include <stdlib.h> +#include <string.h> +#include <time.h> +#include <unistd.h> + +static int g_checks, g_failed; +#define CHECK(cond, ...) do { g_checks++; if (!(cond)) { g_failed++; printf("FAIL: "); printf(__VA_ARGS__); printf("\n"); } } while (0) + +static uint32_t lcg(uint32_t *s) { *s = *s * 1664525u + 1013904223u; return *s; } +static float frand(uint32_t *s, float lo, float hi) { return lo + (hi - lo) * ((float)(lcg(s) >> 8) / 16777216.0f); } + +/* ----------------------------------------------------------------- oracles */ +static void oracle_rmsnorm(const float *x, const float *w, float eps, float *out, size_t dim) { + double ss = 0.0; + for (size_t i = 0; i < dim; i++) ss += (double)x[i] * (double)x[i]; + double mean = ss / (double)dim; + float scale = (float)(1.0 / sqrt(mean + (double)eps)); + for (size_t i = 0; i < dim; i++) { float t = x[i] * scale; out[i] = t * w[i]; } +} +static void oracle_rope_tables(size_t head_dim, size_t pos, float theta, float *cos_half, float *sin_half) { + size_t half = head_dim / 2; + for (size_t i = 0; i < half; i++) { + double exponent = (double)(2 * i) / (double)head_dim; + double freq = 1.0 / pow((double)theta, exponent); + double rot = (double)pos * freq; + sin_half[i] = (float)sin(rot); + cos_half[i] = (float)cos(rot); + } +} +static void oracle_rope(const float *v, size_t heads, size_t head_dim, const float *cos_half, const float *sin_half, float *out) { + size_t half = head_dim / 2; + for (size_t h = 0; h < heads; h++) + for (size_t i = 0; i < half; i++) { + size_t i0 = h * head_dim + i, i1 = i0 + half; + float q0 = v[i0], q1 = v[i1], c = cos_half[i], s = sin_half[i]; + float a = q0 * c, b = q1 * s; out[i0] = a - b; + float d = q0 * s, e = q1 * c; out[i1] = d + e; + } +} +static void oracle_swiglu(const float *g, const float *u, float *out, size_t n) { + for (size_t i = 0; i < n; i++) { double gg = g[i]; double silu = gg / (1.0 + exp(-gg)); out[i] = (float)(silu * (double)u[i]); } +} + +/* |got - want| <= rel*|want| + abs; returns the number of violations and the worst scaled error */ +static size_t compare(const float *got, const float *want, size_t n, double rel, double abs_tol, double *worst) { + size_t bad = 0; *worst = 0.0; + for (size_t i = 0; i < n; i++) { + double d = fabs((double)got[i] - (double)want[i]); + double lim = rel * fabs((double)want[i]) + abs_tol; + double scaled = lim > 0 ? d / lim : (d > 0 ? INFINITY : 0.0); + if (scaled > *worst) *worst = scaled; + if (!(d <= lim)) bad++; /* NaN counts as bad */ + } + return bad; +} + +/* ------------------------------------------------------------- host only */ +static int nvdisasm_check(OmegaGpuEwOp op, const char *name, const char *const *must, int n_must) { + const char *nv = "/usr/local/cuda/bin/nvdisasm"; + if (access(nv, X_OK) != 0) { printf("nvdisasm: not present, listing check skipped for %s\n", name); return 0; } + OmegaBlackwellKernel k; memset(&k, 0, sizeof k); + if (omega_gpu_elementwise_codegen(op, NULL, 0.0f, &k) != OMEGA_GPU_EW_OK) return -1; + char bin[64], lst[64], cmd[256]; + snprintf(bin, sizeof bin, "/tmp/omega_ew_%s_%d.bin", name, (int)getpid()); + snprintf(lst, sizeof lst, "/tmp/omega_ew_%s_%d.sass", name, (int)getpid()); + FILE *f = fopen(bin, "wb"); if (!f) { free(k.code); return -1; } + fwrite(k.code, 1, k.code_size, f); fclose(f); + snprintf(cmd, sizeof cmd, "%s -b SM121 %s > %s 2>&1", nv, bin, lst); + int rc = system(cmd); + free(k.code); + FILE *l = fopen(lst, "r"); if (!l) return -1; + char line[512]; int seen[16] = {0}; int bad = 0, insns = 0; + while (fgets(line, sizeof line, l)) { + if (!strstr(line, "/*0")) continue; + insns++; + if (strstr(line, "?") || strstr(line, "error")) bad++; + for (int i = 0; i < n_must; i++) if (strstr(line, must[i])) seen[i] = 1; + } + fclose(l); + int miss = 0; + for (int i = 0; i < n_must; i++) if (!seen[i]) { printf(" %s: nvdisasm listing lacks %s\n", name, must[i]); miss++; } + printf("nvdisasm %s: rc=%d insns=%d undecodable=%d missing=%d (%s)\n", name, rc, insns, bad, miss, lst); + unlink(bin); + return (rc == 0 && bad == 0 && miss == 0) ? 0 : -1; +} + +static void host_only(void) { + CHECK(omega_blackwell_verify_codegen_fixtures_fb1cut4() == 0, "word fixtures MUFU_EX2 / BAR_SYNC / LDS32 / STS32 (rc %d)", omega_blackwell_verify_codegen_fixtures_fb1cut4()); + float a[256] = {0}, b[256] = {0}, c[256] = {0}; + CHECK(omega_gpu_rmsnorm_f32(0, 128, a, b, 1e-5f, c, NULL) == OMEGA_GPU_EW_BAD_ARGS, "rows=0 refused"); + CHECK(omega_gpu_rmsnorm_f32(1, 100, a, b, 1e-5f, c, NULL) == OMEGA_GPU_EW_BAD_ARGS, "dim not a multiple of 128 refused"); + CHECK(omega_gpu_rmsnorm_f32(1, OMEGA_GPU_EW_MAX_DIM + 128, a, b, 1e-5f, c, NULL) == OMEGA_GPU_EW_TOO_LARGE, "dim over limit refused"); + CHECK(omega_gpu_rope_f32(1, 63, a, b, b, c, NULL) == OMEGA_GPU_EW_BAD_ARGS, "odd head_dim refused"); + CHECK(omega_gpu_rope_f32(1, 64, NULL, b, b, c, NULL) == OMEGA_GPU_EW_BAD_ARGS, "NULL vector refused"); + CHECK(omega_gpu_swiglu_f32(0, a, b, c, NULL) == OMEGA_GPU_EW_BAD_ARGS, "n=0 refused"); + CHECK(omega_gpu_shared_xchg_u32(100, (uint32_t *)a, (uint32_t *)c, NULL) == OMEGA_GPU_EW_BAD_ARGS, "xchg n not a multiple of 128 refused"); + CHECK(strcmp(omega_gpu_elementwise_rc_name(OMEGA_GPU_EW_UNWRITTEN), "UNWRITTEN") == 0, "rc name"); + + struct { OmegaGpuEwOp op; const char *name; const char *must[6]; int n; } ops[] = { + { OMEGA_GPU_EW_EX2, "ex2", { "MUFU.EX2", "@P0 EXIT", "STG.E" }, 3 }, + { OMEGA_GPU_EW_XCHG, "xchg", { "STS [R", "BAR.SYNC", "LDS R" }, 3 }, + { OMEGA_GPU_EW_RMSNORM, "rmsnorm", { "SHFL.DOWN", "BAR.SYNC", "MUFU.RSQ", "@!P0 BRA", "STS [R", "LDS R" }, 6 }, + { OMEGA_GPU_EW_ROPE, "rope", { "FADD", "FMUL", "STG.E" }, 3 }, + { OMEGA_GPU_EW_SWIGLU, "swiglu", { "MUFU.EX2", "MUFU.RCP", "@P0 EXIT" }, 3 }, + }; + for (size_t i = 0; i < sizeof ops / sizeof ops[0]; i++) { + OmegaBlackwellKernel k; memset(&k, 0, sizeof k); + int rc = omega_gpu_elementwise_codegen(ops[i].op, NULL, 0.0f, &k); + CHECK(rc == OMEGA_GPU_EW_OK && k.code_size > 0 && k.gpr_count <= 64, "%s kernel generated (rc %s, %zu insns, %u gprs)", ops[i].name, omega_gpu_elementwise_rc_name(rc), k.insn_count, k.gpr_count); + printf("codegen %s: %zu insns, %u gprs, %u ugprs\n", ops[i].name, k.insn_count, k.gpr_count, k.uniform_gpr_count); + uint8_t digest[32]; memcpy(digest, k.code_digest, 32); + free(k.code); + /* the mutant must be a different kernel */ + omega_gpu_elementwise_test_set_mutant((int)ops[i].op); + memset(&k, 0, sizeof k); + CHECK(omega_gpu_elementwise_codegen(ops[i].op, NULL, 0.0f, &k) == OMEGA_GPU_EW_OK && memcmp(digest, k.code_digest, 32) != 0, "%s mutant kernel differs", ops[i].name); + free(k.code); + omega_gpu_elementwise_test_set_mutant(0); + CHECK(nvdisasm_check(ops[i].op, ops[i].name, ops[i].must, ops[i].n) == 0, "%s nvdisasm listing decodes and shows the expected instructions", ops[i].name); + } +} + +/* ------------------------------------------------------------- chip gate */ +typedef struct { const char *name; size_t n; int rc; size_t bad; double worst; int pass; int mutant_rc; size_t mutant_bad; int mutant_caught; uint64_t chip_ns; uint32_t calls; uint32_t unwritten; } Case; +static Case g_cases[16]; static int g_ncases; + +static void record(Case c, FILE *out) { + g_cases[g_ncases++] = c; + CHECK(c.pass, "%s rc=%s violations=%zu worst=%g", c.name, omega_gpu_elementwise_rc_name(c.rc), c.bad, c.worst); + CHECK(c.mutant_caught, "%s mutant caught (rc=%s violations=%zu)", c.name, omega_gpu_elementwise_rc_name(c.mutant_rc), c.mutant_bad); + printf("%s %s n=%zu rc=%s violations=%zu worst_scaled_err=%g chip_ns=%" PRIu64 " calls=%u unwritten=%u | mutant rc=%s violations=%zu %s\n", + c.pass && c.mutant_caught ? "PASS" : "FAIL", c.name, c.n, omega_gpu_elementwise_rc_name(c.rc), c.bad, c.worst, c.chip_ns, c.calls, c.unwritten, + omega_gpu_elementwise_rc_name(c.mutant_rc), c.mutant_bad, c.mutant_caught ? "CAUGHT" : "NOT CAUGHT"); + if (out) fprintf(out, "%s{\"case\":\"%s\",\"n\":%zu,\"rc\":\"%s\",\"violations\":%zu,\"worst_scaled_err\":%g,\"pass\":%s,\"chip_elapsed_ns\":%" PRIu64 ",\"chip_calls\":%u,\"unwritten_words\":%u,\"mutant_rc\":\"%s\",\"mutant_violations\":%zu,\"mutant_caught\":%s}", + g_ncases > 1 ? "," : "", c.name, c.n, omega_gpu_elementwise_rc_name(c.rc), c.bad, c.worst, c.pass ? "true" : "false", c.chip_ns, c.calls, c.unwritten, + omega_gpu_elementwise_rc_name(c.mutant_rc), c.mutant_bad, c.mutant_caught ? "true" : "false"); +} + +static int chip(const char *out_path) { + FILE *out = out_path ? fopen(out_path, "w") : NULL; + if (out_path && !out) { printf("cannot open %s\n", out_path); return 2; } + if (out) fprintf(out, "{\"schema\":\"OMEGA_GPU_ELEMENTWISE_V1\",\"tolerances\":{\"ex2_rel\":1e-6,\"xchg\":\"exact\",\"rmsnorm_rel\":1e-5,\"rmsnorm_abs\":1e-6,\"rope\":\"exact\",\"swiglu_rel\":1e-5,\"swiglu_abs\":1e-6},\"cases\":["); + uint32_t seed = 0xfb1c0004u; + OmegaGpuEwInfo info; + + /* 1. EX2 probe, with a negative control on the comparison itself */ + { + size_t n = 4096; float *x = malloc(n * 4), *got = malloc(n * 4), *want = malloc(n * 4), *wrong = malloc(n * 4); + for (size_t i = 0; i < n; i++) { x[i] = frand(&seed, -20.0f, 20.0f); want[i] = (float)exp2((double)x[i]); wrong[i] = (float)exp2((double)x[i] + 1.0); } + Case c = { .name = "ex2_probe", .n = n }; + c.rc = omega_gpu_ex2_f32((uint32_t)n, x, got, &info); + c.bad = compare(got, want, n, 1e-6, 0.0, &c.worst); + double w2; size_t neg = compare(got, wrong, n, 1e-6, 0.0, &w2); + CHECK(neg > n / 2, "ex2 negative control: the check rejects a wrong expectation (%zu of %zu flagged)", neg, n); + c.pass = c.rc == OMEGA_GPU_EW_OK && c.bad == 0; c.chip_ns = info.elapsed_ns; c.calls = info.chip_calls; c.unwritten = info.unwritten_words; + omega_gpu_elementwise_test_set_mutant(OMEGA_GPU_EW_EX2); + c.mutant_rc = omega_gpu_ex2_f32((uint32_t)n, x, got, &info); + c.mutant_bad = compare(got, want, n, 1e-6, 0.0, &w2); + c.mutant_caught = c.mutant_rc != OMEGA_GPU_EW_OK || c.mutant_bad > 0; + omega_gpu_elementwise_test_set_mutant(0); + record(c, out); free(x); free(got); free(want); free(wrong); + } + /* 2. shared-memory exchange probe (STS, BAR.SYNC, LDS) */ + { + size_t n = 4096; uint32_t *x = malloc(n * 4), *got = malloc(n * 4); + for (size_t i = 0; i < n; i++) x[i] = lcg(&seed); + Case c = { .name = "shared_xchg_probe", .n = n }; + c.rc = omega_gpu_shared_xchg_u32((uint32_t)n, x, got, &info); + for (size_t i = 0; i < n; i++) if (got[i] != x[i ^ (OMEGA_GPU_EW_THREADS - 1)]) c.bad++; + c.pass = c.rc == OMEGA_GPU_EW_OK && c.bad == 0; c.chip_ns = info.elapsed_ns; c.calls = info.chip_calls; c.unwritten = info.unwritten_words; + omega_gpu_elementwise_test_set_mutant(OMEGA_GPU_EW_XCHG); + c.mutant_rc = omega_gpu_shared_xchg_u32((uint32_t)n, x, got, &info); + for (size_t i = 0; i < n; i++) if (got[i] != x[i ^ (OMEGA_GPU_EW_THREADS - 1)]) c.mutant_bad++; + c.mutant_caught = c.mutant_rc != OMEGA_GPU_EW_OK || c.mutant_bad > 0; + omega_gpu_elementwise_test_set_mutant(0); + record(c, out); free(x); free(got); + } + /* 3. rmsnorm at the model hidden sizes (TinyLlama and Llama-3.2-1B: 2048), plus small and large */ + { size_t dims[3] = { 2048, 256, 8192 }; size_t rowss[3] = { 4, 1, 2 }; + for (int t = 0; t < 3; t++) { + size_t dim = dims[t], rows = rowss[t], n = rows * dim; float eps = 1e-5f; + float *x = malloc(n * 4), *w = malloc(dim * 4), *got = malloc(n * 4), *want = malloc(n * 4), *again = malloc(n * 4); + for (size_t i = 0; i < n; i++) x[i] = frand(&seed, -3.0f, 3.0f); + for (size_t i = 0; i < dim; i++) w[i] = frand(&seed, 0.5f, 1.5f); + for (size_t r = 0; r < rows; r++) oracle_rmsnorm(x + r * dim, w, eps, want + r * dim, dim); + char name[64]; snprintf(name, sizeof name, "rmsnorm_%zux%zu", rows, dim); + Case c = { .name = strdup(name), .n = n }; + c.rc = omega_gpu_rmsnorm_f32((uint32_t)rows, (uint32_t)dim, x, w, eps, got, &info); + c.bad = compare(got, want, n, 1e-5, 1e-6, &c.worst); + c.pass = c.rc == OMEGA_GPU_EW_OK && c.bad == 0; c.chip_ns = info.elapsed_ns; c.calls = info.chip_calls; c.unwritten = info.unwritten_words; + OmegaGpuEwInfo i2; int rc2 = omega_gpu_rmsnorm_f32((uint32_t)rows, (uint32_t)dim, x, w, eps, again, &i2); + CHECK(rc2 == OMEGA_GPU_EW_OK && i2.kernel_cache_hit && memcmp(got, again, n * 4) == 0, "%s repeat run (cache hit) is bit-identical", name); + omega_gpu_elementwise_test_set_mutant(OMEGA_GPU_EW_RMSNORM); + double w2; c.mutant_rc = omega_gpu_rmsnorm_f32((uint32_t)rows, (uint32_t)dim, x, w, eps, got, &info); + c.mutant_bad = compare(got, want, n, 1e-5, 1e-6, &w2); + c.mutant_caught = c.mutant_rc != OMEGA_GPU_EW_OK || c.mutant_bad > 0; + omega_gpu_elementwise_test_set_mutant(0); + record(c, out); free(x); free(w); free(got); free(want); free(again); + } } + /* 4. rope: TinyLlama (32 q heads, 4 kv heads, head_dim 64, theta 10000) and Llama-3.2-1B (32/8, 64, 500000) */ + { struct { size_t heads, hd, pos; float theta; } rs[4] = { { 32, 64, 17, 10000.0f }, { 4, 64, 17, 10000.0f }, { 32, 64, 1023, 500000.0f }, { 8, 64, 1023, 500000.0f } }; + for (int t = 0; t < 4; t++) { + size_t heads = rs[t].heads, hd = rs[t].hd, n = heads * hd, half = hd / 2; + float *v = malloc(n * 4), *got = malloc(n * 4), *want = malloc(n * 4), *ch = malloc(half * 4), *sh = malloc(half * 4); + for (size_t i = 0; i < n; i++) v[i] = frand(&seed, -4.0f, 4.0f); + oracle_rope_tables(hd, rs[t].pos, rs[t].theta, ch, sh); + oracle_rope(v, heads, hd, ch, sh, want); + char name[64]; snprintf(name, sizeof name, "rope_%zuh_%zud_pos%zu_theta%g", heads, hd, rs[t].pos, rs[t].theta); + Case c = { .name = strdup(name), .n = n }; + c.rc = omega_gpu_rope_f32((uint32_t)heads, (uint32_t)hd, v, ch, sh, got, &info); + c.bad = compare(got, want, n, 0.0, 0.0, &c.worst); + c.pass = c.rc == OMEGA_GPU_EW_OK && c.bad == 0; c.chip_ns = info.elapsed_ns; c.calls = info.chip_calls; c.unwritten = info.unwritten_words; + omega_gpu_elementwise_test_set_mutant(OMEGA_GPU_EW_ROPE); + double w2; c.mutant_rc = omega_gpu_rope_f32((uint32_t)heads, (uint32_t)hd, v, ch, sh, got, &info); + c.mutant_bad = compare(got, want, n, 0.0, 0.0, &w2); + c.mutant_caught = c.mutant_rc != OMEGA_GPU_EW_OK || c.mutant_bad > 0; + omega_gpu_elementwise_test_set_mutant(0); + record(c, out); free(v); free(got); free(want); free(ch); free(sh); + } } + /* 5. swiglu at the model ffn sizes (TinyLlama 5632, Llama-3.2-1B 8192) and an odd tail */ + { size_t ns[3] = { 5632, 8192, 1000 }; + for (int t = 0; t < 3; t++) { + size_t n = ns[t]; + float *g = malloc(n * 4), *u = malloc(n * 4), *got = malloc(n * 4), *want = malloc(n * 4); + for (size_t i = 0; i < n; i++) { g[i] = frand(&seed, -12.0f, 12.0f); u[i] = frand(&seed, -2.0f, 2.0f); } + oracle_swiglu(g, u, want, n); + char name[64]; snprintf(name, sizeof name, "swiglu_%zu", n); + Case c = { .name = strdup(name), .n = n }; + c.rc = omega_gpu_swiglu_f32((uint32_t)n, g, u, got, &info); + c.bad = compare(got, want, n, 1e-5, 1e-6, &c.worst); + c.pass = c.rc == OMEGA_GPU_EW_OK && c.bad == 0; c.chip_ns = info.elapsed_ns; c.calls = info.chip_calls; c.unwritten = info.unwritten_words; + omega_gpu_elementwise_test_set_mutant(OMEGA_GPU_EW_SWIGLU); + double w2; c.mutant_rc = omega_gpu_swiglu_f32((uint32_t)n, g, u, got, &info); + c.mutant_bad = compare(got, want, n, 1e-5, 1e-6, &w2); + c.mutant_caught = c.mutant_rc != OMEGA_GPU_EW_OK || c.mutant_bad > 0; + omega_gpu_elementwise_test_set_mutant(0); + record(c, out); free(g); free(u); free(got); free(want); + } } + /* 6. stale-SM-instruction-cache guard (cut 1b finding, omega #256): 10 distinct kernels + * (5 ops + 5 mutants) in rotation, two rounds. Every launch uploads code into a freshly + * allocated page, so a kernel routinely lands on the code address its predecessor used, + * and 10 keys evict the 8-slot kernel cache. Each clean launch must match the oracle and + * each mutant must still be caught; a stale icache would make a mutant pass or a clean + * kernel fail. Red was observed by cut 1b on matmul before its invalidate (receipt + * FB1-CUT1B-f629798); this build carries the invalidate, so the case is a guard. */ + { + enum { RN = 256, RH = 4, RD = 64 }; + float *x = malloc(RN * 4), *w = malloc(RN * 4), *u = malloc(RN * 4), *got = malloc(RN * 4), *want = malloc(RN * 4); + float *ch = malloc(RD / 2 * 4), *sh = malloc(RD / 2 * 4); + uint32_t *xu = malloc(RN * 4), *gu = malloc(RN * 4); + for (size_t i = 0; i < RN; i++) { x[i] = frand(&seed, -3.0f, 3.0f); w[i] = frand(&seed, 0.5f, 1.5f); u[i] = frand(&seed, -2.0f, 2.0f); xu[i] = lcg(&seed); } + oracle_rope_tables(RD, 17, 10000.0f, ch, sh); + Case c = { .name = "icache_reuse_rotation", .n = 20 }; + c.rc = OMEGA_GPU_EW_OK; c.mutant_rc = OMEGA_GPU_EW_OK; c.mutant_caught = 1; + const int order[10] = { OMEGA_GPU_EW_EX2, -OMEGA_GPU_EW_SWIGLU, OMEGA_GPU_EW_XCHG, -OMEGA_GPU_EW_EX2, OMEGA_GPU_EW_RMSNORM, + -OMEGA_GPU_EW_XCHG, OMEGA_GPU_EW_SWIGLU, -OMEGA_GPU_EW_ROPE, OMEGA_GPU_EW_ROPE, -OMEGA_GPU_EW_RMSNORM }; + for (int step = 0; step < 20; step++) { + int round = step / 10, k = step % 10; + int mut = order[k] < 0, op = mut ? -order[k] : order[k]; + omega_gpu_elementwise_test_set_mutant(mut ? op : 0); + int rc; size_t bad = 0; double wst; + switch (op) { + case OMEGA_GPU_EW_EX2: + for (size_t i = 0; i < RN; i++) want[i] = (float)exp2((double)x[i]); + rc = omega_gpu_ex2_f32(RN, x, got, &info); bad = compare(got, want, RN, 1e-6, 0.0, &wst); break; + case OMEGA_GPU_EW_XCHG: + rc = omega_gpu_shared_xchg_u32(RN, xu, gu, &info); + for (size_t i = 0; i < RN; i++) { if (gu[i] != xu[i ^ (OMEGA_GPU_EW_THREADS - 1)]) bad++; } + break; + case OMEGA_GPU_EW_RMSNORM: + oracle_rmsnorm(x, w, 1e-5f, want, RN); + rc = omega_gpu_rmsnorm_f32(1, RN, x, w, 1e-5f, got, &info); bad = compare(got, want, RN, 1e-5, 1e-6, &wst); break; + case OMEGA_GPU_EW_ROPE: + oracle_rope(x, RH, RD, ch, sh, want); + rc = omega_gpu_rope_f32(RH, RD, x, ch, sh, got, &info); bad = compare(got, want, RH * RD, 0.0, 0.0, &wst); break; + default: + oracle_swiglu(x, u, want, RN); + rc = omega_gpu_swiglu_f32(RN, x, u, got, &info); bad = compare(got, want, RN, 1e-5, 1e-6, &wst); break; + } + omega_gpu_elementwise_test_set_mutant(0); + int ok = rc == OMEGA_GPU_EW_OK && bad == 0; + if (!mut && !ok) { c.bad++; if (rc != OMEGA_GPU_EW_OK) c.rc = rc; printf(" rotation %d/%d: clean op %d FAILED rc=%s violations=%zu\n", round, k, op, omega_gpu_elementwise_rc_name(rc), bad); } + if (mut && ok) { c.mutant_bad++; c.mutant_caught = 0; printf(" rotation %d/%d: mutant op %d NOT caught\n", round, k, op); } + c.chip_ns += info.elapsed_ns; c.calls += info.chip_calls; c.unwritten += info.unwritten_words; + } + c.pass = c.bad == 0 && c.rc == OMEGA_GPU_EW_OK; + record(c, out); + free(x); free(w); free(u); free(got); free(want); free(ch); free(sh); free(xu); free(gu); + } + if (out) { + fprintf(out, "],\"checks\":%d,\"failed\":%d,\"verdict\":\"%s\"}\n", g_checks, g_failed, g_failed == 0 ? "OMEGA_GPU_ELEMENTWISE_PASS" : "OMEGA_GPU_ELEMENTWISE_FAIL"); + fclose(out); + } + return 0; +} + +int main(int argc, char **argv) { + const char *out_path = NULL; int host = 0; + for (int i = 1; i < argc; i++) { + if (strcmp(argv[i], "--host-only") == 0) host = 1; + else if (strcmp(argv[i], "--out") == 0 && i + 1 < argc) out_path = argv[++i]; + } + if (host) host_only(); + else if (chip(out_path) != 0) return 2; + printf("%s: %d checks, %d failed\n", g_failed ? "FAIL" : "PASS", g_checks, g_failed); + return g_failed ? 1 : 0; +} diff --git a/tools/run_gpu_elementwise_chip.sh b/tools/run_gpu_elementwise_chip.sh new file mode 100755 index 000000000..9915eb0c1 --- /dev/null +++ b/tools/run_gpu_elementwise_chip.sh @@ -0,0 +1,32 @@ +#!/bin/sh +# tools/run_gpu_elementwise_chip.sh [OUT_ROOT] +# FB-1 cut 4 chip gate (rmsnorm, rope, swiglu, EX2 and shared-exchange probes, +# each against the host oracle and then against its mutant kernel), with a +# sealed receipt folder OUT_ROOT/FB1-CUT4-<sha>/ (default ~/workspace/evidence-out): +# receipt.json machine-readable verdict per case run.log test output +# device.txt kernel, driver, omega and physics shas build.log compiler output +# copies of the three source files the verdict depends on, SHA256SUMS over all +# Run it through the heavy queue only (lanes.sh queue --heavy); never kill it. +set -u +cd "$(dirname "$0")/.." || exit 2 +P=${PHYSICS_DIR:-../physics} +SHA=$(git rev-parse --short HEAD) +OUT=${1:-$HOME/workspace/evidence-out}/FB1-CUT4-$SHA +mkdir -p "$OUT" +if ! make PHYSICS_DIR="$P" build/gpu_elementwise_test > "$OUT/build.log" 2>&1; then + echo "FB1-CUT4 BUILD FAIL (see $OUT/build.log)"; exit 1 +fi +{ + uname -a + nvidia-smi --query-gpu=name,driver_version --format=csv,noheader 2>/dev/null || echo "nvidia-smi: unavailable" + echo "omega $(git rev-parse HEAD) ($(git status --porcelain | wc -l) uncommitted paths)" + echo "physics $(git -C "$P" rev-parse HEAD)" + date -u +%FT%TZ +} > "$OUT/device.txt" +./build/gpu_elementwise_test --out "$OUT/receipt.json" > "$OUT/run.log" 2>&1 +rc=$? +cp src/omega_gpu_elementwise_api.c src/omega_gpu_elementwise_api.h tests/gpu_elementwise_test.c "$OUT/" +(cd "$OUT" && sha256sum -- * > SHA256SUMS) +tail -1 "$OUT/run.log" +echo "FB1-CUT4 chip gate rc=$rc receipt=$OUT/receipt.json" +exit $rc