GLM-OCR / code /tt_glmocr /tt /mk_dec /kernels /md_trisc.cpp
changh95's picture
tt-model push glm-ocr (container)
aa204f5 verified
Raw History Blame Contribute Delete
31.4 kB
// SPDX-License-Identifier: Apache-2.0 // // GLM-OCR decode megakernel (DEC, one decode step), TRISC: all arithmetic. Adapted from this workspace's Qwen3-ASR DEC // (bundles/qwen3-asr tt/mk_dec/kernels/md_trisc.cpp, Apache-2.0), itself from the Qwen3-TTS talker megakernel. // GLM: K loops over the real tiles (DTK, ITK) of the padded partition, no q / k norm (rope tables carry the q scale), // sandwich norms (post_norm: y -> bf16 gather -> rstd -> x += g * y * rstd), untied head, split-K attention with an // (O, m, l) partial per key slot and the merge on the group's slot-0 core. // // Vector layouts (probe tiny_probe.py): a vector is contiguous memory; matmul in0 / out use 1x32 ("tiny") tile views // of it; elementwise / SFPU work uses dense 32x32 views of the same memory (element e = memory element e; vectors // shorter than a tile are zero-padded where a reduction reads them). A tiny matmul result in DST may be combined with // another tiny matmul result or a UNIFORM tile (all elements equal), never with a copy_tile'd tiny tile. // // MM core w, per layer l (the BRISC lands inputs / ships outputs in the same order; the NCRISC streams weights): // norm_send : bf16(x) slice -> CB_XB (the BRISC multicasts it into every core's CB_H) // qkv : rstd = rsqrt(mean(h^2) + eps) from the gathered bf16 h; acc[4] = h @ W'(head w) * rstd; // q / k: RoPE (the q table carries 128^-0.5) -> bf16; v: bf16 -> CB_QO // oproj : y = o @ Wo'[:, slice]; post_norm: bf16(y) gathered (CB_YG), x += g_psa * y * rstd(y) // norm_send, gateup: f = SiLU(h2 @ Wg' * rstd2) * (h2 @ Wu' * rstd2) -> CB_FS // down : y = f @ Wd'[:, slice]; post_norm with g_pm // final : logits slice = (h @ Wh') * rstd -> CB_LS (Wh' = diag(g_final) lm_head^T columns of core w) // ATT core (g, s), per layer: scores of both q heads over the slot's key blocks (K streamed), m / exp / l (fp32), // P V (V streamed) -> the partial (O, mz, lz) in CB_PRO / CB_PRM / CB_PRL; slots s > 0 hand it to the BRISC (sent to // slot 0's CB_MRG); slot 0 merges every active slot's partial -> o = sum w_s O_s / sum w_s l_s -> CB_QO (the BRISC // sends it into every MM core's CB_O). // Matmuls HiFi4, fp32 DST (8 tiles, full sync). #include <cstdint> #include "api/compute/compute_kernel_api.h" #include "api/compute/eltwise_binary.h" #include "api/compute/eltwise_binary_sfpu.h" #include "api/compute/bcast.h" #include "api/compute/matmul.h" #include "api/compute/reduce.h" #include "api/compute/tile_move_copy.h" #include "api/compute/eltwise_unary/exp.h" #include "api/compute/eltwise_unary/recip.h" #include "api/compute/eltwise_unary/rsqrt.h" #include "api/compute/eltwise_unary/binop_with_scalar.h" #include "api/compute/binary_max_min.h" #include "api/compute/reconfig_data_format.h" #include "api/compute/compute_kernel_hw_startup.h" #include "md_defs.hpp" using namespace mtx; #define NOINL __attribute__((noinline, noclone)) // progress word (debug: the dbg dump shows where a stalled TRISC waits): W_STEP = layer * 16 + phase (UNPACK thread) ALWI volatile uint32_t* tsync_ptr(uint32_t w) { const auto& iface = get_local_cb_interface(mtx::CB_SYNC); return reinterpret_cast<volatile uint32_t*>(((iface.fifo_limit - iface.fifo_size) << 4) + w * mtx::SYNC_STRIDE); } #define TSTEP(v) UNPACK((*tsync_ptr(mtx::W_STEP) = (v))) namespace { constexpr uint32_t DT = MT_DT; // DP / 32: tiles of the gathered D-vector (partition width) constexpr uint32_t DTK = MT_DTK; // D / 32: real K tiles constexpr uint32_t IT = MT_IT; // IP / 32: tiles of the gathered SwiGLU vector constexpr uint32_t ITK = MT_ITK; // I / 32: real K tiles of down constexpr uint32_t XS = MT_XS; // residual column tiles per MM core constexpr uint32_t FS = MT_FS; // SwiGLU column tiles per MM core constexpr uint32_t NHD = MT_NHD; // dense 32x32 tiles of the D-vector constexpr uint32_t PT_A = MT_PT_A; // packet tiles of the rings constexpr uint32_t PT_M = MT_PT_M; constexpr uint32_t PT_H = MT_PT_H; constexpr MathFidelity FID = MathFidelity::HiFi4; #ifndef MT_MMBLK #define MT_MMBLK 0 #endif // weight matmuls (bf16 activations x bf16 / bfp8 weights) and the bf16 x bf16 attention matmuls: MT_WFID (2 / 4) constexpr MathFidelity WFID = MT_WFID == 2 ? MathFidelity::HiFi2 : (MT_WFID == 3 ? MathFidelity::HiFi3 : MathFidelity::HiFi4); // full-capacity page counts of the fixed-layout tiny views (CB total / page) constexpr uint32_t CAP_ACC = T32 / TINY32; // 32 constexpr uint32_t CAP_QOT = T16 / TINY16; // 32 constexpr uint32_t CAP_S = 32768 / TINY32; // 256 (2 heads x 4 dense tiles) constexpr uint32_t CAP_SD = 32768 / T32; // 8 constexpr uint32_t CAP_P = 16384 / T16; // 8 constexpr uint32_t CAP_PT = 16384 / TINY16; // 256 constexpr uint32_t CAP_FS = MT_FS_CAP; // CB_FS pages constexpr uint32_t CAP_MRG = MT_CAP_MRG; // CB_MRG pages (ring A memory / T32) bool g_nc = false; // F_NOCOMPUTE: CB protocol only struct Me { uint32_t role, w, hk, nl, eps, inv_d, inv_hd, flags, neg; uint32_t p, nb, done, nohead, stop; uint32_t slot, attk, my, sact, last; // ATT: key slot, slots, own blocks, active slots, owns the last block }; Me me; ALWI void acq() { if (!g_nc) { tile_regs_acquire(); } } ALWI void com() { if (!g_nc) { tile_regs_commit(); } } ALWI void wt() { if (!g_nc) { tile_regs_wait(); } } ALWI void rel() { if (!g_nc) { tile_regs_release(); } } // ---------------------------------------------------------------- LLK wrappers (full operand reconfig: the tile // shapes change between tiny and 32x32 views) template <MathFidelity F> ALWI void mm_init_t(uint32_t in0, uint32_t in1, uint32_t transpose = 0) { if (g_nc) { return; } reconfig_full_operand(in1, in0); // SrcA <- in1, SrcB <- in0 MATH((llk_math_matmul_init<F, MM_THROTTLE>(in0, in1, transpose))); UNPACK((llk_unpack_AB_matmul_init(in0, in1, transpose))); } template <MathFidelity F> ALWI void mm_t(uint32_t in0, uint32_t in1, uint32_t t0, uint32_t t1, uint32_t dst) { if (g_nc) { return; } UNPACK((llk_unpack_AB_matmul(in0, in1, t0, t1))); MATH((llk_math_matmul<F, MM_THROTTLE>(dst))); } // HiFi4: every matmul with an fp32 operand (reductions over ONES, scalar broadcasts) ALWI void mm_init_f(uint32_t in0, uint32_t in1, uint32_t transpose = 0) { mm_init_t<FID>(in0, in1, transpose); } ALWI void mm_f(uint32_t in0, uint32_t in1, uint32_t t0, uint32_t t1, uint32_t dst) { mm_t<FID>(in0, in1, t0, t1, dst); } NOINL void load(uint32_t cb, uint32_t tile, uint32_t dst) { if (g_nc) { return; } reconfig_full_operand_srca(cb); copy_init(cb); copy_tile(cb, tile, dst); } NOINL void fmul(uint32_t a, uint32_t b, uint32_t o) { if (g_nc) { return; } mul_binary_tile_init(); mul_binary_tile(a, b, o); } NOINL void fadd(uint32_t a, uint32_t b, uint32_t o) { if (g_nc) { return; } add_binary_tile_init(); add_binary_tile(a, b, o); } NOINL void fsub(uint32_t a, uint32_t b, uint32_t o) { if (g_nc) { return; } sub_binary_tile_init(); sub_binary_tile(a, b, o); } NOINL void fmax(uint32_t a, uint32_t b, uint32_t o) { if (g_nc) { return; } binary_max_tile_init(); binary_max_tile(a, b, o); } NOINL void fscale(uint32_t a, uint32_t bits) { if (g_nc) { return; } binop_with_scalar_tile_init(); mul_unary_tile(a, bits); } NOINL void faddc(uint32_t a, uint32_t bits) { if (g_nc) { return; } binop_with_scalar_tile_init(); add_unary_tile(a, bits); } NOINL void frsqrt(uint32_t a) { if (g_nc) { return; } rsqrt_tile_init(); rsqrt_tile(a); } NOINL void fexp(uint32_t a) { if (g_nc) { return; } exp_tile_init<false>(); exp_tile<false>(a); } NOINL void frecip(uint32_t a) { if (g_nc) { return; } recip_tile_init(); recip_tile(a); } NOINL void fsilu(uint32_t a) { if (g_nc) { return; } silu_tile_init(); silu_tile(a); } NOINL void pack_to(uint32_t dst, uint32_t cb, uint32_t idx) { if (g_nc) { return; } pack_reconfig_data_format<true>(cb); pack_tile<true>(dst, cb, idx); } // fixed-layout views: full-capacity cycles keep every view at its base address ALWI void vreserve(uint32_t cb, uint32_t cap) { cb_reserve_back(cb, cap); } ALWI void vpush(uint32_t cb, uint32_t cap) { cb_push_back(cb, cap); } ALWI void vwait(uint32_t cb, uint32_t cap) { cb_wait_front(cb, cap); } ALWI void vpop(uint32_t cb, uint32_t cap) { cb_pop_front(cb, cap); } // the pack thread wrote view a; make view b (same memory) readable: pop a, push b (no data movement) // the pack thread wrote view a; give view b (same memory) to a data-movement consumer ALWI void vgive(uint32_t a, uint32_t cap_a, uint32_t b, uint32_t cap_b) { cb_wait_front(a, cap_a); cb_pop_front(a, cap_a); cb_reserve_back(b, cap_b); cb_push_back(b, cap_b); } ALWI void vhand(uint32_t a, uint32_t cap_a, uint32_t b, uint32_t cap_b) { cb_wait_front(a, cap_a); cb_pop_front(a, cap_a); cb_reserve_back(b, cap_b); cb_push_back(b, cap_b); cb_wait_front(b, cap_b); } // weight ring consumer: pages of PT tiles uint32_t wsa_pages = 0; // pages of ring A popped so far (debug stops) struct WS { uint32_t cb, pt, t; ALWI uint32_t next() { if (t == 0) { cb_wait_front(cb, pt); } return t; } ALWI void done() { if (++t == pt) { cb_pop_front(cb, pt); t = 0; if (cb == CB_WA) { ++wsa_pages; } } } ALWI void adv(uint32_t n) { // n tiles of one aligned group (t + n <= pt) t += n; if (t == pt) { cb_pop_front(cb, pt); t = 0; if (cb == CB_WA) { ++wsa_pages; } } } }; WS wsa{CB_WA, PT_A, 0}, wsm{CB_WM, PT_M, 0}, wsh{CB_WH, PT_H, 0}; // DST[dst0 + c] += sum_k in0[k] @ W(c, k) for c < nc (weights column-major sticks: column c, then k) NOINL void mm_cols(uint32_t in0, WS& ws, uint32_t kt, uint32_t nc, uint32_t dst0) { mm_init_t<WFID>(in0, ws.cb); for (uint32_t c = 0; c < nc; ++c) { for (uint32_t k = 0; k < kt; ++k) { const uint32_t w = ws.next(); mm_t<WFID>(in0, ws.cb, k, w, dst0 + c); ws.done(); } } } // MT_MMBLK (arena layout 2): weights k-major in groups of nc columns (for every k the nc tiles of the nc output // columns, contiguous; groups never straddle a packet or the ring end); one block matmul per k (in0 tile k unpacked // once, ct_dim = nc in1 tiles streamed) -> DST[dst0 .. dst0 + nc - 1] #if MT_MMBLK NOINL void mm_blk(uint32_t in0, WS& s, uint32_t kt, uint32_t nc, uint32_t dst0) { if (!g_nc) { reconfig_full_operand(s.cb, in0); MATH((llk_math_matmul_init<WFID, MM_THROTTLE>(in0, s.cb, 0, nc, 1))); UNPACK((llk_unpack_AB_matmul_init(in0, s.cb, 0, nc, 1, 1))); } for (uint32_t k = 0; k < kt; ++k) { const uint32_t w = s.next(); if (!g_nc) { UNPACK((llk_unpack_AB_matmul(in0, s.cb, k, w, nc, 1, 1))); MATH((llk_math_matmul<WFID, MM_THROTTLE>(dst0, nc, 1))); } s.adv(nc); } } #endif #if MT_MMBLK #define MM_W(in0, s, kt, nc, dst0) mm_blk(in0, s, kt, nc, dst0) #else #define MM_W(in0, s, kt, nc, dst0) mm_cols(in0, s, kt, nc, dst0) #endif // uniform total of the dense fp32 tile in CB_T0 (pushed, 1 page): DST[dst] = sum(T0) in every element. // T0 @ ONES (row sums in every column) -> T1; ONES @ T1 (column sums). Pops T0. NOINL void total_t0(uint32_t dst_after) { vwait(CB_T0, 1); vreserve(CB_T1, 1); acq(); mm_init_f(CB_T0, CB_CONST); mm_f(CB_T0, CB_CONST, 0, C_ONES, 0); com(); wt(); pack_to(0, CB_T1, 0); rel(); vpush(CB_T1, 1); vpop(CB_T0, 1); vwait(CB_T1, 1); (void)dst_after; } // DST[dst] = ONES @ T1 (needs the section acquired); pops T1 after the caller's commit ALWI void total_t1(uint32_t dst) { mm_init_f(CB_CONST, CB_T1); mm_f(CB_CONST, CB_T1, C_ONES, 0, dst); } // rstd of a gathered vector (dense bf16 view, NHD tiles; padded columns are zero): -> CB_RS (uniform, 1 page pushed) NOINL void rstd_of(uint32_t cbd) { vreserve(CB_T0, 1); acq(); load(cbd, 0, 0); fmul(0, 0, 0); for (uint32_t t = 1; t < NHD; ++t) { load(cbd, t, 1); fmul(1, 1, 1); fadd(0, 1, 0); } com(); wt(); pack_to(0, CB_T0, 0); rel(); vpush(CB_T0, 1); total_t0(0); vreserve(CB_RS, 1); acq(); total_t1(0); fscale(0, me.inv_d); faddc(0, me.eps); frsqrt(0); com(); wt(); pack_to(0, CB_RS, 0); rel(); vpush(CB_RS, 1); vpop(CB_T1, 1); vwait(CB_RS, 1); } ALWI void rstd_h() { rstd_of(CB_HD); } // ================================================================ MM core NOINL void norm_send() { vwait(CB_X, 1); vreserve(CB_XB, 1); acq(); load(CB_X, 0, 0); com(); wt(); pack_to(0, CB_XB, 0); rel(); vpush(CB_XB, 1); } NOINL void qkv() { vwait(CB_H, DT); vwait(CB_HD, NHD); rstd_h(); acq(); MM_W(CB_H, wsa, DTK, HD_T, 0); load(CB_RS, 0, 4); for (uint32_t c = 0; c < HD_T; ++c) { fmul(c, 4, c); } com(); vpop(CB_RS, 1); if (me.hk == HK_V) { // v: bf16 as is vreserve(CB_QOT, CAP_QOT); wt(); for (uint32_t c = 0; c < HD_T; ++c) { pack_to(c, CB_QOT, c); } rel(); vpush(CB_QOT, CAP_QOT); vgive(CB_QOT, CAP_QOT, CB_QO, 1); // the BRISC sends and pops CB_QO vpop(CB_H, DT); vpop(CB_HD, NHD); return; } // q / k: the accumulators in natural (CB_ACC) and half-swapped (CB_ACS: tiles 2, 3, 0, 1) order vreserve(CB_ACC, CAP_ACC); vreserve(CB_ACS, CAP_ACC); wt(); for (uint32_t c = 0; c < HD_T; ++c) { pack_to(c, CB_ACC, c); pack_to(c, CB_ACS, c ^ 2); } rel(); vpush(CB_ACC, CAP_ACC); vpush(CB_ACS, CAP_ACC); vpop(CB_H, DT); vpop(CB_HD, NHD); vhand(CB_ACC, CAP_ACC, CB_ACCD, 1); vhand(CB_ACS, CAP_ACC, CB_ACSD, 1); // rope (half-split layout): acc * cos + swap(acc) * sinS (the q tables carry 128^-0.5) vreserve(CB_QO, 1); acq(); load(CB_ACCD, 0, 0); load(CB_TAB, 0, 2); fmul(0, 2, 0); load(CB_ACSD, 0, 3); load(CB_TAB, 1, 2); fmul(3, 2, 3); fadd(0, 3, 0); com(); wt(); pack_to(0, CB_QO, 0); // bf16, dense: the first 128 values are the head rel(); vpush(CB_QO, 1); vpop(CB_ACCD, 1); vpop(CB_ACSD, 1); } // sandwich norm: DST 0 .. XS-1 = the y slice (acquired, not committed): bf16(y) -> CB_XB (the BRISC gathers it into // every MM core's CB_YG); rstd(y) from the gathered vector; x += g_k * y * rstd (g_k = CB_G tile k: 0 psa, 1 pm) NOINL void post_norm(uint32_t k) { com(); vreserve(CB_ACC, CAP_ACC); wt(); for (uint32_t c = 0; c < XS; ++c) { pack_to(c, CB_ACC, c); } rel(); vpush(CB_ACC, CAP_ACC); vhand(CB_ACC, CAP_ACC, CB_ACCD, 1); vreserve(CB_XB, 1); acq(); load(CB_ACCD, 0, 0); com(); wt(); pack_to(0, CB_XB, 0); rel(); vpush(CB_XB, 1); vwait(CB_YG, DT); vwait(CB_YGD, NHD); rstd_of(CB_YGD); if (k == 0) { cb_wait_front(CB_G, 2); } acq(); load(CB_ACCD, 0, 0); load(CB_RS, 0, 1); fmul(0, 1, 0); load(CB_G, k, 1); fmul(0, 1, 0); load(CB_X, 0, 1); fadd(0, 1, 0); com(); vpop(CB_X, 1); vpop(CB_ACCD, 1); vpop(CB_RS, 1); vreserve(CB_X, 1); wt(); pack_to(0, CB_X, 0); rel(); vpush(CB_X, 1); vpop(CB_YG, DT); vpop(CB_YGD, NHD); if (k == 1) { cb_pop_front(CB_G, 2); } } NOINL void oproj() { vwait(CB_O, AT); acq(); MM_W(CB_O, wsa, AT, XS, 0); vpop(CB_O, AT); post_norm(0); } NOINL void gateup() { vwait(CB_H, DT); vwait(CB_HD, NHD); rstd_h(); vreserve(CB_FS, CAP_FS); for (uint32_t f0 = 0; f0 < FS; f0 += 2) { const uint32_t nb = FS - f0 < 2 ? FS - f0 : 2; acq(); #if MT_MMBLK mm_blk(CB_H, wsm, DTK, 2 * nb, 0); // per k: gate f0, up f0 (, gate f0 + 1, up f0 + 1) -> DST 0 .. 2 nb - 1 #else for (uint32_t j = 0; j < nb; ++j) { mm_cols(CB_H, wsm, DTK, 2, 2 * j); // gate -> 2j, up -> 2j + 1 } #endif load(CB_RS, 0, 7); for (uint32_t j = 0; j < nb; ++j) { fmul(2 * j, 7, 2 * j); fmul(2 * j + 1, 7, 2 * j + 1); fsilu(2 * j); fmul(2 * j, 2 * j + 1, 2 * j); } com(); wt(); for (uint32_t j = 0; j < nb; ++j) { pack_to(2 * j, CB_FS, f0 + j); } rel(); } vpush(CB_FS, CAP_FS); vpop(CB_RS, 1); vpop(CB_H, DT); vpop(CB_HD, NHD); } NOINL void down() { vwait(CB_F, IT); acq(); MM_W(CB_F, wsm, ITK, XS, 0); vpop(CB_F, IT); post_norm(1); } NOINL void final_out(bool full) { vwait(CB_H, DT); vwait(CB_HD, NHD); if (me.flags & F_DUMP) { // debug: the raw residual (no head) vreserve(CB_HS, 1); acq(); load(CB_X, 0, 0); com(); wt(); pack_to(0, CB_HS, 0); rel(); vpush(CB_HS, 1); vpop(CB_H, DT); vpop(CB_HD, NHD); return; } if (full) { rstd_h(); vreserve(CB_LS, MT_HC); for (uint32_t c0 = 0; c0 < MT_HC; c0 += 7) { const uint32_t nc = MT_HC - c0 < 7 ? MT_HC - c0 : 7; acq(); mm_cols(CB_H, wsh, DTK, nc, 0); load(CB_RS, 0, 7); for (uint32_t c = 0; c < nc; ++c) { fmul(c, 7, c); } com(); wt(); for (uint32_t c = 0; c < nc; ++c) { pack_to(c, CB_LS, c0 + c); } rel(); } vpush(CB_LS, MT_HC); vpop(CB_RS, 1); } vpop(CB_H, DT); vpop(CB_HD, NHD); } // consume every weight page the NCRISC still streams in this run (debug stops) void drain_rings() { const uint32_t na = me.nl * (MT_A_TILES / PT_A), nm = me.nl * (MT_M_TILES / PT_M); uint32_t a = wsa.t ? 1 : 0, m = wsm.t ? 1 : 0; if (wsa.t) { cb_pop_front(CB_WA, PT_A); } if (wsm.t) { cb_pop_front(CB_WM, PT_M); } // pages already consumed by qkv: count them from the tile counter of the A stream a += wsa_pages; while (a < na || m < nm) { if (a < na) { cb_wait_front(CB_WA, PT_A); cb_pop_front(CB_WA, PT_A); ++a; } if (m < nm) { cb_wait_front(CB_WM, PT_M); cb_pop_front(CB_WM, PT_M); ++m; } } } void mm_stream_only() { const uint32_t na = me.nl * (MT_A_TILES / PT_A), nm = me.nl * (MT_M_TILES / PT_M); const bool full = me.nl == N_LAYERS_FULL && !(me.flags & F_DUMP) && !me.nohead; const uint32_t nh = full ? MT_H_TILES / PT_H : 0; uint32_t a = 0, m = 0; while (a < na || m < nm) { // pop whichever ring is ahead (the NCRISC fills both) if (a < na) { cb_wait_front(CB_WA, PT_A); cb_pop_front(CB_WA, PT_A); ++a; } if (m < nm) { cb_wait_front(CB_WM, PT_M); cb_pop_front(CB_WM, PT_M); ++m; } } for (uint32_t i = 0; i < nh; ++i) { cb_wait_front(CB_WH, PT_H); cb_pop_front(CB_WH, PT_H); } } void mm_main() { if (me.flags & F_ARM_STREAM) { mm_stream_only(); return; } cb_wait_front(CB_CONST, N_CONST); const bool qk = me.hk != HK_V; if (qk) { cb_wait_front(CB_TAB, 2); } // x0 (landed by the BRISC in CB_X0) -> CB_X: CB_X is then produced by the packer only vwait(CB_X0, 1); vreserve(CB_X, 1); acq(); load(CB_X0, 0, 0); com(); wt(); pack_to(0, CB_X, 0); rel(); vpush(CB_X, 1); vpop(CB_X0, 1); for (uint32_t l = 0; l < me.nl; ++l) { TSTEP(l * 16 + 1); norm_send(); TSTEP(l * 16 + 2); if (me.stop == 1) { // debug stop: the first norm gather landed; drain the weight rings vwait(CB_H, DT); vwait(CB_HD, NHD); drain_rings(); return; } qkv(); TSTEP(l * 16 + 3); if (me.stop == 2) { // debug stop: the attention outputs landed vwait(CB_O, AT); drain_rings(); return; } oproj(); TSTEP(l * 16 + 4); norm_send(); TSTEP(l * 16 + 5); gateup(); TSTEP(l * 16 + 6); down(); } TSTEP(0xF00); norm_send(); final_out(me.nl == N_LAYERS_FULL && !(me.flags & F_DUMP) && !me.nohead); } // ================================================================ ATT core (kv group g, key slot s) // scores of both heads for the slot's key blocks jl < me.my -> CB_S tiny tiles h * 128 + jl (K streamed); softmax // statistics m_h, l_h; O_h = P_h V (unnormalized); the partial (O, mz, lz) -> CB_PRO / CB_PRM / CB_PRL NOINL void att_partial() { const uint32_t nb = me.my; const uint32_t st = (nb + 31) / 32; // dense score tiles per head const uint32_t tl = (nb - 1) / 32; // the dense tile holding the last block vwait(CB_Q, 2 * HD_T); // full-capacity cycle (fixed layout): heads 0, 1 // the tail of the last dense score tile of each head = NEG (stale entries beyond the last block) vreserve(CB_SD, CAP_SD); acq(); load(CB_CONST, C_ONES, 0); fscale(0, me.neg); com(); wt(); pack_to(0, CB_SD, tl); pack_to(0, CB_SD, 4 + tl); rel(); vpush(CB_SD, CAP_SD); vwait(CB_SD, CAP_SD); vpop(CB_SD, CAP_SD); vreserve(CB_S, CAP_S); for (uint32_t j0 = 0; j0 < nb; j0 += 4) { const uint32_t n = nb - j0 < 4 ? nb - j0 : 4; acq(); for (uint32_t jj = 0; jj < n; ++jj) { const uint32_t j = j0 + jj; cb_wait_front(CB_KR, HD_T); mm_init_t<WFID>(CB_Q, CB_KR, 1); for (uint32_t h = 0; h < 2; ++h) { for (uint32_t d = 0; d < HD_T; ++d) { mm_t<WFID>(CB_Q, CB_KR, h * HD_T + d, d, 2 * jj + h); } } cb_pop_front(CB_KR, HD_T); if (me.last && j + 1 == nb) { // causal mask of the global last block: += e0 @ MASK(p % 32) mm_init_f(CB_CT, CB_MSK); for (uint32_t h = 0; h < 2; ++h) { mm_f(CB_CT, CB_MSK, 32 * C_E0, 0, 2 * jj + h); } } } com(); wt(); for (uint32_t jj = 0; jj < n; ++jj) { for (uint32_t h = 0; h < 2; ++h) { pack_to(2 * jj + h, CB_S, h * 128 + j0 + jj); } } rel(); } vpush(CB_S, CAP_S); vhand(CB_S, CAP_S, CB_SD, CAP_SD); // m_h = max(S_h) (elementwise over the dense tiles, then a scalar reduce, broadcast to a uniform tile) vreserve(CB_T0, 2); acq(); for (uint32_t h = 0; h < 2; ++h) { load(CB_SD, h * 4, h); for (uint32_t t = 1; t < st; ++t) { load(CB_SD, h * 4 + t, 2); fmax(h, 2, h); } } com(); wt(); for (uint32_t h = 0; h < 2; ++h) { pack_to(h, CB_T0, h); } rel(); vpush(CB_T0, 2); vwait(CB_T0, 2); vreserve(CB_T1, 2); acq(); if (!g_nc) { reconfig_full_operand(CB_T0, CB_CONST); reduce_init<PoolType::MAX, ReduceDim::REDUCE_SCALAR>(CB_T0, CB_CONST, CB_T1); for (uint32_t h = 0; h < 2; ++h) { reduce_tile<PoolType::MAX, ReduceDim::REDUCE_SCALAR>(CB_T0, CB_CONST, h, C_ONES, h); } reduce_uninit(CB_T0); } com(); wt(); for (uint32_t h = 0; h < 2; ++h) { pack_to(h, CB_T1, h); } rel(); vpush(CB_T1, 2); vpop(CB_T0, 2); vwait(CB_T1, 2); vreserve(CB_T0, 2); acq(); if (!g_nc) { // m_h uniform: ONES * T1[h][0][0] reconfig_full_operand(CB_CONST, CB_T1); mul_bcast_scalar_init(CB_CONST, CB_T1); for (uint32_t h = 0; h < 2; ++h) { mul_tiles_bcast_scalar(CB_CONST, CB_T1, C_ONES, h, h); } } com(); wt(); for (uint32_t h = 0; h < 2; ++h) { pack_to(h, CB_T0, h); } rel(); vpush(CB_T0, 2); vpop(CB_T1, 2); vwait(CB_T0, 2); // mz = m_0 M01 + m_1 M10 -> CB_PRM vreserve(CB_PRM, 1); acq(); load(CB_T0, 0, 0); load(CB_CONST, C_M01, 1); fmul(0, 1, 0); load(CB_T0, 1, 2); load(CB_CONST, C_M10, 1); fmul(2, 1, 2); fadd(0, 2, 0); com(); wt(); pack_to(0, CB_PRM, 0); rel(); vpush(CB_PRM, 1); constexpr uint32_t EXN = 3; // score tiles per head per DST section (after the 2 m tiles) for (uint32_t t0 = 0; t0 < st; t0 += EXN) { const uint32_t n = st - t0 < EXN ? st - t0 : EXN; acq(); for (uint32_t h = 0; h < 2; ++h) { load(CB_T0, h, h); } for (uint32_t h = 0; h < 2; ++h) { for (uint32_t j = 0; j < n; ++j) { const uint32_t d = 2 + h * n + j; load(CB_SD, h * 4 + t0 + j, d); fsub(d, h, d); fexp(d); } } com(); wt(); for (uint32_t h = 0; h < 2; ++h) { for (uint32_t j = 0; j < n; ++j) { pack_to(2 + h * n + j, CB_P, h * 4 + t0 + j); } } rel(); } vpop(CB_T0, 2); vpop(CB_SD, CAP_SD); vpush(CB_P, CAP_P); vwait(CB_P, CAP_P); // l_h = sum(P_h) from the bf16 P: P_t @ ONES summed over t -> T1 tile h; ONES @ T1; lz = l_0 M01 + l_1 M10 vreserve(CB_T1, 2); acq(); mm_init_f(CB_P, CB_CONST); for (uint32_t h = 0; h < 2; ++h) { for (uint32_t t = 0; t < st; ++t) { mm_f(CB_P, CB_CONST, h * 4 + t, C_ONES, h); } } com(); wt(); for (uint32_t h = 0; h < 2; ++h) { pack_to(h, CB_T1, h); } rel(); vpush(CB_T1, 2); vwait(CB_T1, 2); vreserve(CB_PRL, 1); acq(); mm_init_f(CB_CONST, CB_T1); for (uint32_t h = 0; h < 2; ++h) { mm_f(CB_CONST, CB_T1, C_ONES, h, h); } load(CB_CONST, C_M01, 2); fmul(0, 2, 0); load(CB_CONST, C_M10, 2); fmul(1, 2, 1); fadd(0, 1, 0); com(); wt(); pack_to(0, CB_PRL, 0); rel(); vpop(CB_T1, 2); vpush(CB_PRL, 1); vhand(CB_P, CAP_P, CB_PT, CAP_PT); // O_h = P_h V (V streamed): DST 0..3 head 0, 4..7 head 1 (unnormalized) acq(); for (uint32_t j = 0; j < nb; ++j) { cb_wait_front(CB_VR, HD_T); mm_init_t<WFID>(CB_PT, CB_VR); for (uint32_t h = 0; h < 2; ++h) { for (uint32_t d = 0; d < HD_T; ++d) { mm_t<WFID>(CB_PT, CB_VR, h * 128 + j, d, h * HD_T + d); } } cb_pop_front(CB_VR, HD_T); } com(); vreserve(CB_ACC, CAP_ACC); wt(); for (uint32_t c = 0; c < 2 * HD_T; ++c) { pack_to(c, CB_ACC, c); } rel(); vpush(CB_ACC, CAP_ACC); vpop(CB_PT, CAP_PT); vhand(CB_ACC, CAP_ACC, CB_ACCD, 1); vreserve(CB_PRO, 1); acq(); load(CB_ACCD, 0, 0); com(); wt(); pack_to(0, CB_PRO, 0); rel(); vpush(CB_PRO, 1); vpop(CB_ACCD, 1); vpop(CB_Q, 2 * HD_T); } // slot 0: o = sum_s w_s O_s / sum_s w_s lz_s, w_s = exp(mz_s - M), M = max_s mz_s (elementwise on the two-valued // tiles; the own partial in CB_PRO / PRM / PRL, slot s's at CB_MRG tiles 3 (s - 1) + {0, 1, 2}) -> CB_QO (bf16) NOINL void att_merge() { vwait(CB_PRO, 1); vwait(CB_PRM, 1); vwait(CB_PRL, 1); if (me.sact > 1) { vwait(CB_MRG, CAP_MRG); } vreserve(CB_T0, 1); acq(); load(CB_PRM, 0, 0); for (uint32_t s = 1; s < me.sact; ++s) { load(CB_MRG, 3 * (s - 1) + 1, 1); fmax(0, 1, 0); } com(); wt(); pack_to(0, CB_T0, 0); rel(); vpush(CB_T0, 1); vwait(CB_T0, 1); vreserve(CB_QO, 1); acq(); load(CB_T0, 0, 3); // M load(CB_PRM, 0, 2); fsub(2, 3, 2); fexp(2); // w_0 load(CB_PRO, 0, 0); fmul(0, 2, 0); // O = w_0 O_0 load(CB_PRL, 0, 1); fmul(1, 2, 1); // L = w_0 l_0 for (uint32_t s = 1; s < me.sact; ++s) { const uint32_t b = 3 * (s - 1); load(CB_MRG, b + 1, 2); fsub(2, 3, 2); fexp(2); load(CB_MRG, b, 4); fmul(4, 2, 4); fadd(0, 4, 0); load(CB_MRG, b + 2, 4); fmul(4, 2, 4); fadd(1, 4, 1); } frecip(1); fmul(0, 1, 0); com(); wt(); pack_to(0, CB_QO, 0); // dense bf16: o of head 0 (256 B) then head 1 (256 B); the BRISC sends them rel(); vpush(CB_QO, 1); vpop(CB_T0, 1); vpop(CB_PRO, 1); vpop(CB_PRM, 1); vpop(CB_PRL, 1); if (me.sact > 1) { vpop(CB_MRG, CAP_MRG); } } void att_main() { if (me.stop == 1) { return; } cb_wait_front(CB_CONST, N_CONST); cb_wait_front(CB_MSK, 1); if (me.slot * ((me.nb + me.attk - 1) / me.attk) >= me.nb) { return; // inactive key slot (fewer blocks than slots) } for (uint32_t l = 0; l < me.nl; ++l) { TSTEP(l * 16 + 1); att_partial(); if (me.slot == 0) { att_merge(); } if (me.stop == 2) { return; } } TSTEP(0xF00); } } // namespace void kernel_main() { me.role = get_arg_val<uint32_t>(A_ROLE); me.w = get_arg_val<uint32_t>(A_W); me.hk = get_arg_val<uint32_t>(A_HK); me.nl = get_common_arg_val<uint32_t>(K_NL); me.eps = get_common_arg_val<uint32_t>(K_EPS); me.inv_d = get_common_arg_val<uint32_t>(K_INV_D); me.inv_hd = get_common_arg_val<uint32_t>(K_INV_HD); me.flags = get_common_arg_val<uint32_t>(K_FLAGS); me.neg = get_common_arg_val<uint32_t>(K_NEG); me.stop = get_common_arg_val<uint32_t>(K_STOP); if (me.role != R_MM && me.role != R_ATT) { return; } // the go word ((p + 1) | NOHEAD | DONE) from the BRISC through CB_GO (CBs reset at launch; read_tile_value // hands the UNPACK thread's read to MATH and PACK) cb_wait_front(CB_GO, 1); const uint32_t g = read_tile_value(CB_GO, 0, 0); cb_pop_front(CB_GO, 1); if (g == 0 || (g & GO_DONE)) { return; // done (or the boot never completed: the DM RISCs abort) } me.p = (g & GO_P) - 1; me.nohead = (g & GO_NOHEAD) != 0; me.nb = me.p / 32 + 1; me.slot = get_arg_val<uint32_t>(A_SLOT); me.attk = get_common_arg_val<uint32_t>(K_ATTK); { const uint32_t nbl = (me.nb + me.attk - 1) / me.attk; const uint32_t j0 = me.slot * nbl; const uint32_t j1 = j0 + nbl < me.nb ? j0 + nbl : me.nb; me.my = j0 < me.nb ? j1 - j0 : 0; me.last = j0 < me.nb && j1 == me.nb; me.sact = (me.nb + nbl - 1) / nbl; } g_nc = (me.flags & F_NOCOMPUTE) != 0; if (!g_nc) { compute_kernel_hw_startup<SrcOrder::Reverse>(CB_H, CB_WA, CB_ACC); } if (me.role == R_MM) { mm_main(); } else if (!(me.flags & F_ARM_STREAM)) { att_main(); } }
// SPDX-License-Identifier: Apache-2.0
//
// GLM-OCR decode megakernel (DEC, one decode step), TRISC: all arithmetic. Adapted from this workspace's Qwen3-ASR DEC
// (bundles/qwen3-asr tt/mk_dec/kernels/md_trisc.cpp, Apache-2.0), itself from the Qwen3-TTS talker megakernel.
// GLM: K loops over the real tiles (DTK, ITK) of the padded partition, no q / k norm (rope tables carry the q scale),
// sandwich norms (post_norm: y -> bf16 gather -> rstd -> x += g * y * rstd), untied head, split-K attention with an
// (O, m, l) partial per key slot and the merge on the group's slot-0 core.
//
// Vector layouts (probe tiny_probe.py): a vector is contiguous memory; matmul in0 / out use 1x32 ("tiny") tile views
// of it; elementwise / SFPU work uses dense 32x32 views of the same memory (element e = memory element e; vectors
// shorter than a tile are zero-padded where a reduction reads them). A tiny matmul result in DST may be combined with
// another tiny matmul result or a UNIFORM tile (all elements equal), never with a copy_tile'd tiny tile.
//
// MM core w, per layer l (the BRISC lands inputs / ships outputs in the same order; the NCRISC streams weights):
// norm_send : bf16(x) slice -> CB_XB (the BRISC multicasts it into every core's CB_H)
// qkv : rstd = rsqrt(mean(h^2) + eps) from the gathered bf16 h; acc[4] = h @ W'(head w) * rstd;
// q / k: RoPE (the q table carries 128^-0.5) -> bf16; v: bf16 -> CB_QO
// oproj : y = o @ Wo'[:, slice]; post_norm: bf16(y) gathered (CB_YG), x += g_psa * y * rstd(y)
// norm_send, gateup: f = SiLU(h2 @ Wg' * rstd2) * (h2 @ Wu' * rstd2) -> CB_FS
// down : y = f @ Wd'[:, slice]; post_norm with g_pm
// final : logits slice = (h @ Wh') * rstd -> CB_LS (Wh' = diag(g_final) lm_head^T columns of core w)
// ATT core (g, s), per layer: scores of both q heads over the slot's key blocks (K streamed), m / exp / l (fp32),
// P V (V streamed) -> the partial (O, mz, lz) in CB_PRO / CB_PRM / CB_PRL; slots s > 0 hand it to the BRISC (sent to
// slot 0's CB_MRG); slot 0 merges every active slot's partial -> o = sum w_s O_s / sum w_s l_s -> CB_QO (the BRISC
// sends it into every MM core's CB_O).
// Matmuls HiFi4, fp32 DST (8 tiles, full sync).
#include <cstdint>
#include "api/compute/compute_kernel_api.h"
#include "api/compute/eltwise_binary.h"
#include "api/compute/eltwise_binary_sfpu.h"
#include "api/compute/bcast.h"
#include "api/compute/matmul.h"
#include "api/compute/reduce.h"
#include "api/compute/tile_move_copy.h"
#include "api/compute/eltwise_unary/exp.h"
#include "api/compute/eltwise_unary/recip.h"
#include "api/compute/eltwise_unary/rsqrt.h"
#include "api/compute/eltwise_unary/binop_with_scalar.h"
#include "api/compute/binary_max_min.h"
#include "api/compute/reconfig_data_format.h"
#include "api/compute/compute_kernel_hw_startup.h"
#include "md_defs.hpp"
using namespace mtx;
#define NOINL __attribute__((noinline, noclone))
// progress word (debug: the dbg dump shows where a stalled TRISC waits): W_STEP = layer * 16 + phase (UNPACK thread)
ALWI volatile uint32_t* tsync_ptr(uint32_t w) {
const auto& iface = get_local_cb_interface(mtx::CB_SYNC);
return reinterpret_cast<volatile uint32_t*>(((iface.fifo_limit - iface.fifo_size) << 4) + w * mtx::SYNC_STRIDE);
}
#define TSTEP(v) UNPACK((*tsync_ptr(mtx::W_STEP) = (v)))
namespace {
constexpr uint32_t DT = MT_DT; // DP / 32: tiles of the gathered D-vector (partition width)
constexpr uint32_t DTK = MT_DTK; // D / 32: real K tiles
constexpr uint32_t IT = MT_IT; // IP / 32: tiles of the gathered SwiGLU vector
constexpr uint32_t ITK = MT_ITK; // I / 32: real K tiles of down
constexpr uint32_t XS = MT_XS; // residual column tiles per MM core
constexpr uint32_t FS = MT_FS; // SwiGLU column tiles per MM core
constexpr uint32_t NHD = MT_NHD; // dense 32x32 tiles of the D-vector
constexpr uint32_t PT_A = MT_PT_A; // packet tiles of the rings
constexpr uint32_t PT_M = MT_PT_M;
constexpr uint32_t PT_H = MT_PT_H;
constexpr MathFidelity FID = MathFidelity::HiFi4;
#ifndef MT_MMBLK
#define MT_MMBLK 0
#endif
// weight matmuls (bf16 activations x bf16 / bfp8 weights) and the bf16 x bf16 attention matmuls: MT_WFID (2 / 4)
constexpr MathFidelity WFID = MT_WFID == 2 ? MathFidelity::HiFi2 : (MT_WFID == 3 ? MathFidelity::HiFi3 : MathFidelity::HiFi4);
// full-capacity page counts of the fixed-layout tiny views (CB total / page)
constexpr uint32_t CAP_ACC = T32 / TINY32; // 32
constexpr uint32_t CAP_QOT = T16 / TINY16; // 32
constexpr uint32_t CAP_S = 32768 / TINY32; // 256 (2 heads x 4 dense tiles)
constexpr uint32_t CAP_SD = 32768 / T32; // 8
constexpr uint32_t CAP_P = 16384 / T16; // 8
constexpr uint32_t CAP_PT = 16384 / TINY16; // 256
constexpr uint32_t CAP_FS = MT_FS_CAP; // CB_FS pages
constexpr uint32_t CAP_MRG = MT_CAP_MRG; // CB_MRG pages (ring A memory / T32)
bool g_nc = false; // F_NOCOMPUTE: CB protocol only
struct Me {
uint32_t role, w, hk, nl, eps, inv_d, inv_hd, flags, neg;
uint32_t p, nb, done, nohead, stop;
uint32_t slot, attk, my, sact, last; // ATT: key slot, slots, own blocks, active slots, owns the last block
};
Me me;
ALWI void acq() { if (!g_nc) { tile_regs_acquire(); } }
ALWI void com() { if (!g_nc) { tile_regs_commit(); } }
ALWI void wt() { if (!g_nc) { tile_regs_wait(); } }
ALWI void rel() { if (!g_nc) { tile_regs_release(); } }
// ---------------------------------------------------------------- LLK wrappers (full operand reconfig: the tile
// shapes change between tiny and 32x32 views)
template <MathFidelity F>