CUDApp
CUDA++: AIEN’s GPU machine-code toolchain, runtime and driver client for NVIDIA GPUs without the CUDA toolkit. Hardware coverage and driver replacement limits are explicit.
Brought by drakestapleton
GitHub aien-dev/CUDApp#231 (code only)
Apply it
git checkout -b patch-cf9d76df838c634a 105d65de09386615a748c951c0eb9b31929b2357 curl -fsSL https://interplane.io/drakestapleton/CUDApp/patches/cf9d76df838c634a.patch | git am
Provenance
github-import 1
aien-dev/CUDApp
231
247435982add6b05e974edc8e1668f552408cca5
{"kind":"github-import","owner":"aien-dev","repo":"CUDApp","number":231,"url":"https://github.com/aien-dev/CUDApp/pull/231","export_sha256":"967c79e26a893657b5cdaa45efd442be5dbd2ecfe68e25f9a8c1b5da4d60d452","imported_utc":"2026-11-18T16:38:56Z","metadata":"unavailable","state_derived":true}
Changes
diff --git a/Makefile b/Makefile index 0a8a8b80..88c38a64 100644 --- a/Makefile +++ b/Makefile @@ -229,6 +229,16 @@ test-gpu-fp8: $(GPU_FP8_TEST) ./$(GPU_FP8_TEST) --host-only ./$(GPU_FP8_TEST) --sim +# aien-dev/CUDApp#217 (P-DRA-4 DRA-69): all-heads FP8 lm_head kernel. Host + warp simulator only (bitwise parity with +# the legacy lane_bytes-16 FP8 GEMV for xb 1-8, rows 1-2; double-oracle tolerance; mutants 1-3 caught). No chip path. +.PHONY: test-gpu-fp8-head +GPU_FP8_HEAD_TEST = $(OUT_DIR)/gpu_fp8_head_test +$(GPU_FP8_HEAD_TEST): tests/gpu_fp8_head_test.c tests/bw_warp_sim.h src/omega_blackwell_codegen_fp8head.h src/omega_gpu_fp8_api.h src/omega_blackwell_codegen_moe.h $(OUT_DIR)/libomega_gpu.a + $(CC) $(CFLAGS) -ffp-contract=off -Itests -o $@ tests/gpu_fp8_head_test.c $(OUT_DIR)/libomega_gpu.a -lpthread -lm +test-gpu-fp8-head: $(GPU_FP8_HEAD_TEST) + ./$(GPU_FP8_HEAD_TEST) --host-only + ./$(GPU_FP8_HEAD_TEST) --sim + # omega #457 (2026-10-15): host rewrite of a GPU-cached buffer must be visible to the next launch. Chip only; the gate # is tools/run_gpu_l2_stale_chip.sh. GPU_L2_STALE_TEST = $(OUT_DIR)/gpu_l2_stale_test diff --git a/mk/omega-gpu-engine.mk b/mk/omega-gpu-engine.mk index 30f99522..7b69b74c 100644 --- a/mk/omega-gpu-engine.mk +++ b/mk/omega-gpu-engine.mk @@ -229,7 +229,8 @@ GPU_NATIVE_RUNTIME_SRCS = src/omega_gpu_cmdlist.c src/omega_gpu_fp8_api.c \ src/omega_blackwell_codegen_gemm.c src/omega_gpu_fp8_pack.c src/omega_gpu_mem_cached.c \ src/omega_gpu_hostmath.c src/omega_native_artifact.c src/omega_cubin.c $(CUDAPP_HOST_BINDING) \ src/omega_gpu_q36_graph.c src/omega_gpu_decode_graph.c src/omega_gpu_router_api.c \ - src/omega_gpu_gemm_ex.c src/omega_gpu_gemm.c src/omega_blackwell_codegen_qmma.c + src/omega_gpu_gemm_ex.c src/omega_gpu_gemm.c src/omega_blackwell_codegen_qmma.c \ + src/omega_gpu_fp8_head_api.c src/omega_blackwell_codegen_fp8head.c .PHONY: test-gpu-native-runtime build/test_omega_gpu_native_runtime: tests/test_omega_gpu_session_platform.c tests/native_runtime_controls.h \ $(GPU_FS_LINK) $(GPU_NATIVE_RUNTIME_SRCS) src/omega_gpu_native_runtime.h src/omega_gpu_q36_native.h \ diff --git a/src/omega_blackwell_codegen_fp8head.c b/src/omega_blackwell_codegen_fp8head.c new file mode 100644 index 00000000..29dde0b8 --- /dev/null +++ b/src/omega_blackwell_codegen_fp8head.c @@ -0,0 +1,250 @@ +/* SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception */ +/* omega_blackwell_codegen_fp8head.c: FP8 lm_head GEMV over up to 8 x rows per launch (aien-dev/CUDApp#217). + * See the header for the contract and the argument words. + * + * Scheduling and emitter helpers are omega_blackwell_codegen_moe.c's (copied, static): every instruction waits on + * everything still pending; variable-latency results go through scoreboard 0, loads set the read barrier 1, uniform + * loads scoreboard 2; fixed-latency producers stall 6; ISETP stalls 14 before a predicated branch. A K step issues its + * weight, scale and x row 0 loads back to back (one round trip), decodes the weights once, then runs x row 0's FFMA + * chains; every further x row is one more batch of 4 LDG.128 followed by its FFMA chains. One K step per loop + * iteration: at rows 2, xb 8 a step is ~460 instructions, inside BW_MAX_IR_INSNS (1024) with the reduction tail. + */ +#include "omega_blackwell_codegen_fp8head.h" +#include "omega_blackwell_codegen_moe.h" +#include <string.h> + +#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 +#define SB_RD 1u +#define SB_UGPR 2u +#define NOREG (-1) +#define MAX_LOOPS 4 + +enum { K_FIXED, K_PRED, K_VAR, K_VAR_MORE, K_UVAR, K_STORE, K_EXIT, K_BRA, K_BSSY, K_BSYNC }; + +typedef struct { + BlackwellIRProgram *p; + uint32_t pending; + int err; + int open_start[MAX_LOOPS]; + int depth; +} 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(14, SB_NONE, SB_NONE, wait); e->pending = 0; break; + /* loads read their address operands late (SB_RD): the next load of a batch waits on the read barrier (moe.c) */ + case K_VAR: in.control = CW(4, SB_GPR, SB_RD, wait) | CW_YIELD; e->pending = (1u << SB_GPR) | (1u << SB_RD); break; + case K_VAR_MORE: in.control = CW(4, SB_GPR, SB_RD, (e->pending & (1u << SB_RD))) | CW_YIELD; e->pending |= (1u << SB_GPR) | (1u << SB_RD); 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_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; + case K_BSSY: in.control = CW(1, SB_NONE, SB_NONE, wait) | CW_YIELD; e->pending = 0; break; + case K_BSYNC: in.control = CW(5, SB_NONE, SB_NONE, wait) | CW_YIELD; e->pending = 0; break; + default: e->err = -1; return; + } + if (omega_bw_ir_append(e->p, &in) < 0) e->err = -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 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 V128(Em *e) { int v = omega_bw_ir_alloc_vreg128(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; } + +static void ldcu64(Em *e, int ud, uint32_t off) { BlackwellIRInsn i = I0(BW_IR_LDCU64); i.dst_vreg = ud; i.imm = off; i.is_uniform = true; emit(e, i, K_UVAR); } +static void ldc64(Em *e, int d, uint32_t off) { BlackwellIRInsn i = I0(BW_IR_LDC64); i.dst_vreg = d; i.imm = off; emit(e, i, K_VAR); } +static void ldc32(Em *e, int d, uint32_t off) { BlackwellIRInsn i = I0(BW_IR_LDC); i.dst_vreg = d; i.imm = off; emit(e, i, K_VAR); } +static void s2r(Em *e, int d, uint32_t sr) { BlackwellIRInsn i = I0(BW_IR_S2R); i.dst_vreg = d; i.imm = sr; emit(e, i, K_VAR); } +static void movi(Em *e, int d, uint32_t imm) { BlackwellIRInsn i = I0(BW_IR_MOV_IMM); i.dst_vreg = d; i.imm = imm; emit(e, i, K_FIXED); } +static void movrz(Em *e, int d) { BlackwellIRInsn i = I0(BW_IR_MOV_RZ); i.dst_vreg = d; emit(e, i, K_FIXED); } +/* d = a * imm + c (c NOREG = RZ); a may be a sub-register of a quad */ +static void imadi(Em *e, int d, int a, unsigned asub, uint32_t imm, int c) { BlackwellIRInsn i = I0(BW_IR_IMAD); i.dst_vreg = d; i.src1_vreg = a; i.src1_subreg = (uint8_t)asub; i.imm = imm; i.src3_vreg = c; emit(e, i, K_FIXED); } +/* d64 = a * imm + c64 (IMAD.WIDE.U32) */ +static void imadw(Em *e, int d64, int a, uint32_t imm, int c64) { BlackwellIRInsn i = I0(BW_IR_IMAD_WIDE); i.dst_vreg = d64; i.src1_vreg = a; i.imm = imm; i.src3_vreg = c64; emit(e, i, K_FIXED); } +static void shr(Em *e, int d, int a, unsigned asub, uint32_t imm) { BlackwellIRInsn i = I0(BW_IR_SHF_R); i.dst_vreg = d; i.src1_vreg = a; i.src1_subreg = (uint8_t)asub; i.imm = imm; emit(e, i, K_FIXED); } +static void andi(Em *e, int d, int a, unsigned asub, uint32_t imm) { BlackwellIRInsn i = I0(BW_IR_LOP3_AND); i.dst_vreg = d; i.src1_vreg = a; i.src1_subreg = (uint8_t)asub; i.imm = imm; emit(e, i, K_FIXED); } +static void xorr(Em *e, int d, int a, int b) { BlackwellIRInsn i = I0(BW_IR_LOP3_XOR); i.dst_vreg = d; i.src1_vreg = a; i.src2_vreg = b; emit(e, i, K_FIXED); } +static void ldg128(Em *e, int d, int addr64, uint32_t imm, int udesc, int first) { + BlackwellIRInsn i = I0(BW_IR_LDG_E_128); i.dst_vreg = d; i.src1_vreg = addr64; i.imm = imm; i.ureg = udesc; emit(e, i, first ? K_VAR : K_VAR_MORE); +} +static void ldg32(Em *e, int d, int addr64, int udesc, int first) { BlackwellIRInsn i = I0(BW_IR_LDG_E); i.dst_vreg = d; i.src1_vreg = addr64; i.ureg = udesc; emit(e, i, first ? K_VAR : K_VAR_MORE); } +static void stg(Em *e, int addr64, uint32_t imm, int val, int udesc) { BlackwellIRInsn i = I0(BW_IR_STG_E); i.src1_vreg = addr64; i.src2_vreg = val; i.imm = imm; 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); } +/* d = a * b[bsub] + c */ +static void ffma(Em *e, int d, int a, int b, unsigned bsub, int c) { BlackwellIRInsn i = I0(BW_IR_FFMA); i.dst_vreg = d; i.src1_vreg = a; i.src2_vreg = b; i.src2_subreg = (uint8_t)bsub; i.src3_vreg = c; emit(e, i, K_FIXED); } +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 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 bra_if_p0(Em *e, int target) { BlackwellIRInsn i = I0(BW_IR_BRA); i.predicate_p0 = true; i.imm = (uint32_t)(target - here(e)); emit(e, i, K_BRA); } +static void bra(Em *e, int target) { BlackwellIRInsn i = I0(BW_IR_BRA); i.imm = (uint32_t)(target - here(e)); emit(e, i, K_BRA); } +static int bra_if_p0_fwd(Em *e) { int at = here(e); BlackwellIRInsn i = I0(BW_IR_BRA); i.predicate_p0 = true; i.imm = 1; emit(e, i, K_BRA); return at; } +static void patch_bra(Em *e, int at, int target) { if (!e->err) e->p->insns[at].imm = (uint32_t)(target - at); } +static int bssy_fwd(Em *e) { int at = here(e); BlackwellIRInsn i = I0(BW_IR_BSSY); i.bar_reg = 0; i.imm = 2; emit(e, i, K_BSSY); return at; } +static void bsync(Em *e) { BlackwellIRInsn i = I0(BW_IR_BSYNC); i.bar_reg = 0; emit(e, i, K_BSYNC); } +static void tail(Em *e) { + emit(e, I0(BW_IR_EXIT), K_EXIT); + BlackwellIRInsn self = I0(BW_IR_BRA); + self.control = 0x000fc000u; + if (omega_bw_ir_append(e->p, &self) < 0) e->err = -1; +} +/* a value defined before the loop and read inside it stays live until the back-branch (moe.c) */ +static void loop_begin(Em *e) { if (e->depth >= MAX_LOOPS) { e->err = -1; return; } e->open_start[e->depth++] = here(e); } +static void loop_end(Em *e) { + if (e->depth <= 0) { e->err = -1; return; } + int start = e->open_start[--e->depth], end = here(e) - 1; + 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; + } +} +static int log2u(uint32_t v) { int l = 0; while ((1u << l) < v) l++; return (1u << l) == v ? l : -1; } + +/* e4m3 byte i of word `word` -> f32 bits (value * 2^-120): ((b & 0x7F) << 20) | ((b & 0x80) << 24); moe.c decode_byte */ +static void decode_byte(Em *e, int f, int wq, unsigned word, unsigned i, int u, int a, int s) { + const uint32_t M = 0x07F00000u; + if (i < 3) imadi(e, u, wq, word, 1u << (20u - 8u * i), NOREG); + else shr(e, u, wq, word, 4); + andi(e, a, u, 0, M); + andi(e, s, wq, word, 0x80u << (8u * i)); + if (i < 3) imadi(e, f, s, 0, 1u << (24u - 8u * i), a); + else imadi(e, f, s, 0, 1u, a); +} + +int omega_fp8head_spec_ok(const OmegaFp8HeadSpec *s) { + if (!s) return 0; + const uint32_t step = 32u * OMEGA_FP8HEAD_LANE_BYTES; + if (s->k == 0 || s->k > OMEGA_FP8_MAX_K || s->k % step) return 0; + if (s->rows != 1 && s->rows != 2) return 0; + if (s->warps < 1 || s->warps > 32) return 0; + if (s->xb < 1 || s->xb > OMEGA_FP8HEAD_MAX_XB) return 0; + if (s->mutant < 0 || s->mutant > 3) return 0; + /* immediate offsets of a step's loads inside the 24-bit signed LDG field: x row b at b k 4 + 48, weight row r at r k */ + if ((uint64_t)(s->xb - 1u) * s->k * 4u + 48u >= (1u << 23)) return 0; + if ((uint64_t)(s->rows - 1u) * s->k + OMEGA_FP8HEAD_LANE_BYTES >= (1u << 23)) return 0; + return 1; +} + +int omega_blackwell_codegen_fp8head_prog(const OmegaFp8HeadSpec *spec, BlackwellIRProgram *prog) { + if (!omega_fp8head_spec_ok(spec) || !prog) return -1; + const uint32_t LB = OMEGA_FP8HEAD_LANE_BYTES, K = spec->k, R = spec->rows, W = spec->warps, XB = spec->xb; + const uint32_t KS = K / (32u * LB), KB = K / OMEGA_FP8_BLOCK; + const uint32_t STEP_SCALE = (32u * LB / OMEGA_FP8_BLOCK) * 4u; /* scale bytes per K step (4 blocks) */ + const int log2lpb = log2u(OMEGA_FP8_BLOCK / LB), log2rpb = log2u(OMEGA_FP8_BLOCK / R); + if (log2lpb < 0 || log2rpb < 0) return -1; + omega_bw_ir_init(prog); + Em em; memset(&em, 0, sizeof em); em.p = prog; + Em *e = &em; + + /* ---- prologue ---- */ + int udesc = UV64(e), wbase = V64(e), sbase = V64(e), px = V64(e), py = V64(e); + int rgn = V(e), ys = V(e), stride = V(e); + int tid = V(e), cx = V(e), warp = V(e), lane = V(e), one = V(e); + int xlane = V64(e), wlane = V(e), slane = V(e), rg = V(e); + int pw = V64(e), ps = V64(e), pxc = V64(e), pyr = V64(e), pyb = V64(e), pya = V64(e), srg = V(e), cnt = V(e); + int wq[2], fd[2][16], xq[4], acc[2][OMEGA_FP8HEAD_MAX_XB]; + for (uint32_t r = 0; r < R; r++) { wq[r] = V128(e); for (uint32_t j = 0; j < 16; j++) fd[r][j] = V(e); for (uint32_t b = 0; b < XB; b++) acc[r][b] = V(e); } + for (uint32_t q = 0; q < 4; q++) xq[q] = V128(e); + int sc = V(e), dot = V(e), u = V(e), a = V(e), sg = V(e), t = V(e); + if (e->err) return -1; + ldcu64(e, udesc, 0x358); + ldc64(e, wbase, OMEGA_FP8HEAD_ARG_W); ldc64(e, sbase, OMEGA_FP8HEAD_ARG_S); + ldc64(e, px, OMEGA_FP8HEAD_ARG_X); ldc64(e, py, OMEGA_FP8HEAD_ARG_Y); + ldc32(e, rgn, OMEGA_FP8HEAD_ARG_RG); ldc32(e, ys, OMEGA_FP8HEAD_ARG_YSTRIDE); ldc32(e, stride, OMEGA_FP8HEAD_ARG_STRIDE); + s2r(e, tid, BW_SR_TID_X); s2r(e, cx, BW_SR_CTAID_X); + movi(e, one, 1); + shr(e, warp, tid, 0, 5); + andi(e, lane, tid, 0, 31); + imadw(e, xlane, lane, LB * 4u, px); /* this lane's x' chunk of step 0, x row 0 */ + imadi(e, wlane, lane, 0, LB, NOREG); /* byte offset of this lane's chunk in a row */ + shr(e, slane, lane, 0, (uint32_t)log2lpb); imadi(e, slane, slane, 0, 4, NOREG); /* scale word of this lane in a step */ + imadi(e, rg, cx, 0, W, warp); /* first row group of this warp */ + + /* ---- row-group loop ---- */ + const int L_rg = here(e); + loop_begin(e); + isetp_ge_u32(e, rg, rgn); + const int bra_end = bra_if_p0_fwd(e); + imadw(e, pw, rg, R * K, wbase); imadw(e, pw, wlane, 1, pw); + shr(e, srg, rg, 0, (uint32_t)log2rpb); + if (spec->mutant == 2) xorr(e, srg, srg, one); /* mutant 2: the neighbouring 128-row scale block */ + imadw(e, ps, srg, KB * 4u, sbase); imadw(e, ps, slane, 1, ps); + imadw(e, pxc, one, 0, xlane); + for (uint32_t r = 0; r < R; r++) for (uint32_t b = 0; b < XB; b++) movrz(e, acc[r][b]); + movi(e, cnt, KS); + + /* ---- K loop: one 512-column step per iteration ---- */ + const int L_k = here(e); + loop_begin(e); + for (uint32_t b = 0; b < XB; b++) { + const uint32_t xoff = spec->mutant == 3 ? 0u : b * K * 4u; /* mutant 3: every x row reads row 0 */ + int first = 1; + if (b == 0) { + for (uint32_t r = 0; r < R; r++) { ldg128(e, wq[r], pw, r * K, udesc, first); first = 0; } + ldg32(e, sc, ps, udesc, 0); + } + for (uint32_t q = 0; q < 4; q++) { ldg128(e, xq[q], pxc, xoff + q * 16u, udesc, first); first = 0; } + if (b == 0) + for (uint32_t r = 0; r < R; r++) + for (uint32_t word = 0; word < 4; word++) + for (unsigned i = 0; i < 4; i++) decode_byte(e, fd[r][word * 4u + i], wq[r], word, i, u, a, sg); + for (uint32_t r = 0; r < R; r++) { + movrz(e, dot); + for (uint32_t word = 0; word < 4; word++) + for (unsigned i = 0; i < 4; i++) ffma(e, dot, fd[r][word * 4u + i], xq[word], i, dot); + ffma(e, acc[r][b], dot, sc, 0, acc[r][b]); + } + } + imadw(e, pw, one, 32u * LB, pw); + imadw(e, pxc, one, 32u * LB * 4u, pxc); + imadw(e, ps, one, spec->mutant == 1 ? 0u : STEP_SCALE, ps); /* mutant 1: every step reads the step-0 k-blocks */ + imadi(e, cnt, one, 0, 0xffffffffu, cnt); + isetp_ge_u32(e, cnt, one); + bra_if_p0(e, L_k); + loop_end(e); + + /* ---- warp reduction per (row, x row), lane 0 stores ---- */ + for (uint32_t r = 0; r < R; r++) + for (uint32_t b = 0; b < XB; b++) + for (uint32_t o = 16; o >= 1; o /= 2) { shfl_down(e, t, acc[r][b], o); fadd(e, acc[r][b], acc[r][b], t); } + imadw(e, pyr, rg, R * 4u, py); + isetp_ge_u32(e, lane, one); + const int at_bssy = bssy_fwd(e); + const int bra_skip = bra_if_p0_fwd(e); + for (uint32_t b = 0; b < XB; b++) { + if (b == 0) imadw(e, pyb, one, 0, pyr); else imadw(e, pyb, ys, 1, pyb); + for (uint32_t r = 0; r < R; r++) { imadw(e, pya, one, r * 4u, pyb); stg(e, pya, 0, acc[r][b], udesc); } /* STG.E imm 0 only */ + } + const int at_bsync = here(e); + bsync(e); + patch_bra(e, bra_skip, at_bsync); + patch_bra(e, at_bssy, at_bsync + 1); + imadi(e, rg, stride, 0, 1, rg); + bra(e, L_rg); + loop_end(e); + patch_bra(e, bra_end, here(e)); + tail(e); + if (e->err) return -1; + return omega_bw_regalloc_solve(prog) != 0 ? -1 : 0; +} + +int omega_fp8head_prog_stats(const OmegaFp8HeadSpec *spec, uint32_t *insns, uint32_t *gprs) { + static BlackwellIRProgram prog; /* 1024 insns: too big for a stack frame in a test loop (moe.c) */ + if (insns) *insns = 0; + if (gprs) *gprs = 0; + if (omega_blackwell_codegen_fp8head_prog(spec, &prog) != 0) return -1; + if (insns) *insns = (uint32_t)prog.count; + if (gprs) *gprs = prog.regalloc.peak_gpr_usage; + return 0; +} diff --git a/src/omega_blackwell_codegen_fp8head.h b/src/omega_blackwell_codegen_fp8head.h new file mode 100644 index 00000000..845712aa --- /dev/null +++ b/src/omega_blackwell_codegen_fp8head.h @@ -0,0 +1,78 @@ +/* SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception */ +#ifndef OMEGA_BLACKWELL_CODEGEN_FP8HEAD_H +#define OMEGA_BLACKWELL_CODEGEN_FP8HEAD_H +/* + * omega_blackwell_codegen_fp8head: the FP8 (e4m3, 128 x 128 block-scaled) lm_head GEMV for up to + * OMEGA_FP8HEAD_MAX_XB x rows in one launch (aien-dev/CUDApp#217, P-DRA-4 DRA-69). Each weight row is read once + * per launch and dotted with every x row, so a batched decode stroke of N <= 8 conversations reads the + * 0.509 GB FP8 head once instead of N times. + * + * y[b][r] = sum_c W[r][c] * x[b][c] * S[r / 128][c / 128], b < xb, r < n + * + * Arithmetic (bit-exact contract): per x row b and weight row r, this kernel performs the same f32 operations in + * the same order as the single-x FP8 GEMV at lane_bytes 16 (omega_blackwell_codegen_moe.c, any rows / warps / depth / + * sched / coal, which all share one arithmetic): lane L of the row's warp takes bytes [16 L, 16 L + 16) of each + * 512-byte K step s; dot = 0; dot = fma(decode(w byte j), x'[512 s + 16 L + j], dot) for j = 0..15 (word-major); + * acc = fma(dot, S'[block], acc); after the last step a SHFL.DOWN 16, 8, 4, 2, 1 FADD tree, lane 0 stores. So + * y[b][r] is bit-identical to the single-x kernel's y[r] for x row b (tests/gpu_fp8_head_test.c proves it on the + * warp simulator). The numeric scheme (decode = e4m3 * 2^-120, x' = x * 2^64, S' = S * 2^56) is moe.h's. + * + * Thread mapping: warp w of CTA cx handles row groups rg = cx * warps + w, rg + stride, ... < RG = n / rows; a row + * group is `rows` consecutive weight rows (rows divides 128, so a group never crosses a scale block). Per K step + * the warp loads its rows' 16-byte chunks and the scale word once, decodes them once (16 f32 per row per lane), + * then for each x row b loads that row's 64 bytes of x' (4 LDG.128 through L1: x must be GPU-cached memory to be + * cheap, see omega_gpu_fp8_head_api.h) and runs the FFMA chain of every row. x is not staged in shared memory: + * 8 rows x 2048 f32 = 64 KiB exceed OMEGA_BW_QMD_MAX_SHARED_BYTES (32 KiB). + * + * Constant bank 0 argument words (cbank + 0x380; the layout is this kernel's own, not OMEGA_FP8_ARG_*): + * 0x380 w u64 e4m3 weights [n][k] (omega_gpu_fp8_tensor_entry) + * 0x388 s u64 f32 scales * 2^56 [n / 128][k / 128] + * 0x390 x u64 x' rows: row b at x + b * k * 4 (f32, already * 2^64; contiguous rows) + * 0x398 y u64 y rows: row b at y + b * y_stride + * 0x3a0 RG u32 row groups (n / rows) + * 0x3a4 y_stride u32 bytes between y rows + * 0x3a8 stride u32 row groups per warp iteration (grid_x * warps) + * Grid: grid_x CTAs, grid_y = 1, threads_x = 32 * warps, no shared memory. The kernel does not depend on n, RG, + * y_stride or the grid: one kernel per (k, rows, warps, xb, mutant). + * + * mutant (tests only, never production): 1 never advances the scale pointer (every K step uses the step-0 k-block: + * the wrong-scale-block negative control, wrong whenever k >= 256), 2 reads the neighbouring 128-row scale block + * (row block ^ 1), 3 makes every x row read x row 0 (wrong whenever xb >= 2 and the rows differ). + */ +#include <stdint.h> +#include "omega_blackwell_codegen.h" + +#ifdef __cplusplus +extern "C" { +#endif + +#define OMEGA_FP8HEAD_MAX_XB 8u +#define OMEGA_FP8HEAD_LANE_BYTES 16u /* the single-x kernel's lane width whose arithmetic this kernel reproduces */ +#define OMEGA_FP8HEAD_ARG_W 0x380u +#define OMEGA_FP8HEAD_ARG_S 0x388u +#define OMEGA_FP8HEAD_ARG_X 0x390u +#define OMEGA_FP8HEAD_ARG_Y 0x398u +#define OMEGA_FP8HEAD_ARG_RG 0x3a0u +#define OMEGA_FP8HEAD_ARG_YSTRIDE 0x3a4u +#define OMEGA_FP8HEAD_ARG_STRIDE 0x3a8u +#define OMEGA_FP8HEAD_ARGS_WORDS 11u + +typedef struct { + uint32_t k; /* input columns: a multiple of 512 (32 lanes x 16 bytes), <= OMEGA_FP8_MAX_K */ + uint32_t rows; /* consecutive weight rows per warp: 1 or 2 */ + uint32_t warps; /* warps per CTA, 1..32 */ + uint32_t xb; /* x rows per launch, 1..OMEGA_FP8HEAD_MAX_XB */ + int mutant; /* 0; tests only: 1..3 (see above) */ +} OmegaFp8HeadSpec; + +/* 1 when the generator accepts the spec (shape rules above, immediate offsets inside the 24-bit LDG field). */ +int omega_fp8head_spec_ok(const OmegaFp8HeadSpec *spec); +/* Builds the register-allocated IR program into *prog. 0 ok, -1 refused or over BW_MAX_IR_INSNS / the registers. */ +int omega_blackwell_codegen_fp8head_prog(const OmegaFp8HeadSpec *spec, BlackwellIRProgram *prog); +/* Instruction and peak-register counts (host, no device). 0 ok, -1 refused. */ +int omega_fp8head_prog_stats(const OmegaFp8HeadSpec *spec, uint32_t *insns, uint32_t *gprs); + +#ifdef __cplusplus +} +#endif +#endif diff --git a/src/omega_gpu_fp8_head_api.c b/src/omega_gpu_fp8_head_api.c new file mode 100644 index 00000000..060dc470 --- /dev/null +++ b/src/omega_gpu_fp8_head_api.c @@ -0,0 +1,236 @@ +/* SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception */ +/* omega_gpu_fp8_head_api.c: FP8 lm_head, all x rows in one launch (aien-dev/CUDApp#217). See the header. + * Kernel cache, pinning, register-file check and submission follow omega_gpu_bf16_gemv_api.c. */ +#include "omega_gpu_fp8_head_api.h" +#include "omega_gpu_session.h" +#include "omega_gpu_fmt.h" +#include "omega_gpu_cmdlist.h" +#include <stdlib.h> +#include <string.h> + +#define CACHE_SLOTS 8 +#define MARKER_TIMEOUT_MS 20000ull +#define POISON_F32 (-999.0f) +#define DEFAULT_ROWS 2u +#define DEFAULT_WARPS 8u +#define REG_FILE 65536u +#define SM_THREADS 1536u /* CC 12.x resident threads per SM (OMEGA_GPU_SM_COUNT comment, omega_gpu_fp8_api.h) */ + +typedef struct { + bool valid, pinned; + OmegaFp8HeadSpec spec; + OmegaBlackwellKernel kernel; + OmegaGpuMem code; +} Slot; + +static struct { + OmegaGpuScratch x_buf, y_buf; + uint32_t rows, warps, ctas; /* overrides, 0 = automatic */ + int env_read; + int mutant; + bool hooked; + Slot cache[CACHE_SLOTS]; + unsigned next; +} g; +static int g_rec; /* 1 while a record call runs (lock held): kernel_for must not evict */ + +static void cache_clear_locked(void) { + for (unsigned i = 0; i < CACHE_SLOTS; i++) { + if (!g.cache[i].valid) continue; + omega_gpu_session_free(&g.cache[i].code); + memset(&g.cache[i], 0, sizeof g.cache[i]); + } + g.next = 0; +} +static void on_session_close(void) { + cache_clear_locked(); + omega_gpu_session_scratch_free(&g.x_buf); + omega_gpu_session_scratch_free(&g.y_buf); +} +static OmegaGpuSession *dev_open_locked(void) { + if (!g.hooked) { (void)omega_gpu_session_on_close(on_session_close); g.hooked = true; } + return omega_gpu_session_open(); +} +void omega_gpu_fp8_head_cache_clear(void) { omega_gpu_session_lock(); cache_clear_locked(); omega_gpu_session_unlock(); } +void omega_gpu_fp8_head_set_shape(uint32_t rows, uint32_t warps, uint32_t ctas) { + omega_gpu_session_lock(); g.env_read = 1; g.rows = rows; g.warps = warps; g.ctas = ctas; cache_clear_locked(); omega_gpu_session_unlock(); +} +void omega_gpu_fp8_head_test_set_mutant(int m) { omega_gpu_session_lock(); g.mutant = m; cache_clear_locked(); omega_gpu_session_unlock(); } +int omega_gpu_fp8_head_test_mutant(void) { return g.mutant; } + +/* AIEN_OMEGA_FP8_HEAD_SHAPE=rows:warps:ctas, read once (chip A/B knob; malformed = ignored) */ +static void env_shape(void) { + if (g.env_read) return; + g.env_read = 1; + const char *v = getenv("AIEN_OMEGA_FP8_HEAD_SHAPE"); + if (!v) return; + uint32_t f[3] = { 0, 0, 0 }; unsigned i = 0; + for (const char *p = v; ; p++) { + if (*p >= '0' && *p <= '9') { f[i] = f[i] * 10u + (uint32_t)(*p - '0'); if (f[i] > 100000u) return; } + else if (*p == ':' && i < 2) i++; + else if (*p == 0) break; + else return; + } + if (i != 2) return; + g.rows = f[0]; g.warps = f[1]; g.ctas = f[2]; +} + +static uint32_t gpr_declared(uint32_t peak) { return omega_bw_gpr_declared(peak); } +static bool register_file_fits(uint32_t warps, uint32_t peak) { + uint32_t decl = gpr_declared(peak); + if ((uint64_t)32u * warps * decl <= REG_FILE) return true; + char e[160]; omega_gpu_fmt(e, sizeof e, "fp8 head kernel: %u warps x %u declared registers exceed the 65536-register file", warps, decl); + omega_gpu_session_set_error(e); + return false; +} + +void omega_gpu_fp8_head_spec_for(uint32_t k, uint32_t n, uint32_t xb, OmegaFp8HeadSpec *spec, uint32_t *grid_x) { + env_shape(); + memset(spec, 0, sizeof *spec); + spec->k = k; spec->xb = xb; spec->mutant = g.mutant; + spec->rows = g.rows ? g.rows : (xb <= 1u ? 1u : DEFAULT_ROWS); + spec->warps = g.warps ? g.warps : DEFAULT_WARPS; + if (!grid_x) return; + uint32_t ctas = g.ctas; + if (!ctas) { /* every SM full: CTAs per SM limited by the register file and the resident-thread count */ + uint32_t insns = 0, peak = 0, per_sm = 1; + if (omega_fp8head_prog_stats(spec, &insns, &peak) == 0) { + const uint32_t by_regs = REG_FILE / (32u * spec->warps * gpr_declared(peak)), by_threads = SM_THREADS / (32u * spec->warps); + per_sm = by_regs < by_threads ? by_regs : by_threads; + if (per_sm == 0) per_sm = 1; + } + ctas = OMEGA_GPU_SM_COUNT * per_sm; + } + const uint32_t RG = spec->rows ? n / spec->rows : 0; + uint32_t gx = (RG + spec->warps - 1u) / spec->warps; + if (gx > ctas) gx = ctas; + *grid_x = gx ? gx : 1u; +} + +static int kernel_for(const OmegaFp8HeadSpec *spec, Slot **out, bool *hit) { + for (unsigned i = 0; i < CACHE_SLOTS; i++) { + Slot *s = &g.cache[i]; + if (s->valid && memcmp(&s->spec, spec, sizeof *spec) == 0) { *out = s; *hit = true; return OMEGA_GPU_FP8_OK; } + } + Slot *s = NULL; + for (unsigned i = 0; i < CACHE_SLOTS && !s; i++) { + Slot *c = &g.cache[(g.next + i) % CACHE_SLOTS]; + if (!c->valid || !c->pinned) { s = c; g.next = (unsigned)((c - g.cache) + 1) % CACHE_SLOTS; } + } + if (!s) { omega_gpu_session_set_error("fp8 head kernel cache: every slot holds a prepared kernel"); return OMEGA_GPU_FP8_TOO_LARGE; } + if (g_rec && s->valid) { omega_gpu_session_set_error("fp8 head record: kernel cache miss would evict a resident kernel (omega_gpu_fp8_head_prepare before recording)"); return OMEGA_GPU_FP8_TOO_LARGE; } + BlackwellIRProgram *prog = omega_gpu_host_calloc(1, sizeof *prog); + if (!prog) { omega_gpu_session_set_error("fp8 head codegen: host memory"); return OMEGA_GPU_FP8_CODEGEN_FAIL; } + int cg = omega_blackwell_codegen_fp8head_prog(spec, prog); + size_t need = cg == 0 ? omega_bw_program_code_bytes(prog) : 0; + if (cg != 0 || need == 0) { omega_gpu_host_free(prog); omega_gpu_session_set_error("fp8 head codegen refused the shape"); return OMEGA_GPU_FP8_CODEGEN_FAIL; } + if (!register_file_fits(spec->warps, prog->regalloc.peak_gpr_usage)) { omega_gpu_host_free(prog); return OMEGA_GPU_FP8_TOO_LARGE; } + OmegaGpuMem code; + if (omega_gpu_session_alloc_code(need, &code) != 0) { omega_gpu_host_free(prog); return OMEGA_GPU_FP8_CHIP_FAIL; } + OmegaBlackwellKernel kernel; + cg = omega_blackwell_kernel_encode_into(prog, code.cpu, need, &kernel); + omega_gpu_host_free(prog); + if (cg != 0 || !kernel.code || kernel.code_size != need) { omega_gpu_session_free(&code); return OMEGA_GPU_FP8_CODEGEN_FAIL; } + if (omega_gpu_session_sync_to_gpu(&code) != 0) { omega_gpu_session_free(&code); return OMEGA_GPU_FP8_CHIP_FAIL; } + if (s->valid) omega_gpu_session_free(&s->code); + memset(s, 0, sizeof *s); + s->valid = true; s->spec = *spec; s->kernel = kernel; s->code = code; + *out = s; *hit = false; + return OMEGA_GPU_FP8_OK; +} + +int omega_gpu_fp8_head_prepare(uint32_t k, uint32_t xb) { + OmegaFp8HeadSpec spec; + omega_gpu_session_lock(); + omega_gpu_fp8_head_spec_for(k, 0, xb, &spec, NULL); + int rc = OMEGA_GPU_FP8_OK; + if (!omega_fp8head_spec_ok(&spec)) { omega_gpu_session_set_error("fp8 head: shape refused (k multiple of 512, xb 1..8)"); rc = OMEGA_GPU_FP8_CODEGEN_FAIL; } + else if (!dev_open_locked()) rc = OMEGA_GPU_FP8_CHIP_FAIL; + else { Slot *s = NULL; bool hit = false; rc = kernel_for(&spec, &s, &hit); if (rc == OMEGA_GPU_FP8_OK) s->pinned = true; } + omega_gpu_session_unlock(); + return rc; +} + +/* rec non-NULL: record path (caller holds the lock), x and y are device addresses; else the scratch test path. */ +static int head_core(const OmegaGpuFp8Tensor *t, uint32_t xb, const float *x, float *y, OmegaGpuFp8HeadInfo *info, + OmegaGpuCmdList *rec, uint64_t dev_x, uint64_t dev_y, uint32_t y_stride) { + uint64_t t0 = omega_gpu_session_now_ns(); + if (info) memset(info, 0, sizeof *info); + uint32_t experts = 0, n = 0, k = 0; + omega_gpu_fp8_tensor_shape(t, &experts, &n, &k); + if (!t || experts != 1u || n == 0 || xb == 0 || xb > OMEGA_FP8HEAD_MAX_XB) return OMEGA_GPU_FP8_BAD_ARGS; + if (rec ? (!dev_x || !dev_y || (xb > 1u && y_stride < n) || (uint64_t)y_stride * 4u > 0xffffffffull) : (!x || !y)) return OMEGA_GPU_FP8_BAD_ARGS; + if (!rec) y_stride = n; + if (!rec) omega_gpu_session_lock(); +#define UNLOCK() do { if (!rec) omega_gpu_session_unlock(); } while (0) + OmegaFp8HeadSpec spec; uint32_t grid_x = 1; + omega_gpu_fp8_head_spec_for(k, n, xb, &spec, &grid_x); + if (!omega_fp8head_spec_ok(&spec) || n % spec.rows) { UNLOCK(); omega_gpu_session_set_error("fp8 head: shape refused"); return OMEGA_GPU_FP8_CODEGEN_FAIL; } + const uint32_t RG = n / spec.rows; + uint64_t w_va = 0, s_va = 0; + if (omega_gpu_fp8_tensor_entry(t, 0, &w_va, &s_va) != OMEGA_GPU_FP8_OK) { UNLOCK(); return OMEGA_GPU_FP8_BAD_ARGS; } + int rc = OMEGA_GPU_FP8_OK; + if (!dev_open_locked()) { UNLOCK(); return OMEGA_GPU_FP8_CHIP_FAIL; } + if (!rec) { + int src = omega_gpu_session_scratch(&g.x_buf, (size_t)xb * k * 4u); + if (src == 0) src = omega_gpu_session_scratch(&g.y_buf, (size_t)xb * n * 4u); + if (src != 0) { UNLOCK(); return src == OMEGA_GPU_SESSION_SCRATCH_RESERVED ? OMEGA_GPU_FP8_TOO_LARGE : OMEGA_GPU_FP8_CHIP_FAIL; } + } + Slot *ks = NULL; bool hit = false; + g_rec = rec != NULL; + rc = kernel_for(&spec, &ks, &hit); + g_rec = 0; + if (rc != OMEGA_GPU_FP8_OK) { UNLOCK(); return rc; } + + float *xd = rec ? NULL : g.x_buf.mem.cpu, *yd = rec ? NULL : g.y_buf.mem.cpu; + if (!rec) { + for (uint32_t b = 0; b < xb; b++) omega_fp8_pack_x_f32(x + (size_t)b * k, k, xd + (size_t)b * k); + for (size_t i = 0; i < (size_t)xb * n; i++) yd[i] = POISON_F32; + if (omega_gpu_session_sync_to_gpu(&g.x_buf.mem) != 0 || omega_gpu_session_sync_to_gpu(&g.y_buf.mem) != 0) rc = OMEGA_GPU_FP8_CHIP_FAIL; + } + const uint64_t x_va = rec ? dev_x : g.x_buf.mem.va, y_va = rec ? dev_y : g.y_buf.mem.va; + uint32_t args[OMEGA_FP8HEAD_ARGS_WORDS]; + args[0] = (uint32_t)w_va; args[1] = (uint32_t)(w_va >> 32); + args[2] = (uint32_t)s_va; args[3] = (uint32_t)(s_va >> 32); + args[4] = (uint32_t)x_va; args[5] = (uint32_t)(x_va >> 32); + args[6] = (uint32_t)y_va; args[7] = (uint32_t)(y_va >> 32); + args[8] = RG; args[9] = y_stride * 4u; args[10] = grid_x * spec.warps; + if (info) { + info->n = n; info->k = k; info->xb = xb; info->rows = spec.rows; info->warps = spec.warps; info->grid_x = grid_x; + info->gpr_declared = gpr_declared(ks->kernel.gpr_count); + info->weight_bytes = (uint64_t)n * k; + info->scale_bytes = (uint64_t)(n / OMEGA_FP8_BLOCK) * (k / OMEGA_FP8_BLOCK) * 4u; + info->kernel_cache_hit = hit; + } + if (rc == OMEGA_GPU_FP8_OK) { + OmegaGpuLaunch L = { + .code_va = ks->code.va, .gpr_count = gpr_declared(ks->kernel.gpr_count), + .threads_x = 32u * spec.warps, .threads_y = 1, .grid_x = grid_x, .grid_y = 1, + .num_elements = (size_t)n * xb, + .args = args, .n_args = OMEGA_FP8HEAD_ARGS_WORDS, .timeout_ms = MARKER_TIMEOUT_MS, + .shared_bytes = 0, + }; + if (!omega_bw_gpr_declared_ok(L.gpr_count, ks->kernel.gpr_count)) { omega_gpu_session_set_error("declared registers below peak + 2: refusing to launch"); rc = OMEGA_GPU_FP8_CHIP_FAIL; } + else if (rec) { if (omega_gpu_cmdlist_add(rec, &L) < 0) rc = OMEGA_GPU_FP8_CHIP_FAIL; } + else if (omega_gpu_session_launch(&L, info ? &info->elapsed_ns : NULL, info ? &info->completion_marker : NULL) != 0) rc = OMEGA_GPU_FP8_CHIP_FAIL; + } + if (rc == OMEGA_GPU_FP8_OK && !rec && omega_gpu_session_sync_to_cpu(&g.y_buf.mem) != 0) rc = OMEGA_GPU_FP8_CHIP_FAIL; + if (rc == OMEGA_GPU_FP8_OK && !rec) { + size_t unchanged = 0; + for (size_t i = 0; i < (size_t)xb * n; i++) if (yd[i] == POISON_F32) unchanged++; + if (unchanged) { omega_gpu_session_set_error("fp8 head: output poison survived"); rc = OMEGA_GPU_FP8_CHIP_FAIL; } + else memcpy(y, yd, (size_t)xb * n * sizeof *y); + } + UNLOCK(); + if (info) info->call_ns = omega_gpu_session_now_ns() - t0; + return rc; +} +#undef UNLOCK + +int omega_gpu_fp8_head_gemv_f32(const OmegaGpuFp8Tensor *t, uint32_t xb, const float *x, float *y, OmegaGpuFp8HeadInfo *info) { + return head_core(t, xb, x, y, info, NULL, 0, 0, 0); +} +int omega_gpu_fp8_head_record(OmegaGpuCmdList *cl, const OmegaGpuFp8Tensor *t, uint32_t xb, uint64_t x_va, uint64_t y_va, uint32_t y_stride) { + if (!cl) return OMEGA_GPU_FP8_BAD_ARGS; + return head_core(t, xb, NULL, NULL, NULL, cl, x_va, y_va, y_stride); +} diff --git a/src/omega_gpu_fp8_head_api.h b/src/omega_gpu_fp8_head_api.h new file mode 100644 index 00000000..49c2504b --- /dev/null +++ b/src/omega_gpu_fp8_head_api.h @@ -0,0 +1,67 @@ +/* SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception */ +#ifndef OMEGA_GPU_FP8_HEAD_API_H +#define OMEGA_GPU_FP8_HEAD_API_H +/* + * omega_gpu_fp8_head_api: the FP8 lm_head over up to OMEGA_FP8HEAD_MAX_XB x rows in ONE launch (aien-dev/CUDApp#217, + * P-DRA-4 DRA-69). Kernel: omega_blackwell_codegen_fp8head.h. Weights are an omega_gpu_fp8_tensor (one expert, n x k + * e4m3 + 128 x 128 scales, the upload / omega_gpu_fp8_quantize_bf16 format); the head is read once per launch however + * many x rows it serves, so a batched decode stroke of N heads streams 0.509 GB instead of N x 0.509 GB. + * + * Bit contract: row b of the output is bit-identical to omega_gpu_fp8_gemv_f32 / the legacy single-x record at + * lane_bytes 16 for x row b (same f32 operations in the same order; tests/gpu_fp8_head_test.c --sim proves it on the + * warp simulator, --chip on the device). + * + * x: xb rows of k f32, ALREADY * 2^OMEGA_FP8_X_EXP (the q36 graph's head x'), contiguous (row b at x_va + b * k * 4). + * Every row is re-read once per weight row group, so x should live in GPU-cached memory (the q36 graph copies its + * hidden rows into the cached xq region first). y: row b at y_va + b * y_stride * 4 (y_stride in floats, >= n when + * xb > 1); only [0, n) of each row is written. + * + * Shape: rows 2, warps 8 (rows 1 for xb 1), grid = 48 SMs x the CTAs that fit one SM's register file and warp slots, + * capped at the row-group count. [INFERENCE: no chip timing yet]. AIEN_OMEGA_FP8_HEAD_SHAPE=rows:warps:ctas (read once, + * each 0 = automatic) overrides it for chip A/B; omega_gpu_fp8_head_set_shape overrides the environment. + * + * Record rules are the other APIs': the caller holds omega_gpu_session_lock(); the kernel must already be resident + * (omega_gpu_fp8_head_prepare, which pins it) or the record is refused (TOO_LARGE) rather than evicting a kernel. + * Return codes: OMEGA_GPU_FP8_* (omega_gpu_fp8_api.h). + */ +#include <stdbool.h> +#include <stdint.h> +#include "omega_blackwell_codegen_fp8head.h" +#include "omega_gpu_fp8_api.h" + +#ifdef __cplusplus +extern "C" { +#endif + +typedef struct { + uint32_t n, k, xb; + uint32_t rows, warps, grid_x, gpr_declared; + uint64_t weight_bytes, scale_bytes; /* bytes of the head one launch reads (independent of xb) */ + uint64_t elapsed_ns, call_ns; + uint32_t completion_marker; + bool kernel_cache_hit; +} OmegaGpuFp8HeadInfo; + +/* Spec and grid the API uses for (k, n, xb) at the current shape settings and test mutant. */ +void omega_gpu_fp8_head_spec_for(uint32_t k, uint32_t n, uint32_t xb, OmegaFp8HeadSpec *spec, uint32_t *grid_x); +/* Build and pin the kernel for (k, xb) (n only sizes the grid, not the kernel). */ +int omega_gpu_fp8_head_prepare(uint32_t k, uint32_t xb); +/* Record one launch into cl (caller holds the session lock). t: one expert. */ +struct OmegaGpuCmdList; +int omega_gpu_fp8_head_record(struct OmegaGpuCmdList *cl, const OmegaGpuFp8Tensor *t, uint32_t xb, uint64_t x_va, uint64_t y_va, + uint32_t y_stride); +/* Chip test path: x = xb rows of k plain f32 (packed * 2^64 here), y = xb rows of n f32 (contiguous). Stages through + * GPU-uncached scratch, poisons y and refuses a surviving poison word. */ +int omega_gpu_fp8_head_gemv_f32(const OmegaGpuFp8Tensor *t, uint32_t xb, const float *x, float *y, OmegaGpuFp8HeadInfo *info); + +void omega_gpu_fp8_head_set_shape(uint32_t rows, uint32_t warps, uint32_t ctas); /* 0 = automatic; clears the kernel cache */ +void omega_gpu_fp8_head_cache_clear(void); +/* TEST ONLY: kernel mutant (codegen_fp8head.h: 1 wrong scale k-block, 2 wrong scale row block, 3 x row 0 everywhere); + * clears the kernel cache. */ +void omega_gpu_fp8_head_test_set_mutant(int mutant); +int omega_gpu_fp8_head_test_mutant(void); + +#ifdef __cplusplus +} +#endif +#endif diff --git a/src/omega_gpu_q36_graph.c b/src/omega_gpu_q36_graph.c index 31736829..1c5abc05 100644 --- a/src/omega_gpu_q36_graph.c +++ b/src/omega_gpu_q36_graph.c @@ -13,6 +13,7 @@ #include "omega_gpu_fmt.h" #include "omega_gpu_mem_cached.h" #include "omega_gpu_fp8gemm_api.h" +#include "omega_gpu_fp8_head_api.h" #include "omega_gpu_q36_native.h" #include "omega_gpu_cmdlist_native.h" #include <stdlib.h> @@ -75,6 +76,8 @@ struct OmegaGpuQ36Graph { struct { const OmegaGpuFp8Tensor *mix, *o, *gu, *dn; const OmegaGpuBf16Tensor *ab; uint32_t kind_index; int attn, set; } layer[OMEGA_GPU_Q36_MAX_LAYERS]; int final_set; const OmegaGpuFp8Tensor *head8; /* set_lm_head_fp8: FP8 lm_head (hidden is then written x 2^64, read() undoes it) */ + int fp8head; /* AIEN_OMEGA_Q36_FP8_HEAD=1 (default off, DRA-69): the batch reads head8 once per stroke + * (omega_gpu_fp8_head_api.h) instead of per head (record_head_final) */ /* heads (strokes): slot h of x, hidden, logits and token; head 0's state objects are cfg.gdn / cfg.attn */ uint32_t heads; /* slots laid out (create_heads); 1 = the plain graph */ OmegaGpuGdn *gdn_h[OMEGA_GPU_Q36_MAX_HEADS]; @@ -294,6 +297,7 @@ int omega_gpu_q36_graph_create_heads(const OmegaGpuQ36GraphConfig *cfg, uint32_t } omega_gpu_session_unlock(); if (rc != OMEGA_GPU_DGRAPH_OK) { omega_gpu_q36_graph_free(g); return rc; } + { const char *e = getenv("AIEN_OMEGA_Q36_FP8_HEAD"); g->fp8head = e && e[0] == '1' && e[1] == 0; } { const char *e = getenv("AIEN_OMEGA_Q36_BATCH"); if (e && e[0] == '1' && e[1] == 0 && omega_gpu_q36_graph_set_batch(g, 1) != OMEGA_GPU_DGRAPH_OK) { omega_gpu_q36_graph_free(g); return OMEGA_GPU_DGRAPH_CHIP_FAIL; } } *out = g; return OMEGA_GPU_DGRAPH_OK; @@ -348,6 +352,12 @@ int omega_gpu_q36_graph_set_final_norm(OmegaGpuQ36Graph *g, const float *final_n return rc; } +/* pin the fp8head kernel for every stroke width 1..heads (record_final_heads_fp8; a cache miss while recording is refused) */ +static int fp8head_prepare(uint32_t heads) { + for (uint32_t xb = 1; xb <= heads; xb++) if (omega_gpu_fp8_head_prepare(H, xb) != OMEGA_GPU_FP8_OK) return -1; + return 0; +} + int omega_gpu_q36_graph_set_lm_head_fp8(OmegaGpuQ36Graph *g, const OmegaGpuFp8Tensor *head) { if (!g || g->in_token) return OMEGA_GPU_DGRAPH_BAD_ARGS; if (!head) { g->head8 = NULL; return OMEGA_GPU_DGRAPH_OK; } @@ -357,6 +367,7 @@ int omega_gpu_q36_graph_set_lm_head_fp8(OmegaGpuQ36Graph *g, const OmegaGpuFp8Te memcpy((uint8_t *)cpu_of(g, g->lo.tabs) + (size_t)g->cfg.layers * 64u, t, sizeof t); int rc = omega_gpu_session_sync_to_gpu(&g->buf) == 0 ? OMEGA_GPU_DGRAPH_OK : OMEGA_GPU_DGRAPH_CHIP_FAIL; omega_gpu_session_unlock(); + if (rc == OMEGA_GPU_DGRAPH_OK && g->batch && g->fp8head && fp8head_prepare(g->heads) != 0) rc = OMEGA_GPU_DGRAPH_CHIP_FAIL; if (rc == OMEGA_GPU_DGRAPH_OK) g->head8 = head; return rc; } @@ -621,6 +632,7 @@ int omega_gpu_q36_graph_set_batch(OmegaGpuQ36Graph *g, int on) { for (uint32_t xb = 2; xb <= OMEGA_BF16_MAX_XBATCH && xb <= g->heads; xb++) if (omega_gpu_bf16_prepare_xbatch(k, xb, g->am_ctas * OMEGA_DEC_ARGMAX_SPAN) != OMEGA_GPU_BF16_OK) return OMEGA_GPU_DGRAPH_CHIP_FAIL; } + if (g->head8 && g->fp8head && fp8head_prepare(g->heads) != 0) return OMEGA_GPU_DGRAPH_CHIP_FAIL; g->batch = 1; return OMEGA_GPU_DGRAPH_OK; } @@ -819,15 +831,33 @@ int omega_gpu_q36_graph_record_head_final(OmegaGpuQ36Graph *g, uint32_t h) { return rc == OMEGA_GPU_DGRAPH_OK ? rc : fail(g, NULL, rc); } +/* DRA-69 (AIEN_OMEGA_Q36_FP8_HEAD=1): the FP8 head once per stroke. hidden (already x 2^64, GPU-uncached) is copied into + * the cached xq slots (K_COPY: N * 2048 / 256 rows; xq is free after the last layer, begin_stroke resets xq_layer), one + * fp8head launch for every head (row h of the output bit-identical to head h's record_head_final logits, see + * omega_gpu_fp8_head_api.h), then the argmax per head. TEST mutant 7: the copy leaves the last head out, so that head's + * logits come from its stale layer x'. */ +static int record_final_heads_fp8(OmegaGpuQ36Graph *g, uint32_t N) { + uint32_t w[OMEGA_DEC_GA_WORDS]; memset(w, 0, sizeof w); + const uint64_t xq0 = va_of(g, xq_of(g, 0)); + const uint32_t copy_rows = (g->mutant == 7 ? N - 1u : N) * (H / COPY_ROW); + put64(w, OMEGA_DEC_GA_IN, va_of(g, hidden_of(g, 0))); put64(w, OMEGA_DEC_GA_TAB, va_of(g, g->lo.idtab)); put64(w, OMEGA_DEC_GA_OUT, xq0); + int rc = copy_rows ? add_glue(g, OMEGA_GPU_Q36_K_LM_HEAD, K_COPY, 1, copy_rows, (size_t)copy_rows * COPY_ROW, w, OMEGA_DEC_GA_WORDS) : OMEGA_GPU_DGRAPH_OK; + if (rc == OMEGA_GPU_DGRAPH_OK) + rc = after_op(g, OMEGA_GPU_Q36_K_LM_HEAD, omega_gpu_fp8_head_record(g->cl, g->head8, N, xq0, va_of(g, logits_of(g, 0)), g->am_ctas * OMEGA_DEC_ARGMAX_SPAN)); + for (uint32_t h = 0; h < N && rc == OMEGA_GPU_DGRAPH_OK; h++) rc = rec_argmax(g, va_of(g, logits_of(g, h)), va_of(g, token_of(g, h))); + return rc == OMEGA_GPU_DGRAPH_OK ? rc : fail(g, NULL, rc); +} + /* The batch's final head (v2 lever 1, L312): every head's hidden is ready after the last layer (record_layer_heads), so * the bf16 lm_head runs once per group of up to OMEGA_BF16_MAX_XBATCH heads (the XBATCH form: x rows hidden_of(h0..), * y rows logits_of(h0..), ystride the logits slot; each row bit-identical to its own one-head launch), then the argmax - * per head. The FP8 head keeps the per-head path (stroke() calls record_head_final). */ + * per head. The FP8 head takes record_final_heads_fp8 (stroke() sends it here only with AIEN_OMEGA_Q36_FP8_HEAD=1). */ static int record_final_heads(OmegaGpuQ36Graph *g) { const uint32_t N = g->stroke_heads; if (!g->final_set) return fail(g, "q36 graph: final norm not set", OMEGA_GPU_DGRAPH_BAD_ARGS); for (uint32_t h = 0; h < N; h++) if (!g->hidden_ready[h]) return fail(g, "q36 graph: batch final before the last layer", OMEGA_GPU_DGRAPH_BAD_ARGS); + if (g->head8) return record_final_heads_fp8(g, N); int rc = OMEGA_GPU_DGRAPH_OK; for (uint32_t h0 = 0; h0 < N && rc == OMEGA_GPU_DGRAPH_OK; h0 += OMEGA_BF16_MAX_XBATCH) { const uint32_t xb = N - h0 < OMEGA_BF16_MAX_XBATCH ? N - h0 : OMEGA_BF16_MAX_XBATCH; @@ -881,7 +911,7 @@ int omega_gpu_q36_graph_stroke(OmegaGpuQ36Graph *g, const float *x_embed, const if (g->batch) (void)omega_gpu_q36_graph_record_layer_heads(g, l, pos); else for (uint32_t h = 0; h < heads && !g->failed; h++) (void)omega_gpu_q36_graph_record_head_layer(g, h, l, pos[h]); } - if (g->batch && !g->head8) { if (!g->failed) (void)record_final_heads(g); } + if (g->batch && (!g->head8 || g->fp8head)) { if (!g->failed) (void)record_final_heads(g); } else for (uint32_t h = 0; h < heads && !g->failed; h++) (void)omega_gpu_q36_graph_record_head_final(g, h); return omega_gpu_q36_graph_end_stroke(g, tokens, st); } diff --git a/src/omega_gpu_q36_graph.h b/src/omega_gpu_q36_graph.h index 076b03f7..fe5d4883 100644 --- a/src/omega_gpu_q36_graph.h +++ b/src/omega_gpu_q36_graph.h @@ -90,7 +90,9 @@ int omega_gpu_q36_graph_set_layer(OmegaGpuQ36Graph *g, uint32_t layer, const Ome const OmegaGpuFp8Tensor *o, const OmegaGpuFp8Tensor *gate_up, const OmegaGpuFp8Tensor *down, const float *in_norm); int omega_gpu_q36_graph_set_final_norm(OmegaGpuQ36Graph *g, const float *final_norm); /* f32 [2048] as (1 + w) */ -/* Optional FP8 lm_head: as omega_gpu_q38_graph_set_lm_head_fp8 ([vocab][2048]). */ +/* Optional FP8 lm_head: as omega_gpu_q38_graph_set_lm_head_fp8 ([vocab][2048]). A batched stroke (set_batch) with an FP8 head + * runs the head per head unless AIEN_OMEGA_Q36_FP8_HEAD=1 (read at create, default off; DRA-69): then one + * omega_gpu_fp8_head launch serves every head of the stroke, row h bit-identical to the per-head logits. */ int omega_gpu_q36_graph_set_lm_head_fp8(OmegaGpuQ36Graph *g, const OmegaGpuFp8Tensor *head); /* Strokes: N heads (conversations) through ONE command list, one submit. create_heads lays out N slots of x, hidden, logits * and token; head 0 uses cfg.gdn / cfg.attn, every head (0 included) can be pointed at other state objects by set_head_state (same shapes; @@ -189,7 +191,8 @@ void omega_gpu_q36_graph_set_flush_each(OmegaGpuQ36Graph *g, int on); /* TEST ONLY: 1 SWIGLU up half off by one, 2 GATHER index + 1, 3 GATE dropped, 4 COMBINE skips the shared expert, * 5 the exact head's MASK keeps the rows it should drop and drops the candidates (the greedy gate must catch it), * 6 the exact head's XBOUND drops the c|h| bound (too weak to change most tokens: the host gate saw one golden of five - * diverge at its full scale x0). 0 none. */ + * diverge at its full scale x0), 7 (AIEN_OMEGA_Q36_FP8_HEAD batch only) the hidden -> xq copy leaves the stroke's last head + * out, so its FP8 logits come from a stale x'. 0 none. */ void omega_gpu_q36_graph_test_set_mutant(OmegaGpuQ36Graph *g, int mutant); #ifdef __cplusplus diff --git a/tests/gpu_fp8_head_test.c b/tests/gpu_fp8_head_test.c new file mode 100644 index 00000000..acb7edaa --- /dev/null +++ b/tests/gpu_fp8_head_test.c @@ -0,0 +1,216 @@ +/* SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception */ +/* + * gpu_fp8_head_test: the all-heads FP8 lm_head kernel (omega_blackwell_codegen_fp8head.h, aien-dev/CUDApp#217, + * P-DRA-4 DRA-69). Host and warp-simulator only; nothing here is a chip result. + * + * ./gpu_fp8_head_test --host-only spec refusals, instruction / register budgets for every accepted shape + * ./gpu_fp8_head_test --sim warp simulator: + * 1. bitwise parity: for xb 1..8 and rows 1, 2, row b of the fp8head output is memcmp-identical to the + * legacy single-x FP8 GEMV (omega_blackwell_codegen_moe.c, lane_bytes 16) run on x row b alone; + * 2. oracle: every output within TOL of the double oracle (omega_fp8_gemv_oracle), relative to sum |terms|; + * 3. mutants 1 (scale pointer stuck at k-block 0), 2 (neighbouring 128-row scale block), 3 (every x row reads + * row 0): each must break the oracle check and the bitwise parity. + * FP8HEAD_TEST_FORCE_MUTANT=m negative control of the test itself: builds every "good" kernel of the + * battery with mutant m, so the parity and oracle checks must go red. + * Exit 0 only when every check passes. -ffp-contract=off keeps the double oracle free of FMA. + */ +#include "omega_blackwell_codegen_fp8head.h" +#include "omega_blackwell_codegen_moe.h" +#include "omega_gpu_fp8_api.h" +#include "bw_warp_sim.h" +#include <math.h> +#include <stdio.h> +#include <stdlib.h> +#include <string.h> + +#define TOL 1e-5 +static int g_checks, g_failed, g_force_mutant; +#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); } +static uint8_t rand_e4m3(uint32_t *s) { uint8_t b = (uint8_t)(lcg(s) >> 24); if (omega_fp8_e4m3_is_nan(b)) b = (uint8_t)(b - 1); return b; } + +typedef struct { uint32_t n, k; uint8_t *w; uint16_t *s; float *sf; } Head; +static void head_make(Head *H, uint32_t n, uint32_t k, uint32_t seed) { + H->n = n; H->k = k; + size_t wb = (size_t)n * k, sc = (size_t)(n / 128) * (k / 128); + H->w = aligned_alloc(64, (wb + 63) & ~(size_t)63); H->s = malloc(sc * 2); + H->sf = aligned_alloc(16, (sc * 4 + 15) & ~(size_t)15); + uint32_t st = seed; + for (size_t i = 0; i < wb; i++) H->w[i] = rand_e4m3(&st); + for (size_t i = 0; i < sc; i++) H->s[i] = omega_fp32_to_bf16(frand(&st, 0.001f, 0.1f) * ((lcg(&st) & 1) ? 1.0f : -1.0f)); + if (omega_fp8_pack_scales(H->s, sc, H->sf, 0) != 0) { printf("FAIL: scale pack\n"); exit(2); } +} +static void head_free(Head *H) { free(H->w); free(H->s); free(H->sf); } + +/* fp8head on the simulator, both fragment orders (must agree). xp: xb packed rows (x * 2^64). y: xb rows of n. */ +static int sim_head(const OmegaFp8HeadSpec *spec, const Head *H, const float *xp, float *y, uint32_t ctas, char *msg, size_t ml) { + static BlackwellIRProgram prog; + if (omega_blackwell_codegen_fp8head_prog(spec, &prog) != 0) { snprintf(msg, ml, "codegen refused"); return -1; } + const uint32_t n = H->n, k = H->k, RG = n / spec->rows, xb = spec->xb; + size_t ny = (size_t)xb * n; + float *yd = aligned_alloc(16, (ny * 4 + 15) & ~(size_t)15), *first = malloc(ny * 4); + uint32_t grid_x = (RG + spec->warps - 1) / spec->warps; if (grid_x > ctas) grid_x = ctas; if (!grid_x) grid_x = 1; + int err = 0; + for (int run = 0; run < 2 && !err; run++) { + WsSim s; memset(&s, 0, sizeof s); + s.p = &prog; s.threads = 32 * spec->warps; s.order = run; + uint64_t wa = (uintptr_t)H->w, sa = (uintptr_t)H->sf, xa = (uintptr_t)xp, ya = (uintptr_t)yd; + s.cbank[OMEGA_FP8HEAD_ARG_W / 4] = (uint32_t)wa; s.cbank[OMEGA_FP8HEAD_ARG_W / 4 + 1] = (uint32_t)(wa >> 32); + s.cbank[OMEGA_FP8HEAD_ARG_S / 4] = (uint32_t)sa; s.cbank[OMEGA_FP8HEAD_ARG_S / 4 + 1] = (uint32_t)(sa >> 32); + s.cbank[OMEGA_FP8HEAD_ARG_X / 4] = (uint32_t)xa; s.cbank[OMEGA_FP8HEAD_ARG_X / 4 + 1] = (uint32_t)(xa >> 32); + s.cbank[OMEGA_FP8HEAD_ARG_Y / 4] = (uint32_t)ya; s.cbank[OMEGA_FP8HEAD_ARG_Y / 4 + 1] = (uint32_t)(ya >> 32); + s.cbank[OMEGA_FP8HEAD_ARG_RG / 4] = RG; s.cbank[OMEGA_FP8HEAD_ARG_YSTRIDE / 4] = n * 4; + s.cbank[OMEGA_FP8HEAD_ARG_STRIDE / 4] = grid_x * spec->warps; + s.nranges = 4; /* every global access must land in a declared buffer */ + s.ranges[0].lo = wa; s.ranges[0].hi = wa + (size_t)n * k; + s.ranges[1].lo = sa; s.ranges[1].hi = sa + (size_t)(n / 128) * (k / 128) * 4; + s.ranges[2].lo = xa; s.ranges[2].hi = xa + (size_t)xb * k * 4; + s.ranges[3].lo = ya; s.ranges[3].hi = ya + ny * 4; + for (size_t i = 0; i < ny; i++) yd[i] = -999.0f; + err = ws_run(&s, grid_x, 1); + if (err) { snprintf(msg, ml, "run %d: %s", run, s.msg); break; } + size_t unwritten = 0; for (size_t i = 0; i < ny; i++) unwritten += yd[i] == -999.0f; + if (unwritten) { err = -1; snprintf(msg, ml, "%zu output words never written", unwritten); break; } + if (run == 0) memcpy(first, yd, ny * 4); + else if (memcmp(first, yd, ny * 4)) { err = -1; snprintf(msg, ml, "fragment order changed the result"); } + } + if (!err) memcpy(y, yd, ny * 4); + free(yd); free(first); + return err; +} + +/* legacy single-x FP8 GEMV (lane_bytes 16, one expert) for one packed x row */ +static int sim_legacy(const Head *H, uint32_t rows, const float *xp, float *y, char *msg, size_t ml) { + static BlackwellIRProgram prog; + OmegaFp8GemvSpec sp = { .k = H->k, .lane_bytes = 16, .rows = rows, .warps = 8 }; + if (omega_blackwell_codegen_fp8_gemv_prog(&sp, &prog) != 0) { snprintf(msg, ml, "legacy codegen refused"); return -1; } + const uint32_t n = H->n, RG = n / rows; + uint64_t tab[2] = { (uintptr_t)H->w, (uintptr_t)H->sf }; + float *yd = aligned_alloc(16, ((size_t)n * 4 + 15) & ~(size_t)15); + uint32_t grid_x = (RG + 7) / 8; if (grid_x > 4) grid_x = 4; + WsSim s; memset(&s, 0, sizeof s); + static uint8_t smem[OMEGA_FP8_MAX_K * 4 + 4096]; + s.p = &prog; s.threads = 256; s.smem = smem; s.smem_bytes = omega_fp8_gemv_shared_bytes(&sp); + uint64_t ta = (uintptr_t)tab, xa = (uintptr_t)xp, ya = (uintptr_t)yd; + s.cbank[OMEGA_FP8_ARG_TAB / 4] = (uint32_t)ta; s.cbank[OMEGA_FP8_ARG_TAB / 4 + 1] = (uint32_t)(ta >> 32); + s.cbank[OMEGA_FP8_ARG_X / 4] = (uint32_t)xa; s.cbank[OMEGA_FP8_ARG_X / 4 + 1] = (uint32_t)(xa >> 32); + s.cbank[OMEGA_FP8_ARG_Y / 4] = (uint32_t)ya; s.cbank[OMEGA_FP8_ARG_Y / 4 + 1] = (uint32_t)(ya >> 32); + s.cbank[OMEGA_FP8_ARG_RG / 4] = RG; s.cbank[OMEGA_FP8_ARG_XSTRIDE / 4] = 0; + s.cbank[OMEGA_FP8_ARG_YSTRIDE / 4] = n * 4; s.cbank[OMEGA_FP8_ARG_STRIDE / 4] = grid_x * 8; + s.nranges = 5; + s.ranges[0].lo = (uintptr_t)H->w; s.ranges[0].hi = (uintptr_t)H->w + (size_t)n * H->k; + s.ranges[1].lo = (uintptr_t)H->sf; s.ranges[1].hi = (uintptr_t)H->sf + (size_t)(n / 128) * (H->k / 128) * 4; + s.ranges[2].lo = xa; s.ranges[2].hi = xa + (size_t)H->k * 4; + s.ranges[3].lo = ya; s.ranges[3].hi = ya + (size_t)n * 4; + s.ranges[4].lo = ta; s.ranges[4].hi = ta + sizeof tab; + int err = ws_run(&s, grid_x, 1); + if (err) snprintf(msg, ml, "legacy: %s", s.msg); else memcpy(y, yd, (size_t)n * 4); + free(yd); + return err; +} + +/* worst relative error against the double oracle; *bad = outputs at or over TOL (or NaN) */ +static double oracle_check(const Head *H, uint32_t xb, const float *x, const float *y, size_t *bad) { + double worst = 0; size_t nb = 0; + double *ref = malloc(H->n * sizeof *ref), *mag = malloc(H->n * sizeof *mag); + for (uint32_t b = 0; b < xb; b++) { + omega_fp8_gemv_oracle(H->w, H->s, H->n, H->k, x + (size_t)b * H->k, ref, mag); + for (uint32_t r = 0; r < H->n; r++) { + float v = y[(size_t)b * H->n + r]; + double rel = fabs(ref[r] - (double)v) / (mag[r] > 1e-30 ? mag[r] : 1e-30); + if (rel > worst) worst = rel; + nb += rel >= TOL || isnan(v); + } + } + free(ref); free(mag); + *bad = nb; + return worst; +} + +static void host_only(void) { + uint32_t built = 0, max_insns = 0, max_gprs = 0; + for (uint32_t rows = 1; rows <= 2; rows++) + for (uint32_t xb = 1; xb <= OMEGA_FP8HEAD_MAX_XB; xb++) + for (int m = 0; m <= 3; m++) { + OmegaFp8HeadSpec sp = { .k = 2048, .rows = rows, .warps = 8, .xb = xb, .mutant = m }; + uint32_t ni = 0, ng = 0; + int rc = omega_fp8head_prog_stats(&sp, &ni, &ng); + CHECK(rc == 0 && ni <= BW_MAX_IR_INSNS, "k 2048 rows %u xb %u mutant %d: rc %d, %u insns", rows, xb, m, rc, ni); + if (!rc) { built++; if (ni > max_insns) max_insns = ni; if (ng > max_gprs) max_gprs = ng; } + if (m == 0 && (xb == 1 || xb == 8)) printf("host k 2048 rows %u xb %u: %u insns, %u gprs\n", rows, xb, ni, ng); + } + const OmegaFp8HeadSpec refuse[] = { + { .k = 2000, .rows = 1, .warps = 8, .xb = 1 }, /* k not a multiple of 512 */ + { .k = 2048, .rows = 3, .warps = 8, .xb = 1 }, /* rows must divide 128 and be <= 2 */ + { .k = 2048, .rows = 1, .warps = 0, .xb = 1 }, /* warps 0 */ + { .k = 2048, .rows = 1, .warps = 33, .xb = 1 }, /* warps > 32 */ + { .k = 2048, .rows = 1, .warps = 8, .xb = 0 }, /* xb 0 */ + { .k = 2048, .rows = 1, .warps = 8, .xb = 9 }, /* xb > OMEGA_FP8HEAD_MAX_XB */ + { .k = 2048, .rows = 1, .warps = 8, .xb = 1, .mutant = 4 }, + }; + for (size_t i = 0; i < sizeof refuse / sizeof refuse[0]; i++) + CHECK(!omega_fp8head_spec_ok(&refuse[i]) && omega_fp8head_prog_stats(&refuse[i], NULL, NULL) != 0, "refusal case %zu accepted", i); + printf("host: %u kernels built (rows 1-2, xb 1-8, mutants 0-3), max %u insns / %u gprs, %zu refusals checked\n", built, max_insns, + max_gprs, sizeof refuse / sizeof refuse[0]); +} + +static void sim_battery(void) { + char msg[320]; + const uint32_t n = 256, k = 1024; /* 2 row blocks x 2 k-blocks per 512 step x 2 steps: every mutant has something to break */ + Head H; head_make(&H, n, k, 0x69u); + float *x = malloc((size_t)OMEGA_FP8HEAD_MAX_XB * k * 4), *xp = aligned_alloc(16, (size_t)OMEGA_FP8HEAD_MAX_XB * k * 4); + float *y = malloc((size_t)OMEGA_FP8HEAD_MAX_XB * n * 4), *yl = malloc((size_t)OMEGA_FP8HEAD_MAX_XB * n * 4); + uint32_t st = 0x217u; + for (size_t i = 0; i < (size_t)OMEGA_FP8HEAD_MAX_XB * k; i++) x[i] = frand(&st, -1.0f, 1.0f); + for (uint32_t b = 0; b < OMEGA_FP8HEAD_MAX_XB; b++) omega_fp8_pack_x_f32(x + (size_t)b * k, k, xp + (size_t)b * k); + for (uint32_t rows = 1; rows <= 2; rows++) { + /* legacy reference rows once per row count */ + int lrc = 0; + for (uint32_t b = 0; b < OMEGA_FP8HEAD_MAX_XB && !lrc; b++) lrc = sim_legacy(&H, rows, xp + (size_t)b * k, yl + (size_t)b * n, msg, sizeof msg); + CHECK(lrc == 0, "rows %u legacy sim: %s", rows, msg); + if (lrc) continue; + size_t lbad; double lw = oracle_check(&H, OMEGA_FP8HEAD_MAX_XB, x, yl, &lbad); + CHECK(lbad == 0, "rows %u legacy vs oracle: %zu bad, worst %.3e", rows, lbad, lw); + for (uint32_t xb = 1; xb <= OMEGA_FP8HEAD_MAX_XB; xb++) { + OmegaFp8HeadSpec sp = { .k = k, .rows = rows, .warps = 4, .xb = xb, .mutant = g_force_mutant }; + int rc = sim_head(&sp, &H, xp, y, 3, msg, sizeof msg); /* 3 CTAs x 4 warps < RG: the grid-stride loop runs */ + CHECK(rc == 0, "rows %u xb %u sim: %s", rows, xb, msg); + if (rc) continue; + size_t diff = 0; for (size_t i = 0; i < (size_t)xb * n; i++) diff += memcmp(&y[i], &yl[i], 4) != 0; + size_t bad; double w = oracle_check(&H, xb, x, y, &bad); + CHECK(diff == 0, "rows %u xb %u: %zu of %zu words differ bitwise from the legacy kernel", rows, xb, diff, (size_t)xb * n); + CHECK(bad == 0, "rows %u xb %u: %zu of %zu outputs over TOL (worst %.3e)", rows, xb, bad, (size_t)xb * n, w); + printf("sim rows %u xb %u: bitwise diff %zu/%zu, oracle bad %zu worst_rel %.3e\n", rows, xb, diff, (size_t)xb * n, bad, w); + } + /* mutants at xb 8: each must break both the oracle check and the bitwise parity */ + for (int m = 1; m <= 3; m++) { + OmegaFp8HeadSpec sp = { .k = k, .rows = rows, .warps = 4, .xb = 8, .mutant = m }; + int rc = sim_head(&sp, &H, xp, y, 3, msg, sizeof msg); + size_t diff = 0, bad = 0; double w = 0; + if (!rc) { for (size_t i = 0; i < (size_t)8 * n; i++) diff += memcmp(&y[i], &yl[i], 4) != 0; w = oracle_check(&H, 8, x, y, &bad); } + int caught = rc != 0 || (bad > 0 && diff > 0); + CHECK(caught, "rows %u mutant %d NOT caught (diff %zu bad %zu)", rows, m, diff, bad); + printf("sim rows %u xb 8 mutant %d: %s (rc %d, bitwise diff %zu/%u, oracle bad %zu worst_rel %.3e)\n", rows, m, + caught ? "caught" : "MISSED", rc, diff, 8 * n, bad, w); + } + } + free(x); free(xp); free(y); free(yl); head_free(&H); +} + +int main(int argc, char **argv) { + int sim = 0; + for (int i = 1; i < argc; i++) { + if (!strcmp(argv[i], "--sim")) sim = 1; + else if (!strcmp(argv[i], "--host-only")) sim = 0; + else { fprintf(stderr, "usage: %s --host-only | --sim\n", argv[0]); return 2; } + } + const char *fm = getenv("FP8HEAD_TEST_FORCE_MUTANT"); + if (fm) g_force_mutant = atoi(fm); + if (g_force_mutant) printf("FP8HEAD_TEST_FORCE_MUTANT=%d: every battery kernel is mutant %d (negative control)\n", g_force_mutant, g_force_mutant); + host_only(); + if (sim) sim_battery(); + printf("%s: %d checks, %d failed\n", g_failed ? "FAIL" : "PASS", g_checks, g_failed); + return g_failed ? 1 : 0; +}