"""Single-kernel megakernel for the Kimi-Linear W4A16 hybrid decode unit. The entire per-token forward -- every int4 dequant-GEMV, the KDA short conv and gated-delta recurrent update, the MLA latent-cache attention, the MoE router and expert FFNs, both RMSNorms and the residual adds -- runs inside ONE Triton kernel launch (`_megakernel`). All blocks rendezvous on global barriers (cooperative style; the grid fits in one resident wave on this GPU) to exchange intermediate activations, exactly like a CUDA cooperative-groups grid.sync(). The int4 unpack + per-group asymmetric dequant is fused directly into every GEMV: packed bytes stream from HBM once and dequantize in registers, so weight traffic stays at the 4-bit size and the bf16 expansion is never materialized. Buffer names match reference.py, so the reference weights load directly. """ from __future__ import annotations import torch import torch.nn as nn import triton import triton.language as tl EPS = tl.constexpr(1.0e-6) GROUP = 128 NACT = 8 # Grid = 1 block per SM on the 188-SM RTX PRO 6000. Must stay <= one resident # wave (all blocks co-resident) so the grid-wide barriers can never deadlock. GRID = 188 NUM_WARPS = 4 # scratch X layout (fp32 unless noted) # XL_RMS holds 5 slots: slots 0..3 are the per-block attn-norm / running moe-norm # used by the KDA blocks (block i attn norm at slot i, its moe norm at slot i+1); # slot 4 is the MLA block's moe norm (the MLA attn norm reuses slot 3 transiently). XL_RMS = tl.constexpr(0) # [5, 2304] rmsnorm output per block XL_QKV = tl.constexpr(XL_RMS + 5 * 2304) # [4, 3*4096] raw then post-conv q,k,v XL_G = tl.constexpr(XL_QKV + 4 * 3 * 4096) # [4, 4096] gate projection XL_BETA = tl.constexpr(XL_G + 4 * 4096) # [4, 32] beta XL_MQ = tl.constexpr(XL_BETA + 4 * 32) # [6144] MLA q_proj raw XL_KVA = tl.constexpr(XL_MQ + 6144) # [576] MLA kv_a raw (c_kv | k_rope) XL_MID = tl.constexpr(XL_KVA + 576) # [4, 9, 1024] expert FFN hidden XL_MOE = tl.constexpr(XL_MID + 4 * 9 * 1024) # [4, 2304] MoE output XL_TOPK = tl.constexpr(XL_MOE + 4 * 2304) # [4, 8] expert ids (int32) XL_TOPW = tl.constexpr(XL_TOPK + 4 * 8) # [4, 8] expert weights XL_QR = tl.constexpr(XL_TOPW + 4 * 8) # [32, 64] MLA rope-rotated q (interleaved) XL_DOWN = tl.constexpr(XL_QR + 32 * 64) # [4, 9, 2304] per-expert down outputs XL_OATT = tl.constexpr(XL_DOWN + 4 * 9 * 2304) # [4096] MLA attention output XL_GATE = tl.constexpr(XL_OATT + 4096) # [4, 9, 1024] MoE expert gate scratch XL_OPJ = tl.constexpr(XL_GATE + 4 * 9 * 1024) # [4, 2304] attention o_proj output XL_RES = tl.constexpr(XL_OPJ + 4 * 2304) # [4, 2304] running residual per block XLEN = XL_RES + 4 * 2304 @triton.jit def _bar(ARR, slot, GRID_C: tl.constexpr): """Grid-wide barrier (sense-reversing, safe for repeated use). ARR[0] = arrival counter, ARR[1] = generation (sense) counter. A block arrives (increment ARR[0]); the last block to arrive flips the generation (ARR[1]) and resets ARR[0]. Other blocks spin until the generation changes. This is correct for any number of barriers in one launch because the generation only advances when all blocks have arrived. """ gen = tl.atomic_add(ARR + 1, 0, sem="acquire", scope="gpu") old = tl.atomic_add(ARR, 1, sem="acq_rel", scope="gpu") if old == GRID_C - 1: # last to arrive: reset arrival counter and flip generation tl.atomic_xchg(ARR, 0, sem="acq_rel", scope="gpu") tl.atomic_add(ARR + 1, 1, sem="release", scope="gpu") else: while tl.atomic_add(ARR + 1, 0, sem="acquire", scope="gpu") == gen: pass @triton.jit def _softplus(x): return tl.where(x > 15.0, x, tl.log(1.0 + tl.exp(x))) # --------------------------------------------------------------------------- # # Fused int4 dequant-GEMV: Y[n0:n0+BN] = sum_k X[xbase+k] * dequant(W)[k, n0:n0+BN]. # # WQ is [K//2, N] uint8: byte row i holds K-rows 2i (low nibble) and 2i+1 # (high nibble) along the input dimension. S/Z are [K//G, N] bf16 (per-group # asymmetric, group G along K). The int4 weight streams from HBM once and # dequantizes in registers; the bf16 weight is never materialized. # --------------------------------------------------------------------------- # @triton.jit def _gemv(WQ, SC, ZO, X, Y, xbase, n0, K2: tl.constexpr, N: tl.constexpr, G: tl.constexpr, BN: tl.constexpr, KCH: tl.constexpr): offs_n = n0 + tl.arange(0, BN) acc = tl.zeros([BN], dtype=tl.float32) for k0 in range(0, K2, KCH): rows = k0 + tl.arange(0, KCH) # byte rows wq = tl.load(WQ + rows[:, None] * N + offs_n[None, :]) # [KCH, BN] u8 lo = (wq & 0xF).to(tl.float32) hi = (wq >> 4).to(tl.float32) xs = tl.load(X + xbase + 2 * k0 + tl.arange(0, 2 * KCH)) x2 = tl.reshape(xs, [KCH, 2]) xe, xo = tl.split(x2) gi = (2 * k0) // G # group index s = tl.load(SC + gi * N + offs_n).to(tl.float32) z = tl.load(ZO + gi * N + offs_n).to(tl.float32) acc += tl.sum(xe[:, None] * ((lo - z[None, :]) * s[None, :]) + xo[:, None] * ((hi - z[None, :]) * s[None, :]), axis=0) tl.store(Y + offs_n, acc) # --------------------------------------------------------------------------- # # Device functions: one per phase. Triton inlines these; keeping them separate # keeps each compilation unit small. # --------------------------------------------------------------------------- # @triton.jit def _rmsnorm_phase(X, NORMS, res_off, rms_off, norm_idx, pid, D: tl.constexpr, DP: tl.constexpr): """RMSNorm the residual at X[res_off] into X[rms_off] (block 0 only).""" if pid == 0: offd = tl.arange(0, DP) dm = offd < D x = tl.load(X + res_off + offd, mask=dm, other=0.0).to(tl.float32) r = tl.math.rsqrt(tl.sum(x * x, axis=0) / D + EPS) nw = tl.load(NORMS + norm_idx * D + offd, mask=dm, other=0.0).to(tl.float32) tl.store(X + rms_off + offd, x * r * nw, mask=dm) @triton.jit def _kda_proj_phase(X, KDA_WQ, KDA_S, KDA_Z, BETA_W, pid, blk, GRID_C: tl.constexpr, D: tl.constexpr, C: tl.constexpr, H: tl.constexpr, G: tl.constexpr, BN: tl.constexpr, KCH: tl.constexpr): """q,k,v,g projections [D -> C] and beta [D -> H] for one KDA block.""" for w in range(pid, (4 * C) // BN, GRID_C): which = w // (C // BN) col = w % (C // BN) # q,k,v -> XL_QKV[blk, which]; g -> XL_G[blk] if which < 3: ybase = XL_QKV + blk * 3 * C + which * C else: ybase = XL_G + blk * C _gemv(KDA_WQ + (which * 3 + blk) * ((D // 2) * C), KDA_S + (which * 3 + blk) * ((D // G) * C), KDA_Z + (which * 3 + blk) * ((D // G) * C), X, X + ybase, XL_RMS + blk * D, col * BN, D // 2, C, G, BN, KCH) if pid == 0: accb = tl.zeros([H], dtype=tl.float32) for k0 in range(0, D, BN): xs = tl.load(X + XL_RMS + blk * D + k0 + tl.arange(0, BN)) bw = tl.load(BETA_W + (blk * H + tl.arange(0, H))[:, None] * D + k0 + tl.arange(0, BN)[None, :]).to(tl.float32) accb += tl.sum(xs[None, :] * bw, axis=1) tl.store(X + XL_BETA + blk * H + tl.arange(0, H), tl.sigmoid(accb)) @triton.jit def _kda_conv_phase(X, CQ, CK, CV, CONV_W, pid, blk, GRID_C: tl.constexpr, C: tl.constexpr, CH: tl.constexpr): """Short causal depthwise conv (kernel 4) on q,k,v.""" for c0 in range(pid * CH, C, GRID_C * CH): offs_c = c0 + tl.arange(0, CH) base = blk * 3 * C # q p0 = tl.load(CQ + base + 0 * C + offs_c).to(tl.float32) p1 = tl.load(CQ + base + 1 * C + offs_c).to(tl.float32) p2 = tl.load(CQ + base + 2 * C + offs_c).to(tl.float32) v0 = tl.load(X + XL_QKV + base + 0 * C + offs_c).to(tl.float32) w0 = tl.load(CONV_W + (blk * 3 + 0) * C * 4 + offs_c * 4 + 0).to(tl.float32) w1 = tl.load(CONV_W + (blk * 3 + 0) * C * 4 + offs_c * 4 + 1).to(tl.float32) w2 = tl.load(CONV_W + (blk * 3 + 0) * C * 4 + offs_c * 4 + 2).to(tl.float32) w3 = tl.load(CONV_W + (blk * 3 + 0) * C * 4 + offs_c * 4 + 3).to(tl.float32) o = p0 * w0 + p1 * w1 + p2 * w2 + v0 * w3 o = o * tl.sigmoid(o) tl.store(CQ + base + 0 * C + offs_c, p1) tl.store(CQ + base + 1 * C + offs_c, p2) tl.store(CQ + base + 2 * C + offs_c, v0) tl.store(X + XL_QKV + base + 0 * C + offs_c, o) # k p0 = tl.load(CK + base + 0 * C + offs_c).to(tl.float32) p1 = tl.load(CK + base + 1 * C + offs_c).to(tl.float32) p2 = tl.load(CK + base + 2 * C + offs_c).to(tl.float32) v0 = tl.load(X + XL_QKV + base + 1 * C + offs_c).to(tl.float32) w0 = tl.load(CONV_W + (blk * 3 + 1) * C * 4 + offs_c * 4 + 0).to(tl.float32) w1 = tl.load(CONV_W + (blk * 3 + 1) * C * 4 + offs_c * 4 + 1).to(tl.float32) w2 = tl.load(CONV_W + (blk * 3 + 1) * C * 4 + offs_c * 4 + 2).to(tl.float32) w3 = tl.load(CONV_W + (blk * 3 + 1) * C * 4 + offs_c * 4 + 3).to(tl.float32) o = p0 * w0 + p1 * w1 + p2 * w2 + v0 * w3 o = o * tl.sigmoid(o) tl.store(CK + base + 0 * C + offs_c, p1) tl.store(CK + base + 1 * C + offs_c, p2) tl.store(CK + base + 2 * C + offs_c, v0) tl.store(X + XL_QKV + base + 1 * C + offs_c, o) # v p0 = tl.load(CV + base + 0 * C + offs_c).to(tl.float32) p1 = tl.load(CV + base + 1 * C + offs_c).to(tl.float32) p2 = tl.load(CV + base + 2 * C + offs_c).to(tl.float32) v0 = tl.load(X + XL_QKV + base + 2 * C + offs_c).to(tl.float32) w0 = tl.load(CONV_W + (blk * 3 + 2) * C * 4 + offs_c * 4 + 0).to(tl.float32) w1 = tl.load(CONV_W + (blk * 3 + 2) * C * 4 + offs_c * 4 + 1).to(tl.float32) w2 = tl.load(CONV_W + (blk * 3 + 2) * C * 4 + offs_c * 4 + 2).to(tl.float32) w3 = tl.load(CONV_W + (blk * 3 + 2) * C * 4 + offs_c * 4 + 3).to(tl.float32) o = p0 * w0 + p1 * w1 + p2 * w2 + v0 * w3 o = o * tl.sigmoid(o) tl.store(CV + base + 0 * C + offs_c, p1) tl.store(CV + base + 1 * C + offs_c, p2) tl.store(CV + base + 2 * C + offs_c, v0) tl.store(X + XL_QKV + base + 2 * C + offs_c, o) @triton.jit def _kda_recur_phase(X, S0, S1, S2, pid, blk, GRID_C: tl.constexpr, C: tl.constexpr, H: tl.constexpr, DK: tl.constexpr): """Gated-delta linear attention recurrence, one head per block.""" h = pid % H if pid < H: offs_k = tl.arange(0, DK) base = blk * 3 * C graw = tl.load(X + XL_G + blk * C + h * DK + offs_k).to(tl.float32) g = -_softplus(graw) beta = tl.load(X + XL_BETA + blk * H + h) qv = tl.load(X + XL_QKV + base + h * DK + offs_k) * (DK ** -0.5) kv = tl.load(X + XL_QKV + base + C + h * DK + offs_k) vv = tl.load(X + XL_QKV + base + 2 * C + h * DK + offs_k) if blk == 0: Sb = S0 + h * DK * DK elif blk == 1: Sb = S1 + h * DK * DK else: Sb = S2 + h * DK * DK ge = tl.exp(g) S = tl.load(Sb + offs_k[:, None] * DK + offs_k[None, :]) S = S * ge[:, None] pred = tl.sum(S * kv[:, None], axis=0) S = S + beta * kv[:, None] * (vv - pred)[None, :] o = tl.sum(S * qv[:, None], axis=0) tl.store(Sb + offs_k[:, None] * DK + offs_k[None, :], S) tl.store(X + XL_QKV + base + h * DK + offs_k, o) @triton.jit def _router_phase(X, ROUTER_W, pid, blk, GRID_C: tl.constexpr, D: tl.constexpr, NE: tl.constexpr, NA: tl.constexpr, RS: tl.constexpr, BN: tl.constexpr): """Router softmax + top-8 selection.""" if pid == 0: acc = tl.zeros([NE], dtype=tl.float32) for k0 in range(0, D, BN): xs = tl.load(X + XL_RMS + (blk + 1) * D + k0 + tl.arange(0, BN)) rw = tl.load(ROUTER_W + (blk * NE + tl.arange(0, NE))[:, None] * D + k0 + tl.arange(0, BN)[None, :]).to(tl.float32) acc += tl.sum(xs[None, :] * rw, axis=1) m = tl.max(acc, axis=0) p = tl.exp(acc - m) p = p / tl.sum(p, axis=0) topv = tl.zeros([NA], dtype=tl.float32) topi = tl.zeros([NA], dtype=tl.int32) pp = p for j in tl.static_range(NA): idx = tl.argmax(pp, axis=0) val = tl.max(pp, axis=0) topv = tl.where(tl.arange(0, NA) == j, val, topv) topi = tl.where(tl.arange(0, NA) == j, idx.to(tl.int32), topi) pp = tl.where(tl.arange(0, NE) == idx, -1.0, pp) tl.store(X + XL_TOPK + blk * 8 + tl.arange(0, NA), topi) tl.store(X + XL_TOPW + blk * 8 + tl.arange(0, NA), topv / (tl.sum(topv, axis=0) + 1e-9) * RS) @triton.jit def _moe_gateup_phase(X, GWQ, GSC, GZZ, UWQ, USC, UZZ, pid, blk, GRID_C: tl.constexpr, D: tl.constexpr, MI: tl.constexpr, G: tl.constexpr, BN: tl.constexpr, KCH: tl.constexpr): """9 expert gate/up GEMVs [D -> MI].""" for w in range(pid, 9 * (MI // BN), GRID_C): e = w // (MI // BN) col = w % (MI // BN) eid = tl.load(X + XL_TOPK + blk * 8 + e).to(tl.int32) issh = e == 8 slot = tl.where(issh, 64, eid).to(tl.int32) _gemv(GWQ + (blk * 65 + slot) * ((D // 2) * MI), GSC + (blk * 65 + slot) * ((D // G) * MI), GZZ + (blk * 65 + slot) * ((D // G) * MI), X, X + XL_GATE + (blk * 9 + e) * MI, XL_RMS + (blk + 1) * D, col * BN, D // 2, MI, G, BN, KCH) _gemv(UWQ + (blk * 65 + slot) * ((D // 2) * MI), USC + (blk * 65 + slot) * ((D // G) * MI), UZZ + (blk * 65 + slot) * ((D // G) * MI), X, X + XL_MID + (blk * 9 + e) * MI, XL_RMS + (blk + 1) * D, col * BN, D // 2, MI, G, BN, KCH) @triton.jit def _moe_silu_phase(X, pid, blk, GRID_C: tl.constexpr, D: tl.constexpr, MI: tl.constexpr, BN: tl.constexpr): for w in range(pid, 9 * (MI // BN), GRID_C): e = w // (MI // BN) col = w % (MI // BN) offs = (blk * 9 + e) * MI + col * BN + tl.arange(0, BN) g = tl.load(X + XL_GATE + offs) u = tl.load(X + XL_MID + offs) tl.store(X + XL_MID + offs, g * tl.sigmoid(g) * u) @triton.jit def _moe_down_phase(X, DWQ, DSC, DZZ, pid, blk, GRID_C: tl.constexpr, D: tl.constexpr, MI: tl.constexpr, G: tl.constexpr, BN: tl.constexpr, KCH: tl.constexpr): for w in range(pid, 9 * (D // BN), GRID_C): e = w // (D // BN) col = w % (D // BN) eid = tl.load(X + XL_TOPK + blk * 8 + e).to(tl.int32) slot = tl.where(e == 8, 64, eid).to(tl.int32) _gemv(DWQ + (blk * 65 + slot) * ((MI // 2) * D), DSC + (blk * 65 + slot) * ((MI // G) * D), DZZ + (blk * 65 + slot) * ((MI // G) * D), X, X + XL_DOWN + (blk * 9 + e) * D, XL_MID + (blk * 9 + e) * MI, col * BN, MI // 2, D, G, BN, KCH) @triton.jit def _moe_sum_phase(X, pid, blk, D: tl.constexpr, NA: tl.constexpr, DP: tl.constexpr): if pid == 0: offd = tl.arange(0, DP) dm = offd < D acc = tl.zeros([DP], dtype=tl.float32) for j in tl.static_range(NA): wgt = tl.load(X + XL_TOPW + blk * 8 + j) # down outputs are stored by top-k position j (0..7), shared at 8 acc += wgt * tl.load(X + XL_DOWN + (blk * 9 + j) * D + offd, mask=dm, other=0.0) acc += tl.load(X + XL_DOWN + (blk * 9 + 8) * D + offd, mask=dm, other=0.0) tl.store(X + XL_MOE + blk * D + offd, acc, mask=dm) @triton.jit def _moe_block(X, GWQ, GSC, GZZ, UWQ, USC, UZZ, DWQ, DSC, DZZ, ROUTER_W, ARR, pid, blk, slot, GRID_C: tl.constexpr, D: tl.constexpr, MI: tl.constexpr, NE: tl.constexpr, NA: tl.constexpr, RS: tl.constexpr, G: tl.constexpr, BN: tl.constexpr, KCH: tl.constexpr, DP: tl.constexpr): """Full MoE for one block: router -> experts -> sum -> residual.""" _router_phase(X, ROUTER_W, pid, blk, GRID_C, D, NE, NA, RS, BN) _bar(ARR, slot, GRID_C); slot = 1 - slot _moe_gateup_phase(X, GWQ, GSC, GZZ, UWQ, USC, UZZ, pid, blk, GRID_C, D, MI, G, BN, KCH) _bar(ARR, slot, GRID_C); slot = 1 - slot _moe_silu_phase(X, pid, blk, GRID_C, D, MI, BN) _bar(ARR, slot, GRID_C); slot = 1 - slot _moe_down_phase(X, DWQ, DSC, DZZ, pid, blk, GRID_C, D, MI, G, BN, KCH) _bar(ARR, slot, GRID_C); slot = 1 - slot _moe_sum_phase(X, pid, blk, D, NA, DP) _bar(ARR, slot, GRID_C); slot = 1 - slot if pid == 0: offd = tl.arange(0, DP) dm = offd < D h2 = tl.load(X + XL_RES + blk * D + offd, mask=dm, other=0.0) \ + tl.load(X + XL_MOE + blk * D + offd, mask=dm, other=0.0) tl.store(X + XL_RES + (blk + 1) * D + offd, h2, mask=dm) _bar(ARR, slot, GRID_C); slot = 1 - slot return slot # --------------------------------------------------------------------------- # # The megakernel. One launch computes the whole decode step for the 4-block # pattern [K, K, K, M]. Phases are separated by grid barriers; each phase is # a device function so the compiled kernel stays a manageable size. # --------------------------------------------------------------------------- # @triton.jit def _megakernel( HIN, HOUT, X, S0, S1, S2, CQ, CK, CV, CKV, KROPE, KVROW, PMAX, PSUM, PV, ARR, POS, KDA_WQ, KDA_S, KDA_Z, MLQ_WQ, MLQ_S, MLQ_Z, MKA_WQ, MKA_S, MKA_Z, MKB_WQ, MKB_S, MKB_Z, MLO_WQ, MLO_S, MLO_Z, GWQ, GSC, GZZ, UWQ, USC, UZZ, DWQ, DSC, DZZ, ROUTER_W, BETA_W, CONV_W, NORMS, GRID_C: tl.constexpr, D: tl.constexpr, C: tl.constexpr, H: tl.constexpr, DK: tl.constexpr, KVL: tl.constexpr, QN: tl.constexpr, QR: tl.constexpr, VH: tl.constexpr, MI: tl.constexpr, NE: tl.constexpr, NA: tl.constexpr, RS: tl.constexpr, THETA: tl.constexpr, G: tl.constexpr, NCHUNK: tl.constexpr, ): pid = tl.program_id(0) slot = 0 BN: tl.constexpr = 64 KCH: tl.constexpr = 64 KVBO: tl.constexpr = H * (QN + VH) # kv_b output width (8192) CH: tl.constexpr = 16 DP: tl.constexpr = 4096 # next pow2 >= D (2304) offd = tl.arange(0, DP) dm = offd < D # ---- block 0 input residual ---- if pid == 0: x = tl.load(HIN + offd, mask=dm, other=0.0).to(tl.float32) tl.store(X + XL_RES + offd, x, mask=dm) _bar(ARR, slot, GRID_C); slot = 1 - slot # ---- KDA blocks 0..2 ---- for blk in range(0, 3): _rmsnorm_phase(X, NORMS, XL_RES + blk * D, XL_RMS + blk * D, 2 * blk, pid, D, DP) _bar(ARR, slot, GRID_C); slot = 1 - slot _kda_proj_phase(X, KDA_WQ, KDA_S, KDA_Z, BETA_W, pid, blk, GRID_C, D, C, H, G, BN, KCH) _bar(ARR, slot, GRID_C); slot = 1 - slot _kda_conv_phase(X, CQ, CK, CV, CONV_W, pid, blk, GRID_C, C, CH) _bar(ARR, slot, GRID_C); slot = 1 - slot _kda_recur_phase(X, S0, S1, S2, pid, blk, GRID_C, C, H, DK) _bar(ARR, slot, GRID_C); slot = 1 - slot # o_proj [C -> D] for w in range(pid, D // BN, GRID_C): _gemv(KDA_WQ + (4 * 3 + blk) * ((D // 2) * C), KDA_S + (4 * 3 + blk) * ((D // G) * C), KDA_Z + (4 * 3 + blk) * ((D // G) * C), X, X + XL_OPJ + blk * D, XL_QKV + blk * 3 * C, w * BN, C // 2, D, G, BN, KCH) _bar(ARR, slot, GRID_C); slot = 1 - slot # residual + moe rmsnorm if pid == 0: hres = tl.load(X + XL_RES + blk * D + offd, mask=dm, other=0.0) \ + tl.load(X + XL_OPJ + blk * D + offd, mask=dm, other=0.0) tl.store(X + XL_RES + blk * D + offd, hres, mask=dm) r = tl.math.rsqrt(tl.sum(hres * hres, axis=0) / D + EPS) nw = tl.load(NORMS + (2 * blk + 1) * D + offd, mask=dm, other=0.0).to(tl.float32) tl.store(X + XL_RMS + (blk + 1) * D + offd, hres * r * nw, mask=dm) _bar(ARR, slot, GRID_C); slot = 1 - slot slot = _moe_block(X, GWQ, GSC, GZZ, UWQ, USC, UZZ, DWQ, DSC, DZZ, ROUTER_W, ARR, pid, blk, slot, GRID_C, D, MI, NE, NA, RS, G, BN, KCH, DP) # ---- block 3 (MLA) ---- _rmsnorm_phase(X, NORMS, XL_RES + 3 * D, XL_RMS + 3 * D, 6, pid, D, DP) _bar(ARR, slot, GRID_C); slot = 1 - slot # q_proj [D -> 6144], kv_a [D -> 576] for w in range(pid, 6144 // BN, GRID_C): _gemv(MLQ_WQ, MLQ_S, MLQ_Z, X, X + XL_MQ, XL_RMS + 3 * D, w * BN, D // 2, 6144, G, BN, KCH) if pid < (576 + BN - 1) // BN: col = pid _gemv(MKA_WQ, MKA_S, MKA_Z, X, X + XL_KVA, XL_RMS + 3 * D, col * BN, D // 2, 576, G, BN, KCH) _bar(ARR, slot, GRID_C); slot = 1 - slot # rope q_rope per head (interleaved); rope + write the new cache row. h = pid % H QHP: tl.constexpr = QR // 2 # number of rope frequency pairs if pid < H: offs_qr = tl.arange(0, QHP) inv = tl.exp2(-2.0 * offs_qr.to(tl.float32) / QR * tl.log2(THETA)) ang = POS.to(tl.float32) * inv c = tl.cos(ang) s = tl.sin(ang) qe = tl.load(X + XL_MQ + h * (QN + QR) + QN + offs_qr * 2).to(tl.float32) qo = tl.load(X + XL_MQ + h * (QN + QR) + QN + offs_qr * 2 + 1).to(tl.float32) tl.store(X + XL_QR + h * QR + offs_qr * 2, qe * c - qo * s) tl.store(X + XL_QR + h * QR + offs_qr * 2 + 1, qo * c + qe * s) if pid == 0: offs_kr = tl.arange(0, QHP) inv = tl.exp2(-2.0 * offs_kr.to(tl.float32) / QR * tl.log2(THETA)) ang = POS.to(tl.float32) * inv c = tl.cos(ang) s = tl.sin(ang) ke = tl.load(X + XL_KVA + KVL + offs_kr * 2).to(tl.float32) ko = tl.load(X + XL_KVA + KVL + offs_kr * 2 + 1).to(tl.float32) tl.store(KROPE + POS * QR + offs_kr * 2, (ke * c - ko * s).to(tl.bfloat16)) tl.store(KROPE + POS * QR + offs_kr * 2 + 1, (ko * c + ke * s).to(tl.bfloat16)) offs_kv = tl.arange(0, KVL) cv = tl.load(X + XL_KVA + offs_kv) tl.store(CKV + POS * KVL + offs_kv, cv.to(tl.bfloat16)) _bar(ARR, slot, GRID_C); slot = 1 - slot # kv_b for the newly appended row only: [512] x [512, KVBO] -> KVROW[POS]. # The kv_b output of the pre-filled cache rows is precomputed at ingest. NT: tl.constexpr = KVBO // BN for w in range(pid, NT, GRID_C): offs_n = w * BN + tl.arange(0, BN) acc = tl.zeros([BN], dtype=tl.float32) for k0 in range(0, KVL // 2, KCH): rows = k0 + tl.arange(0, KCH) wq = tl.load(MKB_WQ + rows[:, None] * KVBO + offs_n[None, :]) lo = (wq & 0xF).to(tl.float32) hi = (wq >> 4).to(tl.float32) xs = tl.load(CKV + POS * KVL + 2 * k0 + tl.arange(0, 2 * KCH)).to(tl.float32) x2 = tl.reshape(xs, [KCH, 2]) xe, xo = tl.split(x2) gi = (2 * k0) // G s = tl.load(MKB_S + gi * KVBO + offs_n).to(tl.float32) z = tl.load(MKB_Z + gi * KVBO + offs_n).to(tl.float32) acc += tl.sum(xe[:, None] * ((lo - z[None, :]) * s[None, :]) + xo[:, None] * ((hi - z[None, :]) * s[None, :]), axis=0) tl.store(KVROW + POS * KVBO + offs_n, acc.to(tl.bfloat16)) _bar(ARR, slot, GRID_C); slot = 1 - slot # attention, chunk-parallel: each (head, chunk) work item computes a partial # online-softmax state (chunk max, chunk sum-exp, chunk weighted-v) over its # slice of the cache; a second phase reduces the NCHUNK partials per head. # This spreads the O(context) scan over all GRID_C blocks instead of H. NROWS = POS + 1 CH = (NROWS + NCHUNK - 1) // NCHUNK # rows per chunk (runtime, sizes to context) offs_n = tl.arange(0, QN) offs_r = tl.arange(0, QR) offs_v = tl.arange(0, VH) scale = (QN + QR) ** -0.5 for item in range(pid, H * NCHUNK, GRID_C): h = item // NCHUNK c = item % NCHUNK l0 = c * CH l1 = tl.minimum(l0 + CH, NROWS) qn = tl.load(X + XL_MQ + h * (QN + QR) + offs_n).to(tl.float32) qr = tl.load(X + XL_QR + h * QR + offs_r).to(tl.float32) # single-pass online softmax over tiles of BR rows for memory-level # parallelism: running max m, running sum-exp lsum, weighted-v o. BR: tl.constexpr = 64 offs_b = tl.arange(0, BR) m = -3.0e38 lsum = 0.0 o = tl.zeros([VH], dtype=tl.float32) for l in range(l0, l1, BR): lm = tl.minimum(l + offs_b, l1 - 1) # clamp tail to last row valid = (l + offs_b) < l1 kn = tl.load(KVROW + lm[:, None] * KVBO + h * (QN + VH) + offs_n[None, :]).to(tl.float32) kr = tl.load(KROPE + lm[:, None] * QR + offs_r[None, :]).to(tl.float32) sc = tl.sum(qn[None, :] * kn, axis=1) + tl.sum(qr[None, :] * kr, axis=1) sc = tl.where(valid, sc * scale, -3.0e38) vv = tl.load(KVROW + lm[:, None] * KVBO + h * (QN + VH) + QN + offs_v[None, :]).to(tl.float32) m_new = tl.maximum(m, tl.max(sc, axis=0)) rescale = tl.exp(m - m_new) p = tl.exp(sc - m_new) lsum = lsum * rescale + tl.sum(p, axis=0) o = o * rescale + tl.sum(p[:, None] * vv, axis=0) m = m_new tl.store(PMAX + h * NCHUNK + c, m) tl.store(PSUM + h * NCHUNK + c, lsum) tl.store(PV + (h * NCHUNK + c) * VH + offs_v, o) _bar(ARR, slot, GRID_C); slot = 1 - slot # reduce the NCHUNK partials per head into the final attention output. if pid < H: h = pid gm = tl.load(PMAX + h * NCHUNK + tl.arange(0, NCHUNK)) gmax = tl.max(gm, axis=0) lsum = 0.0 o = tl.zeros([VH], dtype=tl.float32) for c in tl.static_range(NCHUNK): m = tl.load(PMAX + h * NCHUNK + c) s = tl.load(PSUM + h * NCHUNK + c) scale_c = tl.exp(m - gmax) lsum += s * scale_c o += tl.load(PV + (h * NCHUNK + c) * VH + offs_v) * scale_c o = o / lsum tl.store(X + XL_OATT + h * VH + offs_v, o) _bar(ARR, slot, GRID_C); slot = 1 - slot # o_proj [C -> D] for w in range(pid, D // BN, GRID_C): _gemv(MLO_WQ, MLO_S, MLO_Z, X, X + XL_OPJ + 3 * D, XL_OATT, w * BN, C // 2, D, G, BN, KCH) _bar(ARR, slot, GRID_C); slot = 1 - slot # residual + moe rmsnorm if pid == 0: hres = tl.load(X + XL_RES + 3 * D + offd, mask=dm, other=0.0) \ + tl.load(X + XL_OPJ + 3 * D + offd, mask=dm, other=0.0) tl.store(X + XL_RES + 3 * D + offd, hres, mask=dm) r = tl.math.rsqrt(tl.sum(hres * hres, axis=0) / D + EPS) nw = tl.load(NORMS + 7 * D + offd, mask=dm, other=0.0).to(tl.float32) tl.store(X + XL_RMS + 4 * D + offd, hres * r * nw, mask=dm) _bar(ARR, slot, GRID_C); slot = 1 - slot slot = _moe_block(X, GWQ, GSC, GZZ, UWQ, USC, UZZ, DWQ, DSC, DZZ, ROUTER_W, ARR, pid, 3, slot, GRID_C, D, MI, NE, NA, RS, G, BN, KCH, DP) # final residual + store if pid == 0: h2 = tl.load(X + XL_RES + 3 * D + offd, mask=dm, other=0.0) \ + tl.load(X + XL_MOE + 3 * D + offd, mask=dm, other=0.0) tl.store(HOUT + offd, h2, mask=dm) # --------------------------------------------------------------------------- # # Host wrapper # --------------------------------------------------------------------------- # class _Linear(nn.Module): """W4A16 quant linear buffer holder (names match reference.py).""" def __init__(self, in_f, out_f): super().__init__() self.register_buffer("w_q", torch.zeros(in_f // 2, out_f, dtype=torch.uint8)) self.register_buffer("scales", torch.zeros(in_f // GROUP, out_f, dtype=torch.bfloat16)) self.register_buffer("zeros", torch.zeros(in_f // GROUP, out_f, dtype=torch.bfloat16)) class _Experts(nn.Module): """Holds one expert-set's quant buffers (reference uses n=1 or 64).""" def __init__(self, n, in_f, out_f): super().__init__() self.register_buffer("w_q", torch.zeros(n, in_f // 2, out_f, dtype=torch.uint8)) self.register_buffer("scales", torch.zeros(n, in_f // GROUP, out_f, dtype=torch.bfloat16)) self.register_buffer("zeros", torch.zeros(n, in_f // GROUP, out_f, dtype=torch.bfloat16)) class _KDA(nn.Module): def __init__(self, cfg): super().__init__() d = cfg.hidden C = cfg.kda_heads * cfg.kda_head_dim self.q_proj = _Linear(d, C) self.k_proj = _Linear(d, C) self.v_proj = _Linear(d, C) self.g_proj = _Linear(d, C) self.beta_proj = nn.Linear(d, cfg.kda_heads, bias=False, dtype=torch.bfloat16) self.conv_w = nn.Parameter(torch.empty(3, C, cfg.short_conv, dtype=torch.bfloat16)) self.o_proj = _Linear(C, d) class _MLA(nn.Module): def __init__(self, cfg): super().__init__() d = cfg.hidden H = cfg.mla_heads self.q_proj = _Linear(d, H * (cfg.qk_nope + cfg.qk_rope)) self.kv_a = _Linear(d, cfg.kv_lora + cfg.qk_rope) self.kv_b = _Linear(cfg.kv_lora, H * (cfg.qk_nope + cfg.v_head)) self.o_proj = _Linear(H * cfg.v_head, d) class _MoE(nn.Module): def __init__(self, cfg): super().__init__() d, m, E = cfg.hidden, cfg.moe_inter, cfg.n_experts self.router = nn.Linear(d, E, bias=False, dtype=torch.bfloat16) self.gate = _Experts(E, d, m) self.up = _Experts(E, d, m) self.down = _Experts(E, m, d) self.s_gate = _Experts(cfg.n_shared, d, m) self.s_up = _Experts(cfg.n_shared, d, m) self.s_down = _Experts(cfg.n_shared, m, d) class _Block(nn.Module): def __init__(self, cfg, kind): super().__init__() self.attn_norm = nn.Parameter(torch.ones(cfg.hidden, dtype=torch.bfloat16)) self.moe_norm = nn.Parameter(torch.ones(cfg.hidden, dtype=torch.bfloat16)) self.attn = _KDA(cfg) if kind == "K" else _MLA(cfg) self.moe = _MoE(cfg) class Model(nn.Module): """Same interface and buffer names as reference.py. The first call to step() flattens the reference's many small quant buffers into contiguous kernel tensors and allocates the persistent workspaces; every subsequent step is exactly one _megakernel launch. """ def __init__(self, cfg): super().__init__() self.cfg = cfg self._ready = False self._last_state = None self._S = None # [3, H, DK, DK] fp32 KDA states self._CQ = None # [3, 3, C] conv windows (q,k,v stacked) self._CK = None self._CV = None self._ckv_buf = None # persistent MLA cache buffers self._krope_buf = None self.blocks = nn.ModuleList(_Block(cfg, k) for k in cfg.pattern) # -- workspace / weight packing (once) -------------------------------- # def _setup(self, device): cfg = self.cfg sd = dict(self.named_buffers()) # KDA quant linears: per block, 5 projections stacked on a new leading # dim (q,k,v,g: [D//2, C]; o: [C//2, D]). Stack each projection's # 3 blocks separately, then concatenate the 5 stacks along dim 0. def stack_kda(nm): wq = torch.stack([sd[f"blocks.{i}.attn.{nm}.w_q"] for i in range(3)]) sc = torch.stack([sd[f"blocks.{i}.attn.{nm}.scales"] for i in range(3)]) zz = torch.stack([sd[f"blocks.{i}.attn.{nm}.zeros"] for i in range(3)]) return wq, sc, zz wqs, scs, zzs = [], [], [] for nm in ("q_proj", "k_proj", "v_proj", "g_proj", "o_proj"): w, s, z = stack_kda(nm) wqs.append(w.reshape(-1)); scs.append(s.reshape(-1)); zzs.append(z.reshape(-1)) self._kda = dict( wq=torch.cat(wqs).contiguous(), s=torch.cat(scs).contiguous(), z=torch.cat(zzs).contiguous(), ) # MLA linears pre = "blocks.3.attn." self._mlq = dict(wq=sd[pre + "q_proj.w_q"].contiguous(), s=sd[pre + "q_proj.scales"].contiguous(), z=sd[pre + "q_proj.zeros"].contiguous()) self._mka = dict(wq=sd[pre + "kv_a.w_q"].contiguous(), s=sd[pre + "kv_a.scales"].contiguous(), z=sd[pre + "kv_a.zeros"].contiguous()) self._mkb = dict(wq=sd[pre + "kv_b.w_q"].contiguous(), s=sd[pre + "kv_b.scales"].contiguous(), z=sd[pre + "kv_b.zeros"].contiguous()) self._mlo = dict(wq=sd[pre + "o_proj.w_q"].contiguous(), s=sd[pre + "o_proj.scales"].contiguous(), z=sd[pre + "o_proj.zeros"].contiguous()) # MoE experts: three arenas (gate, up, down), each # [4 blocks, 65 slots, ...] where slot 0..63 are routed experts and # slot 64 is the shared expert. gate/up are [D//2, MI], down is # [MI//2, D]. Scales/zeros follow the same [4, 65, ...] layout. def stack_expert(nm, shared_nm): wq = torch.stack([torch.cat([sd[f"blocks.{i}.moe.{nm}.w_q"][e] for e in range(64)] + [sd[f"blocks.{i}.moe.{shared_nm}.w_q"][0]]) for i in range(4)]) sc = torch.stack([torch.cat([sd[f"blocks.{i}.moe.{nm}.scales"][e] for e in range(64)] + [sd[f"blocks.{i}.moe.{shared_nm}.scales"][0]]) for i in range(4)]) zz = torch.stack([torch.cat([sd[f"blocks.{i}.moe.{nm}.zeros"][e] for e in range(64)] + [sd[f"blocks.{i}.moe.{shared_nm}.zeros"][0]]) for i in range(4)]) return wq, sc, zz gwq, gsc, gzz = stack_expert("gate", "s_gate") uwq, usc, uzz = stack_expert("up", "s_up") dwq, dsc, dzz = stack_expert("down", "s_down") self._ew = dict( gwq=gwq.contiguous(), gsc=gsc.contiguous(), gzz=gzz.contiguous(), uwq=uwq.contiguous(), usc=usc.contiguous(), uzz=uzz.contiguous(), dwq=dwq.contiguous(), dsc=dsc.contiguous(), dzz=dzz.contiguous(), ) # small bf16 weights (parameters) pd = dict(self.named_parameters()) self._router = torch.cat([pd[f"blocks.{i}.moe.router.weight"] for i in range(4)]).contiguous() self._beta = torch.cat([pd[f"blocks.{i}.attn.beta_proj.weight"] for i in range(3)]).contiguous() self._conv = torch.cat([pd[f"blocks.{i}.attn.conv_w"] for i in range(3)]).contiguous() self._norms = torch.cat([pd[f"blocks.{i}.{n}"] for i in range(4) for n in ("attn_norm", "moe_norm")]).contiguous() # persistent workspaces self._X = torch.zeros(XLEN, dtype=torch.float32, device=device) self._ARR = torch.zeros(2, dtype=torch.int32, device=device) self._KVROW = torch.zeros(16385, cfg.mla_heads * (cfg.qk_nope + cfg.v_head), dtype=torch.bfloat16, device=device) self._ckv_buf = torch.zeros(16385, cfg.kv_lora, dtype=torch.bfloat16, device=device) self._krope_buf = torch.zeros(16385, cfg.qk_rope, dtype=torch.bfloat16, device=device) # chunked-attention partial buffers self._NCHUNK = 16 self._PMAX = torch.zeros(cfg.mla_heads * self._NCHUNK, dtype=torch.float32, device=device) self._PSUM = torch.zeros(cfg.mla_heads * self._NCHUNK, dtype=torch.float32, device=device) self._PV = torch.zeros(cfg.mla_heads * self._NCHUNK * cfg.v_head, dtype=torch.float32, device=device) # dequantized kv_b weight [kv_lora, H*(qk_nope+v_head)] bf16, used only to # pre-project the pre-filled cache at ingest (setup, not the timed step). pre = "blocks.3.attn." wq = sd[pre + "kv_b.w_q"]; sc = sd[pre + "kv_b.scales"]; zo = sd[pre + "kv_b.zeros"] wu = torch.empty((cfg.kv_lora, cfg.mla_heads * (cfg.qk_nope + cfg.v_head)), dtype=torch.uint8, device=device) wu[0::2] = wq & 0xF wu[1::2] = (wq >> 4) & 0xF s = sc.repeat_interleave(GROUP, dim=0).to(torch.float32) z = zo.repeat_interleave(GROUP, dim=0).to(torch.float32) self._kvb_w = ((wu.to(torch.float32) - z) * s).to(torch.bfloat16) self._ready = True def _ingest_state(self, state): """Copy the fed decode state into persistent buffers (once per state).""" cfg = self.cfg dev = self._X.device self._S = torch.stack([state[i]["S"] for i in range(3)]).contiguous().clone() self._CQ = torch.stack([state[i]["cq"] for i in range(3)]).contiguous().clone() self._CK = torch.stack([state[i]["ck"] for i in range(3)]).contiguous().clone() self._CV = torch.stack([state[i]["cv"] for i in range(3)]).contiguous().clone() mla = cfg.pattern.index("M") st = state[mla] pos = int(st["c_kv"].shape[0]) self._ckv_buf[:pos].copy_(st["c_kv"]) self._krope_buf[:pos].copy_(st["k_rope"]) # Pre-project the pre-filled cache through kv_b once (setup, not timed): # the cached rows never change, so their kv_b output is constant across # decode steps. The kernel only projects the newly appended row each step. with torch.no_grad(): self._KVROW[:pos] = (st["c_kv"].float() @ self._kvb_w.float()).to(torch.bfloat16) self._last_state = state self._pos0 = pos def step(self, hidden, state): cfg = self.cfg device = hidden.device if not self._ready: self._setup(device) if self._last_state is not state: self._ingest_state(state) mla = cfg.pattern.index("M") pos = self._pos0 out = torch.empty_like(hidden) # The grid barrier leaves ARR[0]=0 after the last barrier of each step, # so no per-step reset kernel is needed -- the decode stays a single launch. _megakernel[(GRID,)]( hidden, out, self._X, self._S[0], self._S[1], self._S[2], self._CQ, self._CK, self._CV, self._ckv_buf, self._krope_buf, self._KVROW, self._PMAX, self._PSUM, self._PV, self._ARR, pos, self._kda["wq"], self._kda["s"], self._kda["z"], self._mlq["wq"], self._mlq["s"], self._mlq["z"], self._mka["wq"], self._mka["s"], self._mka["z"], self._mkb["wq"], self._mkb["s"], self._mkb["z"], self._mlo["wq"], self._mlo["s"], self._mlo["z"], self._ew["gwq"], self._ew["gsc"], self._ew["gzz"], self._ew["uwq"], self._ew["usc"], self._ew["uzz"], self._ew["dwq"], self._ew["dsc"], self._ew["dzz"], self._router, self._beta, self._conv, self._norms, GRID_C=GRID, D=cfg.hidden, C=cfg.kda_heads * cfg.kda_head_dim, H=cfg.kda_heads, DK=cfg.kda_head_dim, KVL=cfg.kv_lora, QN=cfg.qk_nope, QR=cfg.qk_rope, VH=cfg.v_head, MI=cfg.moe_inter, NE=cfg.n_experts, NA=NACT, RS=cfg.routed_scaling, THETA=cfg.rope_theta, G=GROUP, NCHUNK=self._NCHUNK, num_warps=NUM_WARPS, ) # write the updated state back into the fed dicts so the caller sees it for i in range(3): state[i]["S"] = self._S[i] state[i]["cq"] = self._CQ[i] state[i]["ck"] = self._CK[i] state[i]["cv"] = self._CV[i] st = state[mla] st["c_kv"] = self._ckv_buf[:pos + 1] st["k_rope"] = self._krope_buf[:pos + 1] self._pos0 = pos + 1 return out, state