Interplane page as plain text, for reading tools and agents. English is the reference text: translate it with your own tool. Text in backticks and in ``` blocks (commands, fingerprints, file names) and link targets in <...> are exact: copy them, never translate them. Page: /drakestapleton/CUDApp/patches/f08ca788cd270b65 # 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 Sign in to star 0 stars 0 watching About Files History Releases Proposed changes Issues For developers ## GitHub aien-dev/CUDApp#232 (code only) closed derived `f08ca788cd270b65` #232 Imported from GitHub aien-dev/CUDApp#232 (code only) GitHub's metadata for this pull request is unavailable: its state is DERIVED from the commits (merged: the head is reachable from this project's main; open: GitHub kept a merge ref; else closed). Base `4bbccf084b7309ae89e126c890324e377478b3be` · Head `f89b113b17a97c11a737312c58f4b709aa049dbe` ### Apply it ``` git checkout -b patch-f08ca788cd270b65 4bbccf084b7309ae89e126c890324e377478b3be curl -fsSL https://interplane.io/drakestapleton/CUDApp/patches/f08ca788cd270b65.patch | git am ``` Raw patch (mbox) · Diff ### Provenance This proposal is imported from GitHub; it is not signed by its author. Its import statement and source record: ``` github-import 1 aien-dev/CUDApp 232 f89b113b17a97c11a737312c58f4b709aa049dbe ``` ``` {"kind":"github-import","owner":"aien-dev","repo":"CUDApp","number":232,"url":"https://github.com/aien-dev/CUDApp/pull/232","export_sha256":"967c79e26a893657b5cdaa45efd442be5dbd2ecfe68e25f9a8c1b5da4d60d452","imported_utc":"2026-11-18T16:38:56Z","metadata":"unavailable","state_derived":true} ``` ### Changes ``` diff --git a/Makefile b/Makefile index 0a8a8b80..ee5dedad 100644 --- a/Makefile +++ b/Makefile @@ -375,6 +375,9 @@ $(GPU_QMMA_PROBE_TEST): tests/gpu_qmma_probe_test.c tests/bw_qmma_model.h src/om GPU_QGEMM_TEST = $(OUT_DIR)/gpu_qgemm_test $(GPU_QGEMM_TEST): tests/gpu_qgemm_test.c tests/bw_qmma_model.h tests/bw_warp_sim_tc.h src/omega_gpu_prefill.h src/omega_blackwell_codegen_qg.h $(OUT_DIR)/libomega_gpu.a $(CC) $(CFLAGS) -ffp-contract=off -DWS_MAX_THREADS=1024 -Itests -o $@ tests/gpu_qgemm_test.c $(OUT_DIR)/libomega_gpu.a -lpthread -lm +GPU_PFQ_TEST = $(OUT_DIR)/gpu_pfq_test +$(GPU_PFQ_TEST): tests/gpu_pfq_test.c tests/pfq_legacy_words.h tests/bw_qmma_model.h tests/bw_warp_sim_tc.h src/omega_gpu_pfq_api.h src/omega_blackwell_codegen_qg.h $(OUT_DIR)/libomega_gpu.a + $(CC) $(CFLAGS) -ffp-contract=off -DWS_MAX_THREADS=1024 -Itests -o $@ tests/gpu_pfq_test.c $(OUT_DIR)/libomega_gpu.a -lpthread -lm .PHONY: test-gemm-selectors test-gemm-selectors: $(GPU_PFGEMM_TEST) $(GPU_QGEMM_TEST) $(GPU_FP8GEMM_TEST) python3 tests/gemm_selectors.py $(OUT_DIR) @@ -386,7 +389,7 @@ $(GPU_PFHOST_TEST): tests/gpu_pfhost_test.c tests/bw_warp_sim_tc.h src/omega_gpu # modes that never open the device (each test's main returns before its chip part); chip runs stay under the GB10 lock. .PHONY: test-gpu-prefill-host test-gpu-prefill-host: $(GPU_TC_PROBE_TEST) $(GPU_TCGEMM_TEST) $(GPU_PATTN_TEST) $(GPU_PF_MEM_TEST) $(GPU_PFGEMM_TEST) \ - $(GPU_QMMA_PROBE_TEST) $(GPU_QGEMM_TEST) $(GPU_PFHOST_TEST) + $(GPU_QMMA_PROBE_TEST) $(GPU_QGEMM_TEST) $(GPU_PFHOST_TEST) $(GPU_PFQ_TEST) ./$(GPU_TC_PROBE_TEST) --host-only ./$(GPU_QMMA_PROBE_TEST) --host-only ./$(GPU_PF_MEM_TEST) --host-only @@ -400,7 +403,9 @@ test-gpu-prefill-host: $(GPU_TC_PROBE_TEST) $(GPU_TCGEMM_TEST) $(GPU_PATTN_TEST) ./$(GPU_QGEMM_TEST) --sim ./$(GPU_PFHOST_TEST) --host-only ./$(GPU_PFHOST_TEST) --sim - @echo "test-gpu-prefill-host: PASS (8 prefill tests, host model + warp simulator, no device)" + ./$(GPU_PFQ_TEST) --host-only + ./$(GPU_PFQ_TEST) --sim + @echo "test-gpu-prefill-host: PASS (9 prefill tests, host model + warp simulator, no device)" # omega#456: tools/own30b_decode_profile.c is a link-only recorder built by hand on the Spark; compile it with the # project's -Werror flags so a warning cannot land unseen. .PHONY: check-own30b-decode-profile diff --git a/mk/carried-tests.mk b/mk/carried-tests.mk index 7bdc6e2d..c1884e88 100644 --- a/mk/carried-tests.mk +++ b/mk/carried-tests.mk @@ -29,6 +29,10 @@ $(GPU_GDN_MULTI_TEST): tests/gpu_gdn_multi_test.c tests/bw_warp_sim_k.h src/omeg GPU_PATTN256_TEST = $(OUT_DIR)/gpu_prefill_attn256_test $(GPU_PATTN256_TEST): tests/gpu_prefill_attn256_test.c tests/bw_hmma_model.h tests/bw_warp_sim_pa.h src/omega_gpu_prefill_attn256_api.h src/omega_blackwell_codegen_pattn256.h src/omega_blackwell_codegen_attn256.h $(OUT_DIR)/libomega_gpu.a $(CC) $(CFLAGS) -ffp-contract=off -DWS_MAX_THREADS=256 -Itests -o $@ tests/gpu_prefill_attn256_test.c $(OUT_DIR)/libomega_gpu.a -lpthread -lm +# Qwen3.6-35B-A3B flash-style tensor-core prefill attention (Linear DRA-85, P-DRA-4). +GPU_FATTN256_TEST = $(OUT_DIR)/gpu_prefill_fattn256_test +$(GPU_FATTN256_TEST): tests/gpu_prefill_fattn256_test.c tests/bw_hmma_model.h tests/bw_warp_sim_pa.h src/omega_gpu_prefill_fattn256_api.h src/omega_blackwell_codegen_fattn256.h src/omega_blackwell_codegen_attn256.h $(OUT_DIR)/libomega_gpu.a + $(CC) $(CFLAGS) -ffp-contract=off -DWS_MAX_THREADS=256 -Itests -o $@ tests/gpu_prefill_fattn256_test.c $(OUT_DIR)/libomega_gpu.a -lpthread -lm # Qwen3.8-27B decode graph (sc #642) and the exact two-pass lm_head (HUM L314). GPU_Q38_GRAPH_TEST = $(OUT_DIR)/gpu_q38_graph_test @@ -47,7 +51,7 @@ $(GPU_ISOLATION_TEST): tests/gpu_isolation_test.c tests/bw_warp_sim.h src/omega_ $(CC) $(CFLAGS) -ffp-contract=off -Itests -o $@ tests/gpu_isolation_test.c $(OUT_DIR)/libomega_gpu.a -lpthread -lm .PHONY: test-bw-encode-control test-gpu-decode-attn256 test-gpu-gdn test-gpu-q38-graph-host test-gpu-streams \ - test-gpu-isolation test-carried-bins + test-gpu-isolation test-gpu-prefill-fattn256 test-carried-bins test-bw-encode-control: $(BW_ENCODE_CONTROL_TEST) ./$(BW_ENCODE_CONTROL_TEST) test-gpu-decode-attn256: $(GPU_DATTN256_TEST) @@ -62,8 +66,10 @@ test-gpu-streams: $(GPU_STREAMS_TEST) ./$(GPU_STREAMS_TEST) --sim test-gpu-isolation: $(GPU_ISOLATION_TEST) ./$(GPU_ISOLATION_TEST) --host-only +test-gpu-prefill-fattn256: $(GPU_FATTN256_TEST) + ./$(GPU_FATTN256_TEST) --sim # Chip-only binaries: built here so the host suite at least compiles them. -test-carried-bins: $(GPU_DATTN256_MULTI_TEST) $(GPU_GDN_MULTI_TEST) $(GPU_PATTN256_TEST) $(GPU_EXACT_HEAD_TEST) +test-carried-bins: $(GPU_DATTN256_MULTI_TEST) $(GPU_GDN_MULTI_TEST) $(GPU_PATTN256_TEST) $(GPU_FATTN256_TEST) $(GPU_EXACT_HEAD_TEST) CARRIED_HOST_TESTS = test-bw-encode-control test-gpu-decode-attn256 test-gpu-gdn test-gpu-q38-graph-host \ - test-gpu-streams test-gpu-isolation test-carried-bins + test-gpu-streams test-gpu-isolation test-gpu-prefill-fattn256 test-carried-bins diff --git a/src/omega_blackwell_codegen_attn256.c b/src/omega_blackwell_codegen_attn256.c index 1cec482d..837f3286 100644 --- a/src/omega_blackwell_codegen_attn256.c +++ b/src/omega_blackwell_codegen_attn256.c @@ -183,6 +183,7 @@ int omega_blackwell_codegen_decode_attn256_prog(const OmegaDecodeAttn256Spec *sp const uint32_t D = spec->depth; OmegaDattn256Shape SH; if (omega_dattn256_shape(spec, &SH)) return -1; + if (spec->prep_xstride && (!spec->prep || spec->multi || spec->prep_xstride % 16u || spec->prep_xstride < SH.qkv_words * 4u)) return -1; const uint32_t H = SH.h; /* q heads per CTA row */ const int OLD = SH.qh == OMEGA_DATTN256_Q_HEADS && SH.kvh == OMEGA_DATTN256_KV_HEADS && H == OMEGA_DATTN256_Q_PER_KV; const int MUT = spec->mutant; @@ -202,7 +203,7 @@ int omega_blackwell_codegen_decode_attn256_prog(const OmegaDecodeAttn256Spec *sp s2r(e, tid, BW_SR_TID_X); s2r(e, cx, BW_SR_CTAID_X); s2r(e, cy, BW_SR_CTAID_Y); if (spec->prep && !spec->multi) { /* prefill prep (#545): CTA cx = token cx at position pos0 + cx, its qkv row */ iadd(e, pos, pos, cx); - { int rowoff = V(e); if (e->err) return -1; imadi(e, R(rowoff), R(cx), SH.qkv_words * 4u, NOREG); imadw(e, pqkv, rowoff, 1u, pqkv); } + { int rowoff = V(e); if (e->err) return -1; imadi(e, R(rowoff), R(cx), spec->prep_xstride ? spec->prep_xstride : SH.qkv_words * 4u, NOREG); imadw(e, pqkv, rowoff, 1u, pqkv); } } movi(e, one, 1); movrz(e, R(zero)); movi(e, c7fff, 0x7fffu); movi(e, c16, 16); shr(e, warp, tid, 5); diff --git a/src/omega_blackwell_codegen_attn256.h b/src/omega_blackwell_codegen_attn256.h index caec480e..7afed623 100644 --- a/src/omega_blackwell_codegen_attn256.h +++ b/src/omega_blackwell_codegen_attn256.h @@ -116,6 +116,10 @@ typedef struct { * the K/V append (the prep launch before it wrote every token's rows; a split never reads past its token); * out row t at ARG_OUT + t * ARG_OSTRIDE, partials at ARG_PART + t * ARG_PSTRIDE, counters at ARG_CNT + t * vy * 4. * Every value is the decode launch's, bit for bit (same instructions, same combine order). */ + uint32_t prep_xstride; /* DRA-85 (2026-11-01): prep = 1, multi = 0 only. Bytes between consecutive qkv rows; 0 = qkv_words * 4 + * (the program before this field existed, bit for bit). Qwen3.6-35B-A3B's prefill reads q|k|v out of its + * 9216-word mixer rows (36864 bytes apart, omega_gpu_q36_graph.h ATT_MIX). Must be a multiple of 16 and + * >= qkv_words * 4. Appended last. */ } OmegaDecodeAttn256Spec; /* The shape a spec selects: 0 ok, -1 unsupported. */ diff --git a/src/omega_blackwell_codegen_fattn256.c b/src/omega_blackwell_codegen_fattn256.c new file mode 100644 index 00000000..1501033c --- /dev/null +++ b/src/omega_blackwell_codegen_fattn256.c @@ -0,0 +1,415 @@ +/* SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception */ +/* + * omega_blackwell_codegen_fattn256.c: flash-style causal prefill attention on tensor cores, one warp per 16-row tile, + * no shared memory (see the header; Linear DRA-85). The emitter helpers are omega_blackwell_codegen_pattn256.c's, copied + * unchanged (control words, the read barrier on every load, held scoreboards 3/4 for prefetch loads, loop live ranges, + * HMMA spacing: >= 4 independent HMMAs at stall 8 between dependent ones, stall 15 + NOP 14 before a non-HMMA reader of + * an HMMA result) minus the shared-memory ones, plus a held-scoreboard global prefetch (ldg_pf, lds_pf's twin) and an + * LDG.64 into a quad's sub-register pair (ldg64s). + */ +#include "omega_blackwell_codegen_fattn256.h" +#include "omega_blackwell_codegen_tc.h" +#include + +#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_SYNC, K_EXIT, K_BRA, K_BSSY, K_BSYNC }; + +typedef struct { + BlackwellIRProgram *p; + uint32_t pending, held; + int err; + int open_start[MAX_LOOPS]; + int depth; + uint32_t placeholders; +} 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; + 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_SYNC: in.control = CW(6, SB_NONE, SB_NONE, wait); e->pending = 0; 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 i; memset(&i, 0, sizeof i); + i.op = op; i.dst_vreg = NOREG; i.src1_vreg = NOREG; i.src2_vreg = NOREG; i.src3_vreg = NOREG; i.ureg = NOREG; + return i; +} +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; } + +typedef struct { int v; unsigned s; } Op; +static Op R(int v) { Op o = { v, 0 }; return o; } +static Op S(int v, unsigned s) { Op o = { v, s }; return o; } + +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, Op d, uint32_t imm) { BlackwellIRInsn i = I0(BW_IR_MOV_IMM); i.dst_vreg = d.v; i.dst_subreg = (uint8_t)d.s; i.imm = imm; emit(e, i, K_FIXED); } +static void movrz(Em *e, Op d) { BlackwellIRInsn i = I0(BW_IR_MOV_RZ); i.dst_vreg = d.v; i.dst_subreg = (uint8_t)d.s; emit(e, i, K_FIXED); } +/* d = a * imm + c */ +static void imadi(Em *e, Op d, Op a, uint32_t imm, int c) { BlackwellIRInsn i = I0(BW_IR_IMAD); i.dst_vreg = d.v; i.dst_subreg = (uint8_t)d.s; i.src1_vreg = a.v; i.src1_subreg = (uint8_t)a.s; i.imm = imm; i.src3_vreg = c; emit(e, i, K_FIXED); } +/* d = a * b + c (registers) */ +static void imadr(Em *e, int d, int a, int b, int c) { BlackwellIRInsn i = I0(BW_IR_IMAD); i.dst_vreg = d; i.src1_vreg = a; i.src2_vreg = b; i.src3_vreg = c; emit(e, i, K_FIXED); } +/* d64 = a * imm + c64 */ +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 mov(Em *e, Op d, Op a) { imadi(e, d, a, 1u, NOREG); } +static void shrs(Em *e, int d, Op a, uint32_t imm) { BlackwellIRInsn i = I0(BW_IR_SHF_R); i.dst_vreg = d; i.src1_vreg = a.v; i.src1_subreg = (uint8_t)a.s; i.imm = imm; emit(e, i, K_FIXED); } +static void shr(Em *e, int d, int a, uint32_t imm) { shrs(e, d, R(a), imm); } +static void andi(Em *e, Op d, Op a, uint32_t imm) { BlackwellIRInsn i = I0(BW_IR_LOP3_AND); i.dst_vreg = d.v; i.dst_subreg = (uint8_t)d.s; i.src1_vreg = a.v; i.src1_subreg = (uint8_t)a.s; i.imm = imm; emit(e, i, K_FIXED); } +static void fop(Em *e, BlackwellIROpcode op, Op d, Op a, Op b, Op c) { + BlackwellIRInsn i = I0(op); i.dst_vreg = d.v; i.dst_subreg = (uint8_t)d.s; i.src1_vreg = a.v; i.src1_subreg = (uint8_t)a.s; + i.src2_vreg = b.v; i.src2_subreg = (uint8_t)b.s; i.src3_vreg = c.v; i.src3_subreg = (uint8_t)c.s; emit(e, i, K_FIXED); +} +static void iadd(Em *e, int d, int a, int b) { fop(e, BW_IR_IADD3, R(d), R(a), R(b), R(NOREG)); } +static void fadd(Em *e, Op d, Op a, Op b) { fop(e, BW_IR_FADD, d, a, b, R(NOREG)); } +static void fsub(Em *e, Op d, Op a, Op b) { fop(e, BW_IR_FSUB, d, a, b, R(NOREG)); } +static void fmul(Em *e, Op d, Op a, Op b) { fop(e, BW_IR_FMUL, d, a, b, R(NOREG)); } +static void fmaxx(Em *e, Op d, Op a, Op b) { fop(e, BW_IR_FMNMX_MAX, d, a, b, R(NOREG)); } +static void mufu(Em *e, BlackwellIROpcode op, Op d, Op a, int first) { BlackwellIRInsn i = I0(op); i.dst_vreg = d.v; i.dst_subreg = (uint8_t)d.s; i.src1_vreg = a.v; i.src1_subreg = (uint8_t)a.s; emit(e, i, first ? K_VAR : K_VAR_MORE); } +static void stg(Em *e, int addr64, uint32_t imm, Op val, int udesc) { BlackwellIRInsn i = I0(BW_IR_STG_E); i.src1_vreg = addr64; i.imm = imm; i.src2_vreg = val.v; i.src2_subreg = (uint8_t)val.s; i.ureg = udesc; emit(e, i, K_STORE); } +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); } +/* SHFL.BFLY placeholder (omega_blackwell_codegen_tc.h), patched after encoding */ +static void shfl_bfly(Em *e, int d, int a, uint32_t lanes) { shfl_down(e, d, a, OMEGA_TC_MARK_BFLY | (lanes & 31u)); e->placeholders++; } +/* F2FP.BF16.F32.PACK_AB placeholder: d = bf16_rn(hi) << 16 | bf16_rn(lo) */ +static void f2fp(Em *e, Op d, Op hi, Op lo) { + BlackwellIRInsn i = I0(BW_IR_FMNMX_MAX); i.dst_vreg = d.v; i.dst_subreg = (uint8_t)d.s; i.src1_vreg = hi.v; i.src1_subreg = (uint8_t)hi.s; + i.src2_vreg = lo.v; i.src2_subreg = (uint8_t)lo.s; i.imm = OMEGA_TC_MARK_F2FP; emit(e, i, K_FIXED); e->placeholders++; +} +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 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; +} +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; + } +} +typedef struct { int bssy, bra; } Region; +static Region region_skip_if_p0(Em *e) { Region r; r.bssy = bssy_fwd(e); r.bra = bra_if_p0_fwd(e); return r; } +static void region_end(Em *e, Region r) { int at = here(e); bsync(e); patch_bra(e, r.bra, at); patch_bra(e, r.bssy, at + 1); } + +/* HMMA.16816.F32.BF16 d = a * b + c; b is the register pair at b + bsub (0 or 2); c NOREG = RZ */ +static void hmma(Em *e, int d, int a, int b, unsigned bsub, int c, uint32_t stall) { + BlackwellIRInsn i = I0(BW_IR_HMMA_BF16); i.dst_vreg = d; i.src1_vreg = a; i.src2_vreg = b; i.src2_subreg = (uint8_t)bsub; i.src3_vreg = c; + i.control = CW(stall, SB_NONE, SB_NONE, e->pending); e->pending = 0; + if (omega_bw_ir_append(e->p, &i) < 0) e->err = -1; +} +static void nop(Em *e, uint32_t stall) { + BlackwellIRInsn i = I0(BW_IR_NOP); i.control = CW(stall, SB_NONE, SB_NONE, e->pending); e->pending = 0; + if (omega_bw_ir_append(e->p, &i) < 0) e->err = -1; +} +/* a prefetch LDS.128: scoreboard sb (3 or 4) is held, not waited for, until consume() */ +static void consume(Em *e, unsigned sb) { e->pending |= e->held & (1u << sb); e->held &= ~(1u << sb); } + +/* a prefetch global load: scoreboard sb (3 or 4) is held, not waited for, until consume() */ +static void ldg_pf(Em *e, BlackwellIROpcode op, int d, int addr64, uint32_t imm, int udesc, unsigned sb) { + BlackwellIRInsn in = I0(op); in.dst_vreg = d; in.src1_vreg = addr64; in.imm = imm; in.ureg = udesc; + in.control = CW(4, sb, SB_RD, (e->pending & (1u << SB_RD))) | CW_YIELD; + e->pending |= 1u << SB_RD; e->held |= 1u << sb; + if (omega_bw_ir_append(e->p, &in) < 0) e->err = -1; +} +/* LDG.64 into a sub-register pair (0 or 2) of a quad */ +static void ldg64s(Em *e, Op d, int addr64, uint32_t imm, int udesc, int first) { + BlackwellIRInsn i = I0(BW_IR_LDG_E_64); i.dst_vreg = d.v; i.dst_subreg = (uint8_t)d.s; i.src1_vreg = addr64; i.imm = imm; i.ureg = udesc; + emit(e, i, first ? K_VAR : K_VAR_MORE); +} +/* variant 2: an LDG.64 into a sub-register pair whose value is never read (it pulls the line into L1); scoreboard 5 is + * held until consume(5) */ +static void ldg_touch(Em *e, Op d, int addr64, uint32_t imm, int udesc) { + BlackwellIRInsn in = I0(BW_IR_LDG_E_64); in.dst_vreg = d.v; in.dst_subreg = (uint8_t)d.s; in.src1_vreg = addr64; in.imm = imm; in.ureg = udesc; + in.control = CW(4, 5u, SB_RD, (e->pending & (1u << SB_RD))) | CW_YIELD; + e->pending |= 1u << SB_RD; e->held |= 1u << 5; + if (omega_bw_ir_append(e->p, &in) < 0) e->err = -1; +} + +static const uint32_t NEG_BIG = 0xF149F2CAu; /* -1e30f */ + +int omega_fattn256_shape(const OmegaPrefillFattn256Spec *spec, OmegaFattn256Shape *s) { + const uint32_t qh = spec->q_heads ? spec->q_heads : 16u, kvh = spec->kv_heads ? spec->kv_heads : 2u; + if (kvh == 0 || qh % kvh || qh / kvh > 8u) return -1; + s->qh = qh; s->kvh = kvh; s->group = qh / kvh; s->out_words = qh * 256u; s->qf_pair_bytes = qh * 1024u; + return 0; +} + +int omega_fattn256_spec_ok(const OmegaPrefillFattn256Spec *spec) { + OmegaFattn256Shape s; + return spec && spec->mutant >= 0 && spec->mutant <= 2 && spec->variant >= 0 && spec->variant <= 2 && omega_fattn256_shape(spec, &s) == 0; +} + +int omega_blackwell_codegen_prefill_fattn256_prog(const OmegaPrefillFattn256Spec *spec, BlackwellIRProgram *prog) { + if (!omega_fattn256_spec_ok(spec) || !prog) return -1; + omega_bw_ir_init(prog); + if (omega_bw_ir_set_gpr_limit(prog, BW_PHYS_GPR_HW_LIMIT) != 0) return -1; + Em em; memset(&em, 0, sizeof em); em.p = prog; Em *e = &em; + const int MUT = spec->mutant, V2 = spec->variant == 2; + OmegaFattn256Shape SH; + if (omega_fattn256_shape(spec, &SH) != 0) return -1; + + /* ---- arguments and identities; warps past the chunk exit (warp-uniform, before any barrier or shuffle) ---- */ + int udesc = UV64(e); + int pqf = V64(e), pkc = V64(e), pvc = V64(e); + int pos0 = V(e), mc = V(e), kvs = V(e); + int tid = V(e), cx = V(e), cy = V(e), warp = V(e), lane = V(e), one = V(e), zero = V(e); + int t1 = V(e), t2 = V(e), tokA = V(e), cnt = V(e), dqa = V(e), tt2 = V(e); + /* the loop-carried scalars are defined first so the linear-scan allocator packs them below the quads */ + int mA = V(e), mB = V(e), lA = V(e), lB = V(e), gK = V64(e), gV = V64(e); + if (e->err) return -1; + ldcu64(e, udesc, 0x358); + ldc64(e, pqf, OMEGA_FATTN256_ARG_QF); ldc64(e, pkc, OMEGA_FATTN256_ARG_KC); ldc64(e, pvc, OMEGA_FATTN256_ARG_VC); + ldc32(e, pos0, OMEGA_FATTN256_ARG_POS0); ldc32(e, mc, OMEGA_FATTN256_ARG_MC); ldc32(e, kvs, OMEGA_FATTN256_ARG_KV_STRIDE); + s2r(e, tid, BW_SR_TID_X); s2r(e, cx, BW_SR_CTAID_X); s2r(e, cy, BW_SR_CTAID_Y); + movi(e, R(one), 1); movrz(e, R(zero)); + movrz(e, R(t1)); movrz(e, R(t2)); movrz(e, R(cnt)); movrz(e, R(dqa)); movrz(e, R(tt2)); + movi(e, R(mA), NEG_BIG); movi(e, R(mB), NEG_BIG); movrz(e, R(lA)); movrz(e, R(lB)); + imadw(e, gK, zero, 0u, pkc); imadw(e, gV, zero, 0u, pvc); + shr(e, warp, tid, 5); + andi(e, R(lane), R(tid), 31u); + imadi(e, R(t1), R(warp), 2u, NOREG); + imadi(e, R(tokA), R(cx), OMEGA_FATTN256_TOKENS, t1); /* the warp's row-A token */ + isetp_ge_u32(e, tokA, mc); + const int b_exit = bra_if_p0_fwd(e); + + /* ---- Q: 16 A fragments, k-permuted (header), 32 LDG.64 into the fragment halves ---- */ + int q[16]; + for (unsigned s = 0; s < 16; s++) q[s] = V128(e); + int g = V(e), tq = V(e); + if (e->err) return -1; + shr(e, g, lane, 2); andi(e, R(tq), R(lane), 3u); + { + int hg = V(e), c5 = V(e), ad64 = V64(e); if (e->err) return -1; + movi(e, R(c5), SH.group - 1u); + imadi(e, R(t1), R(g), 0xffffffffu, c5); /* group-1 - g */ + shr(e, t2, t1, 31); /* 1 when g > group-1 */ + imadr(e, hg, t2, t1, g); /* min(g, group-1) */ + shr(e, t1, tokA, 1); /* token pair (tokA < mc, so its slot was written) */ + imadi(e, R(t1), R(t1), SH.kvh, cy); imadi(e, R(t1), R(t1), SH.group, hg); imadi(e, R(t1), R(t1), 1024u, NOREG); + shr(e, t2, tq, 1); imadi(e, R(t1), R(t2), 64u, t1); + andi(e, R(t2), R(tq), 1u); imadi(e, R(t1), R(t2), 8u, t1); + imadw(e, ad64, t1, 1u, pqf); + for (unsigned u = 0; u < 8; u++) + for (unsigned j = 0; j < 4; j++) + ldg64s(e, S(q[2u * u + (j >> 1)], (j & 1u) * 2u), ad64, u * 128u + j * 16u, udesc, u == 0 && j == 0); + } + iadd(e, dqa, pos0, tokA); /* row-A position - kb (kb = 0) */ + /* blocks: the warp's last key is row B's position dqa + 1; nblk = (dqa + 1) / 16 + 1 */ + imadi(e, R(t1), R(one), 1u, dqa); shr(e, t1, t1, 4); imadi(e, R(cnt), R(one), 1u, t1); + imadi(e, R(tt2), R(tq), 2u, NOREG); + + /* ---- per-lane cache pointers: K rows kb + g (+ 8), 16 bytes at 16t; V rows kb + 2t (+1, +8, +9), 8 bytes at 64g ---- */ + int o[32], sc[4], kA[1], kB[1], pp, vb[2][4], bf[1][2]; + for (unsigned i = 0; i < 32; i++) o[i] = V128(e); + int zq = V128(e); + kA[0] = V128(e); kB[0] = V128(e); + if (e->err) return -1; + { + int cyk = V(e); if (e->err) return -1; + imadr(e, cyk, cy, kvs, NOREG); /* byte offset of this KV head's plane */ + imadw(e, gK, cyk, 1u, pkc); imadw(e, gK, g, 512u, gK); imadi(e, R(t1), R(tq), 16u, NOREG); imadw(e, gK, t1, 1u, gK); + imadw(e, gV, cyk, 1u, pvc); imadw(e, gV, tq, 1024u, gV); imadi(e, R(t1), R(g), 64u, NOREG); imadw(e, gV, t1, 1u, gV); + } + /* O = 0 through the tensor core (0 x 0 + RZ, 32 instructions instead of 128 moves); zq dies here */ + for (unsigned k = 0; k < 4; k++) movrz(e, S(zq, k)); + for (unsigned i = 0; i < 32; i++) hmma(e, o[i], zq, zq, 0, NOREG, 8); + + int mxA = V(e), mxB = V(e), alA = V(e), alB = V(e), sh = V(e); + for (unsigned j = 0; j < 4; j++) sc[j] = V128(e); + pp = V128(e); + for (unsigned i = 0; i < 2; i++) for (unsigned r = 0; r < 4; r++) vb[i][r] = V64(e); + for (unsigned j = 0; j < 2; j++) bf[0][j] = V128(e); /* rebuilt every step; the step's 4 HMMAs at stall 8 cover the WAR */ + if (e->err) return -1; + + const int L_m = here(e); + loop_begin(e); + /* ---- S = Q K^T: 8 dim groups x (2 key tiles x 2 k-steps), even / odd k-steps into separate accumulators. + * One K quad pair per group (Q 64 + O 128 + S 16 registers leave no room for a second). The other warp of + * the sub-partition (8 warps on 4) covers an L1 hit with its 4 HMMAs; the first touch of a new 128-byte + * line goes to L2 and is not covered (MODELED, DRA-85 PLAN: 45-115 TFLOPS by how much of it shows) ---- */ + for (unsigned u = 0; u < 8; u++) { + ldg_pf(e, BW_IR_LDG_E_128, kA[0], gK, u * 64u, udesc, 3); + ldg_pf(e, BW_IR_LDG_E_128, kB[0], gK, 8u * 512u + u * 64u, udesc, 3); + consume(e, 3); + hmma(e, sc[0], q[2u * u], kA[0], 0, u ? sc[0] : NOREG, 8); + hmma(e, sc[1], q[2u * u], kB[0], 0, u ? sc[1] : NOREG, 8); + hmma(e, sc[2], q[2u * u + 1u], kA[0], 2, u ? sc[2] : NOREG, 8); + hmma(e, sc[3], q[2u * u + 1u], kB[0], 2, u ? sc[3] : NOREG, 8); + } + nop(e, 15); nop(e, 14); + for (unsigned k = 0; k < 4; k++) { fadd(e, S(sc[0], k), S(sc[0], k), S(sc[2], k)); fadd(e, S(sc[1], k), S(sc[1], k), S(sc[3], k)); } + + /* ---- variant 2: the next block's 128-byte K and V lines into L1 while this block's softmax and PV run, so its + * QK^T loads hit L1 instead of a first-touch L2 round trip. Each lane touches rows g, g + 8 of K at lines + * 0..3 (8 LDG.64 from gK; lanes t share a line) and V rows 2t, 2t + 1, 2t + 8, 2t + 9 at line g >> 1 (4 from gV): + * all 64 + 64 lines. The data lands in sc[3], dead from here to the next QK^T (its value is never read); + * scoreboard 5 is held to the loop end. Skipped on the warp's last block (no next block: no rows past it are + * read). Not register-resident K: Q 64 + O 128 + S 16 leave no room for 64 more registers per lane. ---- */ + if (V2) { + static const uint32_t TV[4] = { 0u, 512u, 4096u, 4608u }; + isetp_ge_u32(e, one, cnt); /* cnt <= 1: the last block */ + const int b = bra_if_p0_fwd(e); + for (unsigned i = 0; i < 12; i++) + ldg_touch(e, S(sc[3], (i & 1u) * 2u), i < 8 ? gK : gV, i < 8 ? 16u * 512u + (i >> 2) * 4096u + (i & 3u) * 128u : 16u * 512u + TV[i - 8u], udesc); + patch_bra(e, b, here(e)); + } + + /* ---- causal mask: key kb + 8j + 2t + (k&1) > row position (row A for k < 2, A + 1 for k >= 2) ---- */ + if (MUT != 1) { + imadi(e, R(t1), R(one), 0xfffffff1u, dqa); shr(e, t1, t1, 31); /* 1 when kb + 15 > row-A position */ + isetp_ge_u32(e, zero, t1); + const int b = bra_if_p0_fwd(e); + imadi(e, R(t2), R(tt2), 0xffffffffu, dqa); /* dqa - 2t */ + for (unsigned j = 0; j < 2; j++) for (unsigned k = 0; k < 4; k++) { + int32_t cst = (k >= 2 ? 1 : 0) - 8 * (int32_t)j - (int32_t)(k & 1u); + imadi(e, R(t1), R(one), (uint32_t)cst, t2); shr(e, t1, t1, 31); imadi(e, R(t1), R(t1), NEG_BIG, NOREG); + fadd(e, S(sc[j], k), S(sc[j], k), R(t1)); + } + patch_bra(e, b, here(e)); + } + + /* ---- online softmax (log2 units) ---- */ + fmaxx(e, R(mxA), S(sc[0], 0), S(sc[0], 1)); fmaxx(e, R(mxB), S(sc[0], 2), S(sc[0], 3)); + fmaxx(e, R(mxA), R(mxA), S(sc[1], 0)); fmaxx(e, R(mxA), R(mxA), S(sc[1], 1)); + fmaxx(e, R(mxB), R(mxB), S(sc[1], 2)); fmaxx(e, R(mxB), R(mxB), S(sc[1], 3)); + shfl_bfly(e, sh, mxA, 1); fmaxx(e, R(mxA), R(mxA), R(sh)); shfl_bfly(e, sh, mxA, 2); fmaxx(e, R(mxA), R(mxA), R(sh)); + shfl_bfly(e, sh, mxB, 1); fmaxx(e, R(mxB), R(mxB), R(sh)); shfl_bfly(e, sh, mxB, 2); fmaxx(e, R(mxB), R(mxB), R(sh)); + fmaxx(e, R(mxA), R(mxA), R(mA)); fmaxx(e, R(mxB), R(mxB), R(mB)); + fsub(e, R(alA), R(mA), R(mxA)); fsub(e, R(alB), R(mB), R(mxB)); + mov(e, R(mA), R(mxA)); mov(e, R(mB), R(mxB)); + for (unsigned j = 0; j < 2; j++) for (unsigned k = 0; k < 4; k++) fsub(e, S(sc[j], k), S(sc[j], k), R(k < 2 ? mA : mB)); + mufu(e, BW_IR_MUFU_EX2, R(alA), R(alA), 1); mufu(e, BW_IR_MUFU_EX2, R(alB), R(alB), 0); + for (unsigned j = 0; j < 2; j++) for (unsigned k = 0; k < 4; k++) mufu(e, BW_IR_MUFU_EX2, S(sc[j], k), S(sc[j], k), 0); + fmul(e, R(lA), R(lA), R(alA)); fmul(e, R(lB), R(lB), R(alB)); + for (unsigned j = 0; j < 2; j++) for (unsigned k = 0; k < 4; k++) fadd(e, R(k < 2 ? lA : lB), R(k < 2 ? lA : lB), S(sc[j], k)); + if (MUT != 2) for (unsigned i = 0; i < 32; i++) for (unsigned k = 0; k < 4; k++) fmul(e, S(o[i], k), S(o[i], k), R(k < 2 ? alA : alB)); + f2fp(e, S(pp, 0), S(sc[0], 1), S(sc[0], 0)); f2fp(e, S(pp, 1), S(sc[0], 3), S(sc[0], 2)); + f2fp(e, S(pp, 2), S(sc[1], 1), S(sc[1], 0)); f2fp(e, S(pp, 3), S(sc[1], 3), S(sc[1], 2)); + + /* ---- O += P V: 8 half steps (h, half) x 4 n-tiles; the value rows double-buffered on scoreboards 3/4 ---- + * row r of a step: keys kb + 2t, kb + 2t + 1, kb + 8 + 2t, kb + 9 + 2t (byte offsets 0, 512, 4096, 4608 from gV) */ + static const uint32_t ROWOFF[4] = { 0u, 512u, 4096u, 4608u }; + for (unsigned r = 0; r < 4; r++) ldg_pf(e, BW_IR_LDG_E_64, vb[0][r], gV, ROWOFF[r], udesc, 3); + consume(e, 3); + for (unsigned st = 0; st < 8; st++) { + const unsigned cur = st & 1u, nx = cur ^ 1u, sbn = 3u + nx, h = st >> 1, hq = st & 1u; + if (st < 7) { + const unsigned h2 = (st + 1u) >> 1, q2 = (st + 1u) & 1u; + for (unsigned r = 0; r < 4; r++) ldg_pf(e, BW_IR_LDG_E_64, vb[nx][r], gV, ROWOFF[r] + 16u * h2 + 8u * q2, udesc, sbn); + } + for (unsigned jj = 0; jj < 2; jj++) { + const int f = bf[0][jj]; + /* b0 / b1 of the even n-tile: low halves (dim 2w) of the key pairs; odd n-tile: the high halves */ + andi(e, R(t1), S(vb[cur][0], jj), 0xffffu); imadi(e, S(f, 0), S(vb[cur][1], jj), 65536u, t1); + andi(e, R(t1), S(vb[cur][2], jj), 0xffffu); imadi(e, S(f, 1), S(vb[cur][3], jj), 65536u, t1); + shrs(e, t1, S(vb[cur][0], jj), 16); andi(e, R(t2), S(vb[cur][1], jj), 0xffff0000u); fop(e, BW_IR_IADD3, S(f, 2), R(t1), R(t2), R(NOREG)); + shrs(e, t1, S(vb[cur][2], jj), 16); andi(e, R(t2), S(vb[cur][3], jj), 0xffff0000u); fop(e, BW_IR_IADD3, S(f, 3), R(t1), R(t2), R(NOREG)); + } + for (unsigned jj = 0; jj < 2; jj++) { + const unsigned n = 8u * h + 4u * hq + 2u * jj; + hmma(e, o[n], pp, bf[0][jj], 0, o[n], 8); hmma(e, o[n + 1u], pp, bf[0][jj], 2, o[n + 1u], 8); + } + if (st < 7) consume(e, sbn); + } + if (V2) { consume(e, 5); imadi(e, S(sc[3], 0), S(sc[3], 0), 1u, NOREG); } /* the touches landed; keeps sc[3] live to here */ + imadw(e, gK, one, 16u * 512u, gK); imadw(e, gV, one, 16u * 512u, gV); + imadi(e, R(dqa), R(one), 0xfffffff0u, dqa); + imadi(e, R(cnt), R(one), 0xffffffffu, cnt); + isetp_ge_u32(e, cnt, one); + bra_if_p0(e, L_m); + loop_end(e); + + /* ---- epilogue: rows g < group (lane-divergent only when group < 8), row B only when tokA + 1 < mc ---- */ + nop(e, 15); nop(e, 14); + { + int pout = V64(e), osc = V(e), ostr = V(e), po = V64(e), po2 = V64(e), eg = V(e), etq = V(e), etid = V(e), ecx = V(e), ecy = V(e), emc = V(e); + int ewarp = V(e), elane = V(e), etok = V(e), cg = V(e); + if (e->err) return -1; + ldc64(e, pout, OMEGA_FATTN256_ARG_OUT); ldc32(e, osc, OMEGA_FATTN256_ARG_OUT_SCALE); ldc32(e, emc, OMEGA_FATTN256_ARG_MC); + ldc32(e, ostr, OMEGA_FATTN256_ARG_OSTRIDE); + s2r(e, etid, BW_SR_TID_X); s2r(e, ecx, BW_SR_CTAID_X); s2r(e, ecy, BW_SR_CTAID_Y); + shr(e, ewarp, etid, 5); andi(e, R(elane), R(etid), 31u); + imadi(e, R(t1), R(ewarp), 2u, NOREG); imadi(e, R(etok), R(ecx), OMEGA_FATTN256_TOKENS, t1); + shfl_bfly(e, sh, lA, 1); fadd(e, R(lA), R(lA), R(sh)); shfl_bfly(e, sh, lA, 2); fadd(e, R(lA), R(lA), R(sh)); + shfl_bfly(e, sh, lB, 1); fadd(e, R(lB), R(lB), R(sh)); shfl_bfly(e, sh, lB, 2); fadd(e, R(lB), R(lB), R(sh)); + mufu(e, BW_IR_MUFU_RCP, R(lA), R(lA), 1); mufu(e, BW_IR_MUFU_RCP, R(lB), R(lB), 0); + fmul(e, R(lA), R(lA), R(osc)); fmul(e, R(lB), R(lB), R(osc)); + for (unsigned i = 0; i < 32; i++) for (unsigned k = 0; k < 4; k++) fmul(e, S(o[i], k), S(o[i], k), R(k < 2 ? lA : lB)); + /* out + etok * ostride + ((cy * group + g) * 256 + 64t) * 4; row B one ostride further */ + shr(e, eg, elane, 2); andi(e, R(etq), R(elane), 3u); + imadr(e, t1, etok, ostr, NOREG); imadw(e, po, t1, 1u, pout); + imadi(e, R(t1), R(ecy), SH.group, eg); imadi(e, R(t1), R(t1), 1024u, NOREG); imadi(e, R(t1), R(etq), 256u, t1); + imadw(e, po, t1, 1u, po); + imadw(e, po2, ostr, 1u, po); + movi(e, R(cg), SH.group); + isetp_ge_u32(e, eg, cg); + Region rg = region_skip_if_p0(e); + for (unsigned row = 0; row < 2; row++) { + int b = -1; + if (row) { imadi(e, R(t1), R(one), 1u, etok); isetp_ge_u32(e, t1, emc); b = bra_if_p0_fwd(e); } + for (unsigned i = 0; i < 32; i++) { + stg(e, row ? po2 : po, i * 4u, S(o[i], 2u * row), udesc); + stg(e, row ? po2 : po, (32u + i) * 4u, S(o[i], 2u * row + 1u), udesc); + } + if (row) patch_bra(e, b, here(e)); + } + region_end(e, rg); + } + patch_bra(e, b_exit, here(e)); + tail(e); + if (e->err) return -1; + if (omega_bw_regalloc_solve(prog) != 0) return -1; + return 0; +} + +int omega_prefill_fattn256_prog_stats(const OmegaPrefillFattn256Spec *spec, uint32_t *insns, uint32_t *gprs, uint32_t *placeholders) { + static BlackwellIRProgram p; + if (omega_blackwell_codegen_prefill_fattn256_prog(spec, &p) != 0) return -1; + if (insns) *insns = (uint32_t)p.count; + if (gprs) *gprs = p.regalloc.peak_gpr_usage; + if (placeholders) { + uint32_t n = 0; + for (size_t i = 0; i < p.count; i++) { + const BlackwellIRInsn *in = &p.insns[i]; + if ((in->op == BW_IR_SHFL_DOWN && (in->imm & OMEGA_TC_MARK_BFLY)) || (in->op == BW_IR_FMNMX_MAX && in->imm == OMEGA_TC_MARK_F2FP)) n++; + } + *placeholders = n; + } + return 0; +} diff --git a/src/omega_blackwell_codegen_fattn256.h b/src/omega_blackwell_codegen_fattn256.h new file mode 100644 index 00000000..6d9d4b35 --- /dev/null +++ b/src/omega_blackwell_codegen_fattn256.h @@ -0,0 +1,92 @@ +/* SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception */ +#ifndef OMEGA_BLACKWELL_CODEGEN_FATTN256_H +#define OMEGA_BLACKWELL_CODEGEN_FATTN256_H +/* + * omega_blackwell_codegen_fattn256: flash-style causal prefill attention on tensor cores for the head_dim 256 + * full-attention layers, one warp per 16-row tile (Linear DRA-85, P-DRA-4 Lane P, 2026-11-01). Target shape: + * Qwen3.6-35B-A3B (16 query heads over 2 KV heads, 8 per KV head: every tile row is a real head); the 27B shape + * (24 / 4, 6 per KV head) also builds, with rows 6, 7 repeating head 5 and never stored, as in pattn256. + * + * The attend launch of omega_gpu_prefill_fattn256_api.h. It reads the same inputs as pattn256's attend + * (omega_blackwell_codegen_pattn256.h): q' in the QF A-fragment layout written by the decode kernel's prep mode, and + * the decode attention's K / V cache planes. What differs is the work split: + * + * pattn256 grid (ceil(m / 8), kvh), 8 tokens per CTA, two warps per row tile (each owns 128 output dims and both + * compute the tile's full S), K and V staged through 16 KiB of shared memory with two CTA barriers per + * 16-key block, every warp walking to the CTA's last key. + * fattn256 grid (ceil(m / 16), kvh), 16 tokens per CTA, ONE warp per row tile owning all 256 output dims (O = 32 + * accumulator fragments = 128 registers, Q = 16 A fragments = 64 registers, both resident), no shared + * memory and no barriers: each lane loads its B fragments straight from the cache rows (LDG.128 / LDG.64 + * through L1; the 8 warps of a CTA and the CTAs of a KV head read the same rows), and each warp stops at its + * own last key (causal work per warp, not per CTA). Warps whose first token is past m exit at once. + * + * Tile of warp w in CTA (cx, cy): rows g = 0..7 = token tokA = cx*16 + 2w, head cy*group + min(g, group-1); rows + * g + 8 = token tokA + 1, same heads. Lane (g, t), t = lane & 3. + * + * S = Q K^T with a k-permutation: the 256 head dims are visited as 8 groups of 32 (u = 0..7); lane (g, t) loads 16 + * bytes = words 16u+4t .. 16u+4t+3 of key rows kb + g and kb + 8 + g (one LDG.128 each). k-step 2u takes words + * 16u+4t (b0) and 16u+4t+1 (b1), k-step 2u+1 words +2 (b0) and +3 (b1). Q's A fragments are loaded once with the same + * permutation from QF: k-step 2u register pair {a0, a1} (j even) or {a2, a3} (j odd) for word 16u+4t+j is the 8-byte + * {tokA, tokA+1} pair at QF_OFF_SHAPE(tp, c, g, 2u + (t >> 1), j) + (t & 1) * 8 (one LDG.64 each, 32 per lane). The + * dot product is a sum over dims, so the permutation (the same on both sides) does not change S. + * + * O = P V with a column permutation: n-tile i (0..31), fragment column n holds output dim 32n + i. For each half + * step (h = 0..3, half q = 0, 1) lane (g, t) loads 8 bytes at byte 64g + 16h + 8q of value rows kb + 2t, kb + 2t + 1, + * kb + 8 + 2t, kb + 9 + 2t (dims 32g + 8h + 4q .. +3) and packs the key pairs (low half = lower key) into the B + * fragments of n-tiles 8h + 4q + {0, 1, 2, 3}. Accumulator element c0, c1 of n-tile i is (row g, dims 64t + i, + * 64t + 32 + i); c2, c3 the same dims of row g + 8. + * + * Softmax, causal mask and P packing are pattn256's: scores already carry log2(e) / 16 (the prep's qk_scale), keys + * kb + 8j + 2t + (k & 1) above the row position get -1e30 (the whole block is skipped when kb + 15 <= row A's + * position), running max per row over the quad (SHFL.BFLY 1, 2), alpha = EX2(m_old - m_new), P to bf16 (F2FP), + * l summed from the unrounded p. Epilogue: l over the quad, out = O * RCP(l) * out_scale. + * + * Keys past the warp's last key in its last block are read (rows the prompt has not reached, or the plane slack) and + * masked, as in pattn256: the cache is zero at allocation and only ever holds finite K/V rows, so 0 * row stays 0. + * The tile of an odd m's last pair reads tokA + 1's QF slot, which the prep never wrote: rows g + 8 of that tile may + * be anything (NaN included); HMMA rows are independent and those rows are never stored. + * Registers: the program opts into BW_PHYS_GPR_HW_LIMIT; 256 threads x the declared count must stay <= 65536. + * Variant 2 (spec.variant = 2, AIEN_OMEGA_Q36_PF_FATTN=2): after a block's QK^T each lane issues 12 LDG.64 touches of + * the next 16-key block (K rows g, g + 8 at their 4 lines, V rows 2t, 2t + 1, 2t + 8, 2t + 9 at line g >> 1: every + * 128-byte line of both 8 KiB blocks) into the dead S quad on held scoreboard 5, waited at the loop end, so the next + * QK^T loads find their lines in L1 rather than paying a first-touch L2 round trip (DRA-85 PLAN model C). It moves + * lines into L1, not K into registers (no room beside Q / O / S). Skipped on the warp's last block. Variants 0 and 1 + * are the same kernel, byte for byte the kernel before variant 2 existed. + * The host simulator (tests/bw_warp_sim_pa.h) runs it; a simulator pass is never a chip result. + */ +#include "omega_blackwell_codegen.h" +#include + +#define OMEGA_FATTN256_WARPS 8u +#define OMEGA_FATTN256_THREADS 256u +#define OMEGA_FATTN256_TOKENS 16u /* tokens per CTA: 8 warps x a token pair */ +#define OMEGA_FATTN256_KEYS 16u /* keys per main-loop block */ +#define OMEGA_FATTN256_SHARED_BYTES 0u + +/* constant bank 0 at 0x380 */ +#define OMEGA_FATTN256_ARG_QF 0x380u /* bf16 QF (OMEGA_PATTN256_QF_OFF_SHAPE layout), ceil(m / 2) token pairs */ +#define OMEGA_FATTN256_ARG_KC 0x388u /* bf16 K plane base of the layer [kv_head][max_pos][256] */ +#define OMEGA_FATTN256_ARG_VC 0x390u /* bf16 V plane base */ +#define OMEGA_FATTN256_ARG_OUT 0x398u /* f32 rows, head h at h * 256 (model dim order) */ +#define OMEGA_FATTN256_ARG_POS0 0x3a0u /* u32 position of chunk token 0 */ +#define OMEGA_FATTN256_ARG_MC 0x3a4u /* u32 tokens, >= 1 */ +#define OMEGA_FATTN256_ARG_KV_STRIDE 0x3a8u /* u32 bytes per KV head plane (max_pos * 512) */ +#define OMEGA_FATTN256_ARG_OUT_SCALE 0x3acu /* f32 */ +#define OMEGA_FATTN256_ARG_OSTRIDE 0x3b0u /* u32 bytes between output rows (>= q_heads * 1024) */ +#define OMEGA_FATTN256_ARGS_WORDS 13u + +typedef struct { + int mutant; /* TEST ONLY. 0 none; 1 no causal mask; 2 O is never rescaled by alpha. Each must be caught. */ + uint32_t q_heads, kv_heads; /* 0, 0 = Qwen3.6-35B-A3B (16, 2). q_heads / kv_heads must be 1..8 (grid y = kv_heads). */ + int variant; /* 0 or 1: the base kernel; 2: next-block L1 touch prefetch (see above). Others refused. */ +} OmegaPrefillFattn256Spec; + +typedef struct { uint32_t qh, kvh, group, out_words, qf_pair_bytes; } OmegaFattn256Shape; +int omega_fattn256_shape(const OmegaPrefillFattn256Spec *spec, OmegaFattn256Shape *s); +int omega_fattn256_spec_ok(const OmegaPrefillFattn256Spec *spec); +/* Builds the register-allocated IR program. 0 ok, -1 refused or over BW_MAX_IR_INSNS / BW_MAX_VREGS / the registers. */ +int omega_blackwell_codegen_prefill_fattn256_prog(const OmegaPrefillFattn256Spec *spec, BlackwellIRProgram *prog); +/* Instruction, peak-register and placeholder counts (host, no device). */ +int omega_prefill_fattn256_prog_stats(const OmegaPrefillFattn256Spec *spec, uint32_t *insns, uint32_t *gprs, uint32_t *placeholders); + +#endif diff --git a/src/omega_blackwell_codegen_qg.c b/src/omega_blackwell_codegen_qg.c index 1455f9f9..a6471b00 100644 --- a/src/omega_blackwell_codegen_qg.c +++ b/src/omega_blackwell_codegen_qg.c @@ -14,12 +14,13 @@ static void fmax_r(Em *e, int d, int a, unsigned asub, int b, unsigned bsub) { int omega_pq_spec_ok(const OmegaPqSpec *s) { if (!s || s->k < 128u || s->k > 32768u || s->k % 128u) return 0; const uint32_t kb = s->k / 128u, g = s->groups ? s->groups : kb; + if (s->stride && (s->stride < s->k || s->stride % 4u || s->stride > (1u << 24))) return 0; return g <= 32u && kb % g == 0 && s->in_type <= OMEGA_QG_IN_BF16 && s->mutant >= 0 && s->mutant <= 3; } int omega_blackwell_codegen_pq_prog(const OmegaPqSpec *spec, BlackwellIRProgram *prog) { if (!omega_pq_spec_ok(spec) || !prog) return -1; - const uint32_t K = spec->k, KB = K / 128u; + const uint32_t K = spec->k, KB = K / 128u, XS = spec->stride ? spec->stride : K; omega_bw_ir_init(prog); Em em; memset(&em, 0, sizeof em); em.p = prog; Em *e = &em; int udesc = UV64(e), px = V64(e), pq = V64(e), ps = V64(e), tid = V(e), row = V(e), warp = V(e); @@ -33,8 +34,8 @@ int omega_blackwell_codegen_pq_prog(const OmegaPqSpec *spec, BlackwellIRProgram s2r(e, cy, BW_SR_CTAID_Y); if (spec->mutant != 3) imadi(e, tid, cy, 0, 32u * spec->groups, tid); } shr(e, warp, tid, 0, 5); - if (spec->in_type == OMEGA_QG_IN_F32) { imadw(e, px, row, K * 4u, px); imadw(e, px, tid, 16u, px); ldg_wide(e, BW_IR_LDG_E_128, v, px, 0, udesc, 1); } - else { imadw(e, px, row, K * 2u, px); imadw(e, px, tid, 8u, px); ldg_wide(e, BW_IR_LDG_E_64, w, px, 0, udesc, 1); } + if (spec->in_type == OMEGA_QG_IN_F32) { imadw(e, px, row, XS * 4u, px); imadw(e, px, tid, 16u, px); ldg_wide(e, BW_IR_LDG_E_128, v, px, 0, udesc, 1); } + else { imadw(e, px, row, XS * 2u, px); imadw(e, px, tid, 8u, px); ldg_wide(e, BW_IR_LDG_E_64, w, px, 0, udesc, 1); } imadw(e, pq, row, K, pq); imadw(e, pq, tid, 4u, pq); imadw(e, ps, row, KB * 4u, ps); imadw(e, ps, warp, 4u, ps); movi(e, fl, 0x0d800000u); /* 2^-100 */ @@ -79,6 +80,7 @@ int omega_qg_spec_ok(const OmegaQgSpec *s) { if (s->n == 0 || s->n % (s->warps * 16u) || (uint64_t)(s->epi == OMEGA_QG_EPI_F32 ? 4u : 1u) * s->n * 16u * s->rt >= (1u << 23)) return 0; /* row stride (n f32, or n / 2 bf16 = n bytes) x 16 rt: the store offsets fit the signed 24-bit field */ if ((16u * s->rt * 4u) % (32u * s->warps)) return 0; /* whole 16-byte staging slots per thread */ if (s->mutant < 0 || s->mutant > 4) return 0; + if (s->ymap > 1u || s->x64 > 1u || (s->ymap && s->epi != OMEGA_QG_EPI_F32)) return 0; return 1; } uint32_t omega_qg_shared_bytes(const OmegaQgSpec *s) { return omega_qg_spec_ok(s) ? 2u * (16u * s->rt * 64u + 16u * s->rt * 4u) : 0u; } @@ -152,7 +154,8 @@ int omega_blackwell_codegen_qgemm_prog(const OmegaQgSpec *spec, BlackwellIRProgr for (uint32_t jj = 0; jj < NJ; jj++) { stgr[jj] = V128(e); scv[jj] = V(e); } if (e->err) return -1; movi(e, onef1, 0x3f800000u); - movi(e, c2m56, 0x23800000u); /* 2^-56: undoes the GEMV tensor's scale fold exactly (sw * 2^-56 is the checkpoint bf16 scale) */ + movi(e, c2m56, spec->x64 ? 0x03800000u : 0x23800000u); /* 2^-56 undoes the GEMV tensor's scale fold exactly (sw * 2^-56 is the + checkpoint bf16 scale); x64 also removes the activations' 2^64: 2^-120 */ #define ISSUE(wset, sb, xoff, woff, with_scale) do { \ for (uint32_t jj = 0; jj < NJ; jj++) { ldw_pf(e, BW_IR_LDG_E_128, stgr[jj], gx[jj], (xoff), udesc, (sb)); ldw_pf(e, BW_IR_LDG_E, scv[jj], gs[jj], 0u, udesc, (sb)); } \ @@ -216,6 +219,8 @@ int omega_blackwell_codegen_qgemm_prog(const OmegaQgSpec *spec, BlackwellIRProgr /* ---- epilogue (as omega_blackwell_codegen_tc2.c, natural SwiGLU order, no extra scale) ---- */ int g2 = V(e), cnt2 = V(e), rrow = V(e), onee = V(e), pyr = V64(e); + int pym = spec->ymap ? V64(e) : NOREG, colb = spec->ymap ? V(e) : NOREG, py0 = spec->ymap ? V64(e) : NOREG, ysx = spec->ymap ? V64(e) : NOREG; + int yrow = spec->ymap ? V(e) : NOREG, r0y = spec->ymap ? V(e) : NOREG, n2y = spec->ymap ? V(e) : NOREG; { int tid2 = V(e), cx2 = V(e), cy2 = V(e), lane2 = V(e), tq3 = V(e), tab2 = V64(e), ten2 = V64(e), rc2 = V64(e), py2 = V64(e), n2 = V(e), nw2 = V(e), r02 = V(e); if (e->err) return -1; @@ -226,7 +231,10 @@ int omega_blackwell_codegen_qgemm_prog(const OmegaQgSpec *spec, BlackwellIRProgr andi(e, lane2, tid2, 0, 31); shr(e, g2, lane2, 0, 2); andi(e, tq3, lane2, 0, 3); imadi(e, r02, rc2, 0, 1, NOREG); imadi(e, cnt2, rc2, 1, 1, NOREG); movi(e, onee, 1); shr(e, tmp, tid2, 0, 5); imadi(e, tmp, tmp, 0, 16u, NOREG); imadi(e, nw2, cx2, 0, SPAN, tmp); - if (spec->epi == OMEGA_QG_EPI_F32) { + if (spec->ymap) { /* DRA-82: row r goes to y row ymap[row0 + r]; the column part is shared by every row */ + ldc64(e, pym, 0x3b0); imadi(e, tmp2, tq3, 0, 2u, nw2); imadi(e, colb, tmp2, 0, 1u, NOREG); + imadw(e, py0, onee, 0, py2); imadi(e, r0y, r02, 0, 1u, NOREG); imadi(e, n2y, n2, 0, 1u, NOREG); + } else if (spec->epi == OMEGA_QG_EPI_F32) { iadd(e, tmp, r02, g2); imadr(e, tmp, tmp, n2, nw2); imadi(e, tmp2, tq3, 0, 2u, NOREG); iadd(e, tmp, tmp, tmp2); imadw(e, pyr, tmp, 4u, py2); } else { iadd(e, tmp, r02, g2); imadr(e, tmp, tmp, n2, NOREG); imadw(e, pyr, tmp, 1u, py2); @@ -245,10 +253,14 @@ int omega_blackwell_codegen_qgemm_prog(const OmegaQgSpec *spec, BlackwellIRProgr int skips[16]; uint32_t nskip = 0; const int at_bssy = bssy_fwd(e); for (uint32_t i = 0; i < RT; i++) for (uint32_t h = 0; h < 2; h++) { - const uint32_t roff = (16u * i + 8u * h) * ystride; + const uint32_t roff = spec->ymap ? 0u : (16u * i + 8u * h) * ystride; imadi(e, rrow, onee, 0, 16u * i + 8u * h, g2); isetp_ge_u32(e, rrow, cnt2); skips[nskip++] = bra_if_p0_fwd(e); + if (spec->ymap) { + iadd(e, yrow, r0y, rrow); imadw(e, ysx, yrow, 4u, pym); ldg32(e, yrow, ysx, udesc, 1); + imadr(e, yrow, yrow, n2y, colb); imadw(e, pyr, yrow, 4u, py0); + } if (spec->epi == OMEGA_QG_EPI_F32) { for (uint32_t j = 0; j < 2; j++) for (unsigned q = 0; q < 2; q++) { BlackwellIRInsn st = I0(BW_IR_STG_E); st.src1_vreg = pyr; st.src2_vreg = acc[i * 2 + j]; st.src2_subreg = (uint8_t)(2u * h + q); st.imm = roff + j * 32u + 4u * q; st.ureg = udesc; emit(e, st, K_STORE); } } else { diff --git a/src/omega_blackwell_codegen_qg.h b/src/omega_blackwell_codegen_qg.h index 55202831..35a95d1a 100644 --- a/src/omega_blackwell_codegen_qg.h +++ b/src/omega_blackwell_codegen_qg.h @@ -19,6 +19,8 @@ * CTA y covers groups yG .. yG+G-1 (thread index offset by 32 G y). groups 0 is the one-CTA form (programs unchanged). * Arguments (cbank 0x380): x u64, q u64, s u64. * mutant (tests only): 1 skips the butterfly (lane-local amax), 2 uses c = 0, 3 drops the ctaid.y offset (groups form). + * stride (DRA-82): input row stride in elements, 0 = k (programs unchanged); a nonzero stride (>= k, multiple of 4) lets + * the quantiser read rows of a wider buffer in place (the q36 router rows, lb_stride / 4). q and s stay dense. */ #include #include "omega_blackwell_codegen.h" @@ -27,7 +29,7 @@ extern "C" { #endif enum { OMEGA_QG_IN_F32 = 0, OMEGA_QG_IN_BF16 = 1 }; -typedef struct { uint32_t k, in_type; int mutant; uint32_t groups; } OmegaPqSpec; +typedef struct { uint32_t k, in_type; int mutant; uint32_t groups; uint32_t stride; } OmegaPqSpec; #define OMEGA_PQ_ARGS_WORDS 6u int omega_pq_spec_ok(const OmegaPqSpec *s); int omega_blackwell_codegen_pq_prog(const OmegaPqSpec *s, BlackwellIRProgram *prog); @@ -47,7 +49,12 @@ int omega_blackwell_codegen_pq_prog(const OmegaPqSpec *s, BlackwellIRProgram *pr * Constant bank 0x380: tiles, rowidx (ignored when direct), xq, y, xs (u64 each), n u32 at 0x3a8. * Grid: n / (warps * 16) x tiles; 32 * warps threads; shared 2 * (16 rt * 64 + 16 rt * 4) bytes. * mutant (tests only): 1 drops sa (uses sw only), 2 never advances the sw pointer, 3 row tile i reads tile i^1, 4 drops step 1 - * of every odd chunk. */ + * of every odd chunk. + * DRA-82 (each 0 = programs unchanged): + * ymap 1 (F32 only): row r of a tile is stored to y row ymap[row0 + r] (u32 table, u64 pointer at cbank 0x3b0; + * OMEGA_QG_ARGS_WORDS_YMAP argument words), read only for rows below cnt. Without ymap y row = row0 + r. + * x64 1: the activations carry an extra 2^64 (the q36 graph's x' and act rows): the scale fold uses 2^-120 instead of + * 2^-56, so y is the true product; exact, since 2^64 moves only exponents of the power-of-two pq scales. */ enum { OMEGA_QG_EPI_F32 = 0, OMEGA_QG_EPI_SWIGLU = 1 }; typedef struct { uint32_t k; /* multiple of 128, 128 .. 32768 */ @@ -58,8 +65,11 @@ typedef struct { uint32_t n; /* output width (weight rows), multiple of warps * 16 */ uint32_t wait; /* stall cycles between a row tile's last QMMA and the first FFMA reading its result */ int mutant; + uint32_t ymap; /* DRA-82: 1 scatters rows through the y map (F32 only) */ + uint32_t x64; /* DRA-82: 1 removes a 2^64 activation scale in the fold */ } OmegaQgSpec; #define OMEGA_QG_ARGS_WORDS 11u +#define OMEGA_QG_ARGS_WORDS_YMAP 14u #define OMEGA_QG_TILE_BYTES 32u int omega_qg_spec_ok(const OmegaQgSpec *s); uint32_t omega_qg_shared_bytes(const OmegaQgSpec *s); diff --git a/src/omega_gpu_pfq_api.c b/src/omega_gpu_pfq_api.c new file mode 100644 index 00000000..9117354c --- /dev/null +++ b/src/omega_gpu_pfq_api.c @@ -0,0 +1,141 @@ +/* SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception */ +/* omega_gpu_pfq_api.c: tiled mma.sync (QMMA) FP8 path for prefill expert GEMMs (DRA-82). See the header. */ +#include "omega_gpu_pfq_api.h" +#include "omega_gpu_prefill.h" +#include "omega_gpu_cmdlist.h" +#include +#include + +_Static_assert(sizeof(OmegaPfqTile) == OMEGA_QG_TILE_BYTES, "tile entry = the q36 graph's segment entry"); +_Static_assert(sizeof(OmegaQgSpec) <= sizeof(((OmegaPfKey *)0)->words), "gemm spec fits the kernel key"); +_Static_assert(sizeof(OmegaPqSpec) <= sizeof(((OmegaPfKey *)0)->words), "quant spec fits the kernel key"); + +static int mutant = -1; +int omega_gpu_pfq_mutant(void) { + if (mutant < 0) { + const char *v = getenv("AIEN_OMEGA_PFQ_MUTANT"); + const long m = v && *v ? strtol(v, NULL, 10) : 0; + mutant = m >= 1 && m <= 4 ? (int)m : 0; + } + return mutant; +} +void omega_gpu_pfq_test_set_mutant(int m) { mutant = m >= 1 && m <= 4 ? m : 0; } + +static uint32_t pfq_wait(void) { + static int w = -1; + if (w < 0) { + const char *v = getenv("AIEN_OMEGA_PFQ_WAIT"); + const long x = v && *v ? strtol(v, NULL, 10) : 45; + w = x >= 0 && x <= 120 ? (int)x : 45; /* 45 cycles: the chip-safe QMMA read distance (evidence OWN30B-L1G-QMMA-PFGEMM-c742aa13) */ + } + return (uint32_t)w; +} + +uint32_t omega_pfq_tile_cap(uint32_t rows, uint32_t segs) { return segs + rows / OMEGA_PFQ_BM; } + +uint32_t omega_pfq_tiles(const OmegaPfqTile *segs, uint32_t nsegs, OmegaPfqTile *tiles, uint32_t cap) { + if (!segs || !tiles) return 0; + const uint32_t skew = omega_gpu_pfq_mutant() == 1 ? 1u : 0u; + uint32_t nt = 0; + for (uint32_t i = 0; i < nsegs; i++) { + const OmegaPfqTile *s = &segs[i]; + for (uint32_t r = 0; r < s->cnt; r += OMEGA_PFQ_BM) { + if (nt >= cap) return 0; + tiles[nt].w_va = s->w_va; tiles[nt].s_va = s->s_va; + tiles[nt].row0 = s->row0 + r - (r ? skew : 0u); + tiles[nt].cnt = s->cnt - r < OMEGA_PFQ_BM ? s->cnt - r : OMEGA_PFQ_BM; + tiles[nt].pad = 0; nt++; + } + } + return nt; +} + +static void put64(uint32_t *a, uint64_t v) { a[0] = (uint32_t)v; a[1] = (uint32_t)(v >> 32); } + +int omega_pfq_quant_plan(const OmegaPfqQuant *q, OmegaPqSpec *spec, OmegaPfqLaunch *L) { + if (!q || !spec || !L || !q->x_va || !q->q_va || !q->s_va) return OMEGA_GPU_PF_BAD_ARGS; + memset(spec, 0, sizeof *spec); memset(L, 0, sizeof *L); + spec->k = q->k; spec->in_type = OMEGA_QG_IN_F32; spec->stride = q->stride; + spec->mutant = omega_gpu_pfq_mutant() == 4 ? 2 : 0; + const uint32_t kb = q->k / 128u; + if (q->k % 128u == 0 && kb > 32u) for (spec->groups = 32u; kb % spec->groups; spec->groups--) {} /* wide row: split over ctaid.y */ + if (!omega_pq_spec_ok(spec)) return OMEGA_GPU_PF_BAD_ARGS; + if (q->rows > 0x7fffffffu) return OMEGA_GPU_PF_TOO_LARGE; + L->threads = 32u * (spec->groups ? spec->groups : kb); + L->grid_x = q->rows; L->grid_y = spec->groups ? kb / spec->groups : 1u; + L->nargs = OMEGA_PQ_ARGS_WORDS; + put64(&L->args[0], q->x_va); put64(&L->args[2], q->q_va); put64(&L->args[4], q->s_va); + return OMEGA_GPU_PF_OK; +} + +int omega_pfq_gemm_plan(const OmegaPfqGemm *c, OmegaQgSpec *spec, OmegaPfqLaunch *L) { + if (!c || !spec || !L || !c->tiles_va || !c->xq_va || !c->xs_va || !c->y_va || c->x64 > 1u) return OMEGA_GPU_PF_BAD_ARGS; + memset(spec, 0, sizeof *spec); memset(L, 0, sizeof *L); + const int m = omega_gpu_pfq_mutant(); + spec->k = c->k; spec->rt = 4u; spec->warps = 8u; spec->wait = pfq_wait(); spec->epi = OMEGA_QG_EPI_F32; + spec->direct = c->rowidx_va == 0; spec->n = c->n; spec->mutant = m == 2 || m == 3 ? m : 0; + spec->ymap = c->ymap_va != 0; spec->x64 = c->x64; + if (!omega_qg_spec_ok(spec)) return OMEGA_GPU_PF_BAD_ARGS; + if (c->ntiles > 65535u) return OMEGA_GPU_PF_TOO_LARGE; + L->threads = 32u * spec->warps; L->grid_x = c->n / omega_qg_span(spec); L->grid_y = c->ntiles; + L->shared = omega_qg_shared_bytes(spec); + const uint64_t va[5] = { c->tiles_va, c->rowidx_va, c->xq_va, c->y_va, c->xs_va }; + for (int i = 0; i < 5; i++) put64(&L->args[2 * i], va[i]); + L->args[10] = c->n; + if (spec->ymap) { put64(&L->args[12], c->ymap_va); L->nargs = OMEGA_QG_ARGS_WORDS_YMAP; } + else L->nargs = OMEGA_QG_ARGS_WORDS; + return OMEGA_GPU_PF_OK; +} + +static int gen_quant(const OmegaPfKey *key, void *prog) { OmegaPqSpec s; memcpy(&s, key->words, sizeof s); return omega_blackwell_codegen_pq_prog(&s, prog); } +static int gen_gemm(const OmegaPfKey *key, void *prog) { OmegaQgSpec s; memcpy(&s, key->words, sizeof s); return omega_blackwell_codegen_qgemm_prog(&s, prog); } + +/* cl NULL: generate and upload only (the prepare calls) */ +static int run_locked(OmegaGpuCmdList *cl, uint32_t kind, const void *spec, size_t spec_bytes, OmegaPfGen gen, const OmegaPfqLaunch *L) { + OmegaPfKey key; memset(&key, 0, sizeof key); key.kind = kind; memcpy(key.words, spec, spec_bytes); + int rc = omega_gpu_pf_open_locked(); + OmegaPfKernel kern; + if (rc == OMEGA_GPU_PF_OK) rc = omega_gpu_pf_kernel_locked(&key, gen, &kern); + if (rc == OMEGA_GPU_PF_OK && cl && L->grid_x && L->grid_y) + rc = omega_gpu_pf_record_locked(cl, &kern, L->threads, L->grid_x, L->grid_y, L->shared, L->args, L->nargs); + return rc; +} + +int omega_gpu_pfq_quant_record_locked(OmegaGpuCmdList *cl, const OmegaPfqQuant *q) { + if (!cl) return OMEGA_GPU_PF_BAD_ARGS; + OmegaPqSpec s; OmegaPfqLaunch L; + int rc = omega_pfq_quant_plan(q, &s, &L); + if (rc != OMEGA_GPU_PF_OK || q->rows == 0) return rc; + return run_locked(cl, OMEGA_PFQ_KIND_QUANT, &s, sizeof s, gen_quant, &L); +} + +int omega_gpu_pfq_gemm_record_locked(OmegaGpuCmdList *cl, const OmegaPfqGemm *c) { + if (!cl) return OMEGA_GPU_PF_BAD_ARGS; + OmegaQgSpec s; OmegaPfqLaunch L; + int rc = omega_pfq_gemm_plan(c, &s, &L); + if (rc != OMEGA_GPU_PF_OK || c->ntiles == 0) return rc; + return run_locked(cl, OMEGA_PFQ_KIND_GEMM, &s, sizeof s, gen_gemm, &L); +} + +int omega_gpu_pfq_quant_prepare(uint32_t k, uint32_t stride) { + const OmegaPfqQuant q = { .k = k, .rows = 0, .stride = stride, .x_va = 1, .q_va = 1, .s_va = 1 }; + OmegaPqSpec s; OmegaPfqLaunch L; + int rc = omega_pfq_quant_plan(&q, &s, &L); + if (rc != OMEGA_GPU_PF_OK) return rc; + omega_gpu_session_lock(); + rc = run_locked(NULL, OMEGA_PFQ_KIND_QUANT, &s, sizeof s, gen_quant, &L); + omega_gpu_session_unlock(); + return rc; +} + +int omega_gpu_pfq_gemm_prepare(uint32_t n, uint32_t k, uint32_t x64, int indexed, int ymap) { + const OmegaPfqGemm c = { .n = n, .k = k, .x64 = x64, .ntiles = 0, .tiles_va = 1, .rowidx_va = indexed ? 1u : 0u, .xq_va = 1, + .xs_va = 1, .ymap_va = ymap ? 1u : 0u, .y_va = 1 }; + OmegaQgSpec s; OmegaPfqLaunch L; + int rc = omega_pfq_gemm_plan(&c, &s, &L); + if (rc != OMEGA_GPU_PF_OK) return rc; + omega_gpu_session_lock(); + rc = run_locked(NULL, OMEGA_PFQ_KIND_GEMM, &s, sizeof s, gen_gemm, &L); + omega_gpu_session_unlock(); + return rc; +} diff --git a/src/omega_gpu_pfq_api.h b/src/omega_gpu_pfq_api.h new file mode 100644 index 00000000..6fec418d --- /dev/null +++ b/src/omega_gpu_pfq_api.h @@ -0,0 +1,71 @@ +/* SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception */ +#ifndef OMEGA_GPU_PFQ_API_H +#define OMEGA_GPU_PFQ_API_H +/* + * omega_gpu_pfq_api: the tiled mma.sync (QMMA) FP8 path for grouped expert GEMMs in prefill (DRA-82, CUDApp #220). + * One expert GEMM is two recorded launches of the native FP8 kernels (omega_blackwell_codegen_qg.h): + * quant f32 activation rows (row stride in elements, 0 = k) -> e4m3 rows of k + f32 power-of-two scales [rows][k / 128] + * gemm grouped GEMM on QMMA over 64-row tiles, weights read IN PLACE from the FP8 GEMV tensor (no second copy) + * Rows come in the segment form of the fp8 gemm record path (OmegaPfqTile is the q36 graph's 32-byte Seg32: w_va, s_va, + * row0, cnt, pad; cnt any size). omega_pfq_tiles cuts each segment into tiles of at most OMEGA_PFQ_BM rows. + * Tile row r: activation row rowidx[row0 + r] (rowidx_va 0: row0 + r), output y row ymap[row0 + r] (ymap_va 0: row0 + r), + * f32 rows of n. The gemm reads rowidx for every row of a tile, cnt or not: a row map needs OMEGA_PFQ_MAP_PAD entries + * past its last row, each naming a row the quantiser wrote (0 does). ymap is read only below cnt. + * x64 1: the activations carry an extra 2^64 (the q36 graph's x' and act rows) and y is the true product. Exact: the + * quantiser's scales are powers of two, so q(2^64 x) = q(x) and s(2^64 x) = 2^64 s(x) unless amax(x) < 2^-164. + * Limit (x64): the fold sa * sw overflows when amax(x) * S >= 2^16 (S the checkpoint weight scale). + * Arithmetic: the qg header's (QMMA chunks accumulated in f32, an exact power-of-two scale fold). NOT bit-identical to the + * FP8 GEMV / fp8gemm FFMA path (activations quantised to e4m3, another summation order): a consumer is gated on output + * tolerance, not bit-identity (q36: AIEN_OMEGA_Q36_PF_QMMA=1, off by default). + * Kernel cache kinds (omega_gpu_prefill.h OmegaPfKey): OMEGA_PFQ_KIND_QUANT, OMEGA_PFQ_KIND_GEMM. + * Shape: 4 row tiles of 16, 8 warps; QMMA read distance AIEN_OMEGA_PFQ_WAIT (0 .. 120, default 45). + * AIEN_OMEGA_PFQ_MUTANT (tests and chip gates only; read once, omega_gpu_pfq_test_set_mutant overrides): + * 1 the tiler starts tile p >= 1 of a segment one row early, 2 the gemm never advances the weight scale pointer (the + * wrong-scale-block mutant), 3 gemm row tile i reads tile i^1, 4 the quantiser uses c = 0. + * Locking: the *_record_locked calls run with the session lock held (as omega_gpu_fp8gemm_record); prepare takes it. + */ +#include +#include "omega_blackwell_codegen_qg.h" + +#ifdef __cplusplus +extern "C" { +#endif +#define OMEGA_PFQ_BM 64u +#define OMEGA_PFQ_MAP_PAD 64u +#define OMEGA_PFQ_KIND_QUANT 0x60u +#define OMEGA_PFQ_KIND_GEMM 0x61u +typedef struct { uint64_t w_va, s_va; uint32_t row0, cnt; uint64_t pad; } OmegaPfqTile; + +/* tiles needed for rows spread over segs segments: segs + rows / OMEGA_PFQ_BM (an upper bound) */ +uint32_t omega_pfq_tile_cap(uint32_t rows, uint32_t segs); +/* cuts segs[0 .. nsegs) into tiles; returns the tile count, 0 when cap is too small or an argument is NULL + * (a table of empty segments also returns 0: nothing to launch) */ +uint32_t omega_pfq_tiles(const OmegaPfqTile *segs, uint32_t nsegs, OmegaPfqTile *tiles, uint32_t cap); + +typedef struct { uint32_t k, rows, stride; uint64_t x_va, q_va, s_va; } OmegaPfqQuant; +typedef struct { + uint32_t n, k, x64, ntiles; + uint64_t tiles_va, rowidx_va, xq_va, xs_va, ymap_va, y_va; +} OmegaPfqGemm; +/* the launch a record call makes (host-checkable: tests run these programs, arguments and grids in the warp simulator) */ +typedef struct { + uint32_t threads, grid_x, grid_y, shared, nargs; + uint32_t args[OMEGA_QG_ARGS_WORDS_YMAP]; +} OmegaPfqLaunch; +/* OMEGA_GPU_PF_OK, or BAD_ARGS / TOO_LARGE (omega_gpu_prefill.h); rows 0 / ntiles 0 plan nothing (grid 0) */ +int omega_pfq_quant_plan(const OmegaPfqQuant *q, OmegaPqSpec *spec, OmegaPfqLaunch *L); +int omega_pfq_gemm_plan(const OmegaPfqGemm *c, OmegaQgSpec *spec, OmegaPfqLaunch *L); + +struct OmegaGpuCmdList; +int omega_gpu_pfq_quant_record_locked(struct OmegaGpuCmdList *cl, const OmegaPfqQuant *q); +int omega_gpu_pfq_gemm_record_locked(struct OmegaGpuCmdList *cl, const OmegaPfqGemm *c); +/* generates and uploads the kernels a later record of this shape uses (a record never has to generate code) */ +int omega_gpu_pfq_quant_prepare(uint32_t k, uint32_t stride); +int omega_gpu_pfq_gemm_prepare(uint32_t n, uint32_t k, uint32_t x64, int indexed, int ymap); + +int omega_gpu_pfq_mutant(void); +void omega_gpu_pfq_test_set_mutant(int m); +#ifdef __cplusplus +} +#endif +#endif diff --git a/src/omega_gpu_prefill_fattn256_api.c b/src/omega_gpu_prefill_fattn256_api.c new file mode 100644 index 00000000..5ebcdf68 --- /dev/null +++ b/src/omega_gpu_prefill_fattn256_api.c @@ -0,0 +1,258 @@ +/* SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception */ +/* + * omega_gpu_prefill_fattn256_api.c: the two launches of the flash-style head_dim 256 prefill attention (Linear DRA-85; + * see the header). Structure copied from omega_gpu_prefill_attn256_api.c: the prep kernel is the decode kernel's own + * program in prep mode (omega_blackwell_codegen_attn256.h, with prep_xstride for strided q|k|v rows), the attend kernel + * is omega_blackwell_codegen_fattn256.h; it uses the SHFL.BFLY / F2FP placeholders of omega_blackwell_codegen_tc.h, so + * its code is patched after encoding and the patch count must equal the program's placeholder count. + */ +#include "omega_gpu_prefill_fattn256_api.h" +#include "omega_blackwell_codegen_tc.h" +#include "omega_gpu_session.h" +#include "omega_gpu_cmdlist.h" +#include + +#define MARKER_TIMEOUT_MS 60000ull +#define POISON_F32 (-999.0f) +enum { KK_PREP, KK_ATTEND, KK_N }; + +typedef struct { + bool valid; + union { OmegaDecodeAttn256Spec prep; OmegaPrefillFattn256Spec att; } spec; + OmegaBlackwellKernel kernel; + OmegaGpuMem code; + uint32_t insns; +} Slot; + +static struct { + bool hooked; + Slot slot[KK_N]; + int prep_mut, att_mut, att_variant; + OmegaGpuMem qf; size_t qf_size; bool have_qf; /* q' scratch */ + OmegaGpuMem qkv, out; size_t qkv_size, out_size; bool have_bufs; /* host-entry staging */ +} g; + +static void bufs_forget(void) { g.have_qf = false; g.qf_size = 0; g.have_bufs = false; g.qkv_size = g.out_size = 0; } +static void on_session_close(void) { memset(g.slot, 0, sizeof g.slot); bufs_forget(); } +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(); +} +static void slots_clear_locked(void) { + for (unsigned k = 0; k < KK_N; k++) { if (g.slot[k].valid) omega_gpu_session_free(&g.slot[k].code); memset(&g.slot[k], 0, sizeof g.slot[k]); } +} +void omega_gpu_prefill_fattn256_test_set_mutant(int prep_mutant, int attend_mutant) { + omega_gpu_session_lock(); g.prep_mut = prep_mutant; g.att_mut = attend_mutant; slots_clear_locked(); omega_gpu_session_unlock(); +} +int omega_gpu_prefill_fattn256_set_variant(int variant) { + if (variant < 0 || variant > 2) return OMEGA_GPU_DATTN_BAD_ARGS; + omega_gpu_session_lock(); g.att_variant = variant; slots_clear_locked(); omega_gpu_session_unlock(); + return OMEGA_GPU_DATTN_OK; +} +void omega_gpu_prefill_fattn256_release(void) { + omega_gpu_session_lock(); + if (g.have_qf) omega_gpu_session_free(&g.qf); + if (g.have_bufs) { omega_gpu_session_free(&g.qkv); omega_gpu_session_free(&g.out); } + bufs_forget(); + omega_gpu_session_unlock(); +} + +/* sh: the cache's head shape (q_heads / kv_heads / q_per_cta) and the prep row stride in bytes (0 = packed) */ +static void spec_of(unsigned kind, const uint32_t *sh, Slot *tmp) { + memset(tmp, 0, sizeof *tmp); + if (kind == KK_PREP) { + tmp->spec.prep.depth = OMEGA_GPU_DATTN256_DEPTH; tmp->spec.prep.mutant = g.prep_mut; tmp->spec.prep.prep = 1; + if (sh) { tmp->spec.prep.q_heads = sh[0]; tmp->spec.prep.kv_heads = sh[1]; tmp->spec.prep.q_per_cta = sh[2]; tmp->spec.prep.prep_xstride = sh[3]; } + } else { + tmp->spec.att.mutant = g.att_mut; tmp->spec.att.variant = g.att_variant; + if (sh) { tmp->spec.att.q_heads = sh[0]; tmp->spec.att.kv_heads = sh[1]; } + } +} +static int prog_of(unsigned kind, const Slot *tmp, BlackwellIRProgram *prog) { + return kind == KK_PREP ? omega_blackwell_codegen_decode_attn256_prog(&tmp->spec.prep, prog) + : omega_blackwell_codegen_prefill_fattn256_prog(&tmp->spec.att, prog); +} +static uint32_t placeholders_of(const BlackwellIRProgram *prog) { + uint32_t n = 0; + for (size_t i = 0; i < prog->count; i++) { + const BlackwellIRInsn *in = &prog->insns[i]; + if ((in->op == BW_IR_SHFL_DOWN && (in->imm & OMEGA_TC_MARK_BFLY)) || (in->op == BW_IR_FMNMX_MAX && in->imm == OMEGA_TC_MARK_F2FP)) n++; + } + return n; +} + +size_t omega_gpu_prefill_fattn256_encode(unsigned kind, uint32_t q_heads, uint32_t kv_heads, uint32_t q_per_cta, uint32_t xstride, + uint8_t *code, size_t cap, uint32_t *gprs, int *patched) { + if (kind >= KK_N) return 0; + const uint32_t sh[4] = { q_heads ? q_heads : 16u, kv_heads ? kv_heads : 2u, q_per_cta ? q_per_cta : 4u, xstride }; + Slot tmp; spec_of(kind, sh, &tmp); + BlackwellIRProgram *prog = omega_gpu_host_calloc(1, sizeof *prog); + if (!prog) return 0; + size_t need = 0; + if (prog_of(kind, &tmp, prog) == 0) need = omega_bw_program_code_bytes(prog); + OmegaBlackwellKernel k; + if (need == 0 || need > cap || omega_blackwell_kernel_encode_into(prog, code, cap, &k) != 0) { omega_gpu_host_free(prog); return 0; } + int np = omega_tc_patch_code(prog, code, need); + if (gprs) *gprs = k.gpr_count; + if (patched) *patched = np; + const int ok = np >= 0 && (uint32_t)np == placeholders_of(prog); + omega_gpu_host_free(prog); + return ok ? need : 0; +} + +/* rec: a record call is running (lock held): a miss is refused instead of compiled */ +static int kernel_for(unsigned kind, const uint32_t *sh, int rec, Slot **out, bool *hit) { + Slot tmp; spec_of(kind, sh, &tmp); + Slot *s = &g.slot[kind]; + if (s->valid && memcmp(&s->spec, &tmp.spec, sizeof tmp.spec) == 0) { *out = s; *hit = true; return OMEGA_GPU_DATTN_OK; } + if (rec) { omega_gpu_session_set_error("prefill fattn256 record: kernel cache miss (warm up before recording)"); return OMEGA_GPU_DATTN_TOO_LARGE; } + if (s->valid) omega_gpu_session_free(&s->code); + memset(s, 0, sizeof *s); + BlackwellIRProgram *prog = omega_gpu_host_calloc(1, sizeof *prog); + if (!prog) { omega_gpu_session_set_error("prefill fattn256 codegen: host memory"); return OMEGA_GPU_DATTN_CODEGEN_FAIL; } + int cg = prog_of(kind, &tmp, 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("prefill fattn256 codegen refused the spec"); return OMEGA_GPU_DATTN_CODEGEN_FAIL; } + /* both launches run 256 threads per CTA: the declared registers must fit the 64K register file (CUDA Programming + * Guide, Compute Capabilities: "maximum number of 32-bit registers per thread block is 64K") */ + if ((uint64_t)OMEGA_FATTN256_THREADS * omega_bw_gpr_declared(prog->regalloc.peak_gpr_usage) > 65536u) { omega_gpu_host_free(prog); omega_gpu_session_set_error("prefill fattn256: register file"); return OMEGA_GPU_DATTN_TOO_LARGE; } + const uint32_t expect = placeholders_of(prog), insns = (uint32_t)prog->count; + OmegaGpuMem code; + if (omega_gpu_session_alloc_code(need, &code) != 0) { omega_gpu_host_free(prog); return OMEGA_GPU_DATTN_CHIP_FAIL; } + OmegaBlackwellKernel kernel; + cg = omega_blackwell_kernel_encode_into(prog, code.cpu, need, &kernel); + int np = cg == 0 ? omega_tc_patch_code(prog, code.cpu, need) : -1; + omega_gpu_host_free(prog); + if (cg != 0 || !kernel.code || kernel.code_size != need) { omega_gpu_session_free(&code); omega_gpu_session_set_error("prefill fattn256 encode"); return OMEGA_GPU_DATTN_CODEGEN_FAIL; } + if (np < 0 || (uint32_t)np != expect) { omega_gpu_session_free(&code); omega_gpu_session_set_error("prefill fattn256: placeholder patch count mismatch"); return OMEGA_GPU_DATTN_CODEGEN_FAIL; } + if (omega_gpu_session_sync_to_gpu(&code) != 0) { omega_gpu_session_free(&code); return OMEGA_GPU_DATTN_CHIP_FAIL; } + memset(s, 0, sizeof *s); + s->valid = true; s->spec = tmp.spec; s->kernel = kernel; s->code = code; s->insns = insns; + *out = s; *hit = false; + return OMEGA_GPU_DATTN_OK; +} + +/* a token pair of q' takes q_heads * 1024 bytes (OMEGA_PATTN256_QF_OFF_SHAPE, the fattn256 Q layout) */ +static size_t qf_bytes(uint32_t rows, uint32_t q_heads) { return (size_t)((rows + 1u) / 2u) * q_heads * 1024u; } +static int qf_locked(size_t need) { + if (g.have_qf && g.qf_size >= need) return 0; + if (g.have_qf) { omega_gpu_session_free(&g.qf); g.have_qf = false; g.qf_size = 0; } + if (omega_gpu_session_alloc(need, &g.qf) != 0) return -1; + g.have_qf = true; g.qf_size = need; + return 0; +} +/* xstride: the prep row stride the record calls will use (0 = packed); a different stride later misses the cache */ +int omega_gpu_prefill_fattn256_reserve_for(const OmegaGpuDecodeAttn256Cache *c, uint32_t max_m, uint32_t xstride) { + if (!c || max_m == 0 || max_m > OMEGA_GPU_FATTN256_MAX_M) return OMEGA_GPU_DATTN_BAD_ARGS; + OmegaGpuDecodeAttn256CacheView v; + if (omega_gpu_decode_attn256_cache_view(c, 0, &v) != OMEGA_GPU_DATTN_OK) return OMEGA_GPU_DATTN_BAD_ARGS; + const uint32_t sh[4] = { v.q_heads, v.kv_heads, v.q_per_cta, xstride == v.qkv_words * 4u ? 0u : xstride }; + omega_gpu_session_lock(); + int rc = dev_open_locked() && qf_locked(qf_bytes(max_m, v.q_heads)) == 0 ? OMEGA_GPU_DATTN_OK : OMEGA_GPU_DATTN_CHIP_FAIL; + /* and builds both kernels, so a record call after reserve never misses the cache */ + for (unsigned k = 0; k < KK_N && rc == OMEGA_GPU_DATTN_OK; k++) { Slot *s = NULL; bool hit = false; rc = kernel_for(k, sh, 0, &s, &hit); } + omega_gpu_session_unlock(); + return rc; +} +static int bufs_locked(size_t qkv_size, size_t out_size) { + if (g.have_bufs && g.qkv_size >= qkv_size && g.out_size >= out_size) return 0; + if (g.have_bufs) { omega_gpu_session_free(&g.qkv); omega_gpu_session_free(&g.out); g.have_bufs = false; g.qkv_size = g.out_size = 0; } + if (omega_gpu_session_alloc(qkv_size, &g.qkv) != 0) return -1; + if (omega_gpu_session_alloc(out_size, &g.out) != 0) { omega_gpu_session_free(&g.qkv); return -1; } + g.have_bufs = true; g.qkv_size = qkv_size; g.out_size = out_size; + return 0; +} + +/* host != 0: qkv / out are host arrays staged through the module buffers (poison-checked); else qkv_va / out_va are + * device buffers. rec non-NULL: record path (lock held, nothing allocated, compiled or submitted). */ +static int core(OmegaGpuDecodeAttn256Cache *c, uint32_t layer, uint32_t pos0, uint32_t m, const float *qkv, uint32_t xstride, float *out, + uint32_t ostride, uint64_t qkv_va, uint64_t out_va, float eps, float out_scale, OmegaGpuPrefillFattn256Info *info, OmegaGpuCmdList *rec) { + uint64_t t0 = omega_gpu_session_now_ns(); + if (info) memset(info, 0, sizeof *info); + const int host = qkv != NULL; + OmegaGpuDecodeAttn256CacheView v; + if (!c || m == 0 || m > OMEGA_GPU_FATTN256_MAX_M || omega_gpu_decode_attn256_cache_view(c, layer, &v) != OMEGA_GPU_DATTN_OK || + pos0 > v.max_pos || m > v.max_pos - pos0 || (host ? !out : (!qkv_va || !out_va || (qkv_va & 15u) || (out_va & 15u)))) return OMEGA_GPU_DATTN_BAD_ARGS; + const uint32_t QKVW = v.qkv_words, OUTW = v.out_words; + /* the prep refuses a stride below a q|k|v row or off 16 bytes; the attend stores rows of out_words f32 */ + if (xstride < QKVW * 4u || (xstride & 15u) || ostride < OUTW * 4u || (ostride & 15u)) return OMEGA_GPU_DATTN_BAD_ARGS; + const OmegaPrefillFattn256Spec as = { .q_heads = v.q_heads, .kv_heads = v.kv_heads }; + if (!omega_fattn256_spec_ok(&as)) return OMEGA_GPU_DATTN_BAD_ARGS; + const uint32_t sh[4] = { v.q_heads, v.kv_heads, v.q_per_cta, xstride == QKVW * 4u ? 0u : xstride }; + if (!rec) omega_gpu_session_lock(); +#define UNLOCK() do { if (!rec) omega_gpu_session_unlock(); } while (0) + if (!dev_open_locked()) { UNLOCK(); return OMEGA_GPU_DATTN_CHIP_FAIL; } + Slot *ks[KK_N] = { NULL, NULL }; bool hit[KK_N] = { false, false }; + int rc = OMEGA_GPU_DATTN_OK; + for (unsigned k = 0; k < KK_N && rc == OMEGA_GPU_DATTN_OK; k++) rc = kernel_for(k, sh, rec != NULL, &ks[k], &hit[k]); + if (rc != OMEGA_GPU_DATTN_OK) { UNLOCK(); return rc; } + if (rec) { if (!g.have_qf || g.qf_size < qf_bytes(m, v.q_heads)) { omega_gpu_session_set_error("prefill fattn256 record: q' scratch not reserved for m tokens"); return OMEGA_GPU_DATTN_TOO_LARGE; } } + else if (qf_locked(qf_bytes(m, v.q_heads)) != 0) { UNLOCK(); return OMEGA_GPU_DATTN_CHIP_FAIL; } + if (host) { + if (bufs_locked((size_t)m * xstride, (size_t)m * ostride) != 0) { UNLOCK(); return OMEGA_GPU_DATTN_CHIP_FAIL; } + memcpy(g.qkv.cpu, qkv, (size_t)m * xstride); + float *od = g.out.cpu; + for (size_t i = 0; i < (size_t)m * (ostride / 4u); i++) od[i] = POISON_F32; + if (omega_gpu_session_sync_to_gpu(&g.qkv) != 0 || omega_gpu_session_sync_to_gpu(&g.out) != 0) rc = OMEGA_GPU_DATTN_CHIP_FAIL; + qkv_va = g.qkv.va; out_va = g.out.va; + } + const uint32_t kvs = v.max_pos * OMEGA_DATTN256_ROW_BYTES, gx_att = (m + OMEGA_FATTN256_TOKENS - 1u) / OMEGA_FATTN256_TOKENS; + float fe = eps, f1 = 1.0f, fo = out_scale, fq = (float)(0.0625 * 1.4426950408889634); /* log2(e) / sqrt(256) */ + uint32_t ue, u1, uo, uq; memcpy(&ue, &fe, 4); memcpy(&u1, &f1, 4); memcpy(&uo, &fo, 4); memcpy(&uq, &fq, 4); + uint32_t ap[OMEGA_DATTN256_ARGS_WORDS], aa[OMEGA_FATTN256_ARGS_WORDS]; +#define A64(a, i, x) do { (a)[i] = (uint32_t)(x); (a)[(i) + 1] = (uint32_t)((uint64_t)(x) >> 32); } while (0) + A64(ap, 0, qkv_va); A64(ap, 2, v.k_va); A64(ap, 4, v.v_va); A64(ap, 6, v.rope_va); A64(ap, 8, v.q_norm_va); A64(ap, 10, v.k_norm_va); + A64(ap, 12, g.qf.va); A64(ap, 14, v.part_va); A64(ap, 16, v.cnt_va); + ap[18] = pos0; ap[19] = OMEGA_DATTN256_CHUNK; ap[20] = 1u; ap[21] = kvs; ap[22] = ue; ap[23] = u1; ap[24] = uq; + A64(aa, 0, g.qf.va); A64(aa, 2, v.k_va); A64(aa, 4, v.v_va); A64(aa, 6, out_va); + aa[8] = pos0; aa[9] = m; aa[10] = kvs; aa[11] = uo; aa[12] = ostride; +#undef A64 + OmegaGpuLaunch L[KK_N] = { + { .code_va = ks[KK_PREP]->code.va, .gpr_count = omega_bw_gpr_declared(ks[KK_PREP]->kernel.gpr_count), + .threads_x = OMEGA_FATTN256_THREADS, .threads_y = 1, .grid_x = m, .grid_y = v.q_heads / v.q_per_cta, + .num_elements = (size_t)m * QKVW, .args = ap, .n_args = OMEGA_DATTN256_ARGS_WORDS, .timeout_ms = MARKER_TIMEOUT_MS, + .shared_bytes = OMEGA_DATTN256_SHARED_BYTES }, + { .code_va = ks[KK_ATTEND]->code.va, .gpr_count = omega_bw_gpr_declared(ks[KK_ATTEND]->kernel.gpr_count), + .threads_x = OMEGA_FATTN256_THREADS, .threads_y = 1, .grid_x = gx_att, .grid_y = v.kv_heads, + .num_elements = (size_t)m * OUTW, .args = aa, .n_args = OMEGA_FATTN256_ARGS_WORDS, .timeout_ms = MARKER_TIMEOUT_MS, + .shared_bytes = OMEGA_FATTN256_SHARED_BYTES }, + }; + if (info) { + info->layer = layer; info->pos0 = pos0; info->m = m; info->grid_x[0] = m; info->grid_x[1] = gx_att; + for (unsigned k = 0; k < KK_N; k++) { info->insns[k] = ks[k]->insns; info->gprs[k] = ks[k]->kernel.gpr_count; info->kernel_cache_hits += hit[k]; } + } + for (unsigned k = 0; k < KK_N && rc == OMEGA_GPU_DATTN_OK; k++) { + if (!omega_bw_gpr_declared_ok(L[k].gpr_count, ks[k]->kernel.gpr_count)) { omega_gpu_session_set_error("declared registers below peak + 2: refusing to launch"); rc = OMEGA_GPU_DATTN_CHIP_FAIL; } + else if (rec) { if (omega_gpu_cmdlist_add(rec, &L[k]) < 0) rc = OMEGA_GPU_DATTN_CHIP_FAIL; } + else if (omega_gpu_session_launch(&L[k], info ? &info->elapsed_ns[k] : NULL, NULL) != 0) rc = OMEGA_GPU_DATTN_CHIP_FAIL; + } + if (rc == OMEGA_GPU_DATTN_OK && host) { + if (omega_gpu_session_sync_to_cpu(&g.out) != 0) rc = OMEGA_GPU_DATTN_CHIP_FAIL; + else { + const float *od = g.out.cpu; + size_t unchanged = 0; + for (size_t t = 0; t < m; t++) for (size_t i = 0; i < OUTW; i++) if (od[t * (ostride / 4u) + i] == POISON_F32) unchanged++; + if (unchanged) { omega_gpu_session_set_error("prefill fattn256: output poison survived"); rc = OMEGA_GPU_DATTN_CHIP_FAIL; } + else for (size_t t = 0; t < m; t++) memcpy((uint8_t *)out + t * ostride, od + t * (ostride / 4u), (size_t)OUTW * 4u); + } + } + UNLOCK(); +#undef UNLOCK + if (info) info->call_ns = omega_gpu_session_now_ns() - t0; + return rc; +} + +int omega_gpu_prefill_fattn256(OmegaGpuDecodeAttn256Cache *c, uint32_t layer, uint32_t pos0, uint32_t m, const float *qkv, + uint32_t xstride, float eps, float out_scale, float *out, uint32_t ostride, OmegaGpuPrefillFattn256Info *info) { + if (!qkv) return OMEGA_GPU_DATTN_BAD_ARGS; + return core(c, layer, pos0, m, qkv, xstride, out, ostride, 0, 0, eps, out_scale, info, NULL); +} +int omega_gpu_prefill_fattn256_dev(OmegaGpuDecodeAttn256Cache *c, uint32_t layer, uint32_t pos0, uint32_t m, uint64_t qkv_va, + uint32_t xstride, float eps, float out_scale, uint64_t out_va, uint32_t ostride, OmegaGpuPrefillFattn256Info *info) { + return core(c, layer, pos0, m, NULL, xstride, NULL, ostride, qkv_va, out_va, eps, out_scale, info, NULL); +} +int omega_gpu_prefill_fattn256_record(OmegaGpuCmdList *cl, OmegaGpuDecodeAttn256Cache *c, uint32_t layer, uint32_t pos0, uint32_t m, + uint64_t qkv_va, uint32_t xstride, float eps, float out_scale, uint64_t out_va, uint32_t ostride) { + if (!cl) return OMEGA_GPU_DATTN_BAD_ARGS; + return core(c, layer, pos0, m, NULL, xstride, NULL, ostride, qkv_va, out_va, eps, out_scale, NULL, cl); +} diff --git a/src/omega_gpu_prefill_fattn256_api.h b/src/omega_gpu_prefill_fattn256_api.h new file mode 100644 index 00000000..31046d47 --- /dev/null +++ b/src/omega_gpu_prefill_fattn256_api.h @@ -0,0 +1,63 @@ +/* SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception */ +#ifndef OMEGA_GPU_PREFILL_FATTN256_API_H +#define OMEGA_GPU_PREFILL_FATTN256_API_H +/* + * omega_gpu_prefill_fattn256_api: flash-style causal prefill attention on the tensor cores for the head_dim 256 decode + * cache (Linear DRA-85, P-DRA-4 Lane P; the attend kernel is omega_blackwell_codegen_fattn256.h). Built for the Qwen3.6 + * 35B full-attention layers (16 q heads / 2 kv heads); any cache shape with q_heads / kv_heads in 1..8 works. + * + * int omega_gpu_prefill_fattn256(c, layer, pos0, m, qkv, xstride, eps, out_scale, out, ostride, info) + * qkv: host f32 rows xstride bytes apart (the first qkv_words of a row are the decode call's q|k|v; the rest, e.g. + * the q36 output gate, is ignored), tokens at positions pos0 .. pos0+m-1 (0 .. pos0-1 of `layer` already cached). + * Appends K and V for those positions with the decode step's own prep instructions (the cache rows equal m decode + * steps' rows) and writes out: host f32 rows ostride bytes apart, the first out_words of each the attention output + * (head h at h * 256, model dim order) times out_scale; the rest of a row is left untouched. Two launches: prep + * (grid m x q_heads / q_per_cta), attend (grid ceil(m / 16) x kv_heads, no shared memory). + * The output is NOT bit-identical to the decode steps (P is rounded to bf16 for the PV product, the sums run in + * another order); the tolerance and the golden-token check are the acceptance (DRA-85 G3). + * int omega_gpu_prefill_fattn256_dev(...): the same with device buffers (16-byte aligned session VAs, no poison check). + * int omega_gpu_prefill_fattn256_record(cl, ...): both launches appended to cl; the caller holds the session lock, + * reserved the q' scratch (reserve_for) and warmed both kernels (a kernel cache miss is refused while recording). + * int omega_gpu_prefill_fattn256_reserve_for(c, max_m, xstride): allocates the q' scratch (ceil(max_m / 2) * q_heads * + * 1024 bytes) and builds both kernels for c's head shape and the q|k|v row stride xstride (0 = packed rows). + * void omega_gpu_prefill_fattn256_release(void). + * int omega_gpu_prefill_fattn256_set_variant(variant): the attend kernel variant for later calls (0 or 1: the base + * kernel, the default; 2: next-block L1 touch prefetch, omega_blackwell_codegen_fattn256.h); drops the kernel cache, + * so a record caller warms up again (reserve_for). BAD_ARGS outside 0..2. + * Returns OMEGA_GPU_DATTN_OK or an OMEGA_GPU_DATTN_* code; the text is in omega_gpu_decode_attn_last_error(). + */ +#include "omega_gpu_decode_attn256_api.h" +#include "omega_blackwell_codegen_fattn256.h" +#include +#include + +#define OMEGA_GPU_FATTN256_MAX_M 32768u + +typedef struct { + uint32_t layer, pos0, m; + uint32_t grid_x[2]; /* prep, attend */ + uint32_t insns[2], gprs[2]; + uint64_t elapsed_ns[2]; /* marker-to-marker chip time of each launch (host and dev paths) */ + uint64_t call_ns; + uint32_t kernel_cache_hits; /* 0..2 */ +} OmegaGpuPrefillFattn256Info; + +int omega_gpu_prefill_fattn256(OmegaGpuDecodeAttn256Cache *c, uint32_t layer, uint32_t pos0, uint32_t m, const float *qkv, + uint32_t xstride, float eps, float out_scale, float *out, uint32_t ostride, OmegaGpuPrefillFattn256Info *info); +int omega_gpu_prefill_fattn256_dev(OmegaGpuDecodeAttn256Cache *c, uint32_t layer, uint32_t pos0, uint32_t m, uint64_t qkv_va, + uint32_t xstride, float eps, float out_scale, uint64_t out_va, uint32_t ostride, OmegaGpuPrefillFattn256Info *info); +struct OmegaGpuCmdList; +int omega_gpu_prefill_fattn256_record(struct OmegaGpuCmdList *cl, OmegaGpuDecodeAttn256Cache *c, uint32_t layer, uint32_t pos0, uint32_t m, + uint64_t qkv_va, uint32_t xstride, float eps, float out_scale, uint64_t out_va, uint32_t ostride); +int omega_gpu_prefill_fattn256_reserve_for(const OmegaGpuDecodeAttn256Cache *c, uint32_t max_m, uint32_t xstride); +void omega_gpu_prefill_fattn256_release(void); +int omega_gpu_prefill_fattn256_set_variant(int variant); + +/* ---- tests ---- */ +void omega_gpu_prefill_fattn256_test_set_mutant(int prep_mutant, int attend_mutant); /* OmegaDecodeAttn256Spec / OmegaPrefillFattn256Spec .mutant */ +/* host: build + encode + patch a kernel (0 prep, 1 attend) for shape q_heads / kv_heads / q_per_cta (0 = 16 / 2 / 4, the q36 cache) and + * prep row stride xstride (0 = packed) into code (cap bytes); returns the code size or 0 */ +size_t omega_gpu_prefill_fattn256_encode(unsigned kind, uint32_t q_heads, uint32_t kv_heads, uint32_t q_per_cta, uint32_t xstride, + uint8_t *code, size_t cap, uint32_t *gprs, int *patched); + +#endif diff --git a/src/omega_gpu_q36_graph.c b/src/omega_gpu_q36_graph.c index 31736829..1d57cec8 100644 --- a/src/omega_gpu_q36_graph.c +++ b/src/omega_gpu_q36_graph.c @@ -13,6 +13,8 @@ #include "omega_gpu_fmt.h" #include "omega_gpu_mem_cached.h" #include "omega_gpu_fp8gemm_api.h" +#include "omega_gpu_pfq_api.h" +#include "omega_gpu_prefill_fattn256_api.h" #include "omega_gpu_q36_native.h" #include "omega_gpu_cmdlist_native.h" #include @@ -101,7 +103,12 @@ struct OmegaGpuQ36Graph { size_t xq, xp, mixN, abN, aggN, attN, op, oN, xp2, guN, actN, actp, dnN; int mutant; uint64_t streamed; /* fp8 GEMM weight bytes every prefill call so far streamed (one pass per mt rows) */ int attn_multi; /* 1 (default): each attention layer in one prep + attend launch pair; AIEN_OMEGA_Q36_PF_ATTN=0: one decode step per token */ - int gdn_multi; /* 1 (default): the GDN layers in one multi-token launch; AIEN_OMEGA_Q36_PF_GDN=0: one decode step per token */ } pf; + int fattn; /* DRA-85, AIEN_OMEGA_Q36_PF_FATTN=1 or 2 (default 0, needs attn_multi): each attention layer's chunk through the flash-style tensor-core attention, kernel variant 1 or 2 */ + int gdn_multi; /* 1 (default): the GDN layers in one multi-token launch; AIEN_OMEGA_Q36_PF_GDN=0: one decode step per token */ + /* DRA-82, AIEN_OMEGA_Q36_PF_QMMA=1 (default 0): the prefill GEMMs on the tensor cores (omega_gpu_pfq_api.h): pq quantises + * natural rows into q8|qs, qg reads the weights in place through 64-row tiles; qxm|qym the combined routed+shared + * row maps, qtgu|qtdn their tile tables, qtd the dense mix|o tables of every layer (qtd_cap tiles each) */ + int qmma; size_t q8, qs, qxm, qym, qtgu, qtdn, qtd; uint32_t qtd_cap, qtd_n, qtg_cap, qtg_n; } pf; int stamps; uint32_t n_kind, tagged_in_list, n_stamp; uint8_t kind[OMEGA_GPU_CMDLIST_MAX_LAUNCHES]; @@ -961,8 +968,14 @@ static int pf_fail(OmegaGpuQ36Graph *g, const char *what) { return fail(g, what, int omega_gpu_q36_graph_prefill_alloc(OmegaGpuQ36Graph *g, uint32_t cap) { if (!g || g->in_token || cap == 0 || cap > OMEGA_GPU_Q36_PREFILL_MAX_ROWS) return OMEGA_GPU_DGRAPH_BAD_ARGS; - if (g->pf.cap >= cap) return OMEGA_GPU_DGRAPH_OK; + const char *qe = getenv("AIEN_OMEGA_Q36_PF_QMMA"); + const int qmma = qe && qe[0] == '1' && qe[1] == 0; + if (g->pf.cap >= cap && g->pf.qmma == qmma) return OMEGA_GPU_DGRAPH_OK; + if (g->pf.cap > cap) cap = g->pf.cap; /* a gate change reallocates at the larger capacity */ const size_t P = cap, R = P * NG, lbs = g->lo.lb_stride; + /* QMMA bypasses the native-artifact GEMM records (they stay the incumbent GEMV's); the quantiser reads x' rows lbs apart */ + if (qmma && (g->native || (lbs & 15u))) return OMEGA_GPU_DGRAPH_BAD_ARGS; + const uint32_t tcg = omega_pfq_tile_cap((uint32_t)R, 257u), tcd = omega_pfq_tile_cap((uint32_t)P, 1u); size_t ho = 0, dof = 0; #define HREG(f, b) do { g->pf.f = ho; ho += al(b); } while (0) #define DREG(f, b) do { g->pf.f = dof; dof += al(b); } while (0) @@ -973,6 +986,13 @@ int omega_gpu_q36_graph_prefill_alloc(OmegaGpuQ36Graph *g, uint32_t cap) { DREG(aggN, P * OMEGA_GPU_Q36_ATT_MIX * 4); DREG(attN, P * OMEGA_GPU_Q36_MIXER_OUT * 4); DREG(op, (P + PF_PAD) * OMEGA_GPU_Q36_MIXER_OUT * 4); DREG(oN, P * H * 4); DREG(xp2, (P + PF_PAD) * H * 4); DREG(guN, R * 2 * EI * 4); DREG(actN, R * EI * 4); DREG(actp, (R + PF_PAD) * EI * 4); DREG(dnN, R * H * 4); + if (qmma) { /* q8|qs hold the widest quantised operand: o's input (P x 4096) or the act rows (R x 512) */ + const size_t qk = P * OMEGA_GPU_Q36_MIXER_OUT > R * EI ? P * OMEGA_GPU_Q36_MIXER_OUT : R * EI; + HREG(qxm, (R + OMEGA_PFQ_MAP_PAD) * 4); HREG(qym, (R + OMEGA_PFQ_MAP_PAD) * 4); + HREG(qtgu, tcg * sizeof(OmegaPfqTile)); HREG(qtdn, tcg * sizeof(OmegaPfqTile)); + HREG(qtd, (size_t)g->cfg.layers * 2u * tcd * sizeof(OmegaPfqTile)); + DREG(q8, qk); DREG(qs, qk / 128u * 4u); + } #undef HREG #undef DREG omega_gpu_session_lock(); @@ -994,6 +1014,17 @@ int omega_gpu_q36_graph_prefill_alloc(OmegaGpuQ36Graph *g, uint32_t cap) { if (r == 0) r = omega_gpu_fp8gemm_prepare_shape(H, 64, 4, 1); if (r == 0) r = omega_gpu_fp8gemm_prepare_shape(EI, 64, 4, 1); if (r == 0 && omega_gpu_router_prepare_rows(g->cfg.router, H * 4u, g->lo.lb_stride) != OMEGA_GPU_ROUTER_OK) r = -1; + if (r == 0 && qmma) { /* the pq/qg programs of every prefill shape, x64 1 (the q36 activations carry 2^64) */ + r = omega_gpu_pfq_quant_prepare(H, 0); + if (r == 0) r = omega_gpu_pfq_quant_prepare(H, (uint32_t)(lbs / 4u)); + if (r == 0) r = omega_gpu_pfq_quant_prepare(OMEGA_GPU_Q36_MIXER_OUT, 0); + if (r == 0) r = omega_gpu_pfq_quant_prepare(EI, 0); + if (r == 0) r = omega_gpu_pfq_gemm_prepare(OMEGA_GPU_Q36_GDN_MIX, H, 1, 0, 0); + if (r == 0) r = omega_gpu_pfq_gemm_prepare(OMEGA_GPU_Q36_ATT_MIX, H, 1, 0, 0); + if (r == 0) r = omega_gpu_pfq_gemm_prepare(H, OMEGA_GPU_Q36_MIXER_OUT, 1, 0, 0); + if (r == 0) r = omega_gpu_pfq_gemm_prepare(2u * EI, H, 1, 1, 1); + if (r == 0) r = omega_gpu_pfq_gemm_prepare(H, EI, 1, 1, 1); + } if (r != 0) rc = OMEGA_GPU_DGRAPH_CHIP_FAIL; } if (rc != OMEGA_GPU_DGRAPH_OK) return rc; @@ -1008,6 +1039,16 @@ int omega_gpu_q36_graph_prefill_alloc(OmegaGpuQ36Graph *g, uint32_t cap) { for (uint32_t h = 0; h < g->heads && g->pf.attn_multi; h++) if (g->attn_h[h] && omega_gpu_decode_attn256_multi_prepare(g->attn_h[h]) != OMEGA_GPU_DATTN_OK) return OMEGA_GPU_DGRAPH_CHIP_FAIL; omega_gpu_decode_attn256_test_set_multi_mutant(g->pf.mutant == 6 ? 1 : 0); /* TEST mutant 6: the attention prep launch dropped */ + /* DRA-85: AIEN_OMEGA_Q36_PF_FATTN=1 swaps the attend launch for the flash attention (omega_gpu_prefill_fattn256_api.h; not + * bit-identical to the steps: the tolerance and the golden tokens are its gate); =2 the same with its variant 2 (next-block + * L1 touch prefetch, same arithmetic). TEST mutant 8: its kernel without the rescale */ + const char *fe = getenv("AIEN_OMEGA_Q36_PF_FATTN"); + g->pf.fattn = g->pf.attn_multi && fe && (fe[0] == '1' || fe[0] == '2') && fe[1] == 0 ? fe[0] - '0' : 0; + if (g->pf.fattn) { omega_gpu_prefill_fattn256_test_set_mutant(0, g->pf.mutant == 8 ? 2 : 0); (void)omega_gpu_prefill_fattn256_set_variant(g->pf.fattn); } + for (uint32_t h = 0; h < g->heads && g->pf.fattn; h++) + if (g->attn_h[h] && omega_gpu_prefill_fattn256_reserve_for(g->attn_h[h], cap, OMEGA_GPU_Q36_ATT_MIX * 4u) != OMEGA_GPU_DATTN_OK) + return OMEGA_GPU_DGRAPH_CHIP_FAIL; + g->pf.qmma = qmma; g->pf.qtd_cap = tcd; g->pf.qtg_cap = tcg; g->pf.qtd_n = 0; g->pf.qtg_n = 0; g->pf.cap = cap; return OMEGA_GPU_DGRAPH_OK; } @@ -1018,6 +1059,46 @@ static uint64_t pf_h(const OmegaGpuQ36Graph *g, size_t off) { return g->pf.hb.va static void *pf_hc(const OmegaGpuQ36Graph *g, size_t off) { return (uint8_t *)g->pf.hb.cpu + off; } static uint64_t pf_d(const OmegaGpuQ36Graph *g, size_t off) { return g->pf.db.va + off; } +/* DRA-82: o runs on the tensor cores only where the mixer leaves natural attN rows (the attention layers and the multi-token + * GDN launch); the per-token GDN steps (AIEN_OMEGA_Q36_PF_GDN=0, pf mutants 1|3) write the permuted op rows only */ +static int pf_qmma_o(const OmegaGpuQ36Graph *g, uint32_t l) { + return g->pf.qmma && (g->layer[l].attn || (g->pf.gdn_multi && g->pf.mutant != 1 && g->pf.mutant != 3)); +} + +/* the dense mix|o tile tables of every layer for an n-row chunk (one 64-row tile per pass, weight entry 0, rows 0 .. n-1) */ +static int pf_qmma_dense_tables(OmegaGpuQ36Graph *g, uint32_t n) { + OmegaPfqTile *t = pf_hc(g, g->pf.qtd); + uint32_t nt = 0; + for (uint32_t l = 0; l < g->cfg.layers; l++) + for (uint32_t w = 0; w < 2u; w++) { + OmegaPfqTile seg; memset(&seg, 0, sizeof seg); + (void)omega_gpu_fp8_tensor_entry(w ? g->layer[l].o : g->layer[l].mix, 0, &seg.w_va, &seg.s_va); + seg.cnt = n; + nt = omega_pfq_tiles(&seg, 1, t + ((size_t)l * 2u + w) * g->pf.qtd_cap, g->pf.qtd_cap); + if (nt == 0) return pf_fail(g, "q36 prefill qmma: dense tile table over capacity"); + } + g->pf.qtd_n = nt; + return OMEGA_GPU_DGRAPH_OK; +} + +/* quantise rows x (k wide, row stride `stride` floats, 0 = k; carrying 2^64) into q8|qs, then y = x W^T on QMMA through the + * tile table at tiles_va; rowidx/ymap 0 = direct rows. Both launches carry the GEMM's kind. */ +static int pf_qmma_gemm(OmegaGpuQ36Graph *g, uint8_t kind, uint64_t x, uint32_t rows, uint32_t stride, uint32_t k, uint32_t nout, + uint64_t tiles_va, uint32_t ntiles, uint64_t rowidx, uint64_t ymap, uint64_t y) { + const uint64_t q8 = pf_d(g, g->pf.q8), qs = pf_d(g, g->pf.qs); + const OmegaPfqQuant q = { .k = k, .rows = rows, .stride = stride, .x_va = x, .q_va = q8, .s_va = qs }; + int rc = after_op(g, kind, omega_gpu_pfq_quant_record_locked(g->cl, &q)); + const OmegaPfqGemm c = { .n = nout, .k = k, .x64 = 1, .ntiles = ntiles, .tiles_va = tiles_va, .rowidx_va = rowidx, + .xq_va = q8, .xs_va = qs, .ymap_va = ymap, .y_va = y }; + if (rc == OMEGA_GPU_DGRAPH_OK) rc = after_op(g, kind, omega_gpu_pfq_gemm_record_locked(g->cl, &c)); + return rc; +} + +static int pf_qmma_dense(OmegaGpuQ36Graph *g, uint8_t kind, uint32_t l, uint32_t w, uint32_t n, uint64_t x, uint32_t k, uint32_t nout, uint64_t y) { + const uint64_t tiles = pf_h(g, g->pf.qtd) + ((uint64_t)l * 2u + w) * g->pf.qtd_cap * sizeof(OmegaPfqTile); + return pf_qmma_gemm(g, kind, x, n, 0, k, nout, tiles, g->pf.qtd_n, 0, 0, y); +} + /* part (a) of layer l: the mixer of every row and the router; ends with the router outputs in pf.rlb */ static int pf_record_mixer(OmegaGpuQ36Graph *g, uint32_t head, uint32_t l, uint32_t n, uint32_t pos0, uint32_t *ids_off, uint32_t *wts_off, uint32_t *xo_off, OmegaGpuRouterDevOut *first_router) { @@ -1028,13 +1109,16 @@ static int pf_record_mixer(OmegaGpuQ36Graph *g, uint32_t head, uint32_t l, uint3 const uint64_t pt2048 = va_of(g, g->lo.ptab), pt4096 = pt2048 + (uint64_t)H * 4u; const uint64_t in_norm = va_of(g, g->lo.norms) + (uint64_t)l * H * 4u, segd = va_of(g, g->lo.segd) + (uint64_t)l * SEGD_ROWS * OMEGA_GEMM_SEG_BYTES; const uint64_t XS = (uint64_t)H * 4u, MOS = (uint64_t)OMEGA_GPU_Q36_MIXER_OUT * 4u; + const int qmix = g->pf.qmma, qo = pf_qmma_o(g, l); /* DRA-82: the QMMA GEMMs read the natural rows (no PERM) */ int rc = OMEGA_GPU_DGRAPH_OK; /* layer 0 normalizes the embeddings; after that the previous layer's per-token COMBINE|NORM left layer l's x' in xq */ if (l == 0) rc = rec_res_rows(g, K_NORM_R, x0, 0, in_norm, xq0, SCALE_2P64, n); - if (rc == OMEGA_GPU_DGRAPH_OK) rc = rec_perm(g, K_PERM_XQ, xq0, pt2048, xp, H, n); + if (rc == OMEGA_GPU_DGRAPH_OK && !qmix) rc = rec_perm(g, K_PERM_XQ, xq0, pt2048, xp, H, n); if (!g->layer[l].attn) { if (rc == OMEGA_GPU_DGRAPH_OK) rc = after_op(g, OMEGA_GPU_Q36_K_AB, omega_gpu_bf16_gemv_rows_record(g->cl, g->layer[l].ab, n, xq0, abN)); - if (rc == OMEGA_GPU_DGRAPH_OK) rc = native_record_gemm(g, OMEGA_GPU_Q36_K_MIX, g->layer[l].mix, n, 1, segd, xp, mixN, 0, 0, 0); + if (rc == OMEGA_GPU_DGRAPH_OK) + rc = qmix ? pf_qmma_dense(g, OMEGA_GPU_Q36_K_MIX, l, 0, n, xq0, H, OMEGA_GPU_Q36_GDN_MIX, mixN) + : native_record_gemm(g, OMEGA_GPU_Q36_K_MIX, g->layer[l].mix, n, 1, segd, xp, mixN, 0, 0, 0); if (g->pf.gdn_multi && g->pf.mutant != 1 && g->pf.mutant != 3) { /* every token's recurrence step in one launch (the decode step T times, bit for bit: omega_gpu_gdn_api.h), the rows * into attN (unused on a GDN layer), then one PERM over the rows. TEST mutant 5: every token reads token 0's a|b. */ @@ -1042,7 +1126,7 @@ static int pf_record_mixer(OmegaGpuQ36Graph *g, uint32_t head, uint32_t l, uint3 rc = after_op(g, OMEGA_GPU_Q36_K_GDN, omega_gpu_gdn_multi_record(g->cl, g->gdn_h[head], ki, n, mixN, mixN + OMEGA_GPU_Q36_GDN_QKV * 4u, OMEGA_GPU_Q36_GDN_MIX * 4u, abN, g->pf.mutant == 5 ? 0u : OMEGA_GPU_Q36_AB * 4u, attN, (uint32_t)MOS, g->cfg.eps_l2, g->cfg.eps, 1.0f, SCALE_2P64)); - if (rc == OMEGA_GPU_DGRAPH_OK) rc = rec_perm(g, K_PERM_O, attN, pt4096, op, OMEGA_GPU_Q36_MIXER_OUT, n); + if (rc == OMEGA_GPU_DGRAPH_OK && !qo) rc = rec_perm(g, K_PERM_O, attN, pt4096, op, OMEGA_GPU_Q36_MIXER_OUT, n); } else for (uint32_t i = 0; i < n && rc == OMEGA_GPU_DGRAPH_OK; i++) { /* TEST mutant 1: the last two tokens' recurrence steps in swapped order */ @@ -1057,16 +1141,21 @@ static int pf_record_mixer(OmegaGpuQ36Graph *g, uint32_t head, uint32_t l, uint3 if (rc == OMEGA_GPU_DGRAPH_OK && g->pf.mutant == 3 && t > 0) rc = rec_perm(g, K_PERM_O, mo, pt4096, op + (t - 1) * MOS, OMEGA_GPU_Q36_MIXER_OUT, 1); } } else { - if (rc == OMEGA_GPU_DGRAPH_OK) rc = native_record_gemm(g, OMEGA_GPU_Q36_K_MIX, g->layer[l].mix, n, 1, segd, xp, mixN, 0, 0, 0); + if (rc == OMEGA_GPU_DGRAPH_OK) + rc = qmix ? pf_qmma_dense(g, OMEGA_GPU_Q36_K_MIX, l, 0, n, xq0, H, OMEGA_GPU_Q36_ATT_MIX, mixN) + : native_record_gemm(g, OMEGA_GPU_Q36_K_MIX, g->layer[l].mix, n, 1, segd, xp, mixN, 0, 0, 0); uint32_t w[OMEGA_DEC_GA_WORDS]; memset(w, 0, sizeof w); put64(w, OMEGA_DEC_GA_IN, mixN); put64(w, OMEGA_DEC_GA_TAB, va_of(g, g->lo.gtab)); put64(w, OMEGA_DEC_GA_OUT, aggN); if (rc == OMEGA_GPU_DGRAPH_OK) rc = add_glue(g, OMEGA_GPU_Q36_K_GATHER, g->mutant == 2 ? K_GATHER_M1 : K_GATHER, (OMEGA_GPU_Q36_ATT_MIX + OMEGA_DEC_THREADS - 1) / OMEGA_DEC_THREADS, n, (size_t)OMEGA_GPU_Q36_ATT_MIX * n, w, OMEGA_DEC_GA_WORDS); const int attn_multi = g->pf.attn_multi; - if (attn_multi && rc == OMEGA_GPU_DGRAPH_OK) /* every token's attention in one prep + attend pair, bit-identical to the steps */ - rc = after_op(g, OMEGA_GPU_Q36_K_ATTN, omega_gpu_decode_attn256_multi_record(g->cl, g->attn_h[head], ki, pos0, n, aggN, OMEGA_GPU_Q36_ATT_MIX * 4u, - g->cfg.eps, SCALE_2P64, attN, (uint32_t)MOS)); + if (attn_multi && rc == OMEGA_GPU_DGRAPH_OK) /* every token's attention in one prep + attend pair (bit-identical to the steps; DRA-85 fattn: tolerance) */ + rc = after_op(g, OMEGA_GPU_Q36_K_ATTN, + g->pf.fattn ? omega_gpu_prefill_fattn256_record(g->cl, g->attn_h[head], ki, pos0, n, aggN, OMEGA_GPU_Q36_ATT_MIX * 4u, g->cfg.eps, + SCALE_2P64, attN, (uint32_t)MOS) + : omega_gpu_decode_attn256_multi_record(g->cl, g->attn_h[head], ki, pos0, n, aggN, OMEGA_GPU_Q36_ATT_MIX * 4u, + g->cfg.eps, SCALE_2P64, attN, (uint32_t)MOS)); const int gate_rows = attn_multi && g->mutant != 3; /* every token's gate in one rows launch (the one-row arithmetic per element) */ if (gate_rows && rc == OMEGA_GPU_DGRAPH_OK) { uint32_t w2[OMEGA_DEC_GT_WORDS]; memset(w2, 0, sizeof w2); @@ -1084,9 +1173,11 @@ static int pf_record_mixer(OmegaGpuQ36Graph *g, uint32_t head, uint32_t l, uint3 rc = add_glue(g, OMEGA_GPU_Q36_K_GATE, g->mutant == 3 ? K_GATE_M1 : K_GATE, OMEGA_GPU_Q36_MIXER_OUT / OMEGA_DEC_THREADS, 1, OMEGA_GPU_Q36_MIXER_OUT, w2, OMEGA_DEC_GT_WORDS); } - if (rc == OMEGA_GPU_DGRAPH_OK) rc = rec_perm(g, K_PERM_O, attN, pt4096, op, OMEGA_GPU_Q36_MIXER_OUT, n); + if (rc == OMEGA_GPU_DGRAPH_OK && !qo) rc = rec_perm(g, K_PERM_O, attN, pt4096, op, OMEGA_GPU_Q36_MIXER_OUT, n); } - if (rc == OMEGA_GPU_DGRAPH_OK) rc = native_record_gemm(g, OMEGA_GPU_Q36_K_O, g->layer[l].o, n, 1, segd + OMEGA_GEMM_SEG_BYTES, op, oN, 0, 0, 0); + if (rc == OMEGA_GPU_DGRAPH_OK) + rc = qo ? pf_qmma_dense(g, OMEGA_GPU_Q36_K_O, l, 1, n, attN, OMEGA_GPU_Q36_MIXER_OUT, H, oN) + : native_record_gemm(g, OMEGA_GPU_Q36_K_O, g->layer[l].o, n, 1, segd + OMEGA_GEMM_SEG_BYTES, op, oN, 0, 0, 0); if (rc == OMEGA_GPU_DGRAPH_OK) rc = rec_res_rows(g, K_ADD_R, x0, oN, 0, 0, 1.0f, n); for (uint32_t r0 = 0; r0 < n && rc == OMEGA_GPU_DGRAPH_OK; r0 += OMEGA_GPU_ROUTER_MAX_ROWS) { const uint32_t rows = n - r0 < OMEGA_GPU_ROUTER_MAX_ROWS ? n - r0 : OMEGA_GPU_ROUTER_MAX_ROWS; @@ -1103,9 +1194,10 @@ static int pf_record_mixer(OmegaGpuQ36Graph *g, uint32_t head, uint32_t l, uint3 } /* the host GROUP: the n * 8 routed picks sorted by expert id (then token, then slot) into segments and row maps, the shared - * expert as its own one-segment table (x' row t, y row t * 9 + 8). Returns the routed segment count. */ + * expert as its own one-segment table (x' row t, y row t * 9 + 8). Returns the routed segment count. With QMMA (DRA-82) the + * same segments, the shared one appended at rows n * 8 .., are cut into 64-row tiles over one combined row map. */ static uint32_t pf_group(OmegaGpuQ36Graph *g, uint32_t l, uint32_t n, uint32_t ids_off) { - const uint32_t S = NG - 1u; + const uint32_t S = NG - 1u, ep = g->pf.qmma ? OMEGA_PFQ_BM : 4u; /* rows per weight pass: one QMMA tile or 4 GEMV rows */ uint32_t cnt[256], start[256]; memset(cnt, 0, sizeof cnt); for (uint32_t t = 0; t < n; t++) { @@ -1122,7 +1214,7 @@ static uint32_t pf_group(OmegaGpuQ36Graph *g, uint32_t l, uint32_t n, uint32_t i (void)omega_gpu_fp8_tensor_entry(g->layer[l].dn, e, &sd[segs].w_va, &sd[segs].s_va); sg[segs].row0 = sd[segs].row0 = row; sg[segs].cnt = sd[segs].cnt = cnt[e]; if (g->pf.mutant == 2 && cnt[e] > 1u) { sg[segs].cnt--; sd[segs].cnt--; } /* TEST mutant 2: every segment one row short */ - g->pf.streamed += (uint64_t)((cnt[e] + 3u) / 4u) * PF_EXPERT_BYTES; /* gate|up and down, 4 rows per pass */ + g->pf.streamed += (uint64_t)((cnt[e] + ep - 1u) / ep) * PF_EXPERT_BYTES; /* gate|up and down, ep rows per pass */ row += cnt[e]; segs++; } uint32_t *xm = pf_hc(g, g->pf.xmap), *ym = pf_hc(g, g->pf.ymap); @@ -1136,10 +1228,22 @@ static uint32_t pf_group(OmegaGpuQ36Graph *g, uint32_t l, uint32_t n, uint32_t i (void)omega_gpu_fp8_tensor_entry(g->layer[l].gu, 256u, &g2->w_va, &g2->s_va); /* expert 256 = the shared expert */ (void)omega_gpu_fp8_tensor_entry(g->layer[l].dn, 256u, &d2->w_va, &d2->s_va); g2->cnt = d2->cnt = n; - g->pf.streamed += (uint64_t)((n + 3u) / 4u) * PF_EXPERT_BYTES; + g->pf.streamed += (uint64_t)((n + ep - 1u) / ep) * PF_EXPERT_BYTES; uint32_t *xm2 = pf_hc(g, g->pf.xmap2), *ym2 = pf_hc(g, g->pf.ymap2); for (uint32_t t = 0; t < n; t++) { xm2[t] = t; ym2[t] = t * NG + S; } for (uint32_t p = n; p < n + PF_PAD; p++) { xm2[p] = 0; ym2[p] = 0; } + if (g->pf.qmma) { + OmegaPfqTile qg[257], qd[257]; + memcpy(qg, sg, (size_t)segs * sizeof *qg); memcpy(qd, sd, (size_t)segs * sizeof *qd); /* Seg32 is the tile entry */ + qg[segs] = (OmegaPfqTile){ .w_va = g2->w_va, .s_va = g2->s_va, .row0 = n * S, .cnt = g2->cnt, .pad = 0 }; + qd[segs] = (OmegaPfqTile){ .w_va = d2->w_va, .s_va = d2->s_va, .row0 = n * S, .cnt = d2->cnt, .pad = 0 }; + uint32_t *qxm = pf_hc(g, g->pf.qxm), *qym = pf_hc(g, g->pf.qym); + memcpy(qxm, xm, (size_t)n * S * 4u); memcpy(qym, ym, (size_t)n * S * 4u); + for (uint32_t t = 0; t < n; t++) { qxm[n * S + t] = t; qym[n * S + t] = t * NG + S; } + for (uint32_t p = n * NG; p < n * NG + OMEGA_PFQ_MAP_PAD; p++) { qxm[p] = 0; qym[p] = 0; } + g->pf.qtg_n = omega_pfq_tiles(qg, segs + 1u, pf_hc(g, g->pf.qtgu), g->pf.qtg_cap); + if (omega_pfq_tiles(qd, segs + 1u, pf_hc(g, g->pf.qtdn), g->pf.qtg_cap) != g->pf.qtg_n) g->pf.qtg_n = 0; + } return segs; } @@ -1150,24 +1254,37 @@ static int pf_record_experts(OmegaGpuQ36Graph *g, uint32_t head, uint32_t l, uin const uint64_t pt2048 = va_of(g, g->lo.ptab), pt512 = pt2048 + (uint64_t)(H + OMEGA_GPU_Q36_MIXER_OUT) * 4u; const uint64_t in_norm = va_of(g, g->lo.norms) + (uint64_t)l * H * 4u, XS = (uint64_t)H * 4u; const uint32_t R = n * NG; const uint32_t S = NG - 1u; /* rows each expert GEMM touches: 8 routed per token, 1 shared */ - int rc = rec_perm(g, K_PERM_XO, rlb + xo_off, pt2048, xp2, H, n); /* the router's x' rows, one launch buffer apart */ - if (rc == OMEGA_GPU_DGRAPH_OK) - rc = native_record_gemm(g, OMEGA_GPU_Q36_K_GATE_UP, g->layer[l].gu, n * S, segs, pf_h(g, g->pf.sgu), xp2, guN, pf_h(g, g->pf.xmap), - pf_h(g, g->pf.ymap), 4); - if (rc == OMEGA_GPU_DGRAPH_OK) - rc = native_record_gemm(g, OMEGA_GPU_Q36_K_GATE_UP, g->layer[l].gu, n, 1, pf_h(g, g->pf.sgu2), xp2, guN, pf_h(g, g->pf.xmap2), - pf_h(g, g->pf.ymap2), 4); + int rc = OMEGA_GPU_DGRAPH_OK; + if (g->pf.qmma) { /* DRA-82: the x' rows quantised in place (one launch buffer apart), routed + shared in one QMMA launch */ + if (g->pf.qtg_n == 0) return pf_fail(g, "q36 prefill qmma: expert tile table over capacity"); + rc = pf_qmma_gemm(g, OMEGA_GPU_Q36_K_GATE_UP, rlb + xo_off, n, (uint32_t)(g->lo.lb_stride / 4u), H, 2u * EI, pf_h(g, g->pf.qtgu), + g->pf.qtg_n, pf_h(g, g->pf.qxm), pf_h(g, g->pf.qym), guN); + } else { + rc = rec_perm(g, K_PERM_XO, rlb + xo_off, pt2048, xp2, H, n); /* the router's x' rows, one launch buffer apart */ + if (rc == OMEGA_GPU_DGRAPH_OK) + rc = native_record_gemm(g, OMEGA_GPU_Q36_K_GATE_UP, g->layer[l].gu, n * S, segs, pf_h(g, g->pf.sgu), xp2, guN, pf_h(g, g->pf.xmap), + pf_h(g, g->pf.ymap), 4); + if (rc == OMEGA_GPU_DGRAPH_OK) + rc = native_record_gemm(g, OMEGA_GPU_Q36_K_GATE_UP, g->layer[l].gu, n, 1, pf_h(g, g->pf.sgu2), xp2, guN, pf_h(g, g->pf.xmap2), + pf_h(g, g->pf.ymap2), 4); + } uint32_t w3[OMEGA_DEC_SW_WORDS]; memset(w3, 0, sizeof w3); put64(w3, OMEGA_DEC_SW_GU, guN); put64(w3, OMEGA_DEC_SW_ACT, actN); putf(w3, OMEGA_DEC_SW_SCALE, SCALE_2P64); if (rc == OMEGA_GPU_DGRAPH_OK) rc = add_glue(g, OMEGA_GPU_Q36_K_SWIGLU, g->mutant == 1 ? K_SW_M1 : K_SW, EI / OMEGA_DEC_THREADS, R, (size_t)R * EI, w3, OMEGA_DEC_SW_WORDS); - if (rc == OMEGA_GPU_DGRAPH_OK) rc = rec_perm(g, K_PERM_ACT, actN, pt512, actp, EI, R); - if (rc == OMEGA_GPU_DGRAPH_OK) - rc = native_record_gemm(g, OMEGA_GPU_Q36_K_DOWN, g->layer[l].dn, n * S, segs, pf_h(g, g->pf.sdn), actp, dnN, pf_h(g, g->pf.ymap), - pf_h(g, g->pf.ymap), 4); - if (rc == OMEGA_GPU_DGRAPH_OK) - rc = native_record_gemm(g, OMEGA_GPU_Q36_K_DOWN, g->layer[l].dn, n, 1, pf_h(g, g->pf.sdn2), actp, dnN, pf_h(g, g->pf.ymap2), - pf_h(g, g->pf.ymap2), 4); + if (g->pf.qmma) { /* act row p is gate_up's y row p: the down GEMM reads and writes through the same y map */ + if (rc == OMEGA_GPU_DGRAPH_OK) + rc = pf_qmma_gemm(g, OMEGA_GPU_Q36_K_DOWN, actN, R, 0, EI, H, pf_h(g, g->pf.qtdn), g->pf.qtg_n, pf_h(g, g->pf.qym), + pf_h(g, g->pf.qym), dnN); + } else { + if (rc == OMEGA_GPU_DGRAPH_OK) rc = rec_perm(g, K_PERM_ACT, actN, pt512, actp, EI, R); + if (rc == OMEGA_GPU_DGRAPH_OK) + rc = native_record_gemm(g, OMEGA_GPU_Q36_K_DOWN, g->layer[l].dn, n * S, segs, pf_h(g, g->pf.sdn), actp, dnN, pf_h(g, g->pf.ymap), + pf_h(g, g->pf.ymap), 4); + if (rc == OMEGA_GPU_DGRAPH_OK) + rc = native_record_gemm(g, OMEGA_GPU_Q36_K_DOWN, g->layer[l].dn, n, 1, pf_h(g, g->pf.sdn2), actp, dnN, pf_h(g, g->pf.ymap2), + pf_h(g, g->pf.ymap2), 4); + } const int last = l + 1 == g->cfg.layers; const uint64_t nw = last ? va_of(g, g->lo.fnorm) : in_norm + H * 4u; /* the last layer: only the last token's COMBINE|NORM is needed (its hidden feeds the head; the state is complete) */ @@ -1573,7 +1690,9 @@ int omega_gpu_q36_graph_prefill(OmegaGpuQ36Graph *g, uint32_t head, const float uint32_t *tok = cpu_of(g, token_of(g, head)); tok[0] = TOKEN_POISON; tok[1] = TOKEN_POISON; memcpy(pf_hc(g, g->pf.x), x_embed, (size_t)n * H * 4u); write_dense_segments(g, n); - if (omega_gpu_session_sync_to_gpu(&g->buf) != 0 || omega_gpu_session_sync_to_gpu(&g->pf.hb) != 0) rc = fail(g, NULL, OMEGA_GPU_DGRAPH_CHIP_FAIL); + if (g->pf.qmma) rc = pf_qmma_dense_tables(g, n); + if (rc == OMEGA_GPU_DGRAPH_OK && (omega_gpu_session_sync_to_gpu(&g->buf) != 0 || omega_gpu_session_sync_to_gpu(&g->pf.hb) != 0)) + rc = fail(g, NULL, OMEGA_GPU_DGRAPH_CHIP_FAIL); } for (uint32_t l = 0; l < g->cfg.layers && rc == OMEGA_GPU_DGRAPH_OK; l++) { uint32_t ids_off = 0, wts_off = 0, xo_off = 0; @@ -1601,8 +1720,10 @@ int omega_gpu_q36_graph_prefill(OmegaGpuQ36Graph *g, uint32_t head, const float if (rc == OMEGA_GPU_DGRAPH_OK && omega_gpu_session_sync_to_cpu(&g->pf.hb) != 0) rc = fail(g, NULL, OMEGA_GPU_DGRAPH_CHIP_FAIL); uint32_t segs = 0; if (rc == OMEGA_GPU_DGRAPH_OK) { - /* the dense trunk: mix (or q|k|v) and o, 8 rows per pass */ - g->pf.streamed += (uint64_t)((n + 7u) / 8u) * H * ((g->layer[l].attn ? OMEGA_GPU_Q36_ATT_MIX : OMEGA_GPU_Q36_GDN_MIX) + OMEGA_GPU_Q36_MIXER_OUT); + /* the dense trunk: mix (or q|k|v) and o, 8 rows per GEMV pass or one 64-row QMMA tile (DRA-82) */ + const uint32_t mp = g->pf.qmma ? OMEGA_PFQ_BM : 8u, opp = pf_qmma_o(g, l) ? OMEGA_PFQ_BM : 8u; + g->pf.streamed += (uint64_t)((n + mp - 1u) / mp) * H * (g->layer[l].attn ? OMEGA_GPU_Q36_ATT_MIX : OMEGA_GPU_Q36_GDN_MIX) + + (uint64_t)((n + opp - 1u) / opp) * H * OMEGA_GPU_Q36_MIXER_OUT; segs = pf_group(g, l, n, ids_off); if (segs == 0 || segs > 256u) rc = pf_fail(g, "q36 prefill: router picks out of range"); } diff --git a/src/omega_gpu_q36_graph.h b/src/omega_gpu_q36_graph.h index 076b03f7..c225f2f2 100644 --- a/src/omega_gpu_q36_graph.h +++ b/src/omega_gpu_q36_graph.h @@ -150,12 +150,23 @@ int omega_gpu_q36_graph_read_buf(OmegaGpuQ36Graph *g, int which, float *out, uin * as ONE multi-token launch per layer (the decode step's arithmetic in a loop, bit-identical to the per-token launches; * mutants 1 and 3 use the per-token form); AIEN_OMEGA_Q36_PF_GDN=0 forces the per-token launches. Each attention layer is * one prep launch (every token's K/V rows) and one attend launch (grid (splits, tokens x rows), the decode kernel per - * token, bit-identical; omega_gpu_decode_attn256_multi_record); AIEN_OMEGA_Q36_PF_ATTN=0 forces the per-token launches. */ + * token, bit-identical; omega_gpu_decode_attn256_multi_record); AIEN_OMEGA_Q36_PF_ATTN=0 forces the per-token launches. + * DRA-82: AIEN_OMEGA_Q36_PF_QMMA=1 (read by prefill_alloc, which reallocates when it changed; default off) moves the mix, + * o, gate_up and down GEMMs onto the tensor cores (omega_gpu_pfq_api.h: per-row e4m3 quantiser + QMMA tiles of 64 rows, + * the routed and shared experts in one launch, no PERM launches). Not bit-identical to the GEMV: the activations are + * quantised to e4m3 per 128-wide block. o stays on the GEMV where the GDN runs per token. Refused with native artifacts. + * DRA-85: AIEN_OMEGA_Q36_PF_FATTN=1 (read by prefill_alloc; default off; ignored with AIEN_OMEGA_Q36_PF_ATTN=0) runs each + * attention layer's attend as the flash-style tensor-core kernel (omega_gpu_prefill_fattn256_api.h, grid ceil(n / 16) x + * kv heads, bf16 HMMA with an online softmax). Not bit-identical to the steps (P rounded to bf16, another summation order): + * the tolerance and the golden tokens are its gate. AIEN_OMEGA_Q36_PF_FATTN=2: the same with the kernel's variant 2 (the + * next 16-key block's K / V lines touched into L1 during softmax + PV; same arithmetic, same output bits as variant 1 in + * the simulator). TEST mutant 8 (with FATTN=1 or 2): its attend kernel without the rescale. */ #define OMEGA_GPU_Q36_PREFILL_MAX_ROWS 128u /* x 8 routed expert rows <= the fp8 gemm's 1024 (the shared expert is its own GEMM) */ int omega_gpu_q36_graph_prefill_alloc(OmegaGpuQ36Graph *g, uint32_t cap); uint32_t omega_gpu_q36_graph_prefill_cap(const OmegaGpuQ36Graph *g); /* fp8 GEMM weight bytes every prefill call on g so far streamed (a running count: take the difference around a call): every expert once per 4 of its rows, the dense mix/o once per 8 - * rows (the ceiling receipt: these bytes over the call time against the memory bandwidth). The bf16 a|b, router and head + * rows, on the QMMA path (AIEN_OMEGA_Q36_PF_QMMA=1) both once per 64-row tile (the ceiling receipt: these bytes over the + * call time against the memory bandwidth). The bf16 a|b, router and head * reads are not counted. */ uint64_t omega_gpu_q36_graph_prefill_streamed(const OmegaGpuQ36Graph *g); int omega_gpu_q36_graph_prefill(OmegaGpuQ36Graph *g, uint32_t head, const float *x_embed, uint32_t n, uint32_t pos0, int want_token, diff --git a/tests/bw_hazard_test.c b/tests/bw_hazard_test.c index e052b090..32450efd 100644 --- a/tests/bw_hazard_test.c +++ b/tests/bw_hazard_test.c @@ -487,7 +487,7 @@ static void sweep(void) { } for (unsigned a = 0; a < 5; a++) for (unsigned w = 8; w <= 16; w *= 2) for (unsigned epi = 0; epi <= 1; epi++) for (unsigned dir = 0; dir <= 1; dir++) for (unsigned wt = 0; wt <= 120; wt += 60) { - OmegaQgSpec s = { ks[a], 4, w, epi, dir, 512, wt, 0 }; + OmegaQgSpec s = { ks[a], 4, w, epi, dir, 512, wt, 0, 0, 0 }; snprintf(v, sizeof v, "k%u warps%u epi%u direct%u n512 wait%u", ks[a], w, epi, dir, wt); if (BUILD(omega_blackwell_codegen_qgemm_prog(&s, &g_prog))) sweep_prog("qgemm", v, P_TC | P_QMMA); } diff --git a/tests/bw_warp_sim_pa.h b/tests/bw_warp_sim_pa.h index 1aae63c4..0922102b 100644 --- a/tests/bw_warp_sim_pa.h +++ b/tests/bw_warp_sim_pa.h @@ -196,7 +196,10 @@ static void ws_lane_exec(WsSim *s, WsLane *l, const BlackwellIRInsn *in, int pc, case BW_IR_LDG_E: { uint64_t ad = ws_rd64(l, in->src1_vreg, p); if (!ws_mem_ok(s, ad, 4, pc)) return; uint32_t x; memcpy(&x, (const void *)(uintptr_t)ad, 4); ws_wrs(l, in->dst_vreg, in->dst_subreg, x, p); break; } case BW_IR_LDG_E_U16: { uint64_t ad = ws_rd64(l, in->src1_vreg, p); if (!ws_mem_ok(s, ad, 2, pc)) return; uint16_t x; memcpy(&x, (const void *)(uintptr_t)ad, 2); ws_wrs(l, in->dst_vreg, in->dst_subreg, x, p); break; } case BW_IR_STG_E: { uint64_t ad = ws_rd64(l, in->src1_vreg, p) + (uint64_t)(int64_t)(int32_t)in->imm; if (!ws_mem_ok(s, ad, 4, pc)) return; memcpy((void *)(uintptr_t)ad, &b, 4); break; } - case BW_IR_LDG_E_64: case BW_IR_LDG_E_128: { unsigned n = in->op == BW_IR_LDG_E_64 ? 8u : 16u; uint64_t ad = ws_rd64(l, in->src1_vreg, p) + (uint64_t)(int64_t)(int32_t)in->imm; if (!ws_mem_ok(s, ad, n, pc)) { if (getenv("WS_DBG")) fprintf(stderr, " tid %u cx %u cy %u\n", tid, cx, cy); return; } if (ad & (n - 1)) { ws_fail(s, WS_E_MEM, pc, "wide global load not naturally aligned"); return; } uint32_t x[4]; memcpy(x, (const void *)(uintptr_t)ad, n); for (unsigned i = 0; i < n / 4; i++) ws_wrs(l, in->dst_vreg, i, x[i], p); break; } + /* the encoder adds dst_subreg to the destination register of LDG.64/.128 as of every op (DRA-85, 2026-11-01: the + * flash prefill attention loads Q pairs into the upper half of an A-fragment quad); a sub-register that breaks the + * load's register alignment has no encoding */ + case BW_IR_LDG_E_64: case BW_IR_LDG_E_128: { unsigned n = in->op == BW_IR_LDG_E_64 ? 8u : 16u; uint64_t ad = ws_rd64(l, in->src1_vreg, p) + (uint64_t)(int64_t)(int32_t)in->imm; if (in->dst_subreg & (n / 4u - 1u)) { ws_fail(s, WS_E_OP, pc, "wide global load into a misaligned sub-register"); return; } if (!ws_mem_ok(s, ad, n, pc)) { if (getenv("WS_DBG")) fprintf(stderr, " tid %u cx %u cy %u\n", tid, cx, cy); return; } if (ad & (n - 1)) { ws_fail(s, WS_E_MEM, pc, "wide global load not naturally aligned"); return; } uint32_t x[4]; memcpy(x, (const void *)(uintptr_t)ad, n); for (unsigned i = 0; i < n / 4; i++) ws_wrs(l, in->dst_vreg, in->dst_subreg + i, x[i], p); break; } case BW_IR_LDS128: { uint32_t ad = a + in->imm; if (ad & 15u) { ws_fail(s, WS_E_SMEM, pc, "LDS.128 address not 16-byte aligned"); return; } for (unsigned i = 0; i < 4; i++) { uint32_t *m = ws_smem(s, ad + 4u * i, pc); if (!m) return; ws_wrs(l, in->dst_vreg, i, *m, p); } break; } case BW_IR_LDS32: { uint32_t *m = ws_smem(s, a, pc); if (!m) return; ws_wrs(l, in->dst_vreg, in->dst_subreg, *m, p); break; } case BW_IR_STS32: { uint32_t *m = ws_smem(s, a, pc); if (!m) return; *m = b; break; } diff --git a/tests/gpu_pfq_test.c b/tests/gpu_pfq_test.c new file mode 100644 index 00000000..824e8c37 --- /dev/null +++ b/tests/gpu_pfq_test.c @@ -0,0 +1,607 @@ +/* SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception */ +/* gpu_pfq_test.c (DRA-82, CUDApp #220): the tiled mma.sync FP8 prefill path, omega_gpu_pfq_api.h. + * --host-only tiler, launch plans, the pre-DRA-82 kernel words (digest of CUDApp main 4bbccf0), the x64 quantiser + * identity, the C reference against a double oracle + * --sim the planned kernels and arguments in the warp simulator: quantiser row stride, row map (rowidx), output + * map (ymap), x64 scales, segments longer than a tile, both issue orders; bit-identical to the C reference, + * untouched output rows left alone; AIEN_OMEGA_PFQ_MUTANT 1..4 each caught + * --chip (inside a GB10 window only) the Qwen3.6 expert shapes of one prefill chunk through a command list: + * quantiser and GEMM outputs bit-identical to the reference, mutants caught, per-launch GPU time + * AIEN_OMEGA_PFQ_MUTANT set in the environment applies to every planned launch, so a clean case then FAILS: the + * end-to-end check of the knob. Verdict line last: "GPU_PFQ: PASS|FAIL". */ +#include "omega_gpu_pfq_api.h" +#include "omega_gpu_prefill.h" +#include "omega_gpu_fp8_api.h" +#include "omega_gpu_cmdlist.h" +#include "bw_warp_sim_tc.h" +#include "pfq_legacy_words.h" +#include +#include +#include +#include + +/* printed by tests/pfq_legacy_words.h built against CUDApp main 4bbccf0 (evidence/DRA-82-pfq/golden-main-4bbccf0.txt) */ +#define PFQ_LEGACY_PROGRAMS 264 +#define PFQ_LEGACY_DIGEST 0x0dd37a9ee7562178ull +#define PAD OMEGA_PFQ_MAP_PAD + +static uint64_t rng = 0x9e3779b97f4a7c15ull; +static uint32_t rnd(void) { rng ^= rng << 13; rng ^= rng >> 7; rng ^= rng << 17; return (uint32_t)(rng >> 16); } +static float u2f(uint32_t u) { float f; memcpy(&f, &u, 4); return f; } +static uint32_t f2u(float f) { uint32_t u; memcpy(&u, &f, 4); return u; } +static int cmp_u64(const void *a, const void *b) { uint64_t x = *(const uint64_t *)a, y = *(const uint64_t *)b; return x < y ? -1 : x > y; } +static int env_mutant; + +/* the quantiser's header semantics (tests/gpu_qgemm_test.c pq_ref; mutant 2 = c 0) */ +static void pq_ref(const float *x, uint32_t k, uint8_t *q, float *s, int mutant) { + for (uint32_t b = 0; b < k / 128; b++) { + float m = ldexpf(1.0f, -100); + for (uint32_t j = 0; j < 128; j++) m = fmaxf(m, fabsf(x[128 * b + j])); + uint32_t mb = f2u(m), E = mb >> 23, M = mb & 0x7fffff, c = mutant == 2 ? 0 : (M + 0x1fffff) >> 23; + s[b] = u2f((E + c - 8) << 23); + const float inv = u2f((262 - E - c) << 23); + for (uint32_t j = 0; j < 128; j++) q[128 * b + j] = qm_e4m3_rne_sat(x[128 * b + j] * inv); + } +} +static float rand_act(void) { + float v = ((float)(rnd() & 0xffffff) / 16777216.0f) * 2.0f - 1.0f; + int r = rnd() % 32; if (r == 0) v *= 300.0f; else if (r == 1) v *= 1e-3f; else if (r == 2) v = 0.0f; + return v; +} +static uint8_t rand_e4m3(void) { for (;;) { uint8_t c = (uint8_t)rnd(); if ((c & 0x7f) != 0x7f) return c; } } + +/* ---------------- one grouped expert GEMM problem ---------------- */ +typedef struct { + uint32_t E, n, k, KB, M, XR, YR, indexed, ymapped, x64; + uint8_t *w; uint16_t *sbf; float *swf; /* [E][n][k] e4m3, scale_inv bf16, GEMV-tensor scales (f32 x 2^56) */ + float *x; /* XR true activation rows */ + uint8_t *xq; float *xs, *xs64; /* XR + PAD rows: e4m3, true scales, the scales of 2^64 x */ + uint32_t *eid, *ridx, *ymap; /* M + PAD entries */ + uint32_t *counts; OmegaPfqTile *seg; /* one segment per expert, in order (zero counts kept) */ + uint32_t x64_mismatch; /* q(2^64 x) != q(x) or s(2^64 x) != 2^64 s(x) outside all-zero blocks */ +} Prob; + +static void prob_make(Prob *P, uint32_t E, uint32_t n, uint32_t k, const uint32_t *counts, uint32_t XR, uint32_t indexed, uint32_t ymapped, uint32_t YR) { + memset(P, 0, sizeof *P); + uint32_t M = 0; for (uint32_t e = 0; e < E; e++) M += counts[e]; + P->E = E; P->n = n; P->k = k; P->KB = k / 128; P->M = M; P->indexed = indexed; P->ymapped = ymapped; + P->XR = indexed ? XR : M; P->YR = ymapped ? YR : M; + const size_t wn = (size_t)E * n * k, sn = (size_t)E * (n / 128) * P->KB, XA = (size_t)P->XR + PAD; + P->w = malloc(wn); P->sbf = malloc(sn * 2); P->swf = malloc(sn * 4); + for (size_t i = 0; i < wn; i++) P->w[i] = rand_e4m3(); + for (size_t i = 0; i < sn; i++) { float s = ldexpf(1.0f + (float)(rnd() & 127) / 128.0f, -(int)(rnd() % 12) - 4); P->sbf[i] = (uint16_t)(f2u(s) >> 16); } + if (omega_fp8_pack_scales(P->sbf, sn, P->swf, 0) != 0) { printf("scale pack refused\n"); exit(2); } + P->x = calloc(XA * k, 4); P->xq = calloc(XA * k, 1); P->xs = calloc(XA * P->KB, 4); P->xs64 = calloc(XA * P->KB, 4); + for (size_t i = 0; i < (size_t)P->XR * k; i++) P->x[i] = rand_act(); + if (P->XR > 3) memset(P->x + 3 * (size_t)k, 0, k * 4); /* an all-zero row: the amax floor */ + if (P->XR > 5) P->x[5 * (size_t)k + 77] = 3.0e4f; /* an outlier */ + float *x64 = malloc(k * 4); uint8_t *q64 = malloc(k); + for (size_t r = 0; r < XA; r++) { + pq_ref(P->x + r * k, k, P->xq + r * k, P->xs + r * P->KB, 0); + for (uint32_t j = 0; j < k; j++) x64[j] = ldexpf(P->x[r * k + j], 64); + pq_ref(x64, k, q64, P->xs64 + r * P->KB, 0); + for (uint32_t b = 0; b < P->KB; b++) { + int zero = 1; for (uint32_t j = 0; j < 128; j++) if (P->x[r * k + 128 * b + j] != 0.0f) zero = 0; + if (memcmp(q64 + 128 * b, P->xq + r * k + 128 * b, 128)) P->x64_mismatch++; + else if (!zero && f2u(P->xs64[r * P->KB + b]) != f2u(ldexpf(P->xs[r * P->KB + b], 64))) P->x64_mismatch++; + } + } + free(x64); free(q64); + P->eid = calloc(M + PAD, 4); P->ridx = calloc(M + PAD, 4); P->ymap = calloc(M + PAD, 4); + P->counts = malloc(E * 4); memcpy(P->counts, counts, E * 4); + P->seg = calloc(E, sizeof *P->seg); + uint32_t row = 0; + for (uint32_t e = 0; e < E; e++) { + P->seg[e].w_va = (uintptr_t)(P->w + (size_t)e * n * k); P->seg[e].s_va = (uintptr_t)(P->swf + (size_t)e * (n / 128) * P->KB); + P->seg[e].row0 = row; P->seg[e].cnt = counts[e]; + for (uint32_t q = 0; q < counts[e]; q++) P->eid[row + q] = e; + row += counts[e]; + } + for (uint32_t p = 0; p < M; p++) P->ridx[p] = indexed ? rnd() % P->XR : p; + uint32_t *perm = malloc((size_t)P->YR * 4); for (uint32_t i = 0; i < P->YR; i++) perm[i] = i; + for (uint32_t i = P->YR; i > 1; i--) { uint32_t j = rnd() % i, t = perm[i - 1]; perm[i - 1] = perm[j]; perm[j] = t; } + for (uint32_t p = 0; p < M; p++) P->ymap[p] = ymapped ? perm[p] : p; + free(perm); +} +static void prob_free(Prob *P) { + free(P->w); free(P->sbf); free(P->swf); free(P->x); free(P->xq); free(P->xs); free(P->xs64); + free(P->eid); free(P->ridx); free(P->ymap); free(P->counts); free(P->seg); +} + +/* the kernel's arithmetic for routed row p, output column c (weight row c), with the TRUE activation scales */ +static const QmmaModel GB10Q = { 32, 26, 0, 2, 0 }; /* chip-exact, evidence OWN30B-L1G-QMMA-PFGEMM-c742aa13 */ +static float qref(const Prob *P, uint32_t p, uint32_t c) { + const uint32_t k = P->k, KB = P->KB, e = P->eid[p], s = P->ridx[p]; + const uint8_t *xr = P->xq + (size_t)s * k, *wr = P->w + ((size_t)e * P->n + c) * k; + const float *swt = P->swf + ((size_t)e * (P->n / 128) + c / 128) * KB; + float acc = 0.0f; + for (uint32_t kb = 0; kb < KB; kb++) { + const float sc = P->xs[(size_t)s * KB + kb] * (swt[kb] * 0x1p-56f); + for (uint32_t h = 0; h < 2; h++) { + float T = 0.0f; + for (uint32_t v = 0; v < 2; v++) { + float av[32], bv[32]; + for (uint32_t t = 0; t < 4; t++) for (uint32_t j = 0; j < 4; j++) { + const uint32_t o = 128 * kb + 64 * h + 16 * t + 8 * v + j; + av[4 * t + j] = qm_e4m3(xr[o]); bv[4 * t + j] = qm_e4m3(wr[o]); + av[16 + 4 * t + j] = qm_e4m3(xr[o + 4]); bv[16 + 4 * t + j] = qm_e4m3(wr[o + 4]); + } + T = qm_dot32(&GB10Q, av, bv, T); + } + acc = fmaf(T, sc, acc); + } + } + return acc; +} +/* double oracle: original bf16 weight scales, dequantised activations */ +static double qoracle(const Prob *P, uint32_t p, uint32_t c, double *mag) { + const uint32_t k = P->k, KB = P->KB, e = P->eid[p], s = P->ridx[p]; + double acc = 0, m = 0; + for (uint32_t j = 0; j < k; j++) { + const double sw = u2f((uint32_t)P->sbf[((size_t)e * (P->n / 128) + c / 128) * KB + j / 128] << 16); + const double t = (double)qm_e4m3(P->w[((size_t)e * P->n + c) * k + j]) * sw * qm_e4m3(P->xq[(size_t)s * k + j]) * P->xs[(size_t)s * KB + j / 128]; + acc += t; m += fabs(t); + } + *mag = m; return acc; +} +/* expected y (YR x n f32): routed rows at their map rows, every other row the 0xee fill */ +static uint32_t *expect_y(const Prob *P) { + uint32_t *y = malloc((size_t)P->YR * P->n * 4); memset(y, 0xee, (size_t)P->YR * P->n * 4); + for (uint32_t p = 0; p < P->M; p++) for (uint32_t c = 0; c < P->n; c++) y[(size_t)P->ymap[p] * P->n + c] = f2u(qref(P, p, c)); + return y; +} +static size_t ydiff(const Prob *P, const uint32_t *got, const uint32_t *want) { + size_t bad = 0; + for (size_t i = 0; i < (size_t)P->YR * P->n; i++) if (got[i] != want[i]) { if (getenv("PFDBG") && bad < 6) printf(" y[%zu][%zu] got %08x want %08x\n", i / P->n, i % P->n, got[i], want[i]); bad++; } + return bad; +} + +/* ---------------- host ---------------- */ +static int tiler_check(const OmegaPfqTile *seg, uint32_t nseg, uint32_t rows, const OmegaPfqTile *t, uint32_t nt) { + int bad = 0; uint8_t *seen = calloc(rows + 1, 1); + for (uint32_t i = 0; i < nt; i++) { + if (t[i].cnt == 0 || t[i].cnt > OMEGA_PFQ_BM || t[i].pad) bad++; + const OmegaPfqTile *s = NULL; + for (uint32_t j = 0; j < nseg; j++) if (seg[j].cnt && t[i].row0 >= seg[j].row0 && t[i].row0 < seg[j].row0 + seg[j].cnt) s = &seg[j]; + if (!s || t[i].w_va != s->w_va || t[i].s_va != s->s_va || t[i].row0 + t[i].cnt > s->row0 + s->cnt) { bad++; continue; } + for (uint32_t r = 0; r < t[i].cnt; r++) seen[t[i].row0 + r]++; + } + for (uint32_t r = 0; r < rows; r++) if (seen[r] != 1) bad++; + free(seen); + return bad; +} +static int host_tiler(void) { + static const uint32_t cnt[] = { 0, 1, 63, 64, 65, 130, 7 }; + const uint32_t ns = sizeof cnt / sizeof cnt[0]; + OmegaPfqTile seg[7], t[32]; uint32_t row = 0, want = 0; + for (uint32_t i = 0; i < ns; i++) { memset(&seg[i], 0, sizeof seg[i]); seg[i].w_va = 0x1000u * (i + 1); seg[i].s_va = 0x100000u * (i + 1); seg[i].row0 = row; seg[i].cnt = cnt[i]; row += cnt[i]; want += (cnt[i] + 63) / 64; } + const uint32_t cap = omega_pfq_tile_cap(row, ns), nt = omega_pfq_tiles(seg, ns, t, 32); + const int bad = tiler_check(seg, ns, row, t, nt); + const int over = omega_pfq_tiles(seg, ns, t, want - 1) != 0, null = omega_pfq_tiles(NULL, ns, t, 32) != 0; + const int ok = nt == want && cap >= want && !bad && !over && !null; + printf("%s tiler: segments {0,1,63,64,65,130,7} -> %u tiles (want %u, cap %u), %d coverage errors, cap-1 %s, NULL %s\n", ok ? "PASS" : "FAIL", + nt, want, cap, bad, over ? "ACCEPTED" : "refused", null ? "ACCEPTED" : "refused"); + return ok ? 0 : 1; +} +static uint64_t words_hash(int qg, const void *spec) { + BlackwellIRProgram *prog = calloc(1, sizeof *prog); uint8_t *code = malloc(1u << 20); uint64_t h = 0xcbf29ce484222325ull; + const int cg = qg ? omega_blackwell_codegen_qgemm_prog(spec, prog) : omega_blackwell_codegen_pq_prog(spec, prog); + if (cg != 0 || pfq_encode_hash(prog, code, 1u << 20, &h, 0) != 0) h = 0; + free(prog); free(code); return h; +} +static int host_words(void) { + uint64_t h = 0; const int n = pfq_legacy_digest(&h); + const int same = n == PFQ_LEGACY_PROGRAMS && h == PFQ_LEGACY_DIGEST; + printf("%s pre-DRA-82 qg/pq kernels: %d programs, digest 0x%016llx (main 4bbccf0: %d, 0x%016llx)\n", same ? "PASS" : "FAIL", + n, (unsigned long long)h, PFQ_LEGACY_PROGRAMS, (unsigned long long)PFQ_LEGACY_DIGEST); + /* negative control: the new fields do change the words, so the digest above would see them leak into legacy specs */ + OmegaQgSpec b; memset(&b, 0, sizeof b); b.k = 2048; b.rt = 4; b.warps = 8; b.epi = OMEGA_QG_EPI_F32; b.n = 1024; b.wait = 45; + OmegaQgSpec y = b, x = b; y.ymap = 1; x.x64 = 1; + OmegaPqSpec p; memset(&p, 0, sizeof p); p.k = 2048; OmegaPqSpec ps = p; ps.stride = 2048 + 68; + const uint64_t hb = words_hash(1, &b), hy = words_hash(1, &y), hx = words_hash(1, &x), hp = words_hash(0, &p), hs = words_hash(0, &ps); + const int ctl = hb && hy && hx && hp && hs && hb != hy && hb != hx && hy != hx && hp != hs; + printf("%s negative control: qg ymap=1 / x64=1 and pq stride change the encoded words (%016llx %016llx %016llx | %016llx %016llx)\n", ctl ? "PASS" : "FAIL", + (unsigned long long)hb, (unsigned long long)hy, (unsigned long long)hx, (unsigned long long)hp, (unsigned long long)hs); + return (same ? 0 : 1) + (ctl ? 0 : 1); +} +static int host_plans(void) { + int bad = 0; OmegaQgSpec s; OmegaPqSpec q; OmegaPfqLaunch L; + OmegaPfqGemm c = { .n = 1024, .k = 2048, .x64 = 1, .ntiles = 21, .tiles_va = 0x10, .rowidx_va = 0x20, .xq_va = 0x30, .xs_va = 0x40, .ymap_va = 0x1234567890ull, .y_va = 0x50 }; + if (omega_pfq_gemm_plan(&c, &s, &L) != OMEGA_GPU_PF_OK || L.nargs != OMEGA_QG_ARGS_WORDS_YMAP || L.args[12] != 0x34567890u || L.args[13] != 0x12u || + L.args[10] != 1024 || L.args[11] != 0 || L.args[6] != 0x50 || L.args[8] != 0x40 || L.threads != 256 || L.grid_x != 1024 / omega_qg_span(&s) || + L.grid_y != 21 || L.shared != omega_qg_shared_bytes(&s) || !s.ymap || !s.x64 || s.direct || s.epi != OMEGA_QG_EPI_F32) { printf(" gemm plan (ymap) wrong\n"); bad++; } + c.ymap_va = 0; c.rowidx_va = 0; c.x64 = 0; + if (omega_pfq_gemm_plan(&c, &s, &L) != OMEGA_GPU_PF_OK || L.nargs != OMEGA_QG_ARGS_WORDS || s.ymap || !s.direct || s.x64) { printf(" gemm plan (plain) wrong\n"); bad++; } + OmegaPfqGemm r = c; r.n = 1000; if (omega_pfq_gemm_plan(&r, &s, &L) != OMEGA_GPU_PF_BAD_ARGS) { printf(" n 1000 accepted\n"); bad++; } + r = c; r.x64 = 2; if (omega_pfq_gemm_plan(&r, &s, &L) != OMEGA_GPU_PF_BAD_ARGS) { printf(" x64 2 accepted\n"); bad++; } + r = c; r.ntiles = 70000; if (omega_pfq_gemm_plan(&r, &s, &L) != OMEGA_GPU_PF_TOO_LARGE) { printf(" 70000 tiles accepted\n"); bad++; } + OmegaPfqQuant u = { .k = 2048, .rows = 128, .stride = 2048 + 1032, .x_va = 1, .q_va = 2, .s_va = 3 }; + if (omega_pfq_quant_plan(&u, &q, &L) != OMEGA_GPU_PF_OK || q.stride != 3080 || L.threads != 512 || L.grid_x != 128 || L.grid_y != 1 || L.nargs != 6) { printf(" quant plan wrong\n"); bad++; } + u.k = 5120; u.stride = 0; + if (omega_pfq_quant_plan(&u, &q, &L) != OMEGA_GPU_PF_OK || q.groups != 20 || L.threads != 640 || L.grid_y != 2) { printf(" quant plan (split row) wrong\n"); bad++; } + u.k = 2048; u.stride = 2040; if (omega_pfq_quant_plan(&u, &q, &L) != OMEGA_GPU_PF_BAD_ARGS) { printf(" stride < k accepted\n"); bad++; } + u.stride = 2050; if (omega_pfq_quant_plan(&u, &q, &L) != OMEGA_GPU_PF_BAD_ARGS) { printf(" stride 2050 accepted\n"); bad++; } + printf("%s launch plans: argument words, grids, refusals (%d wrong)\n", bad ? "FAIL" : "PASS", bad); + return bad ? 1 : 0; +} +static int host_ref(void) { + static const uint32_t cnt[] = { 30, 0, 9, 70 }; + Prob P; prob_make(&P, 4, 256, 384, cnt, 40, 1, 1, 120); + double worst = 0; + for (uint32_t p = 0; p < P.M; p += 3) for (uint32_t c = 0; c < P.n; c++) { double m, o = qoracle(&P, p, c, &m); double d = fabs(qref(&P, p, c) - o) / (m + 1e-30); if (d > worst) worst = d; } + const int ok = worst < 1e-6; + printf("%s C reference vs double oracle: worst error %.3g of the sum of |terms|\n", ok ? "PASS" : "FAIL", worst); + const int x64ok = P.x64_mismatch == 0; + printf("%s x64 quantiser identity: q(2^64 x) == q(x), s(2^64 x) == 2^64 s(x) on %u rows x %u blocks (%u differ; all-zero blocks keep the floor scale, q 0)\n", + x64ok ? "PASS" : "FAIL", P.XR + PAD, P.KB, P.x64_mismatch); + /* INFO (no gate): what the activation quantiser costs against the incumbent GEMV's unquantised f32 activations, on these + * synthetic rows (uniform +-1 with 1/32 x300 outliers, 1/32 x1e-3, 1/32 zeros; NOT model activations) */ + double wa = 0, se = 0, sy = 0; + for (uint32_t p = 0; p < P.M; p += 3) + for (uint32_t c = 0; c < P.n; c++) { + const uint32_t e = P.eid[p], s = P.ridx[p]; + double a = 0, m = 0; + for (uint32_t j = 0; j < P.k; j++) { + const double sw = u2f((uint32_t)P.sbf[((size_t)e * (P.n / 128) + c / 128) * P.KB + j / 128] << 16); + const double t = (double)qm_e4m3(P.w[((size_t)e * P.n + c) * P.k + j]) * sw * P.x[(size_t)s * P.k + j]; + a += t; m += fabs(t); + } + const double d = fabs((double)qref(&P, p, c) - a); + if (m > 0 && d / m > wa) wa = d / m; + se += d * d; sy += a * a; + } + printf("INFO activation e4m3 (per row, per 128-col block, power-of-two scale) vs f32 activations, synthetic rows k %u: worst |dy| %.3g of the sum of |terms|, rms |dy|/rms |y| %.3g\n", + P.k, wa, sy > 0 ? sqrt(se / sy) : 0.0); + prob_free(&P); + return (ok ? 0 : 1) + (x64ok ? 0 : 1); +} + +/* ---------------- warp simulator ---------------- */ +static int sim_quant(uint32_t k, uint32_t stride, uint32_t rows, int x64, size_t *bad, char *msg, size_t msgn) { + const uint32_t XS = stride ? stride : k, KB = k / 128; + float *x = malloc((size_t)rows * XS * 4), *xin = malloc((size_t)rows * XS * 4); + for (size_t i = 0; i < (size_t)rows * XS; i++) x[i] = (i % XS) < k ? rand_act() : 1e30f; /* the gap columns must never be read */ + if (rows > 3) for (uint32_t j = 0; j < k; j++) x[3 * (size_t)XS + j] = 0.0f; + for (size_t i = 0; i < (size_t)rows * XS; i++) xin[i] = (x64 && (i % XS) < k) ? ldexpf(x[i], 64) : x[i]; + uint8_t *q = malloc((size_t)rows * k), *rq = malloc(k); float *s = malloc((size_t)rows * KB * 4), *rs = malloc(KB * 4); + memset(q, 0xee, (size_t)rows * k); memset(s, 0xee, (size_t)rows * KB * 4); + OmegaPfqQuant u = { .k = k, .rows = rows, .stride = stride, .x_va = (uintptr_t)xin, .q_va = (uintptr_t)q, .s_va = (uintptr_t)s }; + OmegaPqSpec sp; OmegaPfqLaunch L; int rc = -1; + static BlackwellIRProgram prog; + if (omega_pfq_quant_plan(&u, &sp, &L) != OMEGA_GPU_PF_OK) snprintf(msg, msgn, "plan refused"); + else if (omega_blackwell_codegen_pq_prog(&sp, &prog) != 0) snprintf(msg, msgn, "codegen refused"); + else { + static WsSim ws; memset(&ws, 0, sizeof ws); + ws.p = &prog; ws.threads = L.threads; + for (uint32_t i = 0; i < L.nargs; i++) ws.cbank[0x380 / 4 + i] = L.args[i]; + ws.ranges[0].lo = (uintptr_t)xin; ws.ranges[0].hi = (uintptr_t)(xin + (size_t)rows * XS); + ws.ranges[1].lo = (uintptr_t)q; ws.ranges[1].hi = (uintptr_t)(q + (size_t)rows * k); + ws.ranges[2].lo = (uintptr_t)s; ws.ranges[2].hi = (uintptr_t)(s + (size_t)rows * KB); + ws.nranges = 3; + rc = ws_run(&ws, L.grid_x, L.grid_y) ? -1 : 0; + if (rc) snprintf(msg, msgn, "simulator %.150s", ws.msg); + } + *bad = 0; + if (!rc) for (uint32_t r = 0; r < rows; r++) { + pq_ref(xin + (size_t)r * XS, k, rq, rs, 0); + for (uint32_t j = 0; j < k; j++) if (rq[j] != q[(size_t)r * k + j]) (*bad)++; + for (uint32_t b = 0; b < KB; b++) if (f2u(rs[b]) != f2u(s[(size_t)r * KB + b])) (*bad)++; + } + free(x); free(xin); free(q); free(rq); free(s); free(rs); + return rc; +} +/* plans, generates and simulates one gemm of P; y gets YR x n f32 */ +static int sim_gemm(const Prob *P, int x64, int order, uint32_t *y, char *msg, size_t msgn) { + const uint32_t cap = omega_pfq_tile_cap(P->M, P->E); + OmegaPfqTile *t = calloc(cap + 1, sizeof *t); + const uint32_t nt = omega_pfq_tiles(P->seg, P->E, t, cap); + const float *xs = x64 ? P->xs64 : P->xs; + memset(y, 0xee, (size_t)P->YR * P->n * 4); + OmegaPfqGemm c = { .n = P->n, .k = P->k, .x64 = (uint32_t)x64, .ntiles = nt, .tiles_va = (uintptr_t)t, .rowidx_va = P->indexed ? (uintptr_t)P->ridx : 0, + .xq_va = (uintptr_t)P->xq, .xs_va = (uintptr_t)xs, .ymap_va = P->ymapped ? (uintptr_t)P->ymap : 0, .y_va = (uintptr_t)y }; + OmegaQgSpec sp; OmegaPfqLaunch L; int rc = -1; + static BlackwellIRProgram prog; + if (!nt) snprintf(msg, msgn, "tiler refused"); + else if (omega_pfq_gemm_plan(&c, &sp, &L) != OMEGA_GPU_PF_OK) snprintf(msg, msgn, "plan refused"); + else if (omega_blackwell_codegen_qgemm_prog(&sp, &prog) != 0) snprintf(msg, msgn, "codegen refused"); + else { + uint8_t *smem = malloc(L.shared); + static WsSim s; memset(&s, 0, sizeof s); + s.p = &prog; s.threads = L.threads; s.smem = smem; s.smem_bytes = L.shared; s.order = order; + for (uint32_t i = 0; i < L.nargs; i++) s.cbank[0x380 / 4 + i] = L.args[i]; + const size_t XA = (size_t)P->XR + PAD; + s.ranges[0].lo = (uintptr_t)t; s.ranges[0].hi = (uintptr_t)(t + nt); + s.ranges[1].lo = (uintptr_t)P->ridx; s.ranges[1].hi = (uintptr_t)(P->ridx + P->M + PAD); + s.ranges[2].lo = (uintptr_t)P->xq; s.ranges[2].hi = (uintptr_t)(P->xq + XA * P->k); + s.ranges[3].lo = (uintptr_t)y; s.ranges[3].hi = (uintptr_t)(y + (size_t)P->YR * P->n); + s.ranges[4].lo = (uintptr_t)P->w; s.ranges[4].hi = (uintptr_t)(P->w + (size_t)P->E * P->n * P->k); + s.ranges[5].lo = (uintptr_t)P->swf; s.ranges[5].hi = (uintptr_t)(P->swf + (size_t)P->E * (P->n / 128) * P->KB); + s.ranges[6].lo = (uintptr_t)xs; s.ranges[6].hi = (uintptr_t)(xs + XA * P->KB); + s.ranges[7].lo = (uintptr_t)P->ymap; s.ranges[7].hi = (uintptr_t)(P->ymap + P->M + PAD); + s.nranges = 8; + rc = ws_run(&s, L.grid_x, L.grid_y) ? -1 : 0; + if (rc) snprintf(msg, msgn, "simulator %.150s", s.msg); + free(smem); + } + free(t); + return rc; +} +/* the q36 prefill's expert GEMMs as omega_gpu_q36_graph.c pf_group lays them out: T tokens x 8 routed picks (distinct experts + * of E-1) sorted by expert, then the shared expert (segment E-1) at rows T*8 .. with x' row t and y row t*9+8. gate_up reads + * x' row = token through rowidx; down reads act row = its own y row (rowidx == ymap). */ +static void q36_layout(Prob *P, uint32_t T, uint32_t E, uint32_t n, uint32_t k, int down) { + uint32_t *pick = malloc((size_t)T * 8 * 4), *cnt = calloc(E, 4); + for (uint32_t t = 0; t < T; t++) + for (uint32_t s = 0; s < 8; s++) { + uint32_t e; int dup; + do { e = rnd() % (E - 1); dup = 0; for (uint32_t j = 0; j < s; j++) dup |= pick[t * 8 + j] == e; } while (dup); + pick[t * 8 + s] = e; cnt[e]++; + } + cnt[E - 1] = T; + prob_make(P, E, n, k, cnt, down ? T * 9 : T, 1, 1, T * 9); + uint32_t *start = calloc(E, 4); for (uint32_t e = 1; e < E; e++) start[e] = start[e - 1] + cnt[e - 1]; + for (uint32_t t = 0; t < T; t++) + for (uint32_t s = 0; s < 8; s++) { const uint32_t p = start[pick[t * 8 + s]]++; P->ymap[p] = t * 9 + s; P->ridx[p] = t; } + for (uint32_t t = 0; t < T; t++) { P->ymap[T * 8 + t] = t * 9 + 8; P->ridx[T * 8 + t] = t; } + if (down) for (uint32_t p = 0; p < P->M; p++) P->ridx[p] = P->ymap[p]; + free(pick); free(cnt); free(start); +} +static int sim(void) { + int fail = 0; char msg[200]; + static const struct { uint32_t k, stride, rows; int x64; } qc[] = { { 2048, 2048 + 68, 9, 1 }, { 2048, 0, 9, 0 }, { 512, 512, 11, 1 }, { 5120, 5120 + 128, 5, 1 }, + { 4096, 0, 9, 1 } /* the q36 o input */ }; + for (size_t i = 0; i < sizeof qc / sizeof qc[0]; i++) { + size_t bad = 0; const int rc = sim_quant(qc[i].k, qc[i].stride, qc[i].rows, qc[i].x64, &bad, msg, sizeof msg); + printf("sim quant k %u stride %u rows %u %s: %s, %zu differ\n", qc[i].k, qc[i].stride, qc[i].rows, qc[i].x64 ? "2^64 x" : "x", rc ? msg : "ran", bad); + if (rc || bad) fail++; + } + { + omega_gpu_pfq_test_set_mutant(4); + size_t bad = 0; const int rc = sim_quant(2048, 2048 + 68, 9, 1, &bad, msg, sizeof msg); + omega_gpu_pfq_test_set_mutant(env_mutant); + printf("sim quant mutant 4 (c = 0): %s\n", rc ? msg : bad ? "caught" : "NOT CAUGHT"); + if (rc || !bad) fail++; + } + static const uint32_t ca[] = { 130, 0, 1, 64, 65, 7 }, cb[] = { 65, 63 }, cc[] = { 20, 64, 100 }; + static const struct { const char *name; const uint32_t *cnt; uint32_t E, n, k, XR, indexed, ymapped, extra; int x64; } gc[] = { + { "A indexed+ymap+x64", ca, 6, 256, 384, 90, 1, 1, 37, 1 }, + { "B direct+ymap", cb, 2, 256, 256, 0, 0, 1, 5, 0 }, + { "C indexed+x64", cc, 3, 256, 128, 50, 1, 0, 0, 1 }, + }; + for (size_t i = 0; i < sizeof gc / sizeof gc[0]; i++) { + uint32_t M = 0; for (uint32_t e = 0; e < gc[i].E; e++) M += gc[i].cnt[e]; + Prob P; prob_make(&P, gc[i].E, gc[i].n, gc[i].k, gc[i].cnt, gc[i].XR, gc[i].indexed, gc[i].ymapped, M + gc[i].extra); + uint32_t *want = expect_y(&P), *y = malloc((size_t)P.YR * P.n * 4), *y0 = malloc((size_t)P.YR * P.n * 4); + for (int order = 0; order < 2; order++) { + const int rc = sim_gemm(&P, gc[i].x64, order, y, msg, sizeof msg); + const size_t bad = rc ? 0 : ydiff(&P, y, want); + printf("sim gemm %s (M %u n %u k %u, %u y rows) order %d: %s, %zu words differ\n", gc[i].name, P.M, P.n, P.k, P.YR, order, rc ? msg : "ran", bad); + if (rc || bad) fail++; + } + if (gc[i].x64) { /* the same problem with true scales and x64 0: the same bits */ + const int rc = sim_gemm(&P, 0, 0, y0, msg, sizeof msg), rc1 = sim_gemm(&P, 1, 0, y, msg, sizeof msg); + const int same = !rc && !rc1 && !memcmp(y0, y, (size_t)P.YR * P.n * 4); + printf("sim gemm %s: x64 on 2^64 scales == x64 off on true scales: %s\n", gc[i].name, same ? "identical" : "DIFFER"); + if (!same) fail++; + } + if (i == 0) for (int m = 1; m <= 3; m++) { + omega_gpu_pfq_test_set_mutant(m); + const int rc = sim_gemm(&P, 1, 0, y, msg, sizeof msg); + omega_gpu_pfq_test_set_mutant(env_mutant); + const size_t bad = rc ? 0 : ydiff(&P, y, want); + printf("sim gemm mutant %d (%s): %s\n", m, m == 1 ? "tiler row skew" : m == 2 ? "wrong scale block" : "tile i^1", rc ? msg : bad ? "caught" : "NOT CAUGHT"); + if (rc || !bad) fail++; + } + free(want); free(y); free(y0); prob_free(&P); + } + /* the q36 shapes: gate_up (n 1024, k 2048) and down (n 2048, k 512) over 12 tokens x (8 routed of 10 + shared); the dense + * mix|o (direct rows, x64) at k 2048 and k 4096 with n cut to 256 (n only multiplies the grid) */ + static const struct { const char *name; uint32_t T, E, n, k; int down; } q36[] = { + { "q36 gate_up routed+shared", 12, 11, 1024, 2048, 0 }, { "q36 down routed+shared", 12, 11, 2048, 512, 1 }, + { "q36 down 72 tokens (segments > 64 rows, n cut to 256)", 72, 11, 256, 512, 1 }, + }; + for (size_t i = 0; i < sizeof q36 / sizeof q36[0]; i++) { + Prob P; q36_layout(&P, q36[i].T, q36[i].E, q36[i].n, q36[i].k, q36[i].down); + uint32_t *want = expect_y(&P), *y = malloc((size_t)P.YR * P.n * 4); + const int rc = sim_gemm(&P, 1, 0, y, msg, sizeof msg); + const size_t bad = rc ? 0 : ydiff(&P, y, want); + printf("sim gemm %s (M %u n %u k %u, %u y rows): %s, %zu words differ\n", q36[i].name, P.M, P.n, P.k, P.YR, rc ? msg : "ran", bad); + if (rc || bad) fail++; + if (i == 0) { /* negative control: the shared expert's y rows dropped from the map (pointed at routed row 0's slot) */ + for (uint32_t t = 0; t < q36[i].T; t++) P.ymap[q36[i].T * 8 + t] = P.ymap[0]; + const int rc2 = sim_gemm(&P, 1, 0, y, msg, sizeof msg); + const size_t bad2 = rc2 ? 0 : ydiff(&P, y, want); + printf("sim gemm %s negative control (shared rows mis-mapped): %s\n", q36[i].name, rc2 ? msg : bad2 ? "caught" : "NOT CAUGHT"); + if (rc2 || !bad2) fail++; + } + free(want); free(y); prob_free(&P); + } + static const uint32_t cd[] = { 9 }; + static const uint32_t dk[] = { 2048, 4096 }; + for (size_t i = 0; i < 2; i++) { + Prob P; prob_make(&P, 1, 256, dk[i], cd, 0, 0, 0, 0); + uint32_t *want = expect_y(&P), *y = malloc((size_t)P.YR * P.n * 4); + const int rc = sim_gemm(&P, 1, 0, y, msg, sizeof msg); + const size_t bad = rc ? 0 : ydiff(&P, y, want); + printf("sim gemm q36 dense (M %u n %u k %u): %s, %zu words differ\n", P.M, P.n, P.k, rc ? msg : "ran", bad); + if (rc || bad) fail++; + free(want); free(y); prob_free(&P); + } + return fail; +} + +/* ---------------- chip: one Qwen3.6 prefill chunk's routed expert GEMMs ---------------- */ +typedef struct { OmegaGpuMem xf, xq, xs, y, tab, ridx, ymap; OmegaGpuFp8Tensor *wt; uint32_t nt, stride; } Dev; +static void dev_free(Dev *d) { + omega_gpu_fp8_tensor_free(d->wt); omega_gpu_pf_free(&d->xf); omega_gpu_pf_free(&d->xq); omega_gpu_pf_free(&d->xs); + omega_gpu_pf_free(&d->y); omega_gpu_pf_free(&d->tab); omega_gpu_pf_free(&d->ridx); omega_gpu_pf_free(&d->ymap); +} +static size_t r16(size_t b) { return (b + 15) & ~(size_t)15; } +static int dev_setup(const Prob *P, uint32_t stride, Dev *d) { + memset(d, 0, sizeof *d); d->stride = stride; + const size_t XA = (size_t)P->XR + PAD; + int rc = omega_gpu_fp8_tensor_upload(P->E, P->n, P->k, P->w, P->sbf, &d->wt) == 0 ? 0 : OMEGA_GPU_PF_CHIP_FAIL; + float *xf = malloc((size_t)P->XR * stride * 4); + for (size_t r = 0; r < P->XR; r++) for (uint32_t j = 0; j < stride; j++) xf[r * stride + j] = j < P->k ? ldexpf(P->x[r * P->k + j], 64) : 1e30f; + if (!rc) rc = omega_gpu_pf_alloc_dev(r16((size_t)P->XR * stride * 4), &d->xf); + if (!rc) rc = omega_gpu_pf_alloc_dev(r16(XA * P->k), &d->xq); + if (!rc) rc = omega_gpu_pf_alloc_dev(r16(XA * P->KB * 4), &d->xs); + if (!rc) rc = omega_gpu_pf_alloc_dev(r16((size_t)P->YR * P->n * 4), &d->y); + if (!rc) rc = omega_gpu_pf_upload(&d->xf, 0, xf, (size_t)P->XR * stride * 4 & ~(size_t)15); + free(xf); + const uint32_t cap = omega_pfq_tile_cap(P->M, P->E); + if (!rc) rc = omega_gpu_pf_alloc_host((size_t)cap * sizeof(OmegaPfqTile), &d->tab); + if (!rc) rc = omega_gpu_pf_alloc_host((size_t)(P->M + PAD) * 4, &d->ridx); + if (!rc) rc = omega_gpu_pf_alloc_host((size_t)(P->M + PAD) * 4, &d->ymap); + if (rc) return rc; + OmegaPfqTile *seg = malloc(P->E * sizeof *seg); memcpy(seg, P->seg, P->E * sizeof *seg); + for (uint32_t e = 0; e < P->E; e++) if (omega_gpu_fp8_tensor_entry(d->wt, e, &seg[e].w_va, &seg[e].s_va) != 0) rc = OMEGA_GPU_PF_CHIP_FAIL; + d->nt = rc ? 0 : omega_pfq_tiles(seg, P->E, d->tab.cpu, cap); + free(seg); + memcpy(d->ridx.cpu, P->ridx, (size_t)(P->M + PAD) * 4); memcpy(d->ymap.cpu, P->ymap, (size_t)(P->M + PAD) * 4); + omega_gpu_session_lock(); + if (omega_gpu_session_sync_to_gpu(&d->tab) || omega_gpu_session_sync_to_gpu(&d->ridx) || omega_gpu_session_sync_to_gpu(&d->ymap)) rc = OMEGA_GPU_PF_CHIP_FAIL; + omega_gpu_session_unlock(); + return rc ? rc : d->nt ? 0 : OMEGA_GPU_PF_BAD_ARGS; +} +static int dev_record(OmegaGpuCmdList *cl, const Prob *P, const Dev *d) { + const OmegaPfqQuant u = { .k = P->k, .rows = P->XR, .stride = d->stride, .x_va = d->xf.va, .q_va = d->xq.va, .s_va = d->xs.va }; + const OmegaPfqGemm c = { .n = P->n, .k = P->k, .x64 = 1, .ntiles = d->nt, .tiles_va = d->tab.va, .rowidx_va = d->ridx.va, .xq_va = d->xq.va, + .xs_va = d->xs.va, .ymap_va = d->ymap.va, .y_va = d->y.va }; + int rc = omega_gpu_pfq_quant_record_locked(cl, &u); + if (!rc) rc = omega_gpu_pfq_gemm_record_locked(cl, &c); + return rc; +} +/* runs both GEMMs once in one list; ns[0..3] = quant, gemm, quant, gemm GPU time */ +static int chip_run(OmegaGpuCmdList *cl, const Prob *P1, const Dev *d1, const Prob *P2, const Dev *d2, uint64_t ns[4]) { + omega_gpu_session_lock(); + omega_gpu_cmdlist_reset(cl); + int rc = dev_record(cl, P1, d1); + if (!rc) rc = dev_record(cl, P2, d2); + OmegaGpuCmdListOpts o; memset(&o, 0, sizeof o); o.stamps = 1; + OmegaGpuCmdListStats st; + if (!rc && omega_gpu_cmdlist_submit(cl, &o, &st) != 0) rc = OMEGA_GPU_PF_CHIP_FAIL; + uint64_t ts[5] = { 0 }; + if (!rc && omega_gpu_cmdlist_stamps(cl, ts, 5) != 5) rc = OMEGA_GPU_PF_CHIP_FAIL; + omega_gpu_session_unlock(); + for (int i = 0; i < 4; i++) ns[i] = ts[i + 1] - ts[i]; + return rc; +} +/* quantiser and gemm outputs against the reference: xq/xs whole, y on sampled routed rows plus every untouched row */ +static size_t chip_check(const Prob *P, const Dev *d, int rows, size_t *qbad) { + const size_t XR = P->XR, yb = (size_t)P->YR * P->n * 4; + uint8_t *xq = malloc(r16(XR * P->k)); float *xs = malloc(r16(XR * P->KB * 4)); uint32_t *y = malloc(r16(yb)); + *qbad = 0; size_t bad = 0; + if (omega_gpu_pf_download(&d->xq, 0, xq, r16(XR * P->k)) || omega_gpu_pf_download(&d->xs, 0, xs, r16(XR * P->KB * 4)) || omega_gpu_pf_download(&d->y, 0, y, r16(yb))) { *qbad = 1; bad = 1; } + else { + for (size_t i = 0; i < XR * P->k; i++) if (xq[i] != P->xq[i]) (*qbad)++; + for (size_t i = 0; i < XR * P->KB; i++) if (f2u(xs[i]) != f2u(P->xs64[i])) (*qbad)++; + uint8_t *hit = calloc(P->YR, 1); for (uint32_t p = 0; p < P->M; p++) hit[P->ymap[p]] = 1; + for (uint32_t r = 0; r < P->YR; r++) if (!hit[r]) for (uint32_t c = 0; c < P->n; c++) if (y[(size_t)r * P->n + c] != 0) bad++; + free(hit); + for (int q = 0; q < rows; q++) { + const uint32_t p = q == 0 ? 0 : q == 1 ? P->M - 1 : rnd() % P->M; + for (uint32_t c = 0; c < P->n; c++) if (y[(size_t)P->ymap[p] * P->n + c] != f2u(qref(P, p, c))) bad++; + } + } + free(xq); free(xs); free(y); + return bad; +} +static int chip(uint32_t tokens, int reps, int rows, uint32_t experts) { + const uint32_t E = experts, T = tokens, NG = 9, R = T * NG; /* 8 routed + the shared slot per token, as the q36 graph lays out actN */ + uint32_t *cnt = calloc(E, 4), *tok_e = malloc((size_t)T * 8 * 4); + for (uint32_t t = 0; t < T; t++) for (uint32_t s = 0; s < 8; s++) { + uint32_t e; int dup; + do { e = rnd() % E; dup = 0; for (uint32_t j = 0; j < s; j++) if (tok_e[t * 8 + j] == e) dup = 1; } while (dup); + tok_e[t * 8 + s] = e; cnt[e]++; + } + uint32_t touched = 0; for (uint32_t e = 0; e < E; e++) touched += cnt[e] != 0; + Prob P1, P2; + prob_make(&P1, E, 1024, 2048, cnt, T, 1, 1, R); /* gate|up: x' rows (2^64), routed by token, out to gu row t * 9 + s */ + prob_make(&P2, E, 2048, 512, cnt, R, 1, 1, R); /* down: act rows t * 9 + s in and out */ + { /* the q36 graph's maps (pf_group): rows grouped by expert, xmap = token, ymap = token * 9 + slot */ + uint32_t *fill = calloc(E, 4), *base = calloc(E, 4); + for (uint32_t e = 1; e < E; e++) base[e] = base[e - 1] + cnt[e - 1]; + for (uint32_t t = 0; t < T; t++) for (uint32_t s = 0; s < 8; s++) { + const uint32_t e = tok_e[t * 8 + s], p = base[e] + fill[e]++; + P1.ridx[p] = t; P1.ymap[p] = t * NG + s; P2.ridx[p] = t * NG + s; P2.ymap[p] = t * NG + s; + } + free(fill); free(base); + } + Dev d1, d2; int fail = 0; + int rc = dev_setup(&P1, 2048 + 64, &d1); + if (!rc) rc = dev_setup(&P2, 0, &d2); + OmegaGpuCmdList *cl = NULL; + if (!rc && omega_gpu_cmdlist_create(8, &cl) != 0) rc = OMEGA_GPU_PF_CHIP_FAIL; + if (!rc) { + omega_gpu_pfq_quant_prepare(2048, 2048 + 64); omega_gpu_pfq_quant_prepare(512, 0); + omega_gpu_pfq_gemm_prepare(1024, 2048, 1, 1, 1); omega_gpu_pfq_gemm_prepare(2048, 512, 1, 1, 1); + } + uint64_t ns[4][32]; if (reps > 32) reps = 32; if (reps < 1) reps = 1; + for (int r = 0; r < reps && !rc; r++) { uint64_t t4[4]; rc = chip_run(cl, &P1, &d1, &P2, &d2, t4); for (int i = 0; i < 4; i++) ns[i][r] = t4[i]; } + if (rc) { printf("chip setup/run: %s (%s)\n", omega_gpu_pf_rc_name(rc), omega_gpu_session_last_error()); fail++; } + else { + size_t q1, q2; const size_t b1 = chip_check(&P1, &d1, rows, &q1), b2 = chip_check(&P2, &d2, rows, &q2); + printf("chip gate_up (T %u, M %u, %u experts touched): quantiser %zu differ, y %zu words differ on %d sampled rows + untouched rows\n", T, P1.M, touched, q1, b1, rows); + printf("chip down (R %u rows): quantiser %zu differ, y %zu words differ\n", R, q2, b2); + if (q1 || q2 || b1 || b2) fail++; + static const char *nm[4] = { "quant x' k 2048", "gemm gate_up n 1024 k 2048", "quant act k 512", "gemm down n 2048 k 512" }; + const double fl[4] = { 0, 2.0 * P1.M * 1024 * 2048, 0, 2.0 * P2.M * 2048 * 512 }, wb[4] = { 0, (double)touched * 1024 * 2048, 0, (double)touched * 2048 * 512 }; + for (int i = 0; i < 4; i++) { + qsort(ns[i], reps, 8, cmp_u64); + const double med = (double)ns[i][reps / 2]; + printf("PFQ %-28s median %.3f us (min %.3f)", nm[i], med / 1e3, ns[i][0] / 1e3); + if (fl[i] > 0) printf(", %.2f TFLOPS, %.1f GB/s of distinct weights", fl[i] / med / 1e3, wb[i] / med); + printf("\n"); + } + for (int m = 1; m <= 4; m++) { + omega_gpu_pfq_test_set_mutant(m); + uint64_t t4[4]; int mrc = 0; + if (m == 1) { /* the tiler mutant changes the table: rebuild it */ + OmegaPfqTile *seg = malloc(E * sizeof *seg); memcpy(seg, P1.seg, E * sizeof *seg); + for (uint32_t e = 0; e < E; e++) (void)omega_gpu_fp8_tensor_entry(d1.wt, e, &seg[e].w_va, &seg[e].s_va); + d1.nt = omega_pfq_tiles(seg, E, d1.tab.cpu, omega_pfq_tile_cap(P1.M, E)); free(seg); + omega_gpu_session_lock(); (void)omega_gpu_session_sync_to_gpu(&d1.tab); omega_gpu_session_unlock(); + } + (void)omega_gpu_pf_upload(&d1.y, 0, calloc(1, r16((size_t)P1.YR * P1.n * 4)), r16((size_t)P1.YR * P1.n * 4)); + mrc = chip_run(cl, &P1, &d1, &P2, &d2, t4); + omega_gpu_pfq_test_set_mutant(env_mutant); + size_t mq1 = 0, mq2 = 0; const size_t mb = mrc ? 0 : chip_check(&P1, &d1, rows > 8 ? 8 : rows, &mq1) + chip_check(&P2, &d2, rows > 8 ? 8 : rows, &mq2); + printf("chip mutant %d: %s\n", m, mrc ? "run failed" : (mb || mq1 || mq2) ? "caught" : "NOT CAUGHT"); + if (mrc || !(mb || mq1 || mq2)) fail++; + if (m == 1) { + OmegaPfqTile *seg = malloc(E * sizeof *seg); memcpy(seg, P1.seg, E * sizeof *seg); + for (uint32_t e = 0; e < E; e++) (void)omega_gpu_fp8_tensor_entry(d1.wt, e, &seg[e].w_va, &seg[e].s_va); + d1.nt = omega_pfq_tiles(seg, E, d1.tab.cpu, omega_pfq_tile_cap(P1.M, E)); free(seg); + omega_gpu_session_lock(); (void)omega_gpu_session_sync_to_gpu(&d1.tab); omega_gpu_session_unlock(); + } + } + } + if (cl) omega_gpu_cmdlist_free(cl); + dev_free(&d1); dev_free(&d2); prob_free(&P1); prob_free(&P2); free(cnt); free(tok_e); + return fail; +} + +int main(int argc, char **argv) { + int host = 1, simm = 1, chipm = 0, reps = 9, rows = 32; uint32_t tokens = 128, experts = 256; + for (int i = 1; i < argc; i++) { + if (!strcmp(argv[i], "--host-only")) simm = 0; + else if (!strcmp(argv[i], "--sim")) host = 0; + else if (!strcmp(argv[i], "--chip")) { chipm = 1; host = 0; simm = 0; } + else if (!strcmp(argv[i], "--tokens") && i + 1 < argc) tokens = (uint32_t)atoi(argv[++i]); + else if (!strcmp(argv[i], "--reps") && i + 1 < argc) reps = atoi(argv[++i]); + else if (!strcmp(argv[i], "--rows") && i + 1 < argc) rows = atoi(argv[++i]); + else if (!strcmp(argv[i], "--experts") && i + 1 < argc) experts = (uint32_t)atoi(argv[++i]); + else { fprintf(stderr, "GPU_PFQ: INVALID argument %s\n", argv[i]); return 2; } + } + if (tokens == 0 || tokens > 4096 || experts < 8 || experts > 256 || rows < 2) { fprintf(stderr, "GPU_PFQ: INVALID --tokens/--experts/--rows\n"); return 2; } + env_mutant = omega_gpu_pfq_mutant(); + printf("AIEN_OMEGA_PFQ_MUTANT=%d%s\n", env_mutant, env_mutant ? " (every planned launch is the mutant: clean cases must FAIL)" : ""); + int fail = 0, cases = 0; + if (host) { fail += host_tiler(); fail += host_words(); fail += host_plans(); fail += host_ref(); cases++; } + if (simm) { fail += sim(); cases++; } + if (chipm) { fail += chip(tokens, reps, rows, experts); cases++; } + if (!cases) { fprintf(stderr, "GPU_PFQ: NOT_RUN (no mode selected)\n"); return 2; } + printf("GPU_PFQ: %s\n", fail ? "FAIL" : "PASS"); + return fail ? 1 : 0; +} diff --git a/tests/gpu_prefill_fattn256_test.c b/tests/gpu_prefill_fattn256_test.c new file mode 100644 index 00000000..16184ba0 --- /dev/null +++ b/tests/gpu_prefill_fattn256_test.c @@ -0,0 +1,683 @@ +/* SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception */ +/* + * gpu_prefill_fattn256_test: the flash-style tensor-core prefill attention for the Qwen3.6-35B-A3B full-attention layers + * (Linear DRA-85, omega_gpu_prefill_fattn256_api.h), on the decode attention's cache (omega_gpu_decode_attn256_api.h) + * in the q36 graph's shape (16 q / 2 KV heads, q_per_cta 4) and strides (q|k|v rows 9216 f32 apart: the output-gate + * words follow and must not be read; output rows ostride bytes apart). + * --host-only codegen budgets of both kernels (instructions <= 1024, registers within the opt-in limit and the + * 256-thread register file, attend placeholders patched), refusals (spec, shape, prep_xstride, API + * arguments), layout constants, reference sanity. No device. + * --sim both launches through tests/bw_warp_sim_pa.h (no chip, no shared memory given to the attend: a shared + * access faults): (pos0, m) points with m = 1, odd m, a 16-token CTA boundary, odd starts, history, a 256 + * boundary, full rope, warps past m; both fragment orders on the small points; --poison SEED starts + * every register as junk. Gates: appended K/V rows bit-equal to m runs of the DECODE program on a twin + * cache (the same simulator), outputs within the tolerance of a double reference, the padding words of + * every output row untouched, prep mutants 1 and 3 and attend mutants 1 (no causal mask) and 2 (no + * rescale) caught. The q' scratch starts as NaN so a slot the prep never wrote shows up. Then the attend + * kernel's variant 2 (next-block L1 touch prefetch) at the same nine points: the same gates, outputs + * bit-identical to variant 1 (the touches never feed arithmetic), attend mutants 1 and 2 caught. + * --variant N the attend kernel variant of the chip run and of a later --sim-point (1 = the base kernel, the default; + * 2); without it AIEN_OMEGA_Q36_PF_FATTN=1 or 2 picks it (as in the q36 graph). --sim runs both. + * (default) the chip: parity (every token up to 512, 8 sampled tokens above), rows bit-identical to m decode calls + * on a twin cache and the next decode step bit-identical on both caches, second call identical, out_scale + * 2^20 exact, device entry == host entry, mutants caught, timing medians of 2048-token chunks at contexts + * 2k, 8k, 32k (and 128k with --max-pos 131072) and with --long the 8192-token chunks ending at 8k and 32k; + * JSON receipt (with the variant) with --out. Chip runs belong to the DRA-85 slices (P-DRA-4 hive chip/DRA-85/). + * --host-only also pins the base kernel's bytes: variant 1's attend encodes to 14976 bytes with FNV-1a64 + * 8700843075116262202, the kernel of 475b72b2 (before variants existed); a change to them must be deliberate. + * Reference and tolerance as gpu_prefill_attn256_test.c: model dim order (zero-centred RMSNorm, RoPE pairs (j, j + + * rotary/2), q.k / 16, causal softmax), q' rounded to bf16 as the prep does, its own bf16 K/V rows; + * |out - ref| <= 5e-3 * max|v| * out_scale per element (P rounded to bf16 for the tensor cores, <= 2^-9 * max|v|). + * The output is not bit-identical to the decode steps (another summation order); host and simulator passes are never + * chip results. + */ +#include "omega_gpu_prefill_fattn256_api.h" +#include "omega_gpu_session.h" +#include "omega_blackwell_codegen_tc.h" +#include "omega_blackwell_codegen_pattn256.h" +#include "bw_warp_sim_pa.h" +#include +#include +#include +#include +#include +#include +#include "test_out_file.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); } +static double now_ms(void) { struct timespec t; clock_gettime(CLOCK_MONOTONIC, &t); return t.tv_sec * 1e3 + t.tv_nsec / 1e6; } +static int cmp_u64(const void *a, const void *b) { uint64_t x = *(const uint64_t *)a, y = *(const uint64_t *)b; return x < y ? -1 : x > y; } +static uint64_t fnv1a64(const void *p, size_t n) { const uint8_t *b = p; uint64_t h = 14695981039346656037ull; for (size_t i = 0; i < n; i++) { h ^= b[i]; h *= 1099511628211ull; } return h; } +static int g_variant = 1; /* attend kernel variant: sim_point's spec, the chip API (--variant) */ +static const double THETA = 10000000.0; /* rope_theta */ +static const float EPS = 1e-6f; +#define HD 256u +/* Qwen3.6-35B-A3B full-attention layer: 16 q / 2 KV heads, the q36 graph's cache (omega_gpu_q36_graph.h: 16, 2, 4) */ +#define QH 16u +#define KVH 2u +#define QPC 4u +#define VY (QH / QPC) /* decode / prep CTA rows */ +#define SPEC_SHAPE , .q_heads = QH, .kv_heads = KVH, .q_per_cta = QPC +#define ATT_SHAPE , .q_heads = QH, .kv_heads = KVH +#define QW ((QH + 2u * KVH) * HD) /* 5120: q | k | v */ +#define XSW 9216u /* f32 per q36 mixer row (OMEGA_GPU_Q36_ATT_MIX: q | k | v | output gate) */ +#define XS (XSW * 4u) /* the q36 graph's xstride */ +#define OW (QH * HD) /* 4096 */ +#define QFP (QH * 1024u) /* q' bytes per token pair */ +#define QEND (QH * HD) +#define KEND (QEND + KVH * HD) +#define RB OMEGA_DATTN256_ROW_BYTES +static const float QKS = (float)((1.0 / 16.0) * 1.4426950408889634); +#define TOL_REL 5e-3 + +/* one layer's random state in MODEL order: m qkv rows, norm weights w (zero-centred), history rows 0..pos0-1 */ +typedef struct { + uint32_t max_pos, pos0, m, rotary; + float *qkv; /* [m][XSW]: q | k | v, then the gate words the kernels must not read */ + float qn[HD], kn[HD]; + uint16_t *kc, *vc; /* [4][max_pos][256] model order */ +} Case; +static void case_make(Case *c, uint32_t max_pos, uint32_t pos0, uint32_t m, uint32_t rotary, uint32_t seed, float qscale) { + uint32_t s = seed; + c->max_pos = max_pos; c->pos0 = pos0; c->m = m; c->rotary = rotary; + c->qkv = malloc((size_t)m * XS); + for (size_t t = 0; t < m; t++) for (size_t i = 0; i < XSW; i++) c->qkv[t * XSW + i] = i < QW ? frand(&s, -1.0f, 1.0f) * (i < QEND ? qscale : 1.0f) : 1e30f; + for (unsigned i = 0; i < HD; i++) { c->qn[i] = frand(&s, -0.2f, 0.2f); c->kn[i] = frand(&s, -0.2f, 0.2f); } + size_t words = (size_t)KVH * max_pos * HD; + c->kc = calloc(words, 2); c->vc = calloc(words, 2); + for (unsigned g = 0; g < KVH; g++) for (uint32_t t = 0; t < pos0; t++) for (unsigned i = 0; i < HD; i++) { + size_t o = ((size_t)g * max_pos + t) * HD + i; + c->kc[o] = omega_dattn_bf16_rne(frand(&s, -1.0f, 1.0f)); c->vc[o] = omega_dattn_bf16_rne(frand(&s, -1.0f, 1.0f)); + } +} +static void case_free(Case *c) { free(c->qkv); free(c->kc); free(c->vc); } +/* the kernel's inputs: q and k heads permuted, v and the gate words as is; norms 1 + w permuted */ +static void case_kernel_qkv(const Case *c, float *qkv_k) { + for (size_t t = 0; t < c->m; t++) { + const float *src = c->qkv + t * XSW; float *dst = qkv_k + t * XSW; + for (unsigned h = 0; h < QH + KVH; h++) omega_dattn256_perm_vec(src + h * HD, dst + h * HD, c->rotary); + memcpy(dst + KEND, src + KEND, (size_t)(XSW - KEND) * 4); + } +} +static void case_kernel_norms(const Case *c, float *qn_k, float *kn_k) { + float t[HD]; + for (unsigned i = 0; i < HD; i++) t[i] = 1.0f + c->qn[i]; + omega_dattn256_perm_vec(t, qn_k, c->rotary); + for (unsigned i = 0; i < HD; i++) t[i] = 1.0f + c->kn[i]; + omega_dattn256_perm_vec(t, kn_k, c->rotary); +} +/* K history rows permuted, V as is, into a [K plane | V plane] buffer laid out like the cache (plane bytes apart) */ +static void case_history_into(const Case *c, uint8_t *kv, size_t plane) { + for (unsigned g = 0; g < KVH; g++) for (uint32_t t = 0; t < c->pos0; t++) { + size_t o = ((size_t)g * c->max_pos + t); + omega_dattn256_perm_vec_bf16(c->kc + o * HD, (uint16_t *)(kv + o * RB), c->rotary); + memcpy(kv + plane + o * RB, c->vc + o * HD, RB); + } +} + +/* ---- double-precision oracle (test-owned: libm) in MODEL order ---- */ +static void norm_rope(double *x, const float *w, float eps, uint32_t rotary, uint32_t pos) { + double ss = 0; for (unsigned i = 0; i < HD; i++) ss += x[i] * x[i]; + double r = 1.0 / sqrt(ss / (double)HD + (double)eps); + for (unsigned i = 0; i < HD; i++) x[i] = x[i] * r * (1.0 + (double)w[i]); + const unsigned half = rotary / 2; + for (unsigned j = 0; j < half; j++) { + double inv = 1.0 / pow(THETA, (double)(2 * j) / (double)rotary), ang = (double)pos * inv, cs = cos(ang), sn = sin(ang); + double x1 = x[j], x2 = x[j + half]; + x[j] = x1 * cs - x2 * sn; x[j + half] = x2 * cs + x1 * sn; + } +} +/* the reference K/V rows (model order, bf16) of every chunk token: kn/vn [m][4][256] */ +static void ref_rows(const Case *c, uint16_t *kn, uint16_t *vn) { + for (size_t t = 0; t < c->m; t++) for (unsigned g = 0; g < KVH; g++) { + const float *row = c->qkv + t * XSW; double k[HD]; + for (unsigned i = 0; i < HD; i++) k[i] = row[QEND + g * HD + i]; + norm_rope(k, c->kn, EPS, c->rotary, c->pos0 + (uint32_t)t); + for (unsigned i = 0; i < HD; i++) { kn[(t * KVH + g) * HD + i] = omega_dattn_bf16_rne((float)k[i]); vn[(t * KVH + g) * HD + i] = omega_dattn_bf16_rne(row[KEND + g * HD + i]); } + } +} +/* reference output of chunk token t: out[4096] (* out_scale) */ +static void ref_token(const Case *c, const uint16_t *kn, const uint16_t *vn, size_t t, float out_scale, double *out) { + const uint32_t pos = c->pos0 + (uint32_t)t; + double *p = malloc(((size_t)pos + 1) * sizeof(double)); + for (unsigned h = 0; h < QH; h++) { + const unsigned g = h / (QH / KVH); + double q[HD]; float qb[HD]; + for (unsigned i = 0; i < HD; i++) q[i] = c->qkv[t * XSW + h * HD + i]; + norm_rope(q, c->qn, EPS, c->rotary, pos); + for (unsigned i = 0; i < HD; i++) qb[i] = omega_dattn_bf16_f32(omega_dattn_bf16_rne((float)(q[i] * (double)QKS))); + double mx = -1e300; + for (uint32_t j = 0; j <= pos; j++) { + const uint16_t *kr = j < c->pos0 ? c->kc + ((size_t)g * c->max_pos + j) * HD : kn + ((size_t)(j - c->pos0) * KVH + g) * HD; + double s = 0; for (unsigned i = 0; i < HD; i++) s += (double)qb[i] * (double)omega_dattn_bf16_f32(kr[i]); + p[j] = s; if (s > mx) mx = s; + } + double l = 0, o[HD]; memset(o, 0, sizeof o); + for (uint32_t j = 0; j <= pos; j++) { + const double w = exp2(p[j] - mx); l += w; + const uint16_t *vr = j < c->pos0 ? c->vc + ((size_t)g * c->max_pos + j) * HD : vn + ((size_t)(j - c->pos0) * KVH + g) * HD; + for (unsigned i = 0; i < HD; i++) o[i] += w * (double)omega_dattn_bf16_f32(vr[i]); + } + for (unsigned i = 0; i < HD; i++) out[h * HD + i] = o[i] / l * (double)out_scale; + } + free(p); +} +/* the tokens parity checks: all up to 512, else first 2, last 2 and 4 spread */ +static size_t parity_tokens(uint32_t m, uint32_t *tok) { + if (m <= 512) { for (uint32_t t = 0; t < m; t++) tok[t] = t; return m; } + const uint32_t pick[8] = { 0, 1, m / 5, (2 * m) / 5, (3 * m) / 5, (4 * m) / 5, m - 2, m - 1 }; + memcpy(tok, pick, sizeof pick); + return 8; +} +/* out: rows osw f32 apart */ +static size_t parity(const Case *c, const uint16_t *kn, const uint16_t *vn, const float *out, size_t osw, float out_scale, double *worst) { + uint32_t *tok = malloc((size_t)(c->m > 8 ? c->m : 8) * 4); size_t nt = parity_tokens(c->m, tok); + double *ref = malloc(OW * sizeof(double)), tol = TOL_REL * out_scale + 1e-6 * out_scale; size_t bad = 0; *worst = 0; + for (size_t k = 0; k < nt; k++) { + ref_token(c, kn, vn, tok[k], out_scale, ref); + for (size_t i = 0; i < OW; i++) { double d = fabs((double)out[(size_t)tok[k] * osw + i] - ref[i]); if (!(d <= tol)) bad++; if (d / tol > *worst || d != d) *worst = d != d ? INFINITY : d / tol; } + } + free(ref); free(tok); + return bad; +} +/* the rows the kernel appended (K permuted, V model order; [4][256] per token at kchip/vchip + t * 1024 words) against + * the reference rows: v exact, k as below */ +static float bf16f(uint16_t h) { uint32_t u = (uint32_t)h << 16; float f; memcpy(&f, &u, 4); return f; } +/* K rows: chip == ref, or one bf16 ulp apart (at most 32 per token), or, for a value left small by the rotation's + * cancellation (x1 cos - x2 sin), within 8 f32 roundings of the head row's largest |k| (8 * 2^-24 * rowmax): the + * chip rotates in f32, the oracle in double, and a 3-ulp gap at 7e-6 in a row of O(1) values is f32 rounding, not a + * kernel error (seen at 30720+2048 and 129024+2048 on 2026-10-18; the rows were bit-equal to the decode program's). */ +static int rows_ok(const Case *c, const uint16_t *kchip, const uint16_t *vchip, const uint16_t *kn, const uint16_t *vn, char *why, size_t n) { + unsigned flips = 0, worst_tok = 0, small = 0; + for (size_t t = 0; t < c->m; t++) { + unsigned tf = 0; + for (unsigned g = 0; g < KVH; g++) { + float rowmax = 0; + for (unsigned i = 0; i < HD; i++) { float a = fabsf(bf16f(kn[(t * KVH + g) * HD + i])); if (a > rowmax) rowmax = a; } + for (unsigned i = 0; i < HD; i++) { + size_t ci = (t * KVH + g) * HD + i, ri = (t * KVH + g) * HD + omega_dattn256_perm_slot(i, c->rotary); + if (vchip[ci] != vn[ci]) { snprintf(why, n, "token %zu v[%u][%u] chip %04x ref %04x", t, g, i, vchip[ci], vn[ci]); return 0; } + if (kchip[ci] == kn[ri]) continue; + int d = (int)kchip[ci] - (int)kn[ri]; + if (d >= -1 && d <= 1) { tf++; continue; } + if (fabsf(bf16f(kchip[ci]) - bf16f(kn[ri])) <= 8.0f * 0x1p-24f * rowmax) { small++; continue; } + snprintf(why, n, "token %zu k[%u] slot %u chip %04x ref %04x (row max %.3g)", t, g, i, kchip[ci], kn[ri], (double)rowmax); + return 0; + } + } + if (tf > 32) { snprintf(why, n, "token %zu: %u one-ulp k flips", t, tf); return 0; } + if (tf > worst_tok) worst_tok = tf; + flips += tf; + } + snprintf(why, n, "ok (%u one-ulp k flips, worst token %u; %u small-value k gaps within 8 f32 roundings of the row max)", flips, worst_tok, small); + return 1; +} +/* ------------------------------------------------------------- host only */ +static void host_only(void) { + uint32_t att_ph = 0; + for (int m = 0; m <= 2; m++) { + OmegaPrefillFattn256Spec s = { .mutant = m ATT_SHAPE }; uint32_t n = 0, gp = 0, ph = 0; + int rc = omega_prefill_fattn256_prog_stats(&s, &n, &gp, &ph); + const uint32_t dec = omega_bw_gpr_declared(gp); + CHECK(rc == 0 && n <= BW_MAX_IR_INSNS && gp <= BW_PHYS_GPR_HW_LIMIT && 256u * dec <= 65536u && ph > 0, + "attend codegen mutant %d: rc %d insns %u gprs %u (declared %u) placeholders %u", m, rc, n, gp, dec, ph); + if (rc == 0 && m == 0) { att_ph = ph; printf("attend: %u instructions, %u registers (declared %u, 256 threads -> %u of 65536), %u placeholders\n", n, gp, dec, 256 * dec, ph); } + } + for (int m = 0; m <= 2; m++) { /* variant 2 within the same budgets */ + OmegaPrefillFattn256Spec s = { .mutant = m ATT_SHAPE, .variant = 2 }; uint32_t n = 0, gp = 0, ph = 0; + int rc = omega_prefill_fattn256_prog_stats(&s, &n, &gp, &ph); + const uint32_t dec = omega_bw_gpr_declared(gp); + CHECK(rc == 0 && n <= BW_MAX_IR_INSNS && gp <= BW_PHYS_GPR_HW_LIMIT && 256u * dec <= 65536u && ph == att_ph, + "attend variant 2 codegen mutant %d: rc %d insns %u gprs %u (declared %u) placeholders %u", m, rc, n, gp, dec, ph); + if (rc == 0 && m == 0) printf("attend variant 2: %u instructions, %u registers (declared %u, 256 threads -> %u of 65536), %u placeholders\n", n, gp, dec, 256 * dec, ph); + } + { OmegaPrefillFattn256Spec s = { .variant = 3 ATT_SHAPE }; CHECK(!omega_fattn256_spec_ok(&s) && omega_prefill_fattn256_prog_stats(&s, NULL, NULL, NULL) != 0, "attend variant 3 refused"); + s.variant = -1; CHECK(!omega_fattn256_spec_ok(&s) && omega_prefill_fattn256_prog_stats(&s, NULL, NULL, NULL) != 0, "attend variant -1 refused"); + CHECK(omega_gpu_prefill_fattn256_set_variant(3) == OMEGA_GPU_DATTN_BAD_ARGS && omega_gpu_prefill_fattn256_set_variant(-1) == OMEGA_GPU_DATTN_BAD_ARGS, "API variant 3 and -1 refused"); } + { static uint8_t vc[1 << 17]; uint32_t gp1 = 0, gp2 = 0; int np = -1; + omega_gpu_prefill_fattn256_set_variant(1); + size_t n1 = omega_gpu_prefill_fattn256_encode(1, QH, KVH, QPC, 0, vc, sizeof vc, &gp1, &np); + const uint64_t h1 = n1 ? fnv1a64(vc, n1) : 0; + CHECK(n1 == 14976 && h1 == 8700843075116262202ull, "variant 1 attend bytes are the 475b72b2 kernel: %zu bytes fnv1a64 %" PRIu64 " (expect 14976, 8700843075116262202)", n1, h1); + omega_gpu_prefill_fattn256_set_variant(2); + size_t n2 = omega_gpu_prefill_fattn256_encode(1, QH, KVH, QPC, 0, vc, sizeof vc, &gp2, &np); + const uint64_t h2 = n2 ? fnv1a64(vc, n2) : 0; + CHECK(n2 > 0 && h2 != h1 && omega_bw_gpr_declared(gp2) == omega_bw_gpr_declared(gp1), "variant 2 attend encodes (%zu bytes, gprs %u, declared %u as variant 1's %u) and differs", n2, gp2, omega_bw_gpr_declared(gp2), omega_bw_gpr_declared(gp1)); + printf("attend bytes: variant 1 %zu fnv1a64 %" PRIu64 " (gprs %u); variant 2 %zu fnv1a64 %" PRIu64 " (gprs %u)\n", n1, h1, gp1, n2, h2, gp2); + omega_gpu_prefill_fattn256_set_variant(g_variant); } + { OmegaPrefillFattn256Spec s = { .mutant = 3 ATT_SHAPE }; CHECK(omega_prefill_fattn256_prog_stats(&s, NULL, NULL, NULL) != 0, "attend mutant 3 refused"); + s.mutant = -1; CHECK(omega_prefill_fattn256_prog_stats(&s, NULL, NULL, NULL) != 0, "attend mutant -1 refused"); + OmegaPrefillFattn256Spec b1 = { .q_heads = 16, .kv_heads = 3 }, b2 = { .q_heads = 18, .kv_heads = 2 }, ok27 = { .q_heads = 24, .kv_heads = 4 }, dflt = { .mutant = 0 }; + CHECK(!omega_fattn256_spec_ok(&b1) && !omega_fattn256_spec_ok(&b2), "attend shapes 16/3 (not a multiple) and 18/2 (group 9 > 8) refused"); + OmegaFattn256Shape sh; uint32_t n27 = 0, n36 = 0; + CHECK(omega_fattn256_spec_ok(&ok27) && omega_fattn256_shape(&dflt, &sh) == 0 && sh.qh == 16 && sh.kvh == 2 && sh.group == 8 && sh.out_words == OW && sh.qf_pair_bytes == QFP, + "attend default shape is the q36 16 / 2 (group 8, %u out words, %u q' bytes per pair); the 27B 24 / 4 builds", OW, QFP); + CHECK(omega_prefill_fattn256_prog_stats(&ok27, &n27, NULL, NULL) == 0 && omega_prefill_fattn256_prog_stats(&dflt, &n36, NULL, NULL) == 0 && n27 > 0 && n36 > 0, "27B and default shapes build"); } + static const int pm[3] = { 0, 1, 3 }; + for (unsigned k = 0; k < 3; k++) { + OmegaDecodeAttn256Spec s = { .depth = OMEGA_GPU_DATTN256_DEPTH, .mutant = pm[k], .prep = 1, .prep_xstride = XS SPEC_SHAPE }; uint32_t n = 0, gp = 0; + int rc = omega_decode_attn256_prog_stats(&s, &n, &gp); + CHECK(rc == 0 && n <= BW_MAX_IR_INSNS && gp <= BW_PHYS_GPR_MAX - 2, "prep (xstride %u) codegen mutant %d: rc %d insns %u gprs %u", XS, pm[k], rc, n, gp); + if (rc == 0 && k == 0) printf("prep (xstride %u): %u instructions, %u registers\n", XS, n, gp); + } + { OmegaDecodeAttn256Spec s = { .depth = OMEGA_GPU_DATTN256_DEPTH, .prep = 1, .prep_xstride = QW * 4u - 16u SPEC_SHAPE }; + CHECK(omega_decode_attn256_prog_stats(&s, NULL, NULL) != 0, "prep_xstride below a q|k|v row refused"); + s.prep_xstride = XS + 4u; CHECK(omega_decode_attn256_prog_stats(&s, NULL, NULL) != 0, "prep_xstride off 16 bytes refused"); + s.prep_xstride = XS; s.prep = 0; CHECK(omega_decode_attn256_prog_stats(&s, NULL, NULL) != 0, "prep_xstride without prep refused (decode unchanged)"); + s.prep = 1; s.multi = 1; CHECK(omega_decode_attn256_prog_stats(&s, NULL, NULL) != 0, "prep_xstride with multi refused (the multi path has its own stride)"); } + static uint8_t code[1 << 17]; + for (unsigned k = 0; k < 2; k++) { + uint32_t gp = 0; int np = -1; size_t n = omega_gpu_prefill_fattn256_encode(k, QH, KVH, QPC, XS, code, sizeof code, &gp, &np); + CHECK(n > 0 && (k == 0 ? np == 0 : (np > 0 && (uint32_t)np == att_ph)), "encode %s: %zu bytes, gprs %u, %d placeholders patched (expect %u)", k ? "attend" : "prep", n, gp, np, k ? att_ph : 0u); + } + CHECK(omega_gpu_prefill_fattn256_encode(2, 0, 0, 0, 0, code, sizeof code, NULL, NULL) == 0, "encode kind 2 refused"); + CHECK(omega_gpu_prefill_fattn256_encode(1, 0, 0, 0, 0, code, 64, NULL, NULL) == 0, "encode into a too-small buffer refused"); + CHECK(omega_gpu_prefill_fattn256_encode(1, 18, 2, 0, 0, code, sizeof code, NULL, NULL) == 0, "encode of a refused shape returns 0"); + CHECK(OMEGA_FATTN256_SHARED_BYTES == 0u && OMEGA_FATTN256_ARGS_WORDS * 4u == OMEGA_FATTN256_ARG_OSTRIDE + 4u - 0x380u, "attend: no shared memory; %u argument words end at OSTRIDE", OMEGA_FATTN256_ARGS_WORDS); + CHECK(OMEGA_PATTN256_QF_OFF_SHAPE(KVH, QH / KVH, 1, 0, 0, 0, 0) == QFP && OMEGA_PATTN256_QF_OFF_SHAPE(KVH, QH / KVH, 0, KVH - 1, QH / KVH - 1, 15, 3) + 16u == QFP, "QF layout: one token pair is %u bytes, densely packed", QFP); + CHECK(omega_gpu_prefill_fattn256(NULL, 0, 0, 1, (const float *)code, XS, EPS, 1.0f, (float *)code, OW * 4u, NULL) == OMEGA_GPU_DATTN_BAD_ARGS, "NULL cache refused"); + CHECK(omega_gpu_prefill_fattn256_record(NULL, NULL, 0, 0, 1, 16, XS, EPS, 1.0f, 16, OW * 4u) == OMEGA_GPU_DATTN_BAD_ARGS, "record without a command list refused"); + CHECK(omega_gpu_prefill_fattn256_reserve_for(NULL, 16, XS) == OMEGA_GPU_DATTN_BAD_ARGS, "reserve without a cache refused before any device work"); + /* reference sanity: one token at position 0 returns its own rounded v */ + { Case c; case_make(&c, 256, 0, 1, 64, 11, 1.0f); uint16_t kn[KVH * HD], vn[KVH * HD]; double ref[OW]; + ref_rows(&c, kn, vn); ref_token(&c, kn, vn, 0, 1.0f, ref); + int good = 1; for (unsigned h = 0; h < QH; h++) for (unsigned i = 0; i < HD; i++) good &= fabs(ref[h * HD + i] - (double)omega_dattn_bf16_f32(vn[(h / (QH / KVH)) * HD + i])) < 1e-12; + CHECK(good, "reference: context 1 returns the rounded v of the head's KV group"); + case_free(&c); } +} +/* ------------------------------------------------------------- simulator */ +static uint64_t g_sim_issues; +static uint32_t g_poison; /* --poison SEED: registers start as junk in every simulated CTA (tests/bw_warp_sim_pa.h reg_poison) */ +typedef struct { + const Case *c; + uint8_t *kv; size_t plane; + float *rope, *norms, *qkv_k; +} SimBufs; +static void cb64(WsSim *s, unsigned off, const void *p) { uint64_t a = (uintptr_t)p; s->cbank[off / 4] = (uint32_t)a; s->cbank[off / 4 + 1] = (uint32_t)(a >> 32); } +static void cbf(WsSim *s, unsigned off, float f) { memcpy(&s->cbank[off / 4], &f, 4); } +/* the decode program (prep 0 or 1) at position pos (prep: tokens pos .. pos+grid_x-1, qkv rows from qkv_k) */ +static int sim_decode_launch(const BlackwellIRProgram *prog, const SimBufs *b, uint32_t pos, uint32_t grid_x, const float *qkv_k, size_t qkv_bytes, + void *out, size_t out_bytes, float *part, size_t part_bytes, uint32_t *cnt, uint32_t splits, int order, char *msg, size_t n) { + static uint8_t smem[OMEGA_DATTN256_SHARED_BYTES]; + WsSim s; memset(&s, 0, sizeof s); + s.p = prog; s.threads = 256; s.order = order; s.reg_poison = g_poison; s.smem = smem; s.smem_bytes = sizeof smem; + cb64(&s, OMEGA_DATTN256_ARG_QKV, qkv_k); cb64(&s, OMEGA_DATTN256_ARG_KC, b->kv); cb64(&s, OMEGA_DATTN256_ARG_VC, b->kv + b->plane); + cb64(&s, OMEGA_DATTN256_ARG_ROPE, b->rope); cb64(&s, OMEGA_DATTN256_ARG_QN, b->norms); cb64(&s, OMEGA_DATTN256_ARG_KN, b->norms + HD); + cb64(&s, OMEGA_DATTN256_ARG_OUT, out); cb64(&s, OMEGA_DATTN256_ARG_PART, part); cb64(&s, OMEGA_DATTN256_ARG_CNT, cnt); + s.cbank[OMEGA_DATTN256_ARG_POS / 4] = pos; s.cbank[OMEGA_DATTN256_ARG_PER_SPLIT / 4] = 256; s.cbank[OMEGA_DATTN256_ARG_SPLITS / 4] = splits; + s.cbank[OMEGA_DATTN256_ARG_KV_STRIDE / 4] = b->c->max_pos * RB; + cbf(&s, OMEGA_DATTN256_ARG_EPS, EPS); cbf(&s, OMEGA_DATTN256_ARG_OUT_SCALE, 1.0f); cbf(&s, OMEGA_DATTN256_ARG_QK_SCALE, QKS); + s.nranges = 5; + s.ranges[0].lo = (uintptr_t)qkv_k; s.ranges[0].hi = (uintptr_t)qkv_k + qkv_bytes; + s.ranges[1].lo = (uintptr_t)b->kv; s.ranges[1].hi = (uintptr_t)b->kv + 2 * b->plane; + s.ranges[2].lo = (uintptr_t)b->rope; s.ranges[2].hi = (uintptr_t)b->rope + (size_t)b->c->max_pos * OMEGA_DATTN256_ROPE_ROW_BYTES; + s.ranges[3].lo = (uintptr_t)b->norms; s.ranges[3].hi = (uintptr_t)b->norms + 2048; + s.ranges[4].lo = (uintptr_t)out; s.ranges[4].hi = (uintptr_t)out + out_bytes; + if (part) { /* prep never touches the partials or counters: no range, so a stray access faults */ + s.ranges[5].lo = (uintptr_t)part; s.ranges[5].hi = (uintptr_t)part + part_bytes; + s.ranges[6].lo = (uintptr_t)cnt; s.ranges[6].hi = (uintptr_t)cnt + 16; s.nranges = 7; + } + int err = ws_run(&s, grid_x, VY); + if (err) { snprintf(msg, n, "%s launch at %u: %s (pc %d)", part ? "decode" : "prep", pos, s.msg, s.err_pc); return -1; } + g_sim_issues += s.warp_issues; + return 0; +} +/* the fattn attend: grid (ceil(m / 16), KVH), no shared memory (smem NULL: any shared access faults) */ +static uint64_t g_att_issues; /* the attend launches' share of g_sim_issues */ +static int sim_attend_launch(const BlackwellIRProgram *prog, const SimBufs *b, const uint8_t *qf, size_t qf_bytes, float *out, size_t osw, int order, char *msg, size_t n) { + const Case *c = b->c; + WsSim s; memset(&s, 0, sizeof s); + s.p = prog; s.threads = OMEGA_FATTN256_THREADS; s.order = order; s.reg_poison = g_poison; s.smem = NULL; s.smem_bytes = OMEGA_FATTN256_SHARED_BYTES; + cb64(&s, OMEGA_FATTN256_ARG_QF, qf); cb64(&s, OMEGA_FATTN256_ARG_KC, b->kv); cb64(&s, OMEGA_FATTN256_ARG_VC, b->kv + b->plane); cb64(&s, OMEGA_FATTN256_ARG_OUT, out); + s.cbank[OMEGA_FATTN256_ARG_POS0 / 4] = c->pos0; s.cbank[OMEGA_FATTN256_ARG_MC / 4] = c->m; s.cbank[OMEGA_FATTN256_ARG_KV_STRIDE / 4] = c->max_pos * RB; + s.cbank[OMEGA_FATTN256_ARG_OSTRIDE / 4] = (uint32_t)(osw * 4); + cbf(&s, OMEGA_FATTN256_ARG_OUT_SCALE, 1.0f); + s.nranges = 3; + s.ranges[0].lo = (uintptr_t)qf; s.ranges[0].hi = (uintptr_t)qf + qf_bytes; + s.ranges[1].lo = (uintptr_t)b->kv; s.ranges[1].hi = (uintptr_t)b->kv + 2 * b->plane; + s.ranges[2].lo = (uintptr_t)out; s.ranges[2].hi = (uintptr_t)out + (size_t)c->m * osw * 4; + int err = ws_run(&s, (c->m + OMEGA_FATTN256_TOKENS - 1) / OMEGA_FATTN256_TOKENS, KVH); + if (err) { snprintf(msg, n, "attend: %s (pc %d)", s.msg, s.err_pc); return -1; } + g_sim_issues += s.warp_issues; g_att_issues += s.warp_issues; + return 0; +} +/* output rows OSW_SIM f32 apart: 16 padding words per row that the attend must leave alone */ +#define OSW_SIM (OW + 16u) +static uint64_t g_sim_out_fnv; /* FNV-1a64 of the last sim_point's output rows (padding included) */ +static int sim_point(uint32_t max_pos, uint32_t pos0, uint32_t m, uint32_t rotary, float qscale, uint32_t seed, int orders, int prep_mut, int att_mut, + char *msg, size_t n, double *worst, size_t *bad) { + static BlackwellIRProgram pprog, aprog, dprog; + OmegaDecodeAttn256Spec ps = { .depth = OMEGA_GPU_DATTN256_DEPTH, .mutant = prep_mut, .prep = 1, .prep_xstride = XS SPEC_SHAPE }, ds = { .depth = OMEGA_GPU_DATTN256_DEPTH SPEC_SHAPE }; + OmegaPrefillFattn256Spec as = { .mutant = att_mut ATT_SHAPE, .variant = g_variant }; + if (omega_blackwell_codegen_decode_attn256_prog(&ps, &pprog) != 0 || omega_blackwell_codegen_prefill_fattn256_prog(&as, &aprog) != 0 || + omega_blackwell_codegen_decode_attn256_prog(&ds, &dprog) != 0) { snprintf(msg, n, "codegen refused"); return -1; } + Case c; case_make(&c, max_pos, pos0, m, rotary, seed, qscale); + SimBufs b = { .c = &c }; + b.plane = (size_t)KVH * max_pos * RB + OMEGA_DATTN256_PLANE_SLACK; + b.kv = aligned_alloc(16, 2 * b.plane); + uint8_t *twin = aligned_alloc(16, 2 * b.plane); + b.rope = aligned_alloc(16, (size_t)max_pos * OMEGA_DATTN256_ROPE_ROW_BYTES); + for (uint32_t p = 0; p < max_pos; p++) omega_dattn256_rope_row(p, THETA, rotary, b.rope + (size_t)p * 256); + b.norms = aligned_alloc(16, 2048); case_kernel_norms(&c, b.norms, b.norms + HD); + b.qkv_k = aligned_alloc(16, (size_t)m * XS); case_kernel_qkv(&c, b.qkv_k); + const size_t qf_bytes = (size_t)((m + 1) / 2) * QFP, ob = (size_t)m * OSW_SIM * 4; + uint8_t *qf = aligned_alloc(16, qf_bytes); + float *out = aligned_alloc(16, ob), *copy = malloc(ob); + int err = 0; + for (int order = 0; order < orders && !err; order++) { + memset(b.kv, 0, 2 * b.plane); case_history_into(&c, b.kv, b.plane); + memset(qf, 0xff, qf_bytes); /* NaN bf16 pairs: a slot the prep never wrote poisons its row */ + for (size_t i = 0; i < (size_t)m * OSW_SIM; i++) out[i] = -999.0f; + err = sim_decode_launch(&pprog, &b, pos0, m, b.qkv_k, (size_t)m * XS, qf, qf_bytes, NULL, 0, NULL, 0, order, msg, n); + if (!err) err = sim_attend_launch(&aprog, &b, qf, qf_bytes, out, OSW_SIM, order, msg, n); + if (err) break; + size_t unwritten = 0, pad = 0; + for (size_t t = 0; t < m; t++) for (size_t i = 0; i < OSW_SIM; i++) { const int u = out[t * OSW_SIM + i] == -999.0f; if (i < OW) unwritten += u; else pad += !u; } + if (unwritten || pad) { err = -1; snprintf(msg, n, "%zu output words never written, %zu padding words written", unwritten, pad); break; } + if (order == 0) memcpy(copy, out, ob); + else if (memcmp(copy, out, ob) != 0) { err = -1; snprintf(msg, n, "the fragment order changed the result"); } + } + if (!err) { + g_sim_out_fnv = fnv1a64(out, ob); + /* twin: m decode steps of the decode program from the same history */ + memset(twin, 0, 2 * b.plane); case_history_into(&c, twin, b.plane); + SimBufs tb = b; tb.kv = twin; + float *dout = aligned_alloc(16, OW * 4); + const uint32_t smax = (pos0 + m + 255) / 256; + float *part = aligned_alloc(16, (size_t)VY * smax * OMEGA_DATTN256_PARTIAL_WORDS * 4); + uint32_t *cnt = aligned_alloc(16, 16); + for (uint32_t t = 0; t < m && !err; t++) { + const uint32_t pos = pos0 + t, splits = (pos + 256) / 256; + memset(cnt, 0, 16); + err = sim_decode_launch(&dprog, &tb, pos, splits, b.qkv_k + (size_t)t * XSW, QW * 4, dout, OW * 4, part, (size_t)VY * splits * OMEGA_DATTN256_PARTIAL_WORDS * 4, cnt, splits, 0, msg, n); + } + free(dout); free(part); free(cnt); + size_t rowdiff = 0; + for (unsigned h = 0; h < 2 * KVH && !err; h++) { + const size_t o = (h >= KVH ? b.plane : 0) + (size_t)(h % KVH) * max_pos * RB; + for (uint32_t t = 0; t < pos0 + m; t++) rowdiff += memcmp(b.kv + o + (size_t)t * RB, twin + o + (size_t)t * RB, RB) != 0; + } + uint16_t *kn = malloc((size_t)m * KVH * HD * 2), *vn = malloc((size_t)m * KVH * HD * 2), *kch = malloc((size_t)m * KVH * HD * 2), *vch = malloc((size_t)m * KVH * HD * 2); + ref_rows(&c, kn, vn); + for (uint32_t t = 0; t < m; t++) for (unsigned g = 0; g < KVH; g++) { + const size_t o = ((size_t)g * max_pos + pos0 + t) * RB; + memcpy(kch + ((size_t)t * KVH + g) * HD, b.kv + o, RB); memcpy(vch + ((size_t)t * KVH + g) * HD, b.kv + b.plane + o, RB); + } + char why[160]; + if (!err) { + int rok = rows_ok(&c, kch, vch, kn, vn, why, sizeof why); + *bad = parity(&c, kn, vn, out, OSW_SIM, 1.0f, worst); + if (rowdiff) *bad += 1000000; + if (!rok) *bad += 2000000; + snprintf(msg, n, "bad=%zu worst=%.3f rows vs decode twin: %zu differ; vs reference: %s", *bad, *worst, rowdiff, why); + } + free(kn); free(vn); free(kch); free(vch); + } + free(b.kv); free(twin); free(b.rope); free(b.norms); free(b.qkv_k); free(qf); free(out); free(copy); case_free(&c); + return err; +} +/* variant 1: the nine points (output hashes kept) and all four mutants; variant 2: the same points, each output + * bit-identical to variant 1's, and the attend mutants (the prep does not depend on the attend variant) */ +static void sim_battery(int variant) { + char msg[400]; double worst; size_t bad; + static uint64_t v1_fnv[16]; + g_variant = variant; + struct { uint32_t max_pos, pos0, m, rot; float qs; int orders; const char *name; } pts[] = { + { 256, 0, 1, 64, 1.0f, 2, "one token at position 0" }, + { 256, 0, 16, 64, 1.0f, 2, "16 tokens from 0 (one full CTA)" }, + { 256, 0, 17, 64, 1.0f, 2, "17 tokens from 0 (CTA boundary, odd m)" }, + { 256, 0, 37, 64, 1.0f, 2, "37 tokens from 0 (odd m, partial CTA)" }, + { 256, 37, 19, 64, 1.0f, 2, "19 tokens from 37 (odd start)" }, + { 256, 100, 19, 64, 4.0f, 1, "19 tokens from 100, sharp q (x4)" }, + { 512, 250, 40, 64, 1.0f, 1, "40 tokens from 250 (crosses 256)" }, + { 256, 0, 24, 256, 1.0f, 1, "24 tokens from 0, full rope (rotary 256)" }, + { 512, 300, 50, 64, 1.0f, 1, "50 tokens from 300 (history > 256, warps past m)" }, + }; + for (size_t i = 0; i < sizeof pts / sizeof pts[0]; i++) { + double t0 = now_ms(); + int err = sim_point(pts[i].max_pos, pts[i].pos0, pts[i].m, pts[i].rot, pts[i].qs, 100 + (uint32_t)i, pts[i].orders, 0, 0, msg, sizeof msg, &worst, &bad); + CHECK(err == 0 && bad == 0, "sim variant %d %s: %s", variant, pts[i].name, msg); + int same = 1; + if (variant == 1) v1_fnv[i] = err ? 0 : g_sim_out_fnv; + else { same = !err && v1_fnv[i] != 0 && g_sim_out_fnv == v1_fnv[i]; CHECK(same, "sim variant %d %s: output differs from variant 1's", variant, pts[i].name); } + printf("sim v%d %-48s %s %s%s (%.1f s)\n", variant, pts[i].name, err ? "ERROR" : bad ? "MISMATCH" : "ok", msg, variant == 1 ? "" : same ? "; output == variant 1" : "; output DIFFERS from variant 1", + (now_ms() - t0) / 1e3); + fflush(stdout); + } + static const struct { int pm, am; } mut[] = { { 1, 0 }, { 3, 0 }, { 0, 1 }, { 0, 2 } }; + for (size_t i = 0; i < sizeof mut / sizeof mut[0]; i++) { + if (variant != 1 && mut[i].pm) continue; + int err = sim_point(256, 40, 24, 64, 1.0f, 200, 1, mut[i].pm, mut[i].am, msg, sizeof msg, &worst, &bad); + int caught = err != 0 || bad > 0; + CHECK(caught, "sim variant %d %s mutant %d NOT caught (%s)", variant, mut[i].pm ? "prep" : "attend", mut[i].pm ? mut[i].pm : mut[i].am, msg); + printf("sim v%d %s mutant %d at 24 tokens from 40: %s (%s)\n", variant, mut[i].pm ? "prep" : "attend", mut[i].pm ? mut[i].pm : mut[i].am, caught ? "caught" : "MISSED", msg); + fflush(stdout); + } + printf("sim v%d: %" PRIu64 " warp issues in total so far\n", variant, g_sim_issues); +} + +/* ------------------------------------------------------------- chip */ +static FILE *g_json; +static int g_json_first = 1; +static int cache_with_history(const Case *c, OmegaGpuDecodeAttn256Cache **out) { + int rc = omega_gpu_decode_attn256_cache_alloc_shape(1, c->max_pos, THETA, c->rotary, QH, KVH, QPC, out); + if (rc != OMEGA_GPU_DATTN_OK) return rc; + float qn_k[HD], kn_k[HD]; case_kernel_norms(c, qn_k, kn_k); + rc = omega_gpu_decode_attn256_set_norms(*out, 0, qn_k, kn_k); + if (rc != OMEGA_GPU_DATTN_OK || c->pos0 == 0) return rc; + uint16_t *kp = malloc((size_t)c->pos0 * RB); + for (unsigned g = 0; g < KVH && rc == OMEGA_GPU_DATTN_OK; g++) { + for (uint32_t t = 0; t < c->pos0; t++) omega_dattn256_perm_vec_bf16(c->kc + ((size_t)g * c->max_pos + t) * HD, kp + (size_t)t * HD, c->rotary); + rc = omega_gpu_decode_attn256_cache_write(*out, 0, g, 0, c->pos0, kp, c->vc + (size_t)g * c->max_pos * HD); + } + free(kp); + return rc; +} +/* the chunk's appended rows, [m][4][256] each (K permuted as stored) */ +static int read_rows(OmegaGpuDecodeAttn256Cache *cc, const Case *c, uint16_t *k, uint16_t *v) { + for (uint32_t t = 0; t < c->m; t++) for (unsigned g = 0; g < KVH; g++) { + int rc = omega_gpu_decode_attn256_cache_read(cc, 0, g, c->pos0 + t, k + ((size_t)t * KVH + g) * HD, v + ((size_t)t * KVH + g) * HD); + if (rc != OMEGA_GPU_DATTN_OK) return rc; + } + return OMEGA_GPU_DATTN_OK; +} +static uint64_t median_u64(uint64_t *v, int n) { qsort(v, (size_t)n, sizeof *v, cmp_u64); return v[n / 2]; } +/* osw: f32 between output rows (OW = the q36 graph's MOS) */ +static int chip_point(uint32_t max_pos, uint32_t pos0, uint32_t m, float qscale, uint32_t seed, int twin, int reps, uint32_t osw) { + printf("-- chip %u tokens from %u (max_pos %u, ostride %u)\n", m, pos0, max_pos, osw * 4); fflush(stdout); + Case c; case_make(&c, max_pos, pos0, m, 64, seed, qscale); + float *qkv_k = malloc((size_t)m * XS); case_kernel_qkv(&c, qkv_k); + const size_t ob = (size_t)m * osw * 4; + float *out = malloc(ob), *out2 = malloc(ob); + const size_t rw = (size_t)m * KVH * HD; + uint16_t *kn = malloc(rw * 2), *vn = malloc(rw * 2), *kch = malloc(rw * 2), *vch = malloc(rw * 2), *ktw = malloc(rw * 2), *vtw = malloc(rw * 2); + OmegaGpuDecodeAttn256Cache *cc = NULL, *tc = NULL; + OmegaGpuPrefillFattn256Info info; + int ok = 1; char why[200]; double worst = 0; size_t bad = 0; + int rc = cache_with_history(&c, &cc); + CHECK(rc == OMEGA_GPU_DATTN_OK, "cache with history: %s %s", omega_gpu_decode_attn_rc_name(rc), rc ? omega_gpu_decode_attn_last_error() : ""); + if (rc != OMEGA_GPU_DATTN_OK) { ok = 0; goto done; } + for (size_t i = 0; i < (size_t)m * osw; i++) out[i] = -999.0f; + rc = omega_gpu_prefill_fattn256(cc, 0, pos0, m, qkv_k, XS, EPS, 1.0f, out, osw * 4, &info); + CHECK(rc == OMEGA_GPU_DATTN_OK, "prefill %u+%u: %s %s", pos0, m, omega_gpu_decode_attn_rc_name(rc), rc ? omega_gpu_decode_attn_last_error() : ""); + if (rc != OMEGA_GPU_DATTN_OK) { ok = 0; goto done; } + printf(" prep %u insns %u regs, attend %u insns %u regs; first call %.3f ms (prep %.3f, attend %.3f)\n", info.insns[0], info.gprs[0], info.insns[1], info.gprs[1], + info.call_ns / 1e6, info.elapsed_ns[0] / 1e6, info.elapsed_ns[1] / 1e6); + ref_rows(&c, kn, vn); + rc = read_rows(cc, &c, kch, vch); + int rok = rc == OMEGA_GPU_DATTN_OK && rows_ok(&c, kch, vch, kn, vn, why, sizeof why); + CHECK(rok, "%u+%u: appended rows vs reference: %s", pos0, m, rc ? "read failed" : why); + double t0 = now_ms(); + bad = parity(&c, kn, vn, out, osw, 1.0f, &worst); + { size_t pad = 0; for (size_t t = 0; t < m; t++) for (size_t i = OW; i < osw; i++) pad += out[t * osw + i] != -999.0f; + CHECK(pad == 0, "%u+%u: %zu output padding words written", pos0, m, pad); bad += pad; } + CHECK(bad == 0, "%u+%u: parity: %zu elements outside the tolerance (worst ratio %.3f)", pos0, m, bad, worst); + printf(" parity: %zu bad, worst ratio %.3f of the tolerance (%.1f s reference); rows: %s\n", bad, worst, (now_ms() - t0) / 1e3, rok ? why : "FAIL"); + ok &= rok && bad == 0; + /* second call over the same positions: the same rows are rewritten, the same output */ + memcpy(out2, out, ob); + rc = omega_gpu_prefill_fattn256(cc, 0, pos0, m, qkv_k, XS, EPS, 1.0f, out2, osw * 4, &info); + CHECK(rc == OMEGA_GPU_DATTN_OK && memcmp(out, out2, ob) == 0 && info.kernel_cache_hits == 2, "%u+%u: second call bit-identical with both kernels cached (rc %d hits %u)", pos0, m, rc, info.kernel_cache_hits); + /* out_scale 2^20: exact */ + rc = omega_gpu_prefill_fattn256(cc, 0, pos0, m, qkv_k, XS, EPS, 1048576.0f, out2, osw * 4, NULL); + { size_t diff = 0; for (size_t t = 0; t < m; t++) for (size_t i = 0; i < OW; i++) diff += out2[t * osw + i] != out[t * osw + i] * 1048576.0f; + CHECK(rc == OMEGA_GPU_DATTN_OK && diff == 0, "%u+%u: out_scale 2^20 is exact (%zu words differ)", pos0, m, diff); } + /* device entry == host entry */ + { + OmegaGpuMem q, o; memset(&q, 0, sizeof q); memset(&o, 0, sizeof o); + omega_gpu_session_lock(); + int arc = omega_gpu_session_open() && omega_gpu_session_alloc((size_t)m * XS, &q) == 0 && omega_gpu_session_alloc(ob, &o) == 0 ? 0 : -1; + if (arc == 0) { memcpy(q.cpu, qkv_k, (size_t)m * XS); float *od = o.cpu; for (size_t i = 0; i < (size_t)m * osw; i++) od[i] = -999.0f; + arc = omega_gpu_session_sync_to_gpu(&q) | omega_gpu_session_sync_to_gpu(&o); } + omega_gpu_session_unlock(); + rc = arc == 0 ? omega_gpu_prefill_fattn256_dev(cc, 0, pos0, m, q.va, XS, EPS, 1.0f, o.va, osw * 4, NULL) : OMEGA_GPU_DATTN_CHIP_FAIL; + omega_gpu_session_lock(); + int same = rc == OMEGA_GPU_DATTN_OK && omega_gpu_session_sync_to_cpu(&o) == 0 && memcmp(o.cpu, out, ob) == 0; + if (q.cpu) omega_gpu_session_free(&q); + if (o.cpu) omega_gpu_session_free(&o); + omega_gpu_session_unlock(); + CHECK(same, "%u+%u: device entry bit-identical to the host entry (rc %s)", pos0, m, omega_gpu_decode_attn_rc_name(rc)); + } + /* twin: m decode calls from the same history; rows bit-identical, then the next decode step on both caches */ + if (twin) { + rc = cache_with_history(&c, &tc); + float *dout = malloc(OW * 4); + t0 = now_ms(); + for (uint32_t t = 0; t < m && rc == OMEGA_GPU_DATTN_OK; t++) rc = omega_gpu_decode_attn256(tc, 0, pos0 + t, qkv_k + (size_t)t * XSW, EPS, 1.0f, dout, NULL); + const double dec_ms = now_ms() - t0; + CHECK(rc == OMEGA_GPU_DATTN_OK, "%u+%u: twin decode loop: %s %s", pos0, m, omega_gpu_decode_attn_rc_name(rc), rc ? omega_gpu_decode_attn_last_error() : ""); + if (rc == OMEGA_GPU_DATTN_OK) rc = read_rows(tc, &c, ktw, vtw); + size_t kd = 0, vd = 0; + for (size_t i = 0; i < rw && rc == OMEGA_GPU_DATTN_OK; i++) { kd += kch[i] != ktw[i]; vd += vch[i] != vtw[i]; } + CHECK(rc == OMEGA_GPU_DATTN_OK && kd == 0 && vd == 0, "%u+%u: rows bit-identical to %u decode calls (k %zu, v %zu words differ)", pos0, m, m, kd, vd); + printf(" twin: %u decode calls %.1f ms; rows k %zu v %zu words differ\n", m, dec_ms, kd, vd); + if (pos0 + m < max_pos && rc == OMEGA_GPU_DATTN_OK) { + float *nq = malloc(QW * 4), *o1 = malloc(OW * 4), *o2 = malloc(OW * 4); uint32_t s = seed ^ 0x5a5a5a5au; + for (unsigned h = 0; h < QH + KVH; h++) { float raw[HD]; for (unsigned i = 0; i < HD; i++) raw[i] = frand(&s, -1.0f, 1.0f); omega_dattn256_perm_vec(raw, nq + h * HD, 64); } + for (unsigned i = KEND; i < QW; i++) nq[i] = frand(&s, -1.0f, 1.0f); + int r1 = omega_gpu_decode_attn256(cc, 0, pos0 + m, nq, EPS, 1.0f, o1, NULL), r2 = omega_gpu_decode_attn256(tc, 0, pos0 + m, nq, EPS, 1.0f, o2, NULL); + CHECK(r1 == OMEGA_GPU_DATTN_OK && r2 == OMEGA_GPU_DATTN_OK && memcmp(o1, o2, OW * 4) == 0, "%u+%u: next decode step bit-identical after prefill and after the decode loop", pos0, m); + free(nq); free(o1); free(o2); + } + free(dout); + } + /* timing: reps calls on the same positions (rows rewritten with the same bits) */ + if (reps > 0) { + uint64_t *pp = malloc((size_t)reps * 8), *aa = malloc((size_t)reps * 8), *cl = malloc((size_t)reps * 8); + for (int r = 0; r < reps && rc == OMEGA_GPU_DATTN_OK; r++) { + rc = omega_gpu_prefill_fattn256(cc, 0, pos0, m, qkv_k, XS, EPS, 1.0f, out2, osw * 4, &info); + pp[r] = info.elapsed_ns[0]; aa[r] = info.elapsed_ns[1]; cl[r] = info.call_ns; + } + CHECK(rc == OMEGA_GPU_DATTN_OK, "%u+%u: timing calls", pos0, m); + if (rc == OMEGA_GPU_DATTN_OK) { + const uint64_t mp = median_u64(pp, reps), ma = median_u64(aa, reps), mc = median_u64(cl, reps); + /* useful work: QK^T and PV over the causal context, 2 flops per multiply-add, 16 heads x 256 dims */ + double flops = 0, kvb = 0; + for (uint32_t t = 0; t < m; t++) flops += 4.0 * (double)(pos0 + t + 1) * QH * HD; + for (uint32_t cx = 0; cx * OMEGA_FATTN256_TOKENS < m; cx++) { /* per CTA: the rows of its last warp (L1 serves the rest) */ + uint32_t nk = (cx + 1) * OMEGA_FATTN256_TOKENS; if (nk > m) nk = m; + kvb += (double)KVH * (((pos0 + nk - 1) >> 4) + 1) * 16.0 * 2 * RB; + } + printf(" timing (median of %d): prep %.3f ms, attend %.3f ms, call %.3f ms -> %.0f tokens/s; attend %.2f TFLOPS useful, %.1f GB/s K/V streamed\n", + reps, mp / 1e6, ma / 1e6, mc / 1e6, m / ((mp + ma) / 1e9), flops / (double)ma / 1e3, kvb / (double)ma); + if (g_json) { + fprintf(g_json, "%s {\"pos0\": %u, \"m\": %u, \"max_pos\": %u, \"reps\": %d, \"prep_ns\": %" PRIu64 ", \"attend_ns\": %" PRIu64 ", \"call_ns\": %" PRIu64 ", \"attend_useful_flops\": %.0f, \"attend_kv_bytes\": %.0f, \"parity_bad\": %zu, \"parity_worst_ratio\": %.4f}", + g_json_first ? "" : ",\n", pos0, m, max_pos, reps, mp, ma, mc, flops, kvb, bad, worst); + g_json_first = 0; + } + } + free(pp); free(aa); free(cl); + } +done: + if (tc) omega_gpu_decode_attn256_cache_free(tc); + if (cc) omega_gpu_decode_attn256_cache_free(cc); + free(qkv_k); free(out); free(out2); free(kn); free(vn); free(kch); free(vch); free(ktw); free(vtw); case_free(&c); + return ok; +} +static void chip_mutants(void) { + static const struct { int pm, am; } mut[] = { { 1, 0 }, { 3, 0 }, { 0, 1 }, { 0, 2 } }; + for (size_t i = 0; i < sizeof mut / sizeof mut[0]; i++) { + omega_gpu_prefill_fattn256_test_set_mutant(mut[i].pm, mut[i].am); + Case c; case_make(&c, 256, 40, 24, 64, 300, 1.0f); + float *qkv_k = malloc((size_t)c.m * XS); case_kernel_qkv(&c, qkv_k); + float *out = malloc((size_t)c.m * OW * 4); + uint16_t *kn = malloc((size_t)c.m * KVH * HD * 2), *vn = malloc((size_t)c.m * KVH * HD * 2), *kch = malloc((size_t)c.m * KVH * HD * 2), *vch = malloc((size_t)c.m * KVH * HD * 2); + OmegaGpuDecodeAttn256Cache *cc = NULL; + int rc = cache_with_history(&c, &cc); + if (rc == OMEGA_GPU_DATTN_OK) rc = omega_gpu_prefill_fattn256(cc, 0, c.pos0, c.m, qkv_k, XS, EPS, 1.0f, out, OW * 4u, NULL); + double worst = 0; size_t bad = 0; char why[200] = ""; + int rok = 1; + if (rc == OMEGA_GPU_DATTN_OK) { + ref_rows(&c, kn, vn); + rok = read_rows(cc, &c, kch, vch) == OMEGA_GPU_DATTN_OK && rows_ok(&c, kch, vch, kn, vn, why, sizeof why); + bad = parity(&c, kn, vn, out, OW, 1.0f, &worst); + } + const int caught = rc != OMEGA_GPU_DATTN_OK || bad > 0 || !rok; + CHECK(caught, "chip %s mutant %d NOT caught", mut[i].pm ? "prep" : "attend", mut[i].pm ? mut[i].pm : mut[i].am); + printf("chip %s mutant %d: %s (rc %s, %zu bad, worst %.1f, rows %s)\n", mut[i].pm ? "prep" : "attend", mut[i].pm ? mut[i].pm : mut[i].am, caught ? "caught" : "MISSED", + omega_gpu_decode_attn_rc_name(rc), bad, worst, rok ? "ok" : "differ"); + if (cc) omega_gpu_decode_attn256_cache_free(cc); + free(qkv_k); free(out); free(kn); free(vn); free(kch); free(vch); case_free(&c); + } + omega_gpu_prefill_fattn256_test_set_mutant(0, 0); +} + +int main(int argc, char **argv) { + int host = 0, sim = 0, reps = 9, quick = 0, timing_only = 0, longp = 0; const char *json = NULL; uint32_t maxp = 32768; + const char *ve = getenv("AIEN_OMEGA_Q36_PF_FATTN"); /* the slices' variant switch; --variant overrides */ + if (ve && (ve[0] == '1' || ve[0] == '2') && ve[1] == 0) g_variant = ve[0] - '0'; + for (int i = 1; i < argc; i++) { + if (!strcmp(argv[i], "--host-only")) host = 1; + else if (!strcmp(argv[i], "--sim")) sim = 1; + else if (!strcmp(argv[i], "--poison") && i + 1 < argc) g_poison = (uint32_t)strtoul(argv[++i], NULL, 0); + else if (!strcmp(argv[i], "--variant") && i + 1 < argc) { + g_variant = atoi(argv[++i]); + if (g_variant < 1 || g_variant > 2) { fprintf(stderr, "--variant: 1 or 2\n"); return 2; } } + else if (!strcmp(argv[i], "--sim-point") && i + 3 < argc) { /* one simulator point: MAX_POS POS0 M (the --variant given before it) */ + uint32_t a = (uint32_t)atoi(argv[i + 1]), b = (uint32_t)atoi(argv[i + 2]), m = (uint32_t)atoi(argv[i + 3]); i += 3; + char msg[400]; double worst = 0; size_t bad = 0; double t0 = now_ms(); + const uint64_t a0 = g_att_issues; + int err = sim_point(a, b, m, 64, 1.0f, 77, 1, 0, 0, msg, sizeof msg, &worst, &bad); + CHECK(err == 0 && bad == 0, "sim point %u+%u (max_pos %u) variant %d: %s", b, m, a, g_variant, msg); + printf("sim point %u tokens from %u (max_pos %u) variant %d: %s %s; attend %" PRIu64 " warp issues (%.1f s)\n", m, b, a, g_variant, + err ? "ERROR" : bad ? "MISMATCH" : "ok", msg, g_att_issues - a0, (now_ms() - t0) / 1e3); + host = 1; } + else if (!strcmp(argv[i], "--quick")) quick = 1; + else if (!strcmp(argv[i], "--timing-only")) timing_only = 1; + else if (!strcmp(argv[i], "--long")) longp = 1; + else if (!strcmp(argv[i], "--reps") && i + 1 < argc) reps = atoi(argv[++i]); + else if (!strcmp(argv[i], "--max-pos") && i + 1 < argc) maxp = (uint32_t)atoi(argv[++i]); + else if (!strcmp(argv[i], "--out") && i + 1 < argc) json = argv[++i]; + else { fprintf(stderr, "usage: %s [--variant 1|2] [--host-only | --sim | --sim-point MAX_POS POS0 M | [--quick] [--timing-only] [--long] [--reps N] [--max-pos 32768|131072] [--out receipt.json]]\n", argv[0]); return 2; } + } + if (reps < 1) reps = 1; + host_only(); /* leaves the API on g_variant */ + if (sim) { const int keep = g_variant; sim_battery(1); sim_battery(2); g_variant = keep; } + if (!host && !sim) { + printf("chip: attend kernel variant %d\n", g_variant); + if (json) { g_json = test_out_open(json); if (g_json) fprintf(g_json, "{\"test\": \"gpu_prefill_fattn256\", \"shape\": \"q36 16/2\", \"variant\": %d, \"xstride\": %u, \"rotary_dim\": 64, \"points\": [\n", g_variant, XS); } + if (!timing_only) { + chip_point(256, 0, 1, 1.0f, 1, 1, 0, OW); + chip_point(256, 0, 37, 1.0f, 2, 1, 0, OW + 16u); + chip_point(512, 100, 19, 1.0f, 3, 1, 0, OW); + chip_point(512, 37, 141, 4.0f, 4, 1, 0, OW); + chip_mutants(); + } + if (!quick) { + chip_point(4096, 0, 2048, 1.0f, 8, !timing_only, reps, OW); + chip_point(8192, 6144, 2048, 1.0f, 9, !timing_only, reps, OW); + chip_point(32768, 30720, 2048, 1.0f, 10, !timing_only, reps, OW); + if (maxp >= 131072) chip_point(131072, 129024, 2048, 1.0f, 11, !timing_only, reps, OW); + } + if (longp) { /* G3 (DRA-85): 8192-token chunks ending at 8k and 32k */ + chip_point(8192, 0, 8192, 1.0f, 12, 0, reps, OW); + chip_point(32768, 24576, 8192, 1.0f, 13, 0, reps, OW); + } + if (g_json) { fprintf(g_json, "\n], \"checks\": %d, \"failed\": %d}\n", g_checks, g_failed); fclose(g_json); } + } + printf("gpu_prefill_fattn256_test: %d checks, %d failed: %s\n", g_checks, g_failed, g_failed ? "FAIL" : "PASS"); + return g_failed ? 1 : 0; +} diff --git a/tests/gpu_qgemm_test.c b/tests/gpu_qgemm_test.c index daf0e9dc..3e47d327 100644 --- a/tests/gpu_qgemm_test.c +++ b/tests/gpu_qgemm_test.c @@ -72,7 +72,7 @@ static int pq_host(void) { } static int pq_sim_one(uint32_t k, uint32_t in_type, uint32_t groups, uint32_t rows, int mutant, size_t *bad_out, char *msg, size_t msgn) { - OmegaPqSpec sp = { k, in_type, mutant, groups }; + OmegaPqSpec sp = { k, in_type, mutant, groups, 0 }; static BlackwellIRProgram prog; if (omega_blackwell_codegen_pq_prog(&sp, &prog) != 0) { snprintf(msg, msgn, "codegen refused"); return -1; } float *x = malloc((size_t)rows * k * 4); uint16_t *xb = malloc((size_t)rows * k * 2); @@ -339,7 +339,7 @@ static int qg_sim(void) { for (size_t c = 0; c < sizeof cs / sizeof cs[0]; c++) { const uint32_t bm = 16 * cs[c].rt; QProb p; qprob_make(&p, cs[c].E, cs[c].n, cs[c].k, cs[c].M, cs[c].xr, cs[c].layout, cs[c].direct, bm); - OmegaQgSpec sp = { cs[c].k, cs[c].rt, cs[c].warps, cs[c].layout == OMEGA_GPU_PF_PLAIN ? OMEGA_QG_EPI_F32 : OMEGA_QG_EPI_SWIGLU, cs[c].direct, cs[c].n, 45, 0 }; + OmegaQgSpec sp = { cs[c].k, cs[c].rt, cs[c].warps, cs[c].layout == OMEGA_GPU_PF_PLAIN ? OMEGA_QG_EPI_F32 : OMEGA_QG_EPI_SWIGLU, cs[c].direct, cs[c].n, 45, 0, 0, 0 }; uint32_t *rows = malloc(p.M * 4); for (uint32_t i = 0; i < p.M; i++) rows[i] = i; void *y = malloc((size_t)(p.M + bm) * p.n * 4); for (int order = 0; order < 2; order++) { diff --git a/tests/pfq_legacy_words.h b/tests/pfq_legacy_words.h new file mode 100644 index 00000000..700b6122 --- /dev/null +++ b/tests/pfq_legacy_words.h @@ -0,0 +1,58 @@ +/* SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception */ +/* pfq_legacy_words.h: digest of the encoded words of every qg / pq spec that existed before DRA-82 (the new spec fields + * pq.stride, qg.ymap, qg.x64 left 0). tests/gpu_pfq_test.c compares it with PFQ_LEGACY_DIGEST, the value this same code + * printed when built against CUDApp main 4bbccf0 (evidence/DRA-82-pfq/). Uses only the pre-DRA-82 fields. */ +#ifndef PFQ_LEGACY_WORDS_H +#define PFQ_LEGACY_WORDS_H +#include +#include +#include +#include "omega_blackwell_codegen.h" +#include "omega_blackwell_codegen_qg.h" +#include "omega_blackwell_codegen_tc.h" +#include "omega_blackwell_codegen_qmma.h" + +/* FNV-1a 64 over (program index, code length, code bytes) of every accepted spec, encoded and patched as + * omega_gpu_pf_kernel_locked does. Returns the number of programs, or -1 when one failed to encode. */ +static uint64_t pfq_fnv(uint64_t h, const void *p, size_t n) { + const uint8_t *b = p; for (size_t i = 0; i < n; i++) { h ^= b[i]; h *= 0x100000001b3ull; } return h; +} +static int pfq_encode_hash(BlackwellIRProgram *prog, uint8_t *code, size_t cap, uint64_t *h, uint32_t idx) { + size_t need = omega_bw_program_code_bytes(prog); + OmegaBlackwellKernel kern; + if (need == 0 || need > cap || omega_blackwell_kernel_encode_into(prog, code, need, &kern) != 0) return -1; + if (omega_tc_patch_code(prog, code, need) < 0 || omega_qmma_patch_code(prog, code, need) < 0) return -1; + uint64_t len = need; + *h = pfq_fnv(*h, &idx, sizeof idx); *h = pfq_fnv(*h, &len, sizeof len); *h = pfq_fnv(*h, code, need); + return 0; +} +static int pfq_legacy_digest(uint64_t *out) { + *out = 0; + BlackwellIRProgram *prog = calloc(1, sizeof *prog); + size_t cap = 1u << 20; uint8_t *code = malloc(cap); + uint64_t h = 0xcbf29ce484222325ull; uint32_t idx = 0; int bad = 0; + if (!prog || !code) { free(prog); free(code); return -1; } + static const uint32_t ks[] = { 128, 512, 2048, 4096 }; + for (unsigned a = 0; a < 4; a++) for (uint32_t w = 8; w <= 16; w *= 2) for (uint32_t epi = 0; epi <= 1; epi++) + for (uint32_t dir = 0; dir <= 1; dir++) for (uint32_t wt = 0; wt <= 45; wt += 45) for (int m = 0; m <= 4; m++) { + OmegaQgSpec s; memset(&s, 0, sizeof s); + s.k = ks[a]; s.rt = 4; s.warps = w; s.epi = epi; s.direct = dir; s.n = epi ? 1024u : 512u; s.wait = wt; s.mutant = m; + if (!omega_qg_spec_ok(&s)) continue; + memset(prog, 0, sizeof *prog); + if (omega_blackwell_codegen_qgemm_prog(&s, prog) != 0 || pfq_encode_hash(prog, code, cap, &h, idx) != 0) bad = 1; + idx++; + } + static const uint32_t pk[] = { 128, 512, 2048, 4096, 8192 }; + for (unsigned a = 0; a < 5; a++) for (uint32_t it = 0; it <= 1; it++) for (int m = 0; m <= 3; m++) for (uint32_t gr = 0; gr <= 2; gr++) { + OmegaPqSpec s; memset(&s, 0, sizeof s); + s.k = pk[a]; s.in_type = it; s.mutant = m; s.groups = gr; + if (!omega_pq_spec_ok(&s) || (gr == 0 && pk[a] > 4096u)) continue; + memset(prog, 0, sizeof *prog); + if (omega_blackwell_codegen_pq_prog(&s, prog) != 0 || pfq_encode_hash(prog, code, cap, &h, idx) != 0) bad = 1; + idx++; + } + free(prog); free(code); + *out = h; + return bad ? -1 : (int)idx; +} +#endif ```