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/omega-mv/patches/aaf6c2d5189ff2cb # omega-mv Omega: a language for verified programs, semantic identity and machine realization. Seed-born work and existing implementations have distinct provenance. Brought by drakestapleton Sign in to star 1 stars 0 watching About Files History Releases Proposed changes Issues For developers ## GitHub aien-dev/omega-mv#256 (code only) closed derived `aaf6c2d5189ff2cb` #256 Imported from GitHub aien-dev/omega-mv#256 (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 `8da7f77194a3fae0c3dd561a76d1fe0e23971867` · Head `4345406bf09a51a3f2de92b61407fb8d3ef90092` ### Apply it ``` git checkout -b patch-aaf6c2d5189ff2cb 8da7f77194a3fae0c3dd561a76d1fe0e23971867 curl -fsSL https://interplane.io/drakestapleton/omega-mv/patches/aaf6c2d5189ff2cb.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/omega-mv 256 4345406bf09a51a3f2de92b61407fb8d3ef90092 ``` ``` {"kind":"github-import","owner":"aien-dev","repo":"omega-mv","number":256,"url":"https://github.com/aien-dev/omega-mv/pull/256","export_sha256":"967c79e26a893657b5cdaa45efd442be5dbd2ecfe68e25f9a8c1b5da4d60d452","imported_utc":"2026-11-18T16:37:00Z","metadata":"unavailable","state_derived":true} ``` ### Changes ``` diff --git a/src/omega_blackwell_codegen.c b/src/omega_blackwell_codegen.c index 258023826..070a1181a 100644 --- a/src/omega_blackwell_codegen.c +++ b/src/omega_blackwell_codegen.c @@ -1204,6 +1204,209 @@ int omega_blackwell_codegen_matmul_tensor(const OmegaMatMulSpec *spec, OmegaBlac return 0; } +/* ---- FB-1 cut 1b: looped tensor matmul ------------------------------------------ + * + * Control words (bundle bits 105..125, decoded from the chip-proven kernel and from + * the vendor compiler's SASS for an equivalent HMMA loop on this chip, 2026-10-04): + * stall = bits 9..12 of w[3], yield = 13, write barrier = 14..16, read barrier = + * 17..19, wait mask = 20..25. 7 in a barrier field means "none". + * LDG (A) 0x001ea800 stall 4, yield, sets SB2 + * LDG.U16 (B) 0x002ea800 stall 4, yield, sets SB2 + * pack IMAD 0x004fca00 stall 5, waits SB2 (every outstanding load has landed) + * HMMA 0x002fca00 stall 5 (fixed latency: the vendor compiler sets no + * write barrier on HMMA either; consumers wait by stall count) + * STG 0x0007e200 stall 1, yield, read barrier SB3 (the store may read its + * data/address registers late; the next writer waits SB3) + * wait SB3 mask bit 23 (0x00800000) on the first instruction that overwrites a + * register a store reads: the C pointer advance. + * Loop-carried registers are kept live to the end of their loop (keep_alive) because + * the allocator is a straight-line linear scan and knows nothing about back edges. + */ +static void bw_keep_alive(BlackwellIRProgram *prog, int from_idx, int to_idx, int last_idx) { + /* every vreg first defined in [from_idx, to_idx) stays live until last_idx */ + for (int v = 0; v < prog->regalloc.num_vregs; v++) { + OmegaLiveInterval *iv = &prog->regalloc.intervals[v]; + if (iv->first_def >= from_idx && iv->first_def < to_idx && iv->last_use < last_idx) + iv->last_use = last_idx; + } +} + +#define BW_APPEND(prog, ...) do { BlackwellIRInsn _i = { __VA_ARGS__ }; if (omega_bw_ir_append((prog), &_i) < 0) return -1; } while (0) + +int omega_blackwell_codegen_matmul_tensor_loop_prog(const OmegaMatMulSpec *spec, uint32_t grid_x, + int mutant, BlackwellIRProgram *prog) { + if (!spec || !prog) return -1; + if (spec->m == 0 || spec->k == 0 || spec->n == 0) return -1; + if (spec->precision != OMEGA_MATMUL_PRECISION_FP16 && spec->precision != OMEGA_MATMUL_PRECISION_BF16) return -1; + if (spec->m % 16 != 0 || spec->n % 8 != 0 || spec->k % 16 != 0) { + fprintf(stderr, "ERROR: looped MatMul tensor codegen requires M%%16, N%%8, K%%16 (got %ux%ux%u)\n", + spec->m, spec->k, spec->n); + return -1; + } + const uint32_t K = spec->k, N = spec->n, NT = N / 8, KSTEPS = K / 16; + if (grid_x == 0 || grid_x > NT) return -1; + /* every immediate below must fit 32 bits: 32 * N (B row-block stride in bytes) is the largest */ + if ((uint64_t)N * 32u > 0xffffffffull || (uint64_t)grid_x * 32u > 0xffffffffull) return -1; + if (mutant && KSTEPS < 2) return -1; + + omega_bw_ir_init(prog); + + int v_ptr_a = omega_bw_ir_alloc_vreg64(prog), v_ptr_b = omega_bw_ir_alloc_vreg64(prog), v_ptr_c = omega_bw_ir_alloc_vreg64(prog); + int uv_desc = omega_bw_ir_alloc_uvreg64(prog); + int v_tid = omega_bw_ir_alloc_vreg(prog), v_ctaid_x = omega_bw_ir_alloc_vreg(prog), v_ctaid_y = omega_bw_ir_alloc_vreg(prog); + int v_group = omega_bw_ir_alloc_vreg(prog), v_tig = omega_bw_ir_alloc_vreg(prog), v_tcol2 = omega_bw_ir_alloc_vreg(prog); + int v_r0 = omega_bw_ir_alloc_vreg(prog), v_r1 = omega_bw_ir_alloc_vreg(prog), v_c1 = omega_bw_ir_alloc_vreg(prog); + int v_idx = omega_bw_ir_alloc_vreg(prog), v_col = omega_bw_ir_alloc_vreg(prog), v_cnt = omega_bw_ir_alloc_vreg(prog); + int v_pa0 = omega_bw_ir_alloc_vreg64(prog), v_pa1 = omega_bw_ir_alloc_vreg64(prog), v_pbcol = omega_bw_ir_alloc_vreg64(prog); + int v_pc0 = omega_bw_ir_alloc_vreg64(prog), v_pc1 = omega_bw_ir_alloc_vreg64(prog); + int v_pa0c = omega_bw_ir_alloc_vreg64(prog), v_pa1c = omega_bw_ir_alloc_vreg64(prog), v_pbc = omega_bw_ir_alloc_vreg64(prog); + int v_ta2 = omega_bw_ir_alloc_vreg64(prog), v_ta3 = omega_bw_ir_alloc_vreg64(prog); + int v_tb1 = omega_bw_ir_alloc_vreg64(prog), v_tb2 = omega_bw_ir_alloc_vreg64(prog), v_tb3 = omega_bw_ir_alloc_vreg64(prog); + int v_tc1 = omega_bw_ir_alloc_vreg64(prog), v_tc3 = omega_bw_ir_alloc_vreg64(prog); + int v_ra = omega_bw_ir_alloc_vreg128(prog), v_rb = omega_bw_ir_alloc_vreg64(prog), v_rd = omega_bw_ir_alloc_vreg128(prog); + int v_b0 = omega_bw_ir_alloc_vreg(prog), v_b1 = omega_bw_ir_alloc_vreg(prog); + if (v_b1 < 0 || uv_desc < 0) return -1; + + const uint32_t CTRL_LDA = 0x001ea800u, CTRL_LDB = 0x002ea800u, CTRL_PACK = 0x004fca00u; + const uint32_t CTRL_HMMA = 0x002fca00u, CTRL_STG_RDBAR3 = 0x0007e200u, CTRL_IMADW_WAIT3 = 0x009fcc00u; + const uint32_t CTRL_MOVRZ_WAIT3 = 0x008fe200u; + + /* prologue: descriptor, pointers, ids */ + BW_APPEND(prog, .op = BW_IR_LDCU64, .dst_vreg = uv_desc, .imm = 0x358, .is_uniform = true); + BW_APPEND(prog, .op = BW_IR_LDC64, .dst_vreg = v_ptr_a, .imm = 0x380); + BW_APPEND(prog, .op = BW_IR_LDC64, .dst_vreg = v_ptr_b, .imm = 0x388); + BW_APPEND(prog, .op = BW_IR_LDC64, .dst_vreg = v_ptr_c, .imm = 0x390); + BW_APPEND(prog, .op = BW_IR_S2R, .dst_vreg = v_tid, .imm = BW_SR_TID_X); + BW_APPEND(prog, .op = BW_IR_S2R, .dst_vreg = v_ctaid_x, .imm = BW_SR_CTAID_X); + BW_APPEND(prog, .op = BW_IR_S2R, .dst_vreg = v_ctaid_y, .imm = BW_SR_CTAID_Y); + BW_APPEND(prog, .op = BW_IR_MOV_IMM, .dst_vreg = v_c1, .imm = 1); + BW_APPEND(prog, .op = BW_IR_SHF_R, .dst_vreg = v_group, .src1_vreg = v_tid, .imm = 2); + BW_APPEND(prog, .op = BW_IR_LOP3_AND, .dst_vreg = v_tig, .src1_vreg = v_tid, .imm = 3); + BW_APPEND(prog, .op = BW_IR_IMAD, .dst_vreg = v_tcol2, .src1_vreg = v_tig, .src2_vreg = -1, .imm = 2, .src3_vreg = -1); + BW_APPEND(prog, .op = BW_IR_IMAD, .dst_vreg = v_r0, .src1_vreg = v_ctaid_y, .src2_vreg = -1, .imm = 16, .src3_vreg = v_group); + BW_APPEND(prog, .op = BW_IR_IMAD, .dst_vreg = v_r1, .src1_vreg = v_c1, .src2_vreg = -1, .imm = 8, .src3_vreg = v_r0); + /* pa0 = A + (r0*K + tcol2)*2 ; pa1 likewise with r1 (A row-major, K bf16 per row) */ + BW_APPEND(prog, .op = BW_IR_IMAD, .dst_vreg = v_idx, .src1_vreg = v_r0, .src2_vreg = -1, .imm = K, .src3_vreg = v_tcol2); + BW_APPEND(prog, .op = BW_IR_IMAD_WIDE, .dst_vreg = v_pa0, .src1_vreg = v_idx, .src2_vreg = -1, .imm = 2, .src3_vreg = v_ptr_a); + BW_APPEND(prog, .op = BW_IR_IMAD, .dst_vreg = v_idx, .src1_vreg = v_r1, .src2_vreg = -1, .imm = K, .src3_vreg = v_tcol2); + BW_APPEND(prog, .op = BW_IR_IMAD_WIDE, .dst_vreg = v_pa1, .src1_vreg = v_idx, .src2_vreg = -1, .imm = 2, .src3_vreg = v_ptr_a); + /* col = ctaid_x (first column tile of this CTA) */ + BW_APPEND(prog, .op = BW_IR_IMAD, .dst_vreg = v_col, .src1_vreg = v_ctaid_x, .src2_vreg = -1, .imm = 1, .src3_vreg = -1); + /* pbcol = B + (tcol2*N + col*8 + group)*2 */ + BW_APPEND(prog, .op = BW_IR_IMAD, .dst_vreg = v_idx, .src1_vreg = v_tcol2, .src2_vreg = -1, .imm = N, .src3_vreg = v_group); + BW_APPEND(prog, .op = BW_IR_IMAD, .dst_vreg = v_idx, .src1_vreg = v_col, .src2_vreg = -1, .imm = 8, .src3_vreg = v_idx); + BW_APPEND(prog, .op = BW_IR_IMAD_WIDE, .dst_vreg = v_pbcol, .src1_vreg = v_idx, .src2_vreg = -1, .imm = 2, .src3_vreg = v_ptr_b); + /* pc0 = C + (r0*N + col*8 + tcol2)*4 ; pc1 with r1 */ + BW_APPEND(prog, .op = BW_IR_IMAD, .dst_vreg = v_idx, .src1_vreg = v_r0, .src2_vreg = -1, .imm = N, .src3_vreg = v_tcol2); + BW_APPEND(prog, .op = BW_IR_IMAD, .dst_vreg = v_idx, .src1_vreg = v_col, .src2_vreg = -1, .imm = 8, .src3_vreg = v_idx); + BW_APPEND(prog, .op = BW_IR_IMAD_WIDE, .dst_vreg = v_pc0, .src1_vreg = v_idx, .src2_vreg = -1, .imm = 4, .src3_vreg = v_ptr_c); + BW_APPEND(prog, .op = BW_IR_IMAD, .dst_vreg = v_idx, .src1_vreg = v_r1, .src2_vreg = -1, .imm = N, .src3_vreg = v_tcol2); + BW_APPEND(prog, .op = BW_IR_IMAD, .dst_vreg = v_idx, .src1_vreg = v_col, .src2_vreg = -1, .imm = 8, .src3_vreg = v_idx); + BW_APPEND(prog, .op = BW_IR_IMAD_WIDE, .dst_vreg = v_pc1, .src1_vreg = v_idx, .src2_vreg = -1, .imm = 4, .src3_vreg = v_ptr_c); + + /* ---- column-tile loop ---- */ + const int L_col = (int)prog->count; + /* accumulator = 0 (the first write waits SB3: the previous tile's stores may still read it) */ + BW_APPEND(prog, .op = BW_IR_MOV_RZ, .dst_vreg = v_rd, .dst_subreg = 0, .control = CTRL_MOVRZ_WAIT3); + BW_APPEND(prog, .op = BW_IR_MOV_RZ, .dst_vreg = v_rd, .dst_subreg = 1); + BW_APPEND(prog, .op = BW_IR_MOV_RZ, .dst_vreg = v_rd, .dst_subreg = 2); + BW_APPEND(prog, .op = BW_IR_MOV_RZ, .dst_vreg = v_rd, .dst_subreg = 3); + /* K cursors start at the row/column bases (IMAD.WIDE with imm 0 is a 64-bit copy) */ + BW_APPEND(prog, .op = BW_IR_IMAD_WIDE, .dst_vreg = v_pa0c, .src1_vreg = v_c1, .src2_vreg = -1, .imm = 0, .src3_vreg = v_pa0); + BW_APPEND(prog, .op = BW_IR_IMAD_WIDE, .dst_vreg = v_pa1c, .src1_vreg = v_c1, .src2_vreg = -1, .imm = 0, .src3_vreg = v_pa1); + BW_APPEND(prog, .op = BW_IR_IMAD_WIDE, .dst_vreg = v_pbc, .src1_vreg = v_c1, .src2_vreg = -1, .imm = 0, .src3_vreg = v_pbcol); + BW_APPEND(prog, .op = BW_IR_MOV_IMM, .dst_vreg = v_cnt, .imm = mutant ? KSTEPS - 1 : KSTEPS); + + /* ---- K loop: one 16x16 A fragment and one 16x8 B fragment per step ---- */ + const int L_k = (int)prog->count; + BW_APPEND(prog, .op = BW_IR_IMAD_WIDE, .dst_vreg = v_ta2, .src1_vreg = v_c1, .src2_vreg = -1, .imm = 16, .src3_vreg = v_pa0c); + BW_APPEND(prog, .op = BW_IR_IMAD_WIDE, .dst_vreg = v_ta3, .src1_vreg = v_c1, .src2_vreg = -1, .imm = 16, .src3_vreg = v_pa1c); + BW_APPEND(prog, .op = BW_IR_IMAD_WIDE, .dst_vreg = v_tb1, .src1_vreg = v_c1, .src2_vreg = -1, .imm = 2u * N, .src3_vreg = v_pbc); + BW_APPEND(prog, .op = BW_IR_IMAD_WIDE, .dst_vreg = v_tb2, .src1_vreg = v_c1, .src2_vreg = -1, .imm = 16u * N, .src3_vreg = v_pbc); + BW_APPEND(prog, .op = BW_IR_IMAD_WIDE, .dst_vreg = v_tb3, .src1_vreg = v_c1, .src2_vreg = -1, .imm = 18u * N, .src3_vreg = v_pbc); + /* A: a0,a1 at (r0, kk+tcol2) ; a2,a3 at (r1, ...) ; a4,a5 at (r0, +8) ; a6,a7 at (r1, +8) */ + BW_APPEND(prog, .op = BW_IR_LDG_E, .dst_vreg = v_ra, .dst_subreg = 0, .src1_vreg = v_pa0c, .src2_vreg = -1, .src3_vreg = -1, .ureg = uv_desc, .control = CTRL_LDA); + BW_APPEND(prog, .op = BW_IR_LDG_E, .dst_vreg = v_ra, .dst_subreg = 1, .src1_vreg = v_pa1c, .src2_vreg = -1, .src3_vreg = -1, .ureg = uv_desc, .control = CTRL_LDA); + BW_APPEND(prog, .op = BW_IR_LDG_E, .dst_vreg = v_ra, .dst_subreg = 2, .src1_vreg = v_ta2, .src2_vreg = -1, .src3_vreg = -1, .ureg = uv_desc, .control = CTRL_LDA); + BW_APPEND(prog, .op = BW_IR_LDG_E, .dst_vreg = v_ra, .dst_subreg = 3, .src1_vreg = v_ta3, .src2_vreg = -1, .src3_vreg = -1, .ureg = uv_desc, .control = CTRL_LDA); + /* B: rows kk+tcol2, +1, +8, +9 at column col*8+group */ + BW_APPEND(prog, .op = BW_IR_LDG_E_U16, .dst_vreg = v_b0, .src1_vreg = v_pbc, .src2_vreg = -1, .src3_vreg = -1, .ureg = uv_desc, .control = CTRL_LDB); + BW_APPEND(prog, .op = BW_IR_LDG_E_U16, .dst_vreg = v_b1, .src1_vreg = v_tb1, .src2_vreg = -1, .src3_vreg = -1, .ureg = uv_desc, .control = CTRL_LDB); + BW_APPEND(prog, .op = BW_IR_IMAD, .dst_vreg = v_rb, .dst_subreg = 0, .src1_vreg = v_b1, .src2_vreg = -1, .imm = 0x10000, .src3_vreg = v_b0, .control = CTRL_PACK); + BW_APPEND(prog, .op = BW_IR_LDG_E_U16, .dst_vreg = v_b0, .src1_vreg = v_tb2, .src2_vreg = -1, .src3_vreg = -1, .ureg = uv_desc, .control = CTRL_LDB); + BW_APPEND(prog, .op = BW_IR_LDG_E_U16, .dst_vreg = v_b1, .src1_vreg = v_tb3, .src2_vreg = -1, .src3_vreg = -1, .ureg = uv_desc, .control = CTRL_LDB); + BW_APPEND(prog, .op = BW_IR_IMAD, .dst_vreg = v_rb, .dst_subreg = 1, .src1_vreg = v_b1, .src2_vreg = -1, .imm = 0x10000, .src3_vreg = v_b0, .control = CTRL_PACK); + /* rd += ra * rb (accumulate in place) */ + BW_APPEND(prog, .op = (spec->precision == OMEGA_MATMUL_PRECISION_BF16) ? BW_IR_HMMA_BF16 : BW_IR_HMMA_F16, + .dst_vreg = v_rd, .dst_subreg = 0, .src1_vreg = v_ra, .src1_subreg = 0, .src2_vreg = v_rb, .src2_subreg = 0, + .src3_vreg = v_rd, .src3_subreg = 0, .control = CTRL_HMMA); + /* advance K: A by 16 bf16 (32 bytes), B by 16 rows (32 N bytes); every load above has landed (packs waited SB2) */ + BW_APPEND(prog, .op = BW_IR_IMAD_WIDE, .dst_vreg = v_pa0c, .src1_vreg = v_c1, .src2_vreg = -1, .imm = 32, .src3_vreg = v_pa0c); + BW_APPEND(prog, .op = BW_IR_IMAD_WIDE, .dst_vreg = v_pa1c, .src1_vreg = v_c1, .src2_vreg = -1, .imm = 32, .src3_vreg = v_pa1c); + BW_APPEND(prog, .op = BW_IR_IMAD_WIDE, .dst_vreg = v_pbc, .src1_vreg = v_c1, .src2_vreg = -1, .imm = 32u * N, .src3_vreg = v_pbc); + BW_APPEND(prog, .op = BW_IR_IMAD, .dst_vreg = v_cnt, .src1_vreg = v_c1, .src2_vreg = -1, .imm = 0xffffffffu, .src3_vreg = v_cnt); + BW_APPEND(prog, .op = BW_IR_ISETP_GE, .dst_vreg = -1, .src1_vreg = v_cnt, .src2_vreg = -1, .imm = 1, .src3_vreg = -1); + { + int here = (int)prog->count; + BW_APPEND(prog, .op = BW_IR_BRA, .imm = (uint32_t)(int32_t)(L_k - here), .predicate_p0 = true); + } + const int L_k_end = (int)prog->count - 1; + + /* ---- store the 16x8 tile: d0 (r0, c), d1 (r0, c+1), d2 (r1, c), d3 (r1, c+1) ---- */ + BW_APPEND(prog, .op = BW_IR_IMAD_WIDE, .dst_vreg = v_tc1, .src1_vreg = v_c1, .src2_vreg = -1, .imm = 4, .src3_vreg = v_pc0); + BW_APPEND(prog, .op = BW_IR_IMAD_WIDE, .dst_vreg = v_tc3, .src1_vreg = v_c1, .src2_vreg = -1, .imm = 4, .src3_vreg = v_pc1); + BW_APPEND(prog, .op = BW_IR_STG_E, .src1_vreg = v_pc0, .src2_vreg = v_rd, .src2_subreg = 0, .src3_vreg = -1, .ureg = uv_desc, .control = CTRL_STG_RDBAR3); + BW_APPEND(prog, .op = BW_IR_STG_E, .src1_vreg = v_tc1, .src2_vreg = v_rd, .src2_subreg = 1, .src3_vreg = -1, .ureg = uv_desc, .control = CTRL_STG_RDBAR3); + BW_APPEND(prog, .op = BW_IR_STG_E, .src1_vreg = v_pc1, .src2_vreg = v_rd, .src2_subreg = 2, .src3_vreg = -1, .ureg = uv_desc, .control = CTRL_STG_RDBAR3); + BW_APPEND(prog, .op = BW_IR_STG_E, .src1_vreg = v_tc3, .src2_vreg = v_rd, .src2_subreg = 3, .src3_vreg = -1, .ureg = uv_desc, .control = CTRL_STG_RDBAR3); + /* next column tile of this CTA: col += grid_x ; B by grid_x*8 bf16 ; C by grid_x*8 f32 (waits SB3 first) */ + BW_APPEND(prog, .op = BW_IR_IMAD, .dst_vreg = v_col, .src1_vreg = v_c1, .src2_vreg = -1, .imm = grid_x, .src3_vreg = v_col); + BW_APPEND(prog, .op = BW_IR_IMAD_WIDE, .dst_vreg = v_pc0, .src1_vreg = v_c1, .src2_vreg = -1, .imm = grid_x * 32u, .src3_vreg = v_pc0, .control = CTRL_IMADW_WAIT3); + BW_APPEND(prog, .op = BW_IR_IMAD_WIDE, .dst_vreg = v_pc1, .src1_vreg = v_c1, .src2_vreg = -1, .imm = grid_x * 32u, .src3_vreg = v_pc1); + BW_APPEND(prog, .op = BW_IR_IMAD_WIDE, .dst_vreg = v_pbcol, .src1_vreg = v_c1, .src2_vreg = -1, .imm = grid_x * 16u, .src3_vreg = v_pbcol); + BW_APPEND(prog, .op = BW_IR_ISETP_GE, .dst_vreg = -1, .src1_vreg = v_col, .src2_vreg = -1, .imm = NT, .src3_vreg = -1); + { + int here = (int)prog->count; + BW_APPEND(prog, .op = BW_IR_BRA, .imm = (uint32_t)(int32_t)(L_col - here), .predicate_p0 = true, .predicate_not = true); + } + const int L_col_end = (int)prog->count - 1; + BW_APPEND(prog, .op = BW_IR_EXIT); + BW_APPEND(prog, .op = BW_IR_BRA); + + /* loop-carried values live to the end of their loop */ + bw_keep_alive(prog, 0, L_col, L_col_end); + bw_keep_alive(prog, L_col, L_k, L_k_end); + /* K-loop temporaries too: a load's address pair must never be recycled by a + * later instruction of the same iteration (the load may read it late). */ + bw_keep_alive(prog, L_k, L_k_end, L_k_end); + /* the accumulator is read by the stores after the K loop */ + if (prog->regalloc.intervals[v_rd].last_use < L_col_end) prog->regalloc.intervals[v_rd].last_use = L_col_end; + + return omega_bw_regalloc_solve(prog); +} + +int omega_blackwell_codegen_matmul_tensor_loop(const OmegaMatMulSpec *spec, uint32_t grid_x, + int mutant, OmegaBlackwellKernel *kernel) { + if (!spec || !kernel) return -1; + BlackwellIRProgram prog; + if (omega_blackwell_codegen_matmul_tensor_loop_prog(spec, grid_x, mutant, &prog) != 0) return -1; + size_t max_bytes = 4096; + kernel->code = malloc(max_bytes); + if (!kernel->code) return -1; + size_t emitted_size = 0; + if (omega_bw_encode_program(&prog, kernel->code, max_bytes, &emitted_size) != 0) { + free(kernel->code); + kernel->code = NULL; + return -1; + } + kernel->code_size = emitted_size; + kernel->insn_count = emitted_size / 16; + kernel->gpr_count = prog.regalloc.peak_gpr_usage; + kernel->uniform_gpr_count = prog.regalloc.peak_ugpr_usage; + sha256_hash(kernel->code, kernel->code_size, kernel->code_digest); + return 0; +} + int omega_blackwell_verify_codegen_fixtures(void) { OmegaRegAlloc ra; memset(&ra, 0, sizeof(ra)); diff --git a/src/omega_blackwell_codegen.h b/src/omega_blackwell_codegen.h index 63f6d356d..69500b48b 100644 --- a/src/omega_blackwell_codegen.h +++ b/src/omega_blackwell_codegen.h @@ -161,6 +161,21 @@ int omega_blackwell_codegen_matmul_i32(const OmegaMatMulSpec *spec, OmegaBlackwe int omega_blackwell_codegen_matmul_tensor_prog(const OmegaMatMulSpec *spec, BlackwellIRProgram *prog); int omega_blackwell_codegen_matmul_tensor(const OmegaMatMulSpec *spec, OmegaBlackwellKernel *kernel); +/* FB-1 cut 1b: looped Tensor Core matmul. One warp per CTA. CTA (x, y) owns row + * tile y (16 rows) and column tiles x, x + grid_x, x + 2 grid_x, ... (8 columns + * each); the whole K dimension is accumulated in the HMMA accumulator on the + * chip (no host K slicing). Requires M % 16 == 0, N % 8 == 0, K % 16 == 0 and + * 1 <= grid_x <= N / 8. The kernel does not depend on M (rows come from + * CTAID.Y), so one kernel serves every row count of a (K, N, grid_x) triple. + * Uses only instructions already present in the chip-proven single-tile kernel + * plus the predicated backward BRA and ISETP.GE this IR already encodes. + * mutant != 0 drops the last K step (test oracle: the wrong kernel must be + * caught by the parity test; never set in production). */ +int omega_blackwell_codegen_matmul_tensor_loop_prog(const OmegaMatMulSpec *spec, uint32_t grid_x, + int mutant, BlackwellIRProgram *prog); +int omega_blackwell_codegen_matmul_tensor_loop(const OmegaMatMulSpec *spec, uint32_t grid_x, + int mutant, OmegaBlackwellKernel *kernel); + /* Unit test for instruction encoding bitfield fixtures (Gate 3) */ int omega_blackwell_verify_codegen_fixtures(void); diff --git a/src/omega_blackwell_matmul.h b/src/omega_blackwell_matmul.h index e089a49a7..9100b3c2a 100644 --- a/src/omega_blackwell_matmul.h +++ b/src/omega_blackwell_matmul.h @@ -5,9 +5,9 @@ #include #include -#define OMEGA_BW_MATMUL_MAX_M 1024 -#define OMEGA_BW_MATMUL_MAX_K 1024 -#define OMEGA_BW_MATMUL_MAX_N 1024 +#define OMEGA_BW_MATMUL_MAX_M 8192 +#define OMEGA_BW_MATMUL_MAX_K 16384 +#define OMEGA_BW_MATMUL_MAX_N 262144 /* Precision modes for Milestone 18 tensor matrix multiplication */ typedef enum { diff --git a/src/omega_blackwell_submit.c b/src/omega_blackwell_submit.c index babdda506..097195615 100644 --- a/src/omega_blackwell_submit.c +++ b/src/omega_blackwell_submit.c @@ -13,7 +13,6 @@ /* Second completion marker payload for the C3 tail (marker page + 0x10), the same value as * src/omega_blackwell_engine.c BE_MARKER2_PAYLOAD and src/omega_numeric_divsqrt_gb10.c:1152. */ -#define OMEGA_BW_MARKER2_PAYLOAD 0x46464646u static const uint32_t SETUP_WORDS[18] = { 0x20012061, 0x0000cec0, 0x20012092, 0x00000001, 0x200120a8, 0x0000000f, 0x2001255d, 0x00000003, diff --git a/src/omega_blackwell_submit.h b/src/omega_blackwell_submit.h index eba680fde..a4357c5d0 100644 --- a/src/omega_blackwell_submit.h +++ b/src/omega_blackwell_submit.h @@ -10,6 +10,7 @@ #include #define OMEGA_BW_MARKER_COMPLETION_PAYLOAD 0x44444444U +#define OMEGA_BW_MARKER2_PAYLOAD 0x46464646u /* C3 second release, after the L2 flush */ #define OMEGA_BW_SEMAPHORE_INTERMEDIATE_INIT 5U #define OMEGA_BW_SEMAPHORE_INTERMEDIATE_DONE 6U diff --git a/src/omega_gpu_matmul_api.c b/src/omega_gpu_matmul_api.c index 61e41d332..9c3478151 100644 --- a/src/omega_gpu_matmul_api.c +++ b/src/omega_gpu_matmul_api.c @@ -1,24 +1,82 @@ +/* + * omega_gpu_matmul_api.c: FB-1 cut 1b. See the header for the contract. + * + * Submission path: the same words the chip-proven single-tile path uses + * (omega_blackwell_execute_matmul_tensor: SETUP_WORDS, constant bank upload, + * QMD0/QMD1 launch, first marker release, then the C3 tail: L2_FLUSH_DIRTY and a + * second release on uncached memory that the host waits for before reading). + * Every buffer both sides touch is GPU-uncached (nvos.h NVOS32_ATTR2_GPU_CACHEABLE: + * "For system memory this will not be coherent with direct CPU mappings"). + * Difference from cut 1: the device, channel, pushbuffer, constant bank, marker + * page, QMD page and kernel code buffers persist for the process; the GPFIFO is + * retired after every completed launch (nvrm_enqueue refuses to overrun + * unretired entries, nvrm.c). + */ #include "omega_gpu_matmul_api.h" +#include "omega_blackwell_codegen.h" #include "omega_blackwell_matmul.h" +#include "omega_blackwell_qmd.h" #include "omega_blackwell_submit.h" +#include "m16_native.h" +#include "nvrm.h" +#include #include #include #include +#include -/* Small in-process kernel cache keyed by shape. Eight shapes cover a decode - * loop (gemv per projection) comfortably; least-recently-inserted is evicted. */ #define CACHE_SLOTS 8 +#define PAGE 0x1000ull +#define MARKER_TIMEOUT_MS 20000ull /* a 1x2048x128256 call is ~0.1 s; 20 s is a stall, not a slow run */ +#define POISON_F32 (-999.0f) +#define ORACLE_TOL 1e-5 + +/* Same words as src/omega_blackwell_submit.c SETUP_WORDS (compute class setup). */ +static const uint32_t SETUP_WORDS[18] = { + 0x20012061, 0x0000cec0, 0x20012092, 0x00000001, 0x200120a8, 0x0000000f, 0x2001255d, 0x00000003, + 0x2001255e, 0x20000000, 0x2001255f, 0x000fffff, 0x20012557, 0x00000003, 0x20012558, 0x22000000, + 0x20012559, 0x00000000, +}; + +struct OmegaGpuTensor { + uint32_t k, n, kp, np; + NvrmMem mem; /* kp x np bf16 */ +}; typedef struct { bool valid; - uint32_t m, k, n; + uint32_t kp, np, grid_x; + int mutant; OmegaMatMulSpec spec; OmegaBlackwellKernel kernel; + NvrmMem code; /* resident copy of kernel.code */ } CacheSlot; -static CacheSlot g_cache[CACHE_SLOTS]; -static unsigned g_cache_next; -static pthread_mutex_t g_cache_mu = PTHREAD_MUTEX_INITIALIZER; +static struct { + bool open, blocked; + M16NativeContext ctx; + NvrmMem pb, cbank, marker, qmd; /* per-launch scratch, reused */ + NvrmMem a_buf, c_buf; /* activation and result staging, grown on demand */ + size_t a_cap, c_cap; + uint32_t cta_budget; + int oracle, mutant; + CacheSlot cache[CACHE_SLOTS]; + unsigned cache_next; +} g = { .cta_budget = OMEGA_GPU_MATMUL_MAX_CTAS, .oracle = 1 }; + +static pthread_mutex_t g_mu = PTHREAD_MUTEX_INITIALIZER; +static const char *g_err = ""; +#define FAILAT(s) (g_err = (s)) +const char *omega_gpu_matmul_last_error(void) { return g_err; } + +static uint64_t now_ns(void) { + struct timespec t; + clock_gettime(CLOCK_MONOTONIC, &t); + return (uint64_t)t.tv_sec * 1000000000ull + (uint64_t)t.tv_nsec; +} + +static uint32_t round_up(uint32_t v, uint32_t q) { return (v + q - 1) / q * q; } +static size_t page_up(size_t b) { b = (b + PAGE - 1) & ~(PAGE - 1); return b < PAGE ? PAGE : b; } const char *omega_gpu_matmul_rc_name(int rc) { switch (rc) { @@ -32,146 +90,401 @@ const char *omega_gpu_matmul_rc_name(int rc) { } } -void omega_gpu_matmul_cache_clear(void) { - pthread_mutex_lock(&g_cache_mu); +int omega_gpu_matmul_is_blocked(void) { return g.blocked ? 1 : 0; } + +/* ---- device lifetime (caller holds g_mu) ---- */ + +static int dev_alloc(size_t bytes, NvrmMem *out) { + return nvrm_alloc_gpu_uncached(&g.ctx.rm, page_up(bytes), out) == 0 ? 0 : -1; +} + +static void dev_free(NvrmMem *m) { + if (m->cpu) (void)nvrm_free(&g.ctx.rm, m); + memset(m, 0, sizeof *m); +} + +static void cache_clear_locked(void) { for (unsigned i = 0; i < CACHE_SLOTS; i++) { - if (g_cache[i].valid) omega_blackwell_kernel_free(&g_cache[i].kernel); - memset(&g_cache[i], 0, sizeof g_cache[i]); + CacheSlot *s = &g.cache[i]; + if (!s->valid) continue; + omega_blackwell_kernel_free(&s->kernel); + if (g.open && !g.blocked) dev_free(&s->code); + memset(s, 0, sizeof *s); + } + g.cache_next = 0; +} + +static int dev_open_locked(void) { + if (g.blocked) return -1; + if (g.open) return 0; + memset(&g.ctx, 0, sizeof g.ctx); + if (m16_native_open(&g.ctx) != 0) { FAILAT("m16_native_open"); return -1; } + if (m16_native_create_channel(&g.ctx) != 0) { FAILAT("m16_native_create_channel"); m16_native_close(&g.ctx); return -1; } + if (dev_alloc(0x10000, &g.pb) || dev_alloc(PAGE, &g.cbank) || dev_alloc(PAGE, &g.marker) || dev_alloc(0x10000, &g.qmd)) { + FAILAT("device scratch alloc"); + m16_native_close(&g.ctx); + memset(&g.pb, 0, sizeof g.pb); memset(&g.cbank, 0, sizeof g.cbank); + memset(&g.marker, 0, sizeof g.marker); memset(&g.qmd, 0, sizeof g.qmd); + return -1; + } + g.ctx.pb_mem = g.pb; /* m16_native_enqueue_methods copies the method stream here */ + g.open = true; + return 0; +} + +void omega_gpu_device_close(void) { + pthread_mutex_lock(&g_mu); + if (g.open && !g.blocked) { + cache_clear_locked(); + dev_free(&g.a_buf); dev_free(&g.c_buf); g.a_cap = g.c_cap = 0; + dev_free(&g.qmd); dev_free(&g.marker); dev_free(&g.cbank); dev_free(&g.pb); + m16_native_close(&g.ctx); + g.open = false; } - g_cache_next = 0; - pthread_mutex_unlock(&g_cache_mu); -} - -/* Returns a slot holding a generated kernel for the shape, or NULL with *rc set. - * The slot stays valid until cache_clear or eviction; callers copy spec+kernel - * pointers under the lock and release before the chip call (kernel code bytes - * are immutable once generated, eviction only happens under the same lock, and - * with 8 slots a caller's shape cannot be evicted by its own call). */ -static int kernel_for_shape(uint32_t m, uint32_t k, uint32_t n, - OmegaMatMulSpec *spec_out, OmegaBlackwellKernel *kernel_out, - bool *hit) { - pthread_mutex_lock(&g_cache_mu); + pthread_mutex_unlock(&g_mu); +} + +void omega_gpu_matmul_cache_clear(void) { + pthread_mutex_lock(&g_mu); + cache_clear_locked(); + pthread_mutex_unlock(&g_mu); +} + +void omega_gpu_matmul_set_cta_budget(uint32_t ctas) { + pthread_mutex_lock(&g_mu); + g.cta_budget = ctas ? ctas : OMEGA_GPU_MATMUL_MAX_CTAS; + cache_clear_locked(); + pthread_mutex_unlock(&g_mu); +} + +uint32_t omega_gpu_matmul_cta_budget(void) { return g.cta_budget; } + +void omega_gpu_matmul_set_oracle(int on) { g.oracle = on ? 1 : 0; } + +void omega_gpu_matmul_test_set_mutant(int on) { + pthread_mutex_lock(&g_mu); + g.mutant = on ? 1 : 0; + cache_clear_locked(); + pthread_mutex_unlock(&g_mu); +} + +/* Staging buffer at least `bytes` long (grown by reallocation; contents not kept). */ +static int staging(NvrmMem *buf, size_t *cap, size_t bytes) { + if (*cap >= bytes && buf->cpu) return 0; + dev_free(buf); + *cap = 0; + if (dev_alloc(bytes, buf) != 0) return -1; + *cap = buf->size; + return 0; +} + +/* ---- kernel cache (caller holds g_mu, device open) ---- */ + +static int kernel_for(uint32_t kp, uint32_t np, uint32_t grid_x, CacheSlot **out, bool *hit) { for (unsigned i = 0; i < CACHE_SLOTS; i++) { - CacheSlot *s = &g_cache[i]; - if (s->valid && s->m == m && s->k == k && s->n == n) { - *spec_out = s->spec; - *kernel_out = s->kernel; - *hit = true; - pthread_mutex_unlock(&g_cache_mu); + CacheSlot *s = &g.cache[i]; + if (s->valid && s->kp == kp && s->np == np && s->grid_x == grid_x && s->mutant == g.mutant) { + *out = s; *hit = true; return OMEGA_GPU_MATMUL_OK; } } OmegaMatMulSpec spec; - if (omega_matmul_spec_init(&spec, m, k, n, OMEGA_MATMUL_PRECISION_BF16) != 0) { - pthread_mutex_unlock(&g_cache_mu); - return OMEGA_GPU_MATMUL_TOO_LARGE; - } + /* the kernel ignores M; 16 keeps the spec inside the tile rule */ + if (omega_matmul_spec_init(&spec, 16, kp, np, OMEGA_MATMUL_PRECISION_BF16) != 0) return OMEGA_GPU_MATMUL_TOO_LARGE; OmegaBlackwellKernel kernel; memset(&kernel, 0, sizeof kernel); - if (omega_blackwell_codegen_matmul(&spec, &kernel) != 0 || !kernel.code || kernel.code_size == 0) { - pthread_mutex_unlock(&g_cache_mu); + if (omega_blackwell_codegen_matmul_tensor_loop(&spec, grid_x, g.mutant, &kernel) != 0 || !kernel.code || kernel.code_size == 0) return OMEGA_GPU_MATMUL_CODEGEN_FAIL; + NvrmMem code; + if (dev_alloc(kernel.code_size, &code) != 0) { FAILAT("kernel code alloc"); omega_blackwell_kernel_free(&kernel); return OMEGA_GPU_MATMUL_CHIP_FAIL; } + memcpy(code.cpu, kernel.code, kernel.code_size); + CacheSlot *s = &g.cache[g.cache_next]; + g.cache_next = (g.cache_next + 1) % CACHE_SLOTS; + if (s->valid) { omega_blackwell_kernel_free(&s->kernel); dev_free(&s->code); } + s->valid = true; s->kp = kp; s->np = np; s->grid_x = grid_x; s->mutant = g.mutant; + s->spec = spec; s->kernel = kernel; s->code = code; + *out = s; *hit = false; + return OMEGA_GPU_MATMUL_OK; +} + +/* ---- one launch (caller holds g_mu, device open, not blocked) ---- */ + +static int launch(const CacheSlot *ks, uint64_t a_va, uint64_t b_va, uint64_t c_va, + uint32_t grid_x, uint32_t grid_y, uint64_t *elapsed_ns, uint32_t *marker_out) { + const uint32_t threads_x = 32, threads_y = 1; + uint32_t cbank_data[OMEGA_BW_CBANK_DRIVER_WORDS]; + uint32_t cbank_args[OMEGA_BW_CBANK_MATMUL_ARGS_WORDS]; + omega_blackwell_build_cbank_driver_2d(cbank_data, g.cbank.va, threads_x, threads_y, grid_x, grid_y); + omega_blackwell_build_cbank_args_matmul(cbank_args, a_va, b_va, c_va, grid_y * 16u, ks->kp, ks->np); + memcpy(g.cbank.cpu, cbank_data, sizeof cbank_data); + memcpy((uint8_t *)g.cbank.cpu + 0x380, cbank_args, sizeof cbank_args); + + const uint64_t qmd0_va = g.qmd.va, qmd1_va = g.qmd.va + 0x1000, sem_va = g.qmd.va + 0x2000, scratch_va = g.qmd.va + 0x4000; + uint32_t gpr = ks->kernel.gpr_count > 64u ? round_up(ks->kernel.gpr_count, 8u) : 64u; + OmegaBlackwellQmdConfig cfg = { + .code_va = ks->code.va, .cbank_va = g.cbank.va, .scratch_va = scratch_va, .sem_va = sem_va, + .qmd0_va = qmd0_va, .qmd1_va = qmd1_va, .num_elements = (size_t)grid_x * grid_y * 128u, + .threads_per_block = 32, .grid_width = grid_x * grid_y, .threads_x = threads_x, .threads_y = threads_y, + .grid_x = grid_x, .grid_y = grid_y, .gpr_count = gpr, + }; + uint32_t qmd0_words[OMEGA_BW_QMD_WORDS], qmd1_words[OMEGA_BW_QMD_WORDS]; + omega_blackwell_build_qmd0(qmd0_words, qmd0_va, qmd1_va); + omega_blackwell_build_qmd1(qmd1_words, &cfg); + if (omega_blackwell_verify_qmd_invariants(qmd1_words) != 0) { FAILAT("qmd invariants"); return OMEGA_GPU_MATMUL_CHIP_FAIL; } + memcpy(g.qmd.cpu, qmd0_words, sizeof qmd0_words); + memcpy((uint8_t *)g.qmd.cpu + 0x1000, qmd1_words, sizeof qmd1_words); + + volatile uint32_t *hsem = (volatile uint32_t *)((uint8_t *)g.qmd.cpu + 0x2000); + volatile uint32_t *hmarker = (volatile uint32_t *)g.marker.cpu; + volatile uint32_t *hmarker2 = (volatile uint32_t *)((uint8_t *)g.marker.cpu + 0x10); + *hsem = 0; *hmarker = 0; *hmarker2 = 0; + __asm__ volatile("dsb sy" ::: "memory"); + + uint32_t pb[1024]; + size_t n = 0; + memcpy(&pb[n], SETUP_WORDS, sizeof SETUP_WORDS); n += sizeof SETUP_WORDS / 4; + /* Invalidate the SM instruction, constant and data caches before this launch. + * Kernel code lives in GPU-uncached memory, but the SM instruction cache is + * not coherent with host writes: when a cache slot is evicted and its code + * address is reused for a different kernel, the chip ran stale instructions + * (FB1-CUT1B-f629798 sweep: 8x1024x8, 192x16x192, 512x16x64 unwritten, + * 128x16x512 hung, all after the eighth distinct kernel). Method and bits + * from NVIDIA open-gpu-doc classes/compute/clcec0.h (BLACKWELL_COMPUTE_B): + * NVCEC0_INVALIDATE_SHADER_CACHES 0x021c, INSTRUCTION 0:0, DATA 4:4, + * CONSTANT 12:12 (the 0x021c form waits for idle first). */ + pb[n++] = nvrm_mthd(1, 0x021c, 1); pb[n++] = (1u << 0) | (1u << 4) | (1u << 12); + /* constant bank 0: driver words then our arguments at 0x380 (inline upload, same as cut 1) */ + pb[n++] = nvrm_mthd(1, 0x0188, 2); pb[n++] = (uint32_t)(g.cbank.va >> 32); pb[n++] = (uint32_t)g.cbank.va; + pb[n++] = nvrm_mthd(1, 0x0180, 2); pb[n++] = 0x00000380; pb[n++] = 0x00000001; + pb[n++] = nvrm_mthd(1, 0x01b0, 1); pb[n++] = 0x00000041; + pb[n++] = (224u << 16) | (1u << 13) | (0x01b4 >> 2) | (6u << 28); + memcpy(&pb[n], cbank_data, 224 * 4); n += 224; + pb[n++] = nvrm_mthd(1, 0x0188, 2); pb[n++] = (uint32_t)((g.cbank.va + 0x380) >> 32); pb[n++] = (uint32_t)(g.cbank.va + 0x380); + pb[n++] = nvrm_mthd(1, 0x0180, 2); pb[n++] = 0x00000028; pb[n++] = 0x00000001; + pb[n++] = nvrm_mthd(1, 0x01b0, 1); pb[n++] = 0x00000041; + pb[n++] = (10u << 16) | (1u << 13) | (0x01b4 >> 2) | (6u << 28); + memcpy(&pb[n], cbank_args, 10 * 4); n += 10; + /* QMD0 (null grid, dependence 2) */ + pb[n++] = (98u << 16) | (1u << 13) | (0x0318 >> 2) | (2u << 28); + pb[n++] = (1u << 30) | (uint32_t)((qmd0_va >> 40) & 0x1ff); pb[n++] = (uint32_t)(qmd0_va >> 8); + memcpy(&pb[n], qmd0_words, 96 * 4); n += 96; + /* intermediate semaphore init */ + pb[n++] = nvrm_mthd(1, 0x0188, 2); pb[n++] = (uint32_t)(sem_va >> 32); pb[n++] = (uint32_t)sem_va; + pb[n++] = nvrm_mthd(1, 0x0180, 2); pb[n++] = 0x00000004; pb[n++] = 0x00000001; + pb[n++] = nvrm_mthd(1, 0x01b0, 1); pb[n++] = 0x00000041; + pb[n++] = (1u << 16) | (1u << 13) | (0x01b4 >> 2) | (6u << 28); + pb[n++] = OMEGA_BW_SEMAPHORE_INTERMEDIATE_INIT; + /* QMD1 (the kernel) */ + pb[n++] = (98u << 16) | (1u << 13) | (0x0318 >> 2) | (2u << 28); + pb[n++] = (1u << 30) | (uint32_t)((qmd1_va >> 40) & 0x1ff); pb[n++] = (uint32_t)(qmd1_va >> 8); + memcpy(&pb[n], qmd1_words, 96 * 4); n += 96; + /* first marker */ + pb[n++] = nvrm_mthd(0, 0x005c, 5); + pb[n++] = (uint32_t)g.marker.va; pb[n++] = (uint32_t)(g.marker.va >> 32); + pb[n++] = OMEGA_BW_MARKER_COMPLETION_PAYLOAD; pb[n++] = 0; pb[n++] = 0x1 | (1u << 20); + /* C3 tail: L2_FLUSH_DIRTY, then the second release on the uncached marker page */ + pb[n++] = nvrm_mthd(0, 0x0028, 4); pb[n++] = 0; pb[n++] = 0; pb[n++] = 0; pb[n++] = (0x10u << 27); + pb[n++] = nvrm_mthd(0, 0x005c, 5); + pb[n++] = (uint32_t)(g.marker.va + 0x10); pb[n++] = (uint32_t)((g.marker.va + 0x10) >> 32); + pb[n++] = OMEGA_BW_MARKER2_PAYLOAD; pb[n++] = 0; pb[n++] = 0x1 | (1u << 20); + + uint64_t t0 = now_ns(); + if (m16_native_submit_methods(&g.ctx, pb, n) != 0) { FAILAT("submit_methods"); return OMEGA_GPU_MATMUL_CHIP_FAIL; } + if (m16_native_wait_marker(hmarker, OMEGA_BW_MARKER_COMPLETION_PAYLOAD, MARKER_TIMEOUT_MS) != 0 || + m16_native_wait_marker(hmarker2, OMEGA_BW_MARKER2_PAYLOAD, MARKER_TIMEOUT_MS) != 0) { + g.blocked = true; (void)FAILAT("marker wait timed out (latched)"); /* uncertain completion: keep everything, refuse every later call */ + return OMEGA_GPU_MATMUL_CHIP_FAIL; } - CacheSlot *s = &g_cache[g_cache_next]; - g_cache_next = (g_cache_next + 1) % CACHE_SLOTS; - if (s->valid) omega_blackwell_kernel_free(&s->kernel); - s->valid = true; - s->m = m; s->k = k; s->n = n; - s->spec = spec; - s->kernel = kernel; - *spec_out = spec; - *kernel_out = kernel; - *hit = false; - pthread_mutex_unlock(&g_cache_mu); + __asm__ volatile("dsb sy" ::: "memory"); + uint64_t t1 = now_ns(); + nvrm_retire(&g.ctx.rm, g.ctx.rm.put); /* both releases landed: the GPFIFO entry is consumed */ + if (*hsem != OMEGA_BW_SEMAPHORE_INTERMEDIATE_DONE) { FAILAT("intermediate semaphore not DONE"); return OMEGA_GPU_MATMUL_CHIP_FAIL; } + if (elapsed_ns) *elapsed_ns += t1 - t0; + if (marker_out) *marker_out = *hmarker; return OMEGA_GPU_MATMUL_OK; } -static uint32_t round_up(uint32_t v, uint32_t q) { return (v + q - 1) / q * q; } +/* ---- tensors ---- */ -int omega_gpu_matmul_bf16(uint32_t m, uint32_t k, uint32_t n, - const uint16_t *a, const uint16_t *b, float *c, - OmegaGpuMatmulInfo *info) { - if (info) memset(info, 0, sizeof *info); - if (!a || !b || !c || m == 0 || k == 0 || n == 0) return OMEGA_GPU_MATMUL_BAD_ARGS; - if (m > OMEGA_BW_MATMUL_MAX_M || k > OMEGA_BW_MATMUL_MAX_K || n > OMEGA_BW_MATMUL_MAX_N) - return OMEGA_GPU_MATMUL_TOO_LARGE; - const uint32_t mp = round_up(m, OMEGA_GPU_MATMUL_TILE_M); - const uint32_t np = round_up(n, OMEGA_GPU_MATMUL_TILE_N); - const uint32_t tk = OMEGA_GPU_MATMUL_TILE_K; - const uint32_t slices = (k + tk - 1) / tk; - /* CTA envelope: the kernel rasters 16x16 tiles (grid_x = np/16 rounded up, - * grid_y = rows/16). Keep grid_x * grid_y <= OMEGA_GPU_MATMUL_MAX_CTAS by - * limiting the rows handed to one launch. */ - const uint32_t grid_x = (np + 15) / 16; - uint32_t rows_per_call = (OMEGA_GPU_MATMUL_MAX_CTAS / grid_x) * OMEGA_GPU_MATMUL_TILE_M; - if (rows_per_call < OMEGA_GPU_MATMUL_TILE_M) rows_per_call = OMEGA_GPU_MATMUL_TILE_M; /* grid_x alone exceeds: 1024 cols = 64 CTAs, still inside */ - if (rows_per_call > mp) rows_per_call = mp; - const uint32_t row_blocks = (mp + rows_per_call - 1) / rows_per_call; +void omega_gpu_tensor_shape(const OmegaGpuTensor *t, uint32_t *k, uint32_t *n) { + if (k) *k = t ? t->k : 0; + if (n) *n = t ? t->n : 0; +} + +int omega_gpu_tensor_upload_bf16(uint32_t k, uint32_t n, const uint16_t *b, OmegaGpuTensor **out) { + if (out) *out = NULL; + if (!b || !out || k == 0 || n == 0) return OMEGA_GPU_MATMUL_BAD_ARGS; + if (k > OMEGA_BW_MATMUL_MAX_K || n > OMEGA_BW_MATMUL_MAX_N) return OMEGA_GPU_MATMUL_TOO_LARGE; + OmegaGpuTensor *t = calloc(1, sizeof *t); + if (!t) return OMEGA_GPU_MATMUL_BAD_ARGS; + t->k = k; t->n = n; t->kp = round_up(k, OMEGA_GPU_MATMUL_TILE_K); t->np = round_up(n, OMEGA_GPU_MATMUL_TILE_N); + int rc = OMEGA_GPU_MATMUL_OK; + pthread_mutex_lock(&g_mu); + if (dev_open_locked() != 0 || (FAILAT("tensor alloc"), dev_alloc((size_t)t->kp * t->np * 2u, &t->mem) != 0)) rc = OMEGA_GPU_MATMUL_CHIP_FAIL; + pthread_mutex_unlock(&g_mu); + if (rc != OMEGA_GPU_MATMUL_OK) { free(t); return rc; } + uint16_t *d = t->mem.cpu; + if (t->np != n || t->kp != k) memset(d, 0, (size_t)t->kp * t->np * 2u); + for (uint32_t r = 0; r < k; r++) memcpy(&d[(size_t)r * t->np], &b[(size_t)r * n], (size_t)n * 2u); + __asm__ volatile("dsb sy" ::: "memory"); + *out = t; + return OMEGA_GPU_MATMUL_OK; +} + +int omega_gpu_tensor_upload_f32(uint32_t k, uint32_t n, const float *b, OmegaGpuTensor **out) { + if (out) *out = NULL; + if (!b || !out || k == 0 || n == 0) return OMEGA_GPU_MATMUL_BAD_ARGS; + if (k > OMEGA_BW_MATMUL_MAX_K || n > OMEGA_BW_MATMUL_MAX_N) return OMEGA_GPU_MATMUL_TOO_LARGE; + size_t cnt = (size_t)k * n; + uint16_t *h = malloc(cnt * sizeof *h); + if (!h) return OMEGA_GPU_MATMUL_BAD_ARGS; + for (size_t i = 0; i < cnt; i++) h[i] = omega_fp32_to_bf16(b[i]); + int rc = omega_gpu_tensor_upload_bf16(k, n, h, out); + free(h); + return rc; +} + +void omega_gpu_tensor_free(OmegaGpuTensor *t) { + if (!t) return; + pthread_mutex_lock(&g_mu); + if (g.open && !g.blocked) dev_free(&t->mem); + pthread_mutex_unlock(&g_mu); + free(t); +} + +/* ---- the matmul ---- */ + +static int matmul_core(uint32_t m, const uint16_t *a, const OmegaGpuTensor *b, float *c, OmegaGpuMatmulInfo *info) { + const uint32_t k = b->k, n = b->n, kp = b->kp, np = b->np; + const uint32_t mp = round_up(m, OMEGA_GPU_MATMUL_TILE_M), mt = mp / 16, nt = np / 8; + pthread_mutex_lock(&g_mu); + int rc = OMEGA_GPU_MATMUL_OK; + if (g.blocked && FAILAT("process latched")) { pthread_mutex_unlock(&g_mu); return OMEGA_GPU_MATMUL_CHIP_FAIL; } + if (dev_open_locked() != 0) { pthread_mutex_unlock(&g_mu); return OMEGA_GPU_MATMUL_CHIP_FAIL; } + const uint32_t budget = g.cta_budget ? g.cta_budget : OMEGA_GPU_MATMUL_MAX_CTAS; + /* rows per launch: all of them unless the row tiles alone exceed the budget */ + uint32_t rows_per_launch = mt <= budget ? mp : budget * 16u; + uint32_t grid_y_full = rows_per_launch / 16u; + uint32_t grid_x = budget / grid_y_full; if (grid_x == 0) grid_x = 1; if (grid_x > nt) grid_x = nt; if (info) { - info->m = m; info->k = k; info->n = n; info->padded_m = mp; info->padded_n = np; - info->k_slices = slices; info->rows_per_call = rows_per_call; + info->m = m; info->k = k; info->n = n; info->padded_m = mp; info->padded_n = np; info->padded_k = kp; + info->k_slices = 1; info->rows_per_call = rows_per_launch; info->grid_x = grid_x; info->grid_y = grid_y_full; + info->resident = true; info->kernel_cache_hit = true; + strncpy(info->target_chip, "NVIDIA DGX Spark (Grace Blackwell GB10)", sizeof info->target_chip - 1); + info->sm_architecture = 121; + } + if (staging(&g.a_buf, &g.a_cap, (size_t)mp * kp * 2u) != 0 || staging(&g.c_buf, &g.c_cap, (size_t)mp * np * 4u) != 0) { + pthread_mutex_unlock(&g_mu); return OMEGA_GPU_MATMUL_CHIP_FAIL; } + /* activation rows in, zero padded; result rows poisoned */ + uint16_t *ad = g.a_buf.cpu; + if (mp != m || kp != k) memset(ad, 0, (size_t)mp * kp * 2u); + for (uint32_t r = 0; r < m; r++) memcpy(&ad[(size_t)r * kp], &a[(size_t)r * k], (size_t)k * 2u); + float *cd = g.c_buf.cpu; + for (size_t i = 0; i < (size_t)m * np; i++) cd[i] = POISON_F32; + __asm__ volatile("dsb sy" ::: "memory"); - uint16_t *ap = calloc((size_t)rows_per_call * tk, sizeof *ap); - uint16_t *bp = calloc((size_t)tk * np, sizeof *bp); - float *cp = malloc((size_t)rows_per_call * np * sizeof *cp); - if (!ap || !bp || !cp) { free(ap); free(bp); free(cp); return OMEGA_GPU_MATMUL_BAD_ARGS; } - for (size_t i = 0; i < (size_t)m * n; i++) c[i] = 0.0f; + for (uint32_t r0 = 0; r0 < mp && rc == OMEGA_GPU_MATMUL_OK; r0 += rows_per_launch) { + uint32_t rows = mp - r0 < rows_per_launch ? mp - r0 : rows_per_launch; + uint32_t grid_y = rows / 16u; + CacheSlot *ks = NULL; bool hit = false; + rc = kernel_for(kp, np, grid_x, &ks, &hit); + if (rc != OMEGA_GPU_MATMUL_OK) break; + if (info && !hit) info->kernel_cache_hit = false; + rc = launch(ks, g.a_buf.va + (uint64_t)r0 * kp * 2u, b->mem.va, g.c_buf.va + (uint64_t)r0 * np * 4u, + grid_x, grid_y, info ? &info->elapsed_ns : NULL, info ? &info->completion_marker : NULL); + if (info) info->chip_calls++; + } + if (rc == OMEGA_GPU_MATMUL_OK) { + /* the chip must have written every real output word (poison check, as the engine does) */ + size_t unchanged = 0; + for (uint32_t r = 0; r < m; r++) { + const float *row = &cd[(size_t)r * np]; + for (uint32_t j = 0; j < n; j++) if (row[j] == POISON_F32) unchanged++; + memcpy(&c[(size_t)r * n], row, (size_t)n * sizeof *c); + } + if (unchanged) { FAILAT("output poison survived"); rc = OMEGA_GPU_MATMUL_CHIP_FAIL; } + } + pthread_mutex_unlock(&g_mu); + return rc; +} - bool all_parity = true, any_miss = false; - int rc = OMEGA_GPU_MATMUL_OK; - for (uint32_t s = 0; s < slices && rc == OMEGA_GPU_MATMUL_OK; s++) { - const uint32_t k0 = s * tk; - const uint32_t kw = (k - k0 < tk) ? (k - k0) : tk; - /* B slice: rows k0..k0+kw of columns 0..n, zero elsewhere (row-major 16 x np) */ - memset(bp, 0, (size_t)tk * np * sizeof *bp); - for (uint32_t j = 0; j < kw; j++) - memcpy(&bp[(size_t)j * np], &b[(size_t)(k0 + j) * n], n * sizeof *bp); - for (uint32_t rb = 0; rb < row_blocks && rc == OMEGA_GPU_MATMUL_OK; rb++) { - const uint32_t r0 = rb * rows_per_call; - uint32_t rows = mp - r0 < rows_per_call ? mp - r0 : rows_per_call; - rows = round_up(rows, OMEGA_GPU_MATMUL_TILE_M); - const uint32_t rows_real = (m > r0) ? ((m - r0 < rows) ? (m - r0) : rows) : 0; - OmegaMatMulSpec spec; - OmegaBlackwellKernel kernel; - bool hit = false; - rc = kernel_for_shape(rows, tk, np, &spec, &kernel, &hit); - if (rc != OMEGA_GPU_MATMUL_OK) break; - if (info) { if (hit) info->kernel_cache_hit = true; else any_miss = true; } - /* A slice: rows r0..r0+rows_real of columns k0..k0+kw, zero elsewhere (row-major rows x 16) */ - memset(ap, 0, (size_t)rows * tk * sizeof *ap); - for (uint32_t i = 0; i < rows_real; i++) - memcpy(&ap[(size_t)i * tk], &a[(size_t)(r0 + i) * k + k0], kw * sizeof *ap); - - OmegaBlackwellMatMulExecution exec; - memset(&exec, 0, sizeof exec); - float max_abs = 0.0f, max_rel = 0.0f; - int r = omega_blackwell_execute_matmul_tensor(&spec, &kernel, ap, bp, cp, &exec, &max_abs, &max_rel); - if (info) { - info->chip_calls++; - info->elapsed_ns += exec.elapsed_ns; - if (max_abs > info->max_abs_err) info->max_abs_err = max_abs; - if (max_rel > info->max_rel_err) info->max_rel_err = max_rel; - info->mismatch_count += exec.mismatch_count; - info->completion_marker = exec.completion_marker; - info->sm_architecture = exec.sm_architecture; - memcpy(info->target_chip, exec.target_chip, sizeof info->target_chip); +static int resident_entry(uint32_t m, const uint16_t *a, const OmegaGpuTensor *b, float *c, OmegaGpuMatmulInfo *info) { + uint64_t t0 = now_ns(); + if (info) memset(info, 0, sizeof *info); + if (!a || !b || !c || m == 0 || !b->mem.cpu) return OMEGA_GPU_MATMUL_BAD_ARGS; + if (m > OMEGA_BW_MATMUL_MAX_M) return OMEGA_GPU_MATMUL_TOO_LARGE; + int rc = matmul_core(m, a, b, c, info); + if (info) info->call_ns = now_ns() - t0; + return rc; +} + +int omega_gpu_matmul_resident_bf16(uint32_t m, const uint16_t *a, const OmegaGpuTensor *b, float *c, + OmegaGpuMatmulInfo *info) { + return resident_entry(m, a, b, c, info); +} + +int omega_gpu_matmul_resident_f32(uint32_t m, const float *a, const OmegaGpuTensor *b, float *c, + OmegaGpuMatmulInfo *info) { + uint64_t t0 = now_ns(); + if (info) memset(info, 0, sizeof *info); + if (!a || !b || !c || m == 0 || !b->mem.cpu) return OMEGA_GPU_MATMUL_BAD_ARGS; + if (m > OMEGA_BW_MATMUL_MAX_M) return OMEGA_GPU_MATMUL_TOO_LARGE; + size_t cnt = (size_t)m * b->k; + uint16_t *h = malloc(cnt * sizeof *h); + if (!h) return OMEGA_GPU_MATMUL_BAD_ARGS; + for (size_t i = 0; i < cnt; i++) h[i] = omega_fp32_to_bf16(a[i]); + int rc = matmul_core(m, h, b, c, info); + free(h); + if (info) info->call_ns = now_ns() - t0; + return rc; +} + +/* Host oracle: double accumulation of the bf16 inputs; an element mismatches when + * its error exceeds ORACLE_TOL of the accumulation scale (sum of |terms|). */ +static void oracle(uint32_t m, uint32_t k, uint32_t n, const uint16_t *a, const uint16_t *b, const float *c, OmegaGpuMatmulInfo *info) { + float max_abs = 0.0f, max_rel = 0.0f; + size_t mism = 0; + for (uint32_t i = 0; i < m; i++) { + for (uint32_t j = 0; j < n; j++) { + double acc = 0.0, scale = 0.0; + for (uint32_t t = 0; t < k; t++) { + double p = (double)omega_bf16_to_fp32(a[(size_t)i * k + t]) * (double)omega_bf16_to_fp32(b[(size_t)t * n + j]); + acc += p; scale += fabs(p); } - if (r != 0 || exec.completion_marker != OMEGA_BW_MARKER_COMPLETION_PAYLOAD) { rc = OMEGA_GPU_MATMUL_CHIP_FAIL; break; } - if (!exec.parity_verified) all_parity = false; - for (uint32_t i = 0; i < rows_real; i++) - for (uint32_t j = 0; j < n; j++) - c[(size_t)(r0 + i) * n + j] += cp[(size_t)i * np + j]; + double d = fabs(acc - (double)c[(size_t)i * n + j]); + double rel = d / (scale > 1e-6 ? scale : 1e-6); + if ((float)d > max_abs) max_abs = (float)d; + if ((float)rel > max_rel) max_rel = (float)rel; + if (rel > ORACLE_TOL) mism++; } } - free(ap); free(bp); free(cp); - if (info) { - info->parity_verified = all_parity && rc == OMEGA_GPU_MATMUL_OK; - if (any_miss) info->kernel_cache_hit = false; /* hit only when every launch found its kernel */ - } + info->max_abs_err = max_abs; info->max_rel_err = max_rel; info->mismatch_count = mism; + info->oracle_ran = true; info->parity_verified = (mism == 0); +} + +int omega_gpu_matmul_bf16(uint32_t m, uint32_t k, uint32_t n, + const uint16_t *a, const uint16_t *b, float *c, + OmegaGpuMatmulInfo *info) { + uint64_t t0 = now_ns(); + OmegaGpuMatmulInfo local; + if (!info) info = &local; + memset(info, 0, sizeof *info); + if (!a || !b || !c || m == 0 || k == 0 || n == 0) return OMEGA_GPU_MATMUL_BAD_ARGS; + if (m > OMEGA_BW_MATMUL_MAX_M || k > OMEGA_BW_MATMUL_MAX_K || n > OMEGA_BW_MATMUL_MAX_N) + return OMEGA_GPU_MATMUL_TOO_LARGE; + OmegaGpuTensor *t = NULL; + int rc = omega_gpu_tensor_upload_bf16(k, n, b, &t); if (rc != OMEGA_GPU_MATMUL_OK) return rc; - if (!all_parity) return OMEGA_GPU_MATMUL_PARITY_FAIL; - return OMEGA_GPU_MATMUL_OK; + rc = matmul_core(m, a, t, c, info); + omega_gpu_tensor_free(t); + info->resident = false; + if (rc == OMEGA_GPU_MATMUL_OK && g.oracle) { + oracle(m, k, n, a, b, c, info); + if (!info->parity_verified) rc = OMEGA_GPU_MATMUL_PARITY_FAIL; + } + info->call_ns = now_ns() - t0; + return rc; } int omega_gpu_matmul_f32(uint32_t m, uint32_t k, uint32_t n, diff --git a/src/omega_gpu_matmul_api.h b/src/omega_gpu_matmul_api.h index e051fdcda..d0ebdb3d3 100644 --- a/src/omega_gpu_matmul_api.h +++ b/src/omega_gpu_matmul_api.h @@ -1,17 +1,27 @@ #ifndef OMEGA_GPU_MATMUL_API_H #define OMEGA_GPU_MATMUL_API_H /* - * omega_gpu_matmul_api: the first native (no CUDA) matrix-multiply entry point - * for the AIEN inference stack (FB-1 cut 1, 2026-10-03). + * omega_gpu_matmul_api: the native (no CUDA) matrix-multiply entry point for + * the AIEN inference stack (FB-1 cut 1, 2026-10-03; cut 1b speed, 2026-10-04). * - * Wraps the chip-proven M16/M17 tensor matmul path (omega_blackwell_submit.c, - * all buffers GPU-uncached, C3 release tail) behind a plain C call that a - * Rust FFI crate can link. Inputs are row-major bf16 (A: m x k, B: k x n), - * output is row-major f32 (C: m x n). Every call also runs the host oracle and - * reports the error bound, so the first consumers get a parity receipt for free - * (cost: one CPU matmul per call; a later cut makes the oracle optional). + * Inputs are row-major bf16 (A: m x k, B: k x n), output is row-major f32 + * (C: m x n). Kernels are generated by our own codegen and cached in-process. * - * Kernels are generated by our own codegen per (m, k, n) and cached in-process. + * Cut 1b: + * - the whole K dimension is accumulated on the chip (looped HMMA kernel, + * omega_blackwell_codegen_matmul_tensor_loop); no host K slicing; + * - the device and its channel are opened once per process and reused; + * - weights are uploaded once (omega_gpu_tensor_upload_*) and stay resident; + * omega_gpu_matmul_resident_* then moves only the activation rows and the + * result per call. The original omega_gpu_matmul_* calls keep working (they + * upload B, run, free) and keep running the host oracle per call as cut 1 + * promised; the resident calls never run an oracle (speed), the caller or + * the test holds the reference. + * - every call poisons the output rows on the device before the launch and + * refuses a result that still holds poison (OUTPUT_UNCHANGED -> CHIP_FAIL). + * - an uncertain completion (marker wait timed out) latches the process: + * nothing is freed or closed (the GPU may still be running) and every later + * call returns CHIP_FAIL, as the engine does (omega_gpu_engine.h). */ #include #include @@ -23,46 +33,73 @@ extern "C" { enum { OMEGA_GPU_MATMUL_OK = 0, - OMEGA_GPU_MATMUL_BAD_ARGS = -1, /* NULL pointer or zero dimension */ + OMEGA_GPU_MATMUL_BAD_ARGS = -1, /* NULL pointer, zero dimension, shape mismatch, out of memory */ OMEGA_GPU_MATMUL_TOO_LARGE = -2, /* a dimension exceeds OMEGA_BW_MATMUL_MAX_* */ OMEGA_GPU_MATMUL_CODEGEN_FAIL = -3, /* our codegen refused the shape */ - OMEGA_GPU_MATMUL_CHIP_FAIL = -4, /* device open, submit, marker or release failed */ - OMEGA_GPU_MATMUL_PARITY_FAIL = -5 /* chip result disagrees with the host oracle */ + OMEGA_GPU_MATMUL_CHIP_FAIL = -4, /* device open, alloc, submit, marker, release or output-written check failed */ + OMEGA_GPU_MATMUL_PARITY_FAIL = -5 /* chip result disagrees with the host oracle (non-resident calls only) */ }; -/* Kernel shape rule today (omega_blackwell_codegen_matmul_tensor): M multiple of - * 16, N multiple of 8, K exactly 16. The API hides it: A and B are zero-padded - * on the host to (Mp x 16) and (16 x Np) slices, one chip call per 16-wide K - * slice, partial products summed on the host in f32. Correct for any shape up - * to the limits; the per-slice device open/submit cost is the known price until - * the in-kernel K loop lands (FB-1 cut 1b). */ +/* Kernel tile rule (omega_blackwell_codegen_matmul_tensor_loop): M multiple of + * 16, N multiple of 8, K multiple of 16. The API zero-pads: A rows/columns on + * the way in per call, B at upload, and reads back only the real m x n block. */ #define OMEGA_GPU_MATMUL_TILE_M 16 #define OMEGA_GPU_MATMUL_TILE_N 8 #define OMEGA_GPU_MATMUL_TILE_K 16 -/* Chip-proven launch envelope (2026-10-03 sweep, evidence GPU-MATMUL-API-2ea8e67): - * grids of <= 100 CTAs return correct tiles, 128 and above lose whole tiles - * (investigation I42). The API never launches more than this many CTAs per - * call and splits rows on the host above it. */ +/* Launch envelope. Cut 1 (2026-10-03 sweep, evidence GPU-MATMUL-API-2ea8e67, + * investigation I42) saw grids of 128 CTAs and above lose output with the + * single-tile kernel. The looped kernel does not need big grids: each CTA walks + * column tiles x, x + grid_x, ... so any shape is one launch inside the budget + * (rows are split across launches only when m / 16 alone exceeds it). The + * budget is a tunable (omega_gpu_matmul_set_cta_budget) so the chip test can + * measure larger grids; the default stays at the proven value until a sealed + * receipt says otherwise. */ #define OMEGA_GPU_MATMUL_MAX_CTAS 64 typedef struct { uint32_t m, k, n; uint32_t padded_m, padded_n;/* shape handed to the kernel */ - uint32_t k_slices; /* 16-wide K slices: ceil(k / 16) */ - uint32_t chip_calls; /* launches made (slices x row blocks) */ + uint32_t k_slices; /* always 1 since cut 1b (whole K on the chip) */ + uint32_t chip_calls; /* launches made (row blocks) */ uint32_t rows_per_call; /* row block height chosen for the CTA envelope */ - uint64_t elapsed_ns; /* sum of chip launch-to-completion over the slices */ - float max_abs_err; /* vs host bf16 oracle */ - float max_rel_err; - size_t mismatch_count; - bool parity_verified; /* every slice agreed with the host oracle */ - uint32_t completion_marker; /* observed first marker word of the last slice */ - bool kernel_cache_hit; /* the padded shape's kernel was already generated */ + uint64_t elapsed_ns; /* sum of chip launch-to-completion over the launches */ + float max_abs_err; /* vs host oracle (non-resident calls only, else 0) */ + float max_rel_err; /* vs host oracle, relative to the accumulation scale */ + size_t mismatch_count; /* host oracle elements beyond tolerance (non-resident calls only) */ + bool parity_verified; /* oracle ran and every element agreed (always false for resident calls) */ + uint32_t completion_marker; /* observed first marker word of the last launch */ + bool kernel_cache_hit; /* every launch found its kernel already generated */ char target_chip[64]; uint32_t sm_architecture; + /* cut 1b additions (appended; earlier fields keep their offsets) */ + uint32_t grid_x, grid_y; /* grid of the last launch */ + uint32_t padded_k; + bool resident; /* B came from a resident tensor handle */ + bool oracle_ran; /* the host oracle was computed for this call */ + uint64_t call_ns; /* wall time of the whole API call (copy-in, launch, wait, copy-out) */ } OmegaGpuMatmulInfo; -/* C[m x n] = A[m x k] * B[k x n], bf16 inputs, f32 output. info may be NULL. */ +/* Resident weight tensor: k x n bf16, zero-padded to the tile rule, kept in + * GPU-uncached unified memory until freed. Opaque. */ +typedef struct OmegaGpuTensor OmegaGpuTensor; + +/* Upload a k x n row-major matrix once. f32 input is rounded to bf16 on the + * host (round-to-nearest-even). Opens the device on first use. */ +int omega_gpu_tensor_upload_bf16(uint32_t k, uint32_t n, const uint16_t *b, OmegaGpuTensor **out); +int omega_gpu_tensor_upload_f32(uint32_t k, uint32_t n, const float *b, OmegaGpuTensor **out); +void omega_gpu_tensor_free(OmegaGpuTensor *t); +void omega_gpu_tensor_shape(const OmegaGpuTensor *t, uint32_t *k, uint32_t *n); + +/* C[m x n] = A[m x k] * B, B resident (k and n come from the handle). No host + * oracle: info->parity_verified is false, mismatch_count 0. */ +int omega_gpu_matmul_resident_bf16(uint32_t m, const uint16_t *a, const OmegaGpuTensor *b, float *c, + OmegaGpuMatmulInfo *info); +int omega_gpu_matmul_resident_f32(uint32_t m, const float *a, const OmegaGpuTensor *b, float *c, + OmegaGpuMatmulInfo *info); + +/* C[m x n] = A[m x k] * B[k x n], bf16 inputs, f32 output. info may be NULL. + * Uploads B for the call, runs, frees it, and checks the result against the + * host oracle (double accumulation, tolerance 1e-5 of the accumulation scale). */ int omega_gpu_matmul_bf16(uint32_t m, uint32_t k, uint32_t n, const uint16_t *a, const uint16_t *b, float *c, OmegaGpuMatmulInfo *info); @@ -76,9 +113,33 @@ int omega_gpu_matmul_f32(uint32_t m, uint32_t k, uint32_t n, /* Name of a return code, for logs and receipts. */ const char *omega_gpu_matmul_rc_name(int rc); -/* Drop every cached kernel (tests; otherwise never needed). */ +/* Drop every cached kernel (host and device copies). */ void omega_gpu_matmul_cache_clear(void); +/* Close the device and free every API-owned buffer (not resident tensors the + * caller still holds; free those first). Refused (no-op) after an uncertain + * completion. The next call reopens. */ +void omega_gpu_device_close(void); + +/* 1 once an uncertain completion has latched this process. */ +int omega_gpu_matmul_is_blocked(void); + +/* Stage name of the most recent CHIP_FAIL ("" if none), for logs and receipts. */ +const char *omega_gpu_matmul_last_error(void); + +/* CTA budget per launch (default OMEGA_GPU_MATMUL_MAX_CTAS; 0 restores it). + * Clears the kernel cache (kernels bake in grid_x). Test and measurement knob. */ +void omega_gpu_matmul_set_cta_budget(uint32_t ctas); +uint32_t omega_gpu_matmul_cta_budget(void); + +/* Host oracle on the non-resident calls (default on). */ +void omega_gpu_matmul_set_oracle(int on); + +/* TEST ONLY. Non-zero generates deliberately wrong kernels (last K step + * dropped) so the parity test can prove it catches a wrong kernel. Clears the + * kernel cache. Production code must never call this. */ +void omega_gpu_matmul_test_set_mutant(int on); + #ifdef __cplusplus } #endif diff --git a/tests/gpu_matmul_api_test.c b/tests/gpu_matmul_api_test.c index beb366762..17297dac3 100644 --- a/tests/gpu_matmul_api_test.c +++ b/tests/gpu_matmul_api_test.c @@ -1,20 +1,26 @@ -/* gpu_matmul_api_test: FB-1 cut 1 gate for omega_gpu_matmul_api. +/* gpu_matmul_api_test: FB-1 cut 1 / 1b gate for omega_gpu_matmul_api. * - * ./gpu_matmul_api_test --host-only argument and limit refusals, codegen only, no chip - * ./gpu_matmul_api_test --out receipt.json chip sweep over shapes, JSON receipt + * ./gpu_matmul_api_test --host-only argument and limit refusals, codegen only, no chip + * ./gpu_matmul_api_test --out receipt.json chip sweep over shapes, JSON receipt + * ./gpu_matmul_api_test --timing --out r.json resident GEMV timing (median of 100 calls) + parity + * ./gpu_matmul_api_test --mutant --out r.json wrong kernel (last K step dropped) must FAIL parity; + * exit 0 when every shape caught it ("mutant killed") + * ./gpu_matmul_api_test --cta-budget N ... run with a different CTA budget (I42 experiment) * * Shapes come from OMEGA_GPU_MATMUL_SHAPES ("m,k,n;m,k,n;..."), default below. - * Pass rule per shape: rc OK, parity verified, end-to-end error < 1e-5 relative to the accumulation scale (bf16 inputs - * against the host bf16 oracle, f32 accumulate; only summation order differs). + * Pass rule per shape: rc OK, parity verified by the API oracle, end-to-end error < 1e-5 relative to + * the accumulation scale (bf16 inputs against a double reference; only accumulation order and the + * chip's f32 accumulator differ), second call hits the kernel cache and agrees bit for bit. */ #include "omega_gpu_matmul_api.h" +#include "omega_blackwell_codegen.h" #include "omega_blackwell_matmul.h" #include +#include #include #include #include #include -#include /* round a float to bf16 and back, as the API does on the way in */ static float bf16r(float f) { uint16_t h = omega_fp32_to_bf16(f); uint32_t u = (uint32_t)h << 16; float o; memcpy(&o, &u, 4); return o; } @@ -22,12 +28,34 @@ static float bf16r(float f) { uint16_t h = omega_fp32_to_bf16(f); uint32_t u = ( 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) +/* cut-1 list unchanged, then the cut-1b Llama shapes (hidden 2048, ffn 8192, vocab 128256) */ static const char *DEFAULT_SHAPES = "16,16,16;32,32,32;64,64,64;128,128,128;256,256,256;512,512,512;" "1,1024,1024;1,256,1024;16,1024,256;8,1024,8;" - "1024,16,128;192,16,192;512,16,64;256,16,256;128,16,512"; + "1024,16,128;192,16,192;512,16,64;256,16,256;128,16,512;" + "1,2048,8192;1,8192,2048;1,2048,128256"; +static const char *MUTANT_SHAPES = "16,32,16;1,2048,8192;64,64,64;1,1024,1024"; +static const char *TIMING_SHAPES = "1,2048,8192;1,8192,2048"; static uint32_t lcg(uint32_t *s) { *s = *s * 1664525u + 1013904223u; return *s; } +static double now_ms(void) { struct timespec t; clock_gettime(CLOCK_MONOTONIC, &t); return t.tv_sec * 1e3 + t.tv_nsec / 1e6; } + +static void fill(float *a, size_t n, uint32_t *seed) { for (size_t i = 0; i < n; i++) a[i] = ((float)(lcg(seed) % 2001) - 1000.0f) / 1000.0f; } + +/* end-to-end: full-K product on the host from the same bf16-rounded inputs, in double; error relative + * to the accumulation scale (sum of |terms|), not to a result that may cancel to near zero */ +static double e2e_max_rel(uint32_t m, uint32_t k, uint32_t n, const float *a, const float *b, const float *c, size_t *bad) { + double worst = 0.0; size_t nbad = 0; + for (size_t i = 0; i < m; i++) for (size_t j = 0; j < n; j++) { + double acc = 0.0, scale = 0.0; + for (size_t t = 0; t < k; t++) { double p = (double)bf16r(a[i * k + t]) * (double)bf16r(b[t * n + j]); acc += p; scale += fabs(p); } + double rel = fabs(acc - (double)c[i * n + j]) / (scale > 1e-6 ? scale : 1e-6); + if (rel > worst) worst = rel; + if (rel >= 1e-5) nbad++; + } + if (bad) *bad = nbad; + return worst; +} static void host_only(void) { float a[16 * 16] = {0}, b[16 * 16] = {0}, c[16 * 16] = {0}; @@ -36,22 +64,46 @@ static void host_only(void) { CHECK(omega_gpu_matmul_f32(16, 16, 16, NULL, b, c, &info) == OMEGA_GPU_MATMUL_BAD_ARGS, "NULL a refused"); CHECK(omega_gpu_matmul_f32(OMEGA_BW_MATMUL_MAX_M + 1, 16, 16, a, b, c, &info) == OMEGA_GPU_MATMUL_TOO_LARGE, "m over limit refused"); CHECK(omega_gpu_matmul_bf16(16, OMEGA_BW_MATMUL_MAX_K + 1, 16, (uint16_t *)a, (uint16_t *)b, c, NULL) == OMEGA_GPU_MATMUL_TOO_LARGE, "k over limit refused (NULL info ok)"); + CHECK(omega_gpu_matmul_bf16(16, 16, OMEGA_BW_MATMUL_MAX_N + 1, (uint16_t *)a, (uint16_t *)b, c, NULL) == OMEGA_GPU_MATMUL_TOO_LARGE, "n over limit refused"); + CHECK(OMEGA_BW_MATMUL_MAX_N >= 128256 && OMEGA_BW_MATMUL_MAX_K >= 8192 && OMEGA_BW_MATMUL_MAX_M >= 2048, "limits cover Llama shapes (vocab 128256, ffn 8192)"); + OmegaGpuTensor *t = NULL; + CHECK(omega_gpu_tensor_upload_f32(0, 16, a, &t) == OMEGA_GPU_MATMUL_BAD_ARGS && t == NULL, "tensor k=0 refused"); + CHECK(omega_gpu_tensor_upload_f32(16, 16, NULL, &t) == OMEGA_GPU_MATMUL_BAD_ARGS, "tensor NULL refused"); + CHECK(omega_gpu_matmul_resident_f32(16, a, NULL, c, &info) == OMEGA_GPU_MATMUL_BAD_ARGS, "resident NULL tensor refused"); CHECK(strcmp(omega_gpu_matmul_rc_name(OMEGA_GPU_MATMUL_PARITY_FAIL), "PARITY_FAIL") == 0, "rc name"); - /* codegen only: shapes must be accepted by our codegen without touching the chip */ + CHECK(omega_gpu_matmul_cta_budget() == OMEGA_GPU_MATMUL_MAX_CTAS, "default CTA budget"); + CHECK(omega_gpu_matmul_is_blocked() == 0, "not blocked at start"); + + /* codegen only: the looped kernel must accept every padded Llama shape without touching the chip */ + struct { uint32_t k, n, gx; } ok[] = { {16, 8, 1}, {2048, 8192, 64}, {8192, 2048, 64}, {2048, 128256, 64}, {1024, 1024, 1}, {16384, 262144, 64} }; + for (size_t i = 0; i < sizeof ok / sizeof ok[0]; i++) { + OmegaMatMulSpec spec; OmegaBlackwellKernel kernel; memset(&kernel, 0, sizeof kernel); + int rc = omega_matmul_spec_init(&spec, 16, ok[i].k, ok[i].n, OMEGA_MATMUL_PRECISION_BF16) == 0 && + omega_blackwell_codegen_matmul_tensor_loop(&spec, ok[i].gx, 0, &kernel) == 0 && kernel.code_size > 0; + CHECK(rc, "loop kernel K=%u N=%u gx=%u generated", ok[i].k, ok[i].n, ok[i].gx); + CHECK(kernel.gpr_count <= 64, "loop kernel K=%u N=%u fits 64 registers (got %u)", ok[i].k, ok[i].n, kernel.gpr_count); + /* the mutant kernel is a different program */ + OmegaBlackwellKernel mut; memset(&mut, 0, sizeof mut); + if (omega_blackwell_codegen_matmul_tensor_loop(&spec, ok[i].gx, 1, &mut) == 0) { + CHECK(memcmp(mut.code_digest, kernel.code_digest, 32) != 0, "mutant kernel differs K=%u N=%u", ok[i].k, ok[i].n); + omega_blackwell_kernel_free(&mut); + } else CHECK(ok[i].k == 16, "mutant refused only for K=16 (K=%u)", ok[i].k); + omega_blackwell_kernel_free(&kernel); + } OmegaMatMulSpec spec; OmegaBlackwellKernel kernel; memset(&kernel, 0, sizeof kernel); - /* documents the kernel rule the API pads around: M%16, N%8, K==16 */ - CHECK(omega_matmul_spec_init(&spec, 16, 16, 8, OMEGA_MATMUL_PRECISION_BF16) == 0 && omega_blackwell_codegen_matmul(&spec, &kernel) == 0 && kernel.code_size > 0, "16x16x8 tile kernel generated"); - omega_blackwell_kernel_free(&kernel); memset(&kernel, 0, sizeof kernel); - CHECK(omega_matmul_spec_init(&spec, 1, 1024, 1024, OMEGA_MATMUL_PRECISION_BF16) == 0 && omega_blackwell_codegen_matmul(&spec, &kernel) != 0, "raw 1x1024x1024 refused by codegen (the API pads and slices it)"); + CHECK(omega_matmul_spec_init(&spec, 16, 24, 16, OMEGA_MATMUL_PRECISION_BF16) == 0 && omega_blackwell_codegen_matmul_tensor_loop(&spec, 1, 0, &kernel) != 0, "K not multiple of 16 refused by codegen (the API pads)"); + CHECK(omega_matmul_spec_init(&spec, 16, 16, 16, OMEGA_MATMUL_PRECISION_BF16) == 0 && omega_blackwell_codegen_matmul_tensor_loop(&spec, 3, 0, &kernel) != 0, "grid_x beyond the column tiles refused"); + /* the single-tile kernel of cut 1 still generates (other gates use it) */ + memset(&kernel, 0, sizeof kernel); + CHECK(omega_matmul_spec_init(&spec, 16, 16, 8, OMEGA_MATMUL_PRECISION_BF16) == 0 && omega_blackwell_codegen_matmul(&spec, &kernel) == 0 && kernel.code_size > 0, "16x16x8 single-tile kernel generated"); + omega_blackwell_kernel_free(&kernel); omega_gpu_matmul_cache_clear(); } -static int chip_sweep(const char *out_path) { - const char *shapes = getenv("OMEGA_GPU_MATMUL_SHAPES"); - if (!shapes || !*shapes) shapes = DEFAULT_SHAPES; +static int chip_sweep(const char *shapes, const char *out_path, int mutant) { FILE *out = out_path ? fopen(out_path, "w") : NULL; if (out_path && !out) { printf("cannot open %s\n", out_path); return 2; } - if (out) fprintf(out, "{\"schema\":\"OMEGA_GPU_MATMUL_API_SWEEP_V1\",\"shapes\":["); + if (out) fprintf(out, "{\"schema\":\"OMEGA_GPU_MATMUL_API_SWEEP_V2\",\"mutant\":%s,\"cta_budget\":%u,\"shapes\":[", mutant ? "true" : "false", omega_gpu_matmul_cta_budget()); char *copy = strdup(shapes); char *save = NULL; int first = 1; @@ -59,65 +111,124 @@ static int chip_sweep(const char *out_path) { unsigned m, k, n; if (sscanf(tok, "%u,%u,%u", &m, &k, &n) != 3) { printf("bad shape %s\n", tok); continue; } size_t na = (size_t)m * k, nb = (size_t)k * n, nc = (size_t)m * n; - float *a = malloc(na * sizeof *a), *b = malloc(nb * sizeof *b), *c = malloc(nc * sizeof *c); + float *a = malloc(na * sizeof *a), *b = malloc(nb * sizeof *b), *c = malloc(nc * sizeof *c), *c2 = malloc(nc * sizeof *c2); + if (!a || !b || !c || !c2) { printf("out of host memory for %s\n", tok); free(a); free(b); free(c); free(c2); continue; } uint32_t seed = 0x5eed0000u ^ (m << 20) ^ (k << 10) ^ n; - for (size_t i = 0; i < na; i++) a[i] = ((float)(lcg(&seed) % 2001) - 1000.0f) / 1000.0f; - for (size_t i = 0; i < nb; i++) b[i] = ((float)(lcg(&seed) % 2001) - 1000.0f) / 1000.0f; + fill(a, na, &seed); fill(b, nb, &seed); for (size_t i = 0; i < nc; i++) c[i] = -12345.0f; - OmegaGpuMatmulInfo info; - struct timespec t0, t1; - clock_gettime(CLOCK_MONOTONIC, &t0); + OmegaGpuMatmulInfo info, info2; + double t0 = now_ms(); int rc = omega_gpu_matmul_f32(m, k, n, a, b, c, &info); - clock_gettime(CLOCK_MONOTONIC, &t1); + double wall_ms = now_ms() - t0; /* second call on the same shape must hit the kernel cache and agree */ - float *c2 = malloc(nc * sizeof *c2); - OmegaGpuMatmulInfo info2; int rc2 = omega_gpu_matmul_f32(m, k, n, a, b, c2, &info2); size_t repeat_mismatch = 0; for (size_t i = 0; i < nc; i++) if (c[i] != c2[i]) repeat_mismatch++; - /* end-to-end: full-K product on the host from the same bf16-rounded inputs, in double */ - double e2e_max_rel = 0.0; - if (rc == OMEGA_GPU_MATMUL_OK) { - for (size_t i = 0; i < m; i++) for (size_t j = 0; j < n; j++) { - double acc = 0.0, scale = 0.0; - for (size_t t = 0; t < k; t++) { - double p = (double)bf16r(a[i * k + t]) * (double)bf16r(b[t * n + j]); - acc += p; scale += fabs(p); - } - /* error relative to the accumulation scale (sum of |terms|), not to a - * result that may cancel to near zero: f32 accumulation over k terms */ - double d = fabs(acc - (double)c[i * n + j]); - double rel = d / (scale > 1e-6 ? scale : 1e-6); - if (rel > e2e_max_rel) e2e_max_rel = rel; - } - } - double wall_ms = (t1.tv_sec - t0.tv_sec) * 1e3 + (t1.tv_nsec - t0.tv_nsec) / 1e6; - int pass = rc == OMEGA_GPU_MATMUL_OK && info.parity_verified && e2e_max_rel < 1e-5 + size_t e2e_bad = 0; + double e2e = (rc == OMEGA_GPU_MATMUL_OK || rc == OMEGA_GPU_MATMUL_PARITY_FAIL) ? e2e_max_rel(m, k, n, a, b, c, &e2e_bad) : 0.0; + int pass = rc == OMEGA_GPU_MATMUL_OK && info.parity_verified && e2e < 1e-5 && rc2 == OMEGA_GPU_MATMUL_OK && info2.kernel_cache_hit && repeat_mismatch == 0; - CHECK(pass, "shape %ux%ux%u rc=%s parity=%d max_rel=%g e2e_rel=%g rc2=%s hit=%d repeat_mismatch=%zu", - m, k, n, omega_gpu_matmul_rc_name(rc), info.parity_verified, info.max_rel_err, e2e_max_rel, - omega_gpu_matmul_rc_name(rc2), info2.kernel_cache_hit, repeat_mismatch); - printf("%s %ux%ux%u rc=%s chip_ns=%" PRIu64 " wall_ms=%.1f max_abs=%g max_rel=%g mismatches=%zu e2e_rel=%g slices=%u calls=%u rows_per_call=%u cache_hit2=%d\n", - pass ? "PASS" : "FAIL", m, k, n, omega_gpu_matmul_rc_name(rc), info.elapsed_ns, wall_ms, - info.max_abs_err, info.max_rel_err, info.mismatch_count, e2e_max_rel, info.k_slices, info.chip_calls, info.rows_per_call, info2.kernel_cache_hit); + if (mutant) { + /* the wrong kernel must be caught: PARITY_FAIL from the API oracle and a visible e2e error */ + int caught = rc == OMEGA_GPU_MATMUL_PARITY_FAIL && !info.parity_verified && e2e >= 1e-5; + CHECK(caught, "mutant shape %ux%ux%u NOT caught: rc=%s parity=%d e2e_rel=%g", m, k, n, omega_gpu_matmul_rc_name(rc), info.parity_verified, e2e); + pass = caught; + } else { + CHECK(pass, "shape %ux%ux%u rc=%s parity=%d max_rel=%g e2e_rel=%g rc2=%s hit=%d repeat_mismatch=%zu", + m, k, n, omega_gpu_matmul_rc_name(rc), info.parity_verified, info.max_rel_err, e2e, + omega_gpu_matmul_rc_name(rc2), info2.kernel_cache_hit, repeat_mismatch); + } + printf("%s %ux%ux%u rc=%s chip_ns=%" PRIu64 " call_ms=%.3f wall_ms=%.1f max_abs=%g max_rel=%g mismatches=%zu e2e_rel=%g e2e_bad=%zu grid=%ux%u calls=%u rows_per_call=%u cache_hit2=%d err=\"%s\"\n", + pass ? (mutant ? "KILLED" : "PASS") : (mutant ? "SURVIVED" : "FAIL"), m, k, n, omega_gpu_matmul_rc_name(rc), info.elapsed_ns, info.call_ns / 1e6, wall_ms, + info.max_abs_err, info.max_rel_err, info.mismatch_count, e2e, e2e_bad, info.grid_x, info.grid_y, info.chip_calls, info.rows_per_call, info2.kernel_cache_hit, rc == OMEGA_GPU_MATMUL_CHIP_FAIL ? omega_gpu_matmul_last_error() : ""); if (out) { fprintf(out, "%s{\"m\":%u,\"k\":%u,\"n\":%u,\"rc\":\"%s\",\"pass\":%s,\"chip_elapsed_ns\":%" PRIu64 - ",\"wall_ms\":%.3f,\"max_abs_err\":%g,\"max_rel_err\":%g,\"mismatch_count\":%zu," + ",\"call_ms\":%.3f,\"wall_ms\":%.3f,\"max_abs_err\":%g,\"max_rel_err\":%g,\"mismatch_count\":%zu," "\"parity_verified\":%s,\"completion_marker\":%u,\"repeat_rc\":\"%s\",\"repeat_cache_hit\":%s," - "\"repeat_mismatch\":%zu,\"e2e_max_rel\":%g,\"k_slices\":%u,\"chip_calls\":%u,\"rows_per_call\":%u,\"padded_m\":%u,\"padded_n\":%u,\"target_chip\":\"%s\",\"sm_architecture\":%u}", + "\"repeat_mismatch\":%zu,\"e2e_max_rel\":%g,\"e2e_bad\":%zu,\"grid_x\":%u,\"grid_y\":%u,\"chip_calls\":%u,\"rows_per_call\":%u,\"padded_m\":%u,\"padded_k\":%u,\"padded_n\":%u,\"target_chip\":\"%s\",\"sm_architecture\":%u}", first ? "" : ",", m, k, n, omega_gpu_matmul_rc_name(rc), pass ? "true" : "false", - info.elapsed_ns, wall_ms, info.max_abs_err, info.max_rel_err, info.mismatch_count, + info.elapsed_ns, info.call_ns / 1e6, wall_ms, info.max_abs_err, info.max_rel_err, info.mismatch_count, info.parity_verified ? "true" : "false", info.completion_marker, omega_gpu_matmul_rc_name(rc2), info2.kernel_cache_hit ? "true" : "false", - repeat_mismatch, e2e_max_rel, info.k_slices, info.chip_calls, info.rows_per_call, info.padded_m, info.padded_n, info.target_chip, info.sm_architecture); + repeat_mismatch, e2e, e2e_bad, info.grid_x, info.grid_y, info.chip_calls, info.rows_per_call, info.padded_m, info.padded_k, info.padded_n, info.target_chip, info.sm_architecture); first = 0; } free(a); free(b); free(c); free(c2); + if (omega_gpu_matmul_is_blocked()) { printf("device latched after an uncertain completion; stopping the sweep\n"); break; } } free(copy); if (out) { - fprintf(out, "],\"checks\":%d,\"failed\":%d,\"verdict\":\"%s\"}\n", g_checks, g_failed, - g_failed == 0 ? "OMEGA_GPU_MATMUL_API_PASS" : "OMEGA_GPU_MATMUL_API_FAIL"); + fprintf(out, "],\"blocked\":%s,\"checks\":%d,\"failed\":%d,\"verdict\":\"%s\"}\n", omega_gpu_matmul_is_blocked() ? "true" : "false", g_checks, g_failed, + g_failed == 0 ? (mutant ? "OMEGA_GPU_MATMUL_MUTANT_KILLED" : "OMEGA_GPU_MATMUL_API_PASS") : (mutant ? "OMEGA_GPU_MATMUL_MUTANT_SURVIVED" : "OMEGA_GPU_MATMUL_API_FAIL")); + fclose(out); + } + return 0; +} + +static int cmp_double(const void *x, const void *y) { double a = *(const double *)x, b = *(const double *)y; return a < b ? -1 : a > b; } + +/* Resident path: upload B once, then 100 calls; median wall time per call must be under 5 ms. + * Parity: first and last result against the double reference (0 elements at or beyond 1e-5). */ +static int timing(const char *shapes, const char *out_path) { + FILE *out = out_path ? fopen(out_path, "w") : NULL; + if (out_path && !out) { printf("cannot open %s\n", out_path); return 2; } + if (out) fprintf(out, "{\"schema\":\"OMEGA_GPU_MATMUL_API_TIMING_V1\",\"cta_budget\":%u,\"calls\":100,\"shapes\":[", omega_gpu_matmul_cta_budget()); + char *copy = strdup(shapes); char *save = NULL; int first = 1; + for (char *tok = strtok_r(copy, ";", &save); tok; tok = strtok_r(NULL, ";", &save)) { + unsigned m, k, n; + if (sscanf(tok, "%u,%u,%u", &m, &k, &n) != 3) { printf("bad shape %s\n", tok); continue; } + size_t na = (size_t)m * k, nb = (size_t)k * n, nc = (size_t)m * n; + float *a = malloc(na * sizeof *a), *b = malloc(nb * sizeof *b), *c = malloc(nc * sizeof *c), *c_first = malloc(nc * sizeof *c_first); + uint16_t *ah = malloc(na * sizeof *ah); + if (!a || !b || !c || !c_first || !ah) { printf("out of host memory\n"); return 2; } + uint32_t seed = 0x7111e000u ^ (m << 20) ^ (k << 10) ^ n; + fill(a, na, &seed); fill(b, nb, &seed); + for (size_t i = 0; i < na; i++) ah[i] = omega_fp32_to_bf16(a[i]); + OmegaGpuTensor *t = NULL; + double tu0 = now_ms(); + int urc = omega_gpu_tensor_upload_f32(k, n, b, &t); + double upload_ms = now_ms() - tu0; + CHECK(urc == OMEGA_GPU_MATMUL_OK, "upload %ux%u rc=%s", k, n, omega_gpu_matmul_rc_name(urc)); + double samples[100]; int ok_calls = 0; OmegaGpuMatmulInfo info; memset(&info, 0, sizeof info); + uint64_t chip_ns_sum = 0; size_t repeat_mismatch = 0; + if (urc == OMEGA_GPU_MATMUL_OK) { + for (int i = 0; i < 100; i++) { + for (size_t j = 0; j < nc; j++) c[j] = -12345.0f; + double t0 = now_ms(); + int rc = omega_gpu_matmul_resident_bf16(m, ah, t, c, &info); + samples[i] = now_ms() - t0; + if (rc == OMEGA_GPU_MATMUL_OK) ok_calls++; + chip_ns_sum += info.elapsed_ns; + if (i == 0) memcpy(c_first, c, nc * sizeof *c); + else for (size_t j = 0; j < nc; j++) if (c[j] != c_first[j]) repeat_mismatch++; + if (omega_gpu_matmul_is_blocked()) break; + } + } + qsort(samples, 100, sizeof samples[0], cmp_double); + double median = samples[50], p90 = samples[90], mn = samples[0], mx = samples[99]; + size_t bad_first = 0, bad_last = 0; + double e2e_first = e2e_max_rel(m, k, n, a, b, c_first, &bad_first); + double e2e_last = e2e_max_rel(m, k, n, a, b, c, &bad_last); + int pass = ok_calls == 100 && bad_first == 0 && bad_last == 0 && repeat_mismatch == 0 && median < 5.0; + CHECK(pass, "timing %ux%ux%u ok_calls=%d median_ms=%.3f e2e_first=%g e2e_last=%g bad=%zu/%zu repeat_mismatch=%zu", + m, k, n, ok_calls, median, e2e_first, e2e_last, bad_first, bad_last, repeat_mismatch); + printf("%s timing %ux%ux%u upload_ms=%.1f ok_calls=%d median_ms=%.3f p90_ms=%.3f min_ms=%.3f max_ms=%.3f chip_ns_mean=%" PRIu64 " grid=%ux%u e2e_first=%g e2e_last=%g repeat_mismatch=%zu\n", + pass ? "PASS" : "FAIL", m, k, n, upload_ms, ok_calls, median, p90, mn, mx, ok_calls ? chip_ns_sum / (uint64_t)ok_calls : 0, info.grid_x, info.grid_y, e2e_first, e2e_last, repeat_mismatch); + if (out) { + fprintf(out, "%s{\"m\":%u,\"k\":%u,\"n\":%u,\"pass\":%s,\"upload_ms\":%.3f,\"ok_calls\":%d,\"median_ms\":%.4f,\"p90_ms\":%.4f,\"min_ms\":%.4f,\"max_ms\":%.4f," + "\"chip_ns_mean\":%" PRIu64 ",\"grid_x\":%u,\"grid_y\":%u,\"e2e_first\":%g,\"e2e_last\":%g,\"e2e_bad_first\":%zu,\"e2e_bad_last\":%zu,\"repeat_mismatch\":%zu}", + first ? "" : ",", m, k, n, pass ? "true" : "false", upload_ms, ok_calls, median, p90, mn, mx, + ok_calls ? chip_ns_sum / (uint64_t)ok_calls : 0, info.grid_x, info.grid_y, e2e_first, e2e_last, bad_first, bad_last, repeat_mismatch); + first = 0; + } + omega_gpu_tensor_free(t); + free(a); free(b); free(c); free(c_first); free(ah); + if (omega_gpu_matmul_is_blocked()) break; + } + free(copy); + if (out) { + fprintf(out, "],\"blocked\":%s,\"checks\":%d,\"failed\":%d,\"verdict\":\"%s\"}\n", omega_gpu_matmul_is_blocked() ? "true" : "false", g_checks, g_failed, + g_failed == 0 ? "OMEGA_GPU_MATMUL_TIMING_PASS" : "OMEGA_GPU_MATMUL_TIMING_FAIL"); fclose(out); } return 0; @@ -125,13 +236,23 @@ static int chip_sweep(const char *out_path) { int main(int argc, char **argv) { const char *out_path = NULL; - int host = 0; + int host = 0, mutant = 0, do_timing = 0; for (int i = 1; i < argc; i++) { if (strcmp(argv[i], "--host-only") == 0) host = 1; + else if (strcmp(argv[i], "--mutant") == 0) mutant = 1; + else if (strcmp(argv[i], "--timing") == 0) do_timing = 1; + else if (strcmp(argv[i], "--cta-budget") == 0 && i + 1 < argc) omega_gpu_matmul_set_cta_budget((uint32_t)strtoul(argv[++i], NULL, 10)); else if (strcmp(argv[i], "--out") == 0 && i + 1 < argc) out_path = argv[++i]; } + const char *shapes = getenv("OMEGA_GPU_MATMUL_SHAPES"); + if (shapes && !*shapes) shapes = NULL; + int rc = 0; if (host) host_only(); - else if (chip_sweep(out_path) != 0) return 2; - printf("%s: %d checks, %d failed\n", g_failed ? "FAIL" : "PASS", g_checks, g_failed); + else if (do_timing) rc = timing(shapes ? shapes : TIMING_SHAPES, out_path); + else if (mutant) { omega_gpu_matmul_test_set_mutant(1); rc = chip_sweep(shapes ? shapes : MUTANT_SHAPES, out_path, 1); omega_gpu_matmul_test_set_mutant(0); } + else rc = chip_sweep(shapes ? shapes : DEFAULT_SHAPES, out_path, 0); + if (!omega_gpu_matmul_is_blocked()) omega_gpu_device_close(); + if (rc) return 2; + printf("%s: %d checks, %d failed%s\n", g_failed ? "FAIL" : "PASS", g_checks, g_failed, mutant ? (g_failed ? " (mutant SURVIVED)" : " (mutant killed)") : ""); return g_failed ? 1 : 0; } diff --git a/tools/run_gpu_matmul_api_chip.sh b/tools/run_gpu_matmul_api_chip.sh new file mode 100755 index 000000000..171acc41e --- /dev/null +++ b/tools/run_gpu_matmul_api_chip.sh @@ -0,0 +1,30 @@ +#!/bin/bash +# run_gpu_matmul_api_chip.sh EVIDENCE_DIR [PHYSICS_DIR] +# FB-1 cut 1b chip gate for omega_gpu_matmul_api (run through lanes.sh queue --heavy, never killed). +# 1. parity sweep (cut-1 shapes + Llama shapes), host double reference, rel < 1e-5 +# 2. mutant sweep: wrong kernel (last K step dropped) must be caught on every shape +# 3. resident GEMV timing: 1x2048x8192 and 1x8192x2048, median of 100 calls < 5 ms +# 4. CTA budget experiment (I42): the same sweep subset at 128 and 256 CTAs, informational +# Verdict line last: "GPU_MATMUL_API_CHIP: PASS|FAIL". Steps 1-3 decide, step 4 is recorded only. +set -u +EVID="${1:?evidence dir}"; PHYS="${2:-$HOME/workspace/hive-worktrees/qual-physics-6d7cf0d}" +HERE="$(cd "$(dirname "$0")/.." && pwd)" +mkdir -p "$EVID" +cd "$HERE" || exit 2 +{ + echo "start $(date -u +%FT%TZ) omega=$(git rev-parse HEAD) dirty=$(git status --porcelain | wc -l) physics=$PHYS" + uname -a; nvidia-smi --query-gpu=name,driver_version --format=csv,noheader 2>/dev/null +} > "$EVID/device.txt" +make PHYSICS_DIR="$PHYS" -j10 build/gpu_matmul_api_test > "$EVID/build.log" 2>&1 || { echo "GPU_MATMUL_API_CHIP: FAIL build"; exit 1; } +T=./build/gpu_matmul_api_test +fail=0 +$T --out "$EVID/receipt-sweep.json" 2>&1 | tee "$EVID/sweep.log"; [ "${PIPESTATUS[0]}" = 0 ] || fail=1 +$T --mutant --out "$EVID/receipt-mutant.json" 2>&1 | tee "$EVID/mutant.log"; [ "${PIPESTATUS[0]}" = 0 ] || fail=1 +$T --timing --out "$EVID/receipt-timing.json" 2>&1 | tee "$EVID/timing.log"; [ "${PIPESTATUS[0]}" = 0 ] || fail=1 +for b in 128 256; do + OMEGA_GPU_MATMUL_SHAPES="256,256,256;1,2048,8192;1,2048,128256" $T --cta-budget $b --out "$EVID/receipt-cta$b.json" 2>&1 | tee "$EVID/cta$b.log" + echo "cta budget $b exit ${PIPESTATUS[0]} (informational)" | tee -a "$EVID/cta$b.log" +done +echo "end $(date -u +%FT%TZ)" >> "$EVID/device.txt" +(cd "$EVID" && sha256sum *.json *.log device.txt > SHA256SUMS) +if [ $fail = 0 ]; then echo "GPU_MATMUL_API_CHIP: PASS"; else echo "GPU_MATMUL_API_CHIP: FAIL"; exit 1; fi ```