From a8d22e8011bf52939a3a2b90ee886debc7cce0bc Mon Sep 17 00:00:00 2001 From: jiant <107457950+JadoTu@users.noreply.github.com> Date: Mon, 16 Nov 2026 09:27:47 +0000 Subject: [PATCH 1/2] introduce the GDN MTP replay V2 design Add fused CuTe DSL kernels for GDN MTP target verification in the PyTorch GDN mixer: one launch per layer runs the Conv4 update and the gated delta-rule replay of the accepted history plus the new candidates without writing a checkpoint, and one launch per step commits every layer's accepted Conv window and history, folding the history into the recurrent checkpoint when it fills its 16-row window. - GDNMtpReplayState keeps a single history buffer per replay slot in the KV cache manager V2 replay-state region, so it follows its request through suspend, resume and slot moves; the kernels address it by replay slot through page-strided 64-bit views and per-layer descriptors. The replay kernel launches as a PDL dependent when its grid fits one wave. - Models whose GDN layers are the PyTorch mixer select it on SM100/SM103 with CUTLASS DSL, BF16 states, 128-wide heads, Conv4 and a linear chain of at most 8 tokens per step, replacing the cached replay and the BF16 fused target verify there. GDN layers whose fused target verify writes an FP8 out_proj input (gdn_verify_tcgen05 / trtllm::gdn_verify) keep the cached replay, as do unsupported configurations and the C++ V1 manager; the FlashInfer ring replay stays opt-in. - Run the new kernel tests on B200, and import the model-config KVCacheLayerSpec of the skip-softmax routing test under its own name. Signed-off-by: jiant <107457950+JadoTu@users.noreply.github.com> --- .../custom_ops/cute_dsl_gdn_mtp_commit.py | 892 ++++++++++++++++++ .../custom_ops/cute_dsl_gdn_mtp_replay.py | 868 +++++++++++++++++ .../_torch/modules/fla/cache_manager.py | 362 ++++++- .../_torch/modules/fla/gdn_metadata.py | 9 + .../_torch/modules/mamba/gdn_mixer.py | 184 +++- .../_torch/modules/mamba/replay_metadata.py | 64 ++ .../_torch/modules/qwen4_exp/cache_manager.py | 23 +- tensorrt_llm/_torch/pyexecutor/_util.py | 25 + .../test_lists/test-db/l0_b200.yml | 1 + .../mamba/test_gdn_kernel_optimizations.py | 157 +++ .../modules/mamba/test_gdn_mtp_replay.py | 498 ++++++++++ .../kv_cache/test_mamba_cache_manager.py | 332 ++++++- 12 files changed, 3389 insertions(+), 26 deletions(-) create mode 100644 tensorrt_llm/_torch/custom_ops/cute_dsl_gdn_mtp_commit.py create mode 100644 tensorrt_llm/_torch/custom_ops/cute_dsl_gdn_mtp_replay.py create mode 100644 tests/unittest/_torch/modules/mamba/test_gdn_mtp_replay.py diff --git a/tensorrt_llm/_torch/custom_ops/cute_dsl_gdn_mtp_commit.py b/tensorrt_llm/_torch/custom_ops/cute_dsl_gdn_mtp_commit.py new file mode 100644 index 000000000000..f575af1525ba --- /dev/null +++ b/tensorrt_llm/_torch/custom_ops/cute_dsl_gdn_mtp_commit.py @@ -0,0 +1,892 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +import cutlass +import cutlass.cute as cute +import cutlass.utils as utils +import torch +from cutlass.cute.nvgpu import warp +from cutlass.cute.runtime import from_dlpack +from cutlass.cute.typing import AddressSpace + +DIM = 128 +VEC = 8 +WVEC = VEC // 4 +NCH = DIM // VEC +NT = 256 +MW = DIM // 32 +NW = NT // 32 // MW +MSTEP = NT // NCH +STRIPW = 64 +NSTRIP = DIM // STRIPW +NJ = DIM * NCH // NT +PAD = 136 +LOG2E = 1.4426950408889634 +CTAS_PER_SM = 2 +# Per-layer history descriptor: U, K and G [base address, replay-slot stride] in bytes. +HIST_FIELDS = 6 + + +def _load_x_vec(gX, layer, position, token, chunk): + r = cute.make_rmem_tensor((VEC,), cutlass.BFloat16) + cute.autovec_copy( + cute.recast_tensor(gX[layer, position, token, chunk, None], cutlass.BFloat16), + r, + ) + return r + + +def _interleave3_store(a, b, c, dst): + out = cute.make_rmem_tensor((3 * VEC,), cutlass.BFloat16) + for q in range(VEC): + out[3 * q] = a[q] + out[3 * q + 1] = b[q] + out[3 * q + 2] = c[q] + cute.autovec_copy(out, dst) + + +def _conv_accept_one(gX, layer, position, chunk, dst): + old = cute.make_rmem_tensor((3 * VEC,), cutlass.BFloat16) + cute.autovec_copy(dst, old) + x0 = _load_x_vec(gX, layer, position, cutlass.Int32(0), chunk) + out = cute.make_rmem_tensor((3 * VEC,), cutlass.BFloat16) + for q in range(VEC): + out[3 * q] = old[3 * q + 1] + out[3 * q + 1] = old[3 * q + 2] + out[3 * q + 2] = x0[q] + cute.autovec_copy(out, dst) + + +def _conv_accept_two(gX, layer, position, chunk, dst): + old = cute.make_rmem_tensor((3 * VEC,), cutlass.BFloat16) + cute.autovec_copy(dst, old) + x0 = _load_x_vec(gX, layer, position, cutlass.Int32(0), chunk) + x1 = _load_x_vec(gX, layer, position, cutlass.Int32(1), chunk) + out = cute.make_rmem_tensor((3 * VEC,), cutlass.BFloat16) + for q in range(VEC): + out[3 * q] = old[3 * q + 2] + out[3 * q + 1] = x0[q] + out[3 * q + 2] = x1[q] + cute.autovec_copy(out, dst) + + +@cute.kernel +def _combined_kernel( + gStateRaw: cute.Tensor, + gStateDesc: cute.Tensor, + gConvRaw: cute.Tensor, + gConvDesc: cute.Tensor, + gX: cute.Tensor, + gHD: cute.Tensor, + gLen: cute.Tensor, + gWI: cute.Tensor, + gAT: cute.Tensor, + gDM: cute.Tensor, + STATE_BASE_ADDR: cutlass.Int64, + CONV_BASE_ADDR: cutlass.Int64, + L: cutlass.Constexpr, + H: cutlass.Constexpr, + RH: cutlass.Constexpr, + W: cutlass.Constexpr, + CAP: cutlass.Constexpr, + C: cutlass.Constexpr, + NCHC: cutlass.Constexpr, + TABLE_CAPACITY: cutlass.Constexpr, + GDN_INDIRECT: cutlass.Constexpr, + CONV_INDIRECT: cutlass.Constexpr, + GDN_BASE: cutlass.Constexpr, + GDN_LAYER_STRIDE: cutlass.Constexpr, + GDN_SLOT_STRIDE: cutlass.Constexpr, + CONV_BASE: cutlass.Constexpr, + CONV_LAYER_STRIDE: cutlass.Constexpr, + CONV_SLOT_STRIDE: cutlass.Constexpr, +): + tid, _, _ = cute.arch.thread_idx() + bid, _, _ = cute.arch.block_idx() + grid, _, _ = cute.arch.grid_dim() + batch = cute.size(gWI, mode=[0]) + + smem = utils.SmemAllocator() + sAccP = smem.allocate_tensor(cutlass.BFloat16, cute.make_layout(DIM * PAD), byte_alignment=16) + sUP = smem.allocate_tensor(cutlass.BFloat16, cute.make_layout(W * PAD), byte_alignment=16) + sKP = smem.allocate_tensor(cutlass.BFloat16, cute.make_layout(W * PAD), byte_alignment=16) + sGD = smem.allocate_tensor( + cutlass.Int64, + cute.make_layout(2 * L if GDN_INDIRECT else 1), + byte_alignment=16, + ) + sCD = smem.allocate_tensor( + cutlass.Int64, + cute.make_layout(2 * L if CONV_INDIRECT else 1), + byte_alignment=16, + ) + sTab = smem.allocate_tensor( + cutlass.Int32, + cute.make_layout((4, TABLE_CAPACITY), stride=(TABLE_CAPACITY, 1)), + byte_alignment=16, + ) + sHD = smem.allocate_tensor(cutlass.Int64, cute.make_layout(HIST_FIELDS * L), byte_alignment=16) + + sAccS = cute.make_tensor( + sAccP.iterator, + cute.make_layout((NSTRIP, DIM, STRIPW), stride=(STRIPW, PAD, 1)), + ) + sAccV = cute.make_tensor( + sAccP.iterator, cute.make_layout((DIM, NCH, VEC), stride=(PAD, VEC, 1)) + ) + sUA = cute.make_tensor(sUP.iterator, cute.make_layout((DIM, W), stride=(1, PAD))) + sUW = cute.make_tensor(sUP.iterator, cute.make_layout((W, NCH, VEC), stride=(PAD, VEC, 1))) + sKB = cute.make_tensor( + sKP.iterator, + cute.make_layout((NSTRIP, STRIPW, W), stride=(STRIPW, 1, PAD)), + ) + sKW = cute.make_tensor(sKP.iterator, cute.make_layout((W, NCH, VEC), stride=(PAD, VEC, 1))) + + # Resolve every per-item and per-layer indirection once per CTA. The work + # metadata is three dependent global loads deep (work item -> position -> + # dummy/accepted); doing it per tile serialises the whole CTA behind that + # chain on every grid-stride step. + for i in cutlass.range(tid, batch, NT): + position = gWI[i, 0] + slot = gWI[i, 1] + start = gWI[i, 2] + replay_slot = gWI[i, 4] + dummy = gDM[position].to(cutlass.Int32) + accepted = gAT[position] + meta = cutlass.Int32(-1) + if dummy == 0: + meta = accepted + ((start + accepted) << 8) + sTab[0, i] = position + sTab[1, i] = slot + sTab[2, i] = meta + sTab[3, i] = replay_slot + for i in cutlass.range(tid, HIST_FIELDS * L, NT): + sHD[i] = gHD[i // HIST_FIELDS, i % HIST_FIELDS] + if cutlass.const_expr(GDN_INDIRECT): + for i in cutlass.range(tid, 2 * L, NT): + sGD[i] = gStateDesc[i // 2, i % 2] + if cutlass.const_expr(CONV_INDIRECT): + for i in cutlass.range(tid, 2 * L, NT): + sCD[i] = gConvDesc[i // 2, i % 2] + cute.arch.barrier() + + mma_op = warp.MmaF16BF16Op(cutlass.BFloat16, cutlass.Float32, (16, 8, 16)) + tiled_mma = cute.make_tiled_mma( + mma_op, cute.make_layout((MW, NW, 1)), permutation_mnk=(64, 32, 16) + ) + thr_mma = tiled_mma.get_slice(tid) + ld_atom = cute.make_copy_atom(warp.LdMatrix8x8x16bOp(True, 4), cutlass.BFloat16) + tc_a = cute.make_tiled_copy_A(ld_atom, tiled_mma) + tc_b = cute.make_tiled_copy_B(ld_atom, tiled_mma) + thr_a = tc_a.get_slice(tid) + thr_b = tc_b.get_slice(tid) + st_atom = cute.make_copy_atom(warp.StMatrix8x8x16bOp(False, 4), cutlass.BFloat16) + st_c_atom = cute.make_tiled_copy_C_atom(st_atom, tiled_mma) + st_r2s = cute.make_tiled_copy_S(st_atom, st_c_atom) + thr_st = st_r2s.get_slice(tid) + + i16 = tid // NCH + cvec = tid % NCH + + # Conv4 raw-input checkpoint. One thread owns one 8-channel packet of one + # (work item, layer); the flat packet space keeps every thread busy for any + # channel count and keeps the candidate_x reads perfectly coalesced. + conv_units = batch * L * NCHC + for cbase in cutlass.range(bid * NT, conv_units, grid * NT): + ci = cbase + tid + if ci < conv_units: + il = ci // NCHC + chunk = ci % NCHC + item = il // L + layer = il % L + meta = sTab[2, item] + if meta >= 0: + accepted = meta & 255 + if accepted > 0: + position = sTab[0, item] + slot = sTab[1, item] + layer_offset = cutlass.Int64(0) + slot_stride = cutlass.Int64(0) + if cutlass.const_expr(CONV_INDIRECT): + layer_offset = sCD[layer * 2] + slot_stride = sCD[layer * 2 + 1] + else: + layer_offset = ( + cutlass.Int64(CONV_BASE) + cutlass.Int64(layer) * CONV_LAYER_STRIDE + ) + slot_stride = cutlass.Int64(CONV_SLOT_STRIDE) + if cutlass.const_expr(CONV_INDIRECT): + conv_addr = ( + layer_offset + + (cutlass.Int64(slot) * slot_stride + cutlass.Int64(chunk) * (3 * VEC)) + * 2 + ) + else: + conv_addr = ( + CONV_BASE_ADDR + + ( + layer_offset + + cutlass.Int64(slot) * slot_stride + + cutlass.Int64(chunk) * (3 * VEC) + ) + * 2 + ) + conv_ptr = cute.make_ptr( + cutlass.BFloat16, + conv_addr, + AddressSpace.gmem, + assumed_align=16, + ) + dst = cute.make_tensor(conv_ptr, cute.make_layout(3 * VEC)) + if accepted >= 3: + x0 = _load_x_vec(gX, layer, position, accepted - 3, chunk) + x1 = _load_x_vec(gX, layer, position, accepted - 2, chunk) + x2 = _load_x_vec(gX, layer, position, accepted - 1, chunk) + _interleave3_store(x0, x1, x2, dst) + elif accepted == 2: + _conv_accept_two(gX, layer, position, chunk, dst) + else: + _conv_accept_one(gX, layer, position, chunk, dst) + + # One CTA owns the small scalar length update. This has no ordering + # dependence with either the Conv stores or the rollover tiles. + if bid == 0: + for item in cutlass.range(tid, batch, NT): + meta = sTab[2, item] + if meta >= 0: + total = meta >> 8 + new_len = total + if total > W: + new_len = total - W + gLen[sTab[3, item]] = new_len + + # Boundary-crossing GDN commit. Runtime B appears only in this grid-stride + # bound, so the same compiled kernel serves every positive batch size. + gdn_units = batch * L * H + for it in cutlass.range(bid, gdn_units, grid): + item = it // (L * H) + rem = it % (L * H) + layer = rem // H + h = rem % H + meta = sTab[2, item] + if meta >= 0: + total = meta >> 8 + if total > W: + tail = total - W + slot = sTab[1, item] + + layer_offset = cutlass.Int64(0) + layer_slot_stride = cutlass.Int64(0) + if cutlass.const_expr(GDN_INDIRECT): + layer_offset = sGD[layer * 2] + layer_slot_stride = sGD[layer * 2 + 1] + else: + layer_offset = cutlass.Int64(GDN_BASE) + cutlass.Int64(layer) * GDN_LAYER_STRIDE + layer_slot_stride = cutlass.Int64(GDN_SLOT_STRIDE) + + if cutlass.const_expr(GDN_INDIRECT): + state_addr = layer_offset + cutlass.Int64(slot) * layer_slot_stride * 2 + else: + state_addr = ( + STATE_BASE_ADDR + + (layer_offset + cutlass.Int64(slot) * layer_slot_stride) * 2 + ) + state_ptr = cute.make_ptr( + cutlass.Int64, + state_addr, + AddressSpace.gmem, + assumed_align=16, + ) + gSt0 = cute.make_tensor( + state_ptr, + cute.make_layout( + (H * RH, DIM, NCH, WVEC), + stride=(DIM * NCH * WVEC, NCH * WVEC, WVEC, 1), + ), + ) + + hv0 = h * RH + + # The checkpoint tile is by far the longest load; issue all of + # it before any of the dependent decay math. + rs = [cute.make_rmem_tensor((WVEC,), cutlass.Int64) for _ in range(NJ)] + gS0 = gSt0[hv0, None, None, None] + for jj in cutlass.range_constexpr(NJ): + cute.autovec_copy(gS0[i16 + MSTEP * jj, cvec, None], rs[jj]) + + # Histories are addressed by replay slot through per-layer + # [base, slot stride] byte pairs, in 64 bits (pool pages). + rslot = cutlass.Int64(sTab[3, item]) + hd = layer * HIST_FIELDS + gUt = cute.make_tensor( + cute.make_ptr( + cutlass.Int64, + sHD[hd] + rslot * sHD[hd + 1], + AddressSpace.gmem, + assumed_align=16, + ), + cute.make_layout( + (CAP, H * RH, NCH, WVEC), + stride=(H * RH * NCH * WVEC, NCH * WVEC, WVEC, 1), + ), + ) + gKt = cute.make_tensor( + cute.make_ptr( + cutlass.Int64, + sHD[hd + 2] + rslot * sHD[hd + 3] + cutlass.Int64(h) * (DIM * 2), + AddressSpace.gmem, + assumed_align=16, + ), + cute.make_layout((CAP, NCH, WVEC), stride=(H * NCH * WVEC, WVEC, 1)), + ) + gGt = cute.make_tensor( + cute.make_ptr( + cutlass.Float32, + sHD[hd + 4] + rslot * sHD[hd + 5], + AddressSpace.gmem, + assumed_align=16, + ), + cute.make_layout((H * RH, CAP), stride=(CAP, 1)), + ) + gend_cur = gGt[hv0, W - 1] + + # Overflow rows are read here and rewritten at the very end, so + # their loads can ride along with the checkpoint stream. + u_units = tail * RH * NCH + k_units = tail * NCH + have_u = tid < u_units + have_k = tid < k_units + rtU = cute.make_rmem_tensor((WVEC,), cutlass.Int64) + rtK = cute.make_rmem_tensor((WVEC,), cutlass.Int64) + uj = tid // (RH * NCH) + urem = tid % (RH * NCH) + uhv = hv0 + urem // NCH + uc = urem % NCH + kj = tid // NCH + kc = tid % NCH + if have_u: + cute.autovec_copy(gUt[W + uj, uhv, uc, None], rtU) + if have_k: + cute.autovec_copy(gKt[W + kj, kc, None], rtK) + + # Stage K once and the first value head's decay-scaled U. + for wb in cutlass.range_constexpr(W // 16): + irow = i16 + wb * 16 + rk = cute.make_rmem_tensor((WVEC,), cutlass.Int64) + ru = cute.make_rmem_tensor((WVEC,), cutlass.Int64) + cute.autovec_copy(gKt[irow, cvec, None], rk) + cute.autovec_copy(gUt[irow, hv0, cvec, None], ru) + gi = gGt[hv0, irow] + dec = cute.exp2((gend_cur - gi) * LOG2E, approx=True, ftz=True) + cute.autovec_copy( + cute.recast_tensor(rk, cutlass.BFloat16), + sKW[irow, cvec, None], + ) + rud = cute.make_rmem_tensor((VEC,), cutlass.BFloat16) + rud.store( + ( + cute.recast_tensor(ru, cutlass.BFloat16).load().to(cutlass.Float32) + * dec + ).to(cutlass.BFloat16) + ) + cute.autovec_copy(rud, sUW[irow, cvec, None]) + + scale = cute.exp2(gend_cur * LOG2E, approx=True, ftz=True) + cute.arch.barrier() + + for hvl in cutlass.range_constexpr(RH): + hv = hv0 + hvl + gSt = gSt0[hv, None, None, None] + + if cutlass.const_expr(hvl + 1 < RH): + hvn = hv + 1 + gend_next = gGt[hvn, W - 1] + run0 = cute.make_rmem_tensor((WVEC,), cutlass.Int64) + cute.autovec_copy(gUt[i16, hvn, cvec, None], run0) + gi0_next = gGt[hvn, i16] + if cutlass.const_expr(W == 32): + run1 = cute.make_rmem_tensor((WVEC,), cutlass.Int64) + cute.autovec_copy(gUt[i16 + 16, hvn, cvec, None], run1) + gi1_next = gGt[hvn, i16 + 16] + + tAs = thr_mma.partition_A(sUA) + tCrA = tiled_mma.make_fragment_A(tAs) + cute.copy(tc_a, thr_a.partition_S(sUA), thr_a.retile(tCrA)) + for strip in cutlass.range_constexpr(NSTRIP): + sB = sKB[strip, None, None] + tBs = thr_mma.partition_B(sB) + tCrB = tiled_mma.make_fragment_B(tBs) + cute.copy(tc_b, thr_b.partition_S(sB), thr_b.retile(tCrB)) + acc = cute.make_rmem_tensor( + tiled_mma.partition_shape_C((DIM, STRIPW)), + cutlass.Float32, + ) + acc.fill(0.0) + for kb in cutlass.range_constexpr(cute.size(tCrA, mode=[2])): + cute.gemm( + tiled_mma, + acc, + tCrA[None, None, kb], + tCrB[None, None, kb], + acc, + ) + sAcc_strip = sAccS[strip, None, None] + tRS_sAcc = thr_st.partition_D(sAcc_strip) + tRS_rAcc = st_r2s.retile(acc) + rC = cute.make_rmem_tensor(tRS_rAcc.shape, cutlass.BFloat16) + rC.store(tRS_rAcc.load().to(cutlass.BFloat16)) + cute.copy(st_r2s, rC, tRS_sAcc) + cute.arch.barrier() + + # The next head was prefetched while this head's MMA ran. + if cutlass.const_expr(hvl + 1 < RH): + dec0_next = cute.exp2( + (gend_next - gi0_next) * LOG2E, + approx=True, + ftz=True, + ) + rud0 = cute.make_rmem_tensor((VEC,), cutlass.BFloat16) + rud0.store( + ( + cute.recast_tensor(run0, cutlass.BFloat16) + .load() + .to(cutlass.Float32) + * dec0_next + ).to(cutlass.BFloat16) + ) + cute.autovec_copy(rud0, sUW[i16, cvec, None]) + if cutlass.const_expr(W == 32): + dec1_next = cute.exp2( + (gend_next - gi1_next) * LOG2E, + approx=True, + ftz=True, + ) + rud1 = cute.make_rmem_tensor((VEC,), cutlass.BFloat16) + rud1.store( + ( + cute.recast_tensor(run1, cutlass.BFloat16) + .load() + .to(cutlass.Float32) + * dec1_next + ).to(cutlass.BFloat16) + ) + cute.autovec_copy(rud1, sUW[i16 + 16, cvec, None]) + + if cutlass.const_expr(hvl + 1 < RH): + gStn = gSt0[hv + 1, None, None, None] + for jj in cutlass.range_constexpr(NJ): + ra = cute.make_rmem_tensor((VEC,), cutlass.BFloat16) + cute.autovec_copy(sAccV[i16 + MSTEP * jj, cvec, None], ra) + ro = cute.make_rmem_tensor((VEC,), cutlass.BFloat16) + ro.store( + ( + cute.recast_tensor(rs[jj], cutlass.BFloat16) + .load() + .to(cutlass.Float32) + * scale + + ra.load().to(cutlass.Float32) + ).to(cutlass.BFloat16) + ) + cute.autovec_copy( + cute.recast_tensor(ro, cutlass.Int64), + gSt[i16 + MSTEP * jj, cvec, None], + ) + if cutlass.const_expr(hvl + 1 < RH): + cute.autovec_copy(gStn[i16 + MSTEP * jj, cvec, None], rs[jj]) + if cutlass.const_expr(hvl + 1 < RH): + scale = cute.exp2(gend_next * LOG2E, approx=True, ftz=True) + if cutlass.const_expr(hvl + 1 < RH): + cute.arch.barrier() + + # Compact only the accepted overflow rows. + if have_u: + cute.autovec_copy(rtU, gUt[uj, uhv, uc, None]) + for ui in cutlass.range(tid + NT, u_units, NT): + j = ui // (RH * NCH) + urem2 = ui % (RH * NCH) + hv2 = hv0 + urem2 // NCH + uc2 = urem2 % NCH + rt = cute.make_rmem_tensor((WVEC,), cutlass.Int64) + cute.autovec_copy(gUt[W + j, hv2, uc2, None], rt) + cute.autovec_copy(rt, gUt[j, hv2, uc2, None]) + + if have_k: + cute.autovec_copy(rtK, gKt[kj, kc, None]) + for ki in cutlass.range(tid + NT, k_units, NT): + kj2 = ki // NCH + kc2 = ki % NCH + rt2 = cute.make_rmem_tensor((WVEC,), cutlass.Int64) + cute.autovec_copy(gKt[W + kj2, kc2, None], rt2) + cute.autovec_copy(rt2, gKt[kj2, kc2, None]) + + g_units = tail * RH + for gidx in cutlass.range(tid, g_units, NT): + gj = gidx // RH + hvl3 = gidx % RH + hv3 = hv0 + hvl3 + eg = gGt[hv3, W - 1] + gGt[hv3, gj] = gGt[hv3, W + gj] - eg + + +@cute.jit +def _launch( + mStateRaw: cute.Tensor, + mStateDesc: cute.Tensor, + mConvRaw: cute.Tensor, + mConvDesc: cute.Tensor, + mX: cute.Tensor, + mHD: cute.Tensor, + mLen: cute.Tensor, + mWI: cute.Tensor, + mAT: cute.Tensor, + mDM: cute.Tensor, + L: cutlass.Constexpr, + H: cutlass.Constexpr, + RH: cutlass.Constexpr, + W: cutlass.Constexpr, + CAP: cutlass.Constexpr, + C: cutlass.Constexpr, + NCHC: cutlass.Constexpr, + TABLE_CAPACITY: cutlass.Constexpr, + RUNTIME_GRID: cutlass.Int32, + GDN_INDIRECT: cutlass.Constexpr, + CONV_INDIRECT: cutlass.Constexpr, + GDN_BASE: cutlass.Constexpr, + GDN_LAYER_STRIDE: cutlass.Constexpr, + GDN_SLOT_STRIDE: cutlass.Constexpr, + CONV_BASE: cutlass.Constexpr, + CONV_LAYER_STRIDE: cutlass.Constexpr, + CONV_SLOT_STRIDE: cutlass.Constexpr, + stream, +): + state_addr = mStateRaw.iterator.toint() + conv_addr = mConvRaw.iterator.toint() + _combined_kernel( + mStateRaw, + mStateDesc, + mConvRaw, + mConvDesc, + mX, + mHD, + mLen, + mWI, + mAT, + mDM, + state_addr, + conv_addr, + L, + H, + RH, + W, + CAP, + C, + NCHC, + TABLE_CAPACITY, + GDN_INDIRECT, + CONV_INDIRECT, + GDN_BASE, + GDN_LAYER_STRIDE, + GDN_SLOT_STRIDE, + CONV_BASE, + CONV_LAYER_STRIDE, + CONV_SLOT_STRIDE, + ).launch( + grid=[RUNTIME_GRID, 1, 1], + block=[NT, 1, 1], + stream=stream, + ) + + +_CACHE = {} +_SM_COUNTS = {} +_DUMMY_DESCRIPTORS = {} + + +def _sm_count(device: torch.device) -> int: + device_index = device.index + if device_index is None: + device_index = torch.cuda.current_device() + count = _SM_COUNTS.get(device_index) + if count is None: + count = torch.cuda.get_device_properties(device_index).multi_processor_count + _SM_COUNTS[device_index] = count + return count + + +def _dummy_descriptors(device: torch.device) -> torch.Tensor: + device_index = device.index + if device_index is None: + device_index = torch.cuda.current_device() + result = _DUMMY_DESCRIPTORS.get(device_index) + if result is None: + result = torch.zeros((1, 2), dtype=torch.int64, device=device) + _DUMMY_DESCRIPTORS[device_index] = result + return result + + +def build_gdn_mtp_history_descriptors( + history_u: list[torch.Tensor], + history_k: list[torch.Tensor], + history_G: list[torch.Tensor], +) -> torch.Tensor: + """Pack each layer's U/K/G history [base address, replay-slot stride] in bytes. + + Each list holds one view per local layer, [R, CAP, HV, 128] (U, BF16), + [R, CAP, H, 128] (K, BF16) and [R, HV, CAP] (G, FP32). Replay slots may be + strided (KV-cache pool pages), but every slot's payload must be dense. + """ + if not (len(history_u) == len(history_k) == len(history_G)) or not history_u: + raise ValueError("GDN MTP history needs the same nonzero number of U/K/G layers") + reference_u, reference_k = history_u[0], history_k[0] + replay_slots, capacity, value_heads, value_dim = reference_u.shape + key_heads, key_dim = reference_k.shape[2:] + if value_dim != DIM or key_dim != DIM: + raise ValueError("GDN MTP history requires key_dim=value_dim=128") + rows = [] + for u, k, g in zip(history_u, history_k, history_G): + if ( + u.shape != reference_u.shape + or k.shape != (replay_slots, capacity, key_heads, DIM) + or g.shape != (replay_slots, value_heads, capacity) + ): + raise ValueError("GDN MTP history layers have inconsistent shapes") + if u.dtype != torch.bfloat16 or k.dtype != torch.bfloat16 or g.dtype != torch.float32: + raise TypeError("GDN MTP K/U histories must be BF16 and G FP32") + if ( + u.stride()[1:] != (value_heads * DIM, DIM, 1) + or k.stride()[1:] != (key_heads * DIM, DIM, 1) + or g.stride()[1:] != (capacity, 1) + ): + raise ValueError("GDN MTP history slot payloads must be dense") + if any(t.device != reference_u.device for t in (u, k, g)): + raise ValueError("GDN MTP history layers must be on one device") + row = [] + for tensor in (u, k, g): + if tensor.data_ptr() % 16 or (tensor.stride(0) * tensor.element_size()) % 16: + raise ValueError("GDN MTP history slots must be 16-byte aligned") + row += [tensor.data_ptr(), tensor.stride(0) * tensor.element_size()] + rows.append(row) + return torch.tensor(rows, dtype=torch.int64, device=reference_u.device) + + +@torch.no_grad() +def gdn_mtp_commit( + ssm_states: torch.Tensor, + conv_states: torch.Tensor, + candidate_x: torch.Tensor, + history_descriptors: torch.Tensor, + history_len: torch.Tensor, + replay_work_items: torch.Tensor, + accepted_tokens: torch.Tensor, + is_dummy: torch.Tensor, + *, + key_heads: int, + value_heads: int, + history_window: int, + ssm_state_descriptors: torch.Tensor | None = None, + conv_state_descriptors: torch.Tensor | None = None, +) -> None: + """Commit accepted Conv and GDN histories for every local layer. + + Affine Cache Manager V2 storage is supplied as slot-major views + [S,L,HV,128,128] and [S,L,C,3]. Indirect storage supplies the first + layer view plus absolute-byte-address descriptors [L,2] whose second + column is the BF16 slot stride. Histories are addressed by replay slot + through ``history_descriptors`` (see ``build_gdn_mtp_history_descriptors``); + ``history_len`` is indexed by replay slot. Work-item columns are + (decode position, state slot, history length at replay, unused, replay slot). + ``candidate_x`` is the full server-capacity buffer; the runtime batch comes + from ``replay_work_items`` and is intentionally absent from the compilation key. + """ + candidate_layers, candidate_capacity, replay_width, channels = candidate_x.shape + layers = history_descriptors.shape[0] + batch = replay_work_items.shape[0] + window = history_window + capacity = window + replay_width + + if batch == 0: + return + + if candidate_layers != layers: + raise ValueError("candidate_x and GDN histories must have the same layer count") + if window != 16: + raise ValueError("GDN MTP commit requires a history window of 16") + if not 1 <= replay_width <= 8: + raise ValueError("GDN MTP commit requires 1 <= tokens_per_step <= 8") + if not 1 <= layers <= 128: + raise ValueError("GDN MTP commit supports 1 <= layers <= 128") + if key_heads <= 0 or value_heads <= 0 or value_heads % key_heads != 0: + raise ValueError("value_heads must be divisible by key_heads") + if channels != (2 * key_heads + value_heads) * DIM: + raise ValueError("candidate_x has an unexpected channel count") + if candidate_capacity < batch: + raise ValueError("batch must be no larger than the candidate buffer") + if ( + history_descriptors.shape != (layers, HIST_FIELDS) + or history_descriptors.dtype != torch.int64 + or not history_descriptors.is_contiguous() + ): + raise ValueError("history_descriptors must be contiguous int64 [layers, 6]") + if history_len.ndim != 1 or history_len.dtype != torch.int32: + raise ValueError("history_len must be an int32 vector indexed by replay slot") + if replay_work_items.ndim != 2 or replay_work_items.shape[0] != batch: + raise ValueError("replay_work_items must have one row per batch item") + if replay_work_items.shape[1] < 5 or replay_work_items.dtype != torch.int32: + raise ValueError("replay_work_items must be int32 with at least five columns") + if accepted_tokens.shape != (batch,) or accepted_tokens.dtype != torch.int32: + raise ValueError("accepted_tokens must be int32 with shape [batch]") + if is_dummy.shape != (batch,) or is_dummy.dtype != torch.bool: + raise ValueError("is_dummy must be bool with shape [batch]") + if candidate_x.dtype != torch.bfloat16 or not candidate_x.is_contiguous(): + raise ValueError("candidate_x must be a contiguous BF16 capacity buffer") + if not replay_work_items.is_contiguous(): + raise ValueError("replay_work_items must be contiguous") + if ssm_states.dtype != torch.bfloat16 or conv_states.dtype != torch.bfloat16: + raise TypeError("GDN and Conv checkpoints must be BF16") + + slots = ssm_states.shape[0] + gdn_indirect = ssm_state_descriptors is not None + conv_indirect = conv_state_descriptors is not None + if gdn_indirect: + if ssm_states.shape != (slots, value_heads, DIM, DIM): + raise ValueError("Indirect SSM state must be the first rank-4 layer view") + if ( + ssm_state_descriptors.shape != (layers, 2) + or ssm_state_descriptors.dtype != torch.int64 + or not ssm_state_descriptors.is_contiguous() + ): + raise ValueError("SSM descriptors must be contiguous int64 [layers, 2]") + gdn_base = gdn_layer_stride = gdn_slot_stride = 0 + state_desc = ssm_state_descriptors + else: + if ssm_states.shape != (slots, layers, value_heads, DIM, DIM): + raise ValueError("Affine SSM state must have shape [slots, layers, HV, 128, 128]") + gdn_base = 0 + gdn_layer_stride = ssm_states.stride(1) if layers > 1 else 0 + gdn_slot_stride = ssm_states.stride(0) + state_desc = _dummy_descriptors(ssm_states.device) + + conv_slots = conv_states.shape[0] + if conv_indirect: + if conv_states.shape != (conv_slots, channels, 3): + raise ValueError("Indirect Conv state must be the first rank-3 layer view") + if ( + conv_state_descriptors.shape != (layers, 2) + or conv_state_descriptors.dtype != torch.int64 + or not conv_state_descriptors.is_contiguous() + ): + raise ValueError("Conv descriptors must be contiguous int64 [layers, 2]") + conv_base = conv_layer_stride = conv_slot_stride = 0 + conv_desc = conv_state_descriptors + else: + if conv_states.shape != (conv_slots, layers, channels, 3): + raise ValueError("Affine Conv state must have shape [slots, layers, channels, 3]") + conv_base = 0 + conv_layer_stride = conv_states.stride(1) if layers > 1 else 0 + conv_slot_stride = conv_states.stride(0) + conv_desc = _dummy_descriptors(conv_states.device) + + tensors = ( + ssm_states, + conv_states, + candidate_x, + history_descriptors, + history_len, + replay_work_items, + accepted_tokens, + is_dummy, + state_desc, + conv_desc, + ) + if any(not tensor.is_cuda for tensor in tensors): + raise ValueError("GDN MTP commit tensors must be CUDA tensors") + if any(tensor.device != candidate_x.device for tensor in tensors): + raise ValueError("GDN MTP commit tensors must be on the same device") + + ratio = value_heads // key_heads + n_chunks = channels // VEC + x_vec = candidate_x.view(torch.int64).view( + layers, candidate_capacity, replay_width, n_chunks, WVEC + ) + dm = is_dummy.view(torch.uint8) + + from cuda.bindings import driver as _drv + + stream = _drv.CUstream(torch.cuda.current_stream().cuda_stream) + mx = from_dlpack(x_vec, assumed_align=16) + mwi = from_dlpack(replay_work_items, assumed_align=16).mark_compact_shape_dynamic( + mode=0, stride_order=(0, 1) + ) + mat = from_dlpack(accepted_tokens, assumed_align=4).mark_compact_shape_dynamic( + mode=0, stride_order=(0,) + ) + mdm = from_dlpack(dm, assumed_align=1).mark_compact_shape_dynamic(mode=0, stride_order=(0,)) + args = ( + from_dlpack(ssm_states, assumed_align=16), + from_dlpack(state_desc, assumed_align=16), + from_dlpack(conv_states, assumed_align=16), + from_dlpack(conv_desc, assumed_align=16), + mx, + from_dlpack(history_descriptors, assumed_align=16), + from_dlpack(history_len, assumed_align=4), + mwi, + mat, + mdm, + ) + + conv_ctas = (batch * layers * n_chunks + NT - 1) // NT + max_gdn_grid = batch * layers * key_heads + grid = min( + max(conv_ctas, max_gdn_grid), + _sm_count(candidate_x.device) * CTAS_PER_SM, + ) + key = ( + candidate_x.device.index, + candidate_capacity, + slots, + conv_slots, + history_len.shape[0], + history_len.stride(0), + replay_work_items.shape[1], + replay_width, + layers, + key_heads, + value_heads, + window, + channels, + gdn_indirect, + conv_indirect, + gdn_base, + gdn_layer_stride, + gdn_slot_stride, + conv_base, + conv_layer_stride, + conv_slot_stride, + ) + fn = _CACHE.get(key) + if fn is None: + fn = cute.compile( + _launch, + *args, + layers, + key_heads, + ratio, + window, + capacity, + channels, + n_chunks, + candidate_capacity, + cutlass.Int32(grid), + gdn_indirect, + conv_indirect, + gdn_base, + gdn_layer_stride, + gdn_slot_stride, + conv_base, + conv_layer_stride, + conv_slot_stride, + stream, + ) + _CACHE[key] = fn + + fn(*args, cutlass.Int32(grid), stream) diff --git a/tensorrt_llm/_torch/custom_ops/cute_dsl_gdn_mtp_replay.py b/tensorrt_llm/_torch/custom_ops/cute_dsl_gdn_mtp_replay.py new file mode 100644 index 000000000000..38127ac953fd --- /dev/null +++ b/tensorrt_llm/_torch/custom_ops/cute_dsl_gdn_mtp_replay.py @@ -0,0 +1,868 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +"""Single-launch BF16 fusion of depthwise causal Conv4 + SiLU + Q/K norm, +gating, GDN state reconstruction, and MTP replay recurrence.""" + +import math + +import cuda.bindings.driver as cuda +import cutlass +import cutlass.cute as cute +import torch +from cutlass.cute.nvgpu import warp as cwarp +from cutlass.cute.runtime import from_dlpack +from cutlass.experimental import primitives as prims +from cutlass.utils import SmemAllocator + +KDIM = 128 +SCALE = 1.0 / math.sqrt(float(KDIM)) +LOG2E = 1.4426950408889634 + +# The A tile holds the 128 checkpoint rows of one value head; it is then reused +# for a small second pass holding the history-K rows and the T new k-hat rows. +AROWS = 128 +RROWS = 64 +APAD = KDIM + 8 # bf16 row pitch of the A / X tiles + +_CACHE = {} +# Dynamic shared memory that keeps a PDL launch at one CTA per SM. +PDL_SMEM_PAD = 80 * 1024 + + +def _use_pdl(num_ctas: int, device: torch.device) -> bool: + """Launch as a PDL dependent only when the whole grid fits in one wave.""" + return num_ctas <= torch.cuda.get_device_properties(device).multi_processor_count + + +@cute.kernel +def _fused_kernel( + mRX: cute.Tensor, # (T, C) bf16 row-strided raw Q/K/V view, row 0 + mCW: cute.Tensor, # (C, 4) bf16 depthwise Conv4 weights + mCS: cute.Tensor, # (C, 3) bf16 Conv checkpoint, slot 0 + mB: cute.Tensor, # (T, BW) bf16 beta gate input, row 0 + mA: cute.Tensor, # (T, AW) bf16 decay gate input, row 0 + mCk: cute.Tensor, # (V, K) bf16 recurrent checkpoint, slot 0 head 0 + mIdx: cute.Tensor, # (B,) int32 recurrent-state slots + mRIdx: cute.Tensor, # (B,) int32 replay-history slots + mDum: cute.Tensor, # (B,) uint8 + mHU: cute.Tensor, # (CAP, HV, V//8, 8) bf16 U history, replay slot 0 + mHK: cute.Tensor, # (CAP, H, K//8, 8) bf16 K history, replay slot 0 + mHG: cute.Tensor, # (HV, CAP) f32 cumulative-G history, replay slot 0 + mHL: cute.Tensor, # (R,) int32 + mAlog: cute.Tensor, # (HV,) f32 + mDtb: cute.Tensor, # (HV,) f32 + mOut: cute.Tensor, # (T, HV, V) bf16, row 0 + mCX: cute.Tensor, # (T, C) bf16, row 0 + T: cutlass.Constexpr, + H: cutlass.Constexpr, + HV: cutlass.Constexpr, + HMAX: cutlass.Constexpr, # history window W = CAPACITY - T + QKVZ: cutlass.Constexpr, # raw_x row stride + RXBS: cutlass.Constexpr, # raw_x batch stride + BW: cutlass.Constexpr, # b row stride + AW: cutlass.Constexpr, # a row stride + OBS: cutlass.Constexpr, # output batch stride + CXBS: cutlass.Constexpr, # candidate_x batch stride + CXRS: cutlass.Constexpr, # candidate_x row stride + CSS: cutlass.Constexpr, # checkpoint slot stride + STATE_HEAD_STRIDE: cutlass.Constexpr, + CVSS: cutlass.Constexpr, # conv_state slot stride + HUSS: cutlass.Constexpr, # history_u replay-slot stride + HKSS: cutlass.Constexpr, # history_k replay-slot stride + HGSS: cutlass.Constexpr, # history_G replay-slot stride + USE_I64: cutlass.Constexpr, + PDL: cutlass.Constexpr, +): + f32 = cutlass.Float32 + bf16 = cutlass.BFloat16 + + C = (2 * H + HV) * KDIM + NC = 2 * T + NCP = ((NC + 7) // 8) * 8 # MMA N must be a multiple of 8 + NACC = NCP + 4 # 16B-aligned padding reduces row aliasing + HPV = HV // H + AMM = AROWS + RBASE = AMM + NROW = HMAX # new k-hat rows inside the reused tile + NWARP_ACT = (HMAX + T + 15) // 16 + NWARP_HIST = HMAX // 16 + NHST = (HMAX * (KDIM // 8)) // 128 + HST_ROWS = 128 // (KDIM // 8) + NGRP = 4 + GS = HMAX // NGRP + + tid, _, _ = cute.arch.thread_idx() + hv, b, _ = cute.arch.block_idx() + h = hv // HPV + value_row = tid + + alloc = SmemAllocator() + pA = alloc.allocate_array(bf16, AMM * APAD, byte_alignment=16) + sA = cute.make_tensor(pA, cute.make_layout((AMM, KDIM), stride=(APAD, 1))) + sA3 = cute.make_tensor(pA, cute.make_layout((AMM, KDIM // 8, 8), stride=(APAD, 8, 1))) + sR = cute.make_tensor(pA, cute.make_layout((RROWS, KDIM), stride=(APAD, 1))) + pX = alloc.allocate_array(bf16, NCP * APAD, byte_alignment=16) + sX = cute.make_tensor(pX, cute.make_layout((NCP, KDIM), stride=(APAD, 1))) + # The A tile is dead once ldmatrix has consumed it, so the FP32 MMA results + # are recast over the same allocation. + pAcc = cute.recast_ptr(pA, dtype=f32) + sAcc = cute.make_tensor(pAcc, cute.make_layout((AMM + RROWS, NCP), stride=(NACC, 1))) + sAcc3 = cute.make_tensor( + pAcc, cute.make_layout((AMM + RROWS, NCP // 4, 4), stride=(NACC, 4, 1)) + ) + sAccM = cute.make_tensor(pAcc, cute.make_layout((AMM, NCP), stride=(NACC, 1))) + sAccR = cute.make_tensor(pAcc + AMM * NACC, cute.make_layout((RROWS, NCP), stride=(NACC, 1))) + pRed = alloc.allocate_array(f32, 4 * 16, byte_alignment=16) + sRed = cute.make_tensor(pRed, cute.make_layout((4, 16), stride=(16, 1))) + pG = alloc.allocate_array(f32, HMAX, byte_alignment=16) + sG = cute.make_tensor(pG, cute.make_layout((HMAX,), stride=(1,))) + pGate = alloc.allocate_array(f32, HMAX + 3 * T + T * T, byte_alignment=16) + sDec = cute.make_tensor(pGate, cute.make_layout((HMAX,), stride=(1,))) + sBeta = cute.make_tensor(pGate + HMAX, cute.make_layout((T,), stride=(1,))) + sCum = cute.make_tensor(pGate + HMAX + T, cute.make_layout((T,), stride=(1,))) + sDD = cute.make_tensor(pGate + HMAX + 2 * T, cute.make_layout((T,), stride=(1,))) + sW = cute.make_tensor(pGate + HMAX + 3 * T, cute.make_layout((T, T), stride=(T, 1))) + pBar = alloc.allocate_array(cutlass.Int64, 1, byte_alignment=8) + if cutlass.const_expr(PDL): + # A PDL launch can start while the previous kernel still holds SMs; keep + # the early CTAs spread one per SM instead of stacked on the idle ones. + alloc.allocate_array(cutlass.Uint8, PDL_SMEM_PAD, byte_alignment=16) + + if tid == 0: + prims.mbarrier_init(pBar, 1) + prims.fence_mbarrier_init() + prims.barrier_cta_sync(0) + + lane = cute.arch.lane_idx() + widx = cute.arch.warp_idx() + + # The whole checkpoint / history chain hangs off these indirections, so + # issue them before the slot-free loads that would otherwise delay them. + slot = mIdx[b].to(cutlass.Int32) + rslot = mRIdx[b].to(cutlass.Int32) + + # ---- slot-independent raw Q/K/V and Conv4 weights -------------------------- + mRXb = cute.make_tensor(mRX.iterator + b * RXBS, cute.make_layout((T, C), stride=(QKVZ, 1))) + cq = h * KDIM + tid + ck = H * KDIM + h * KDIM + tid + cv = 2 * H * KDIM + hv * KDIM + tid + + rq = cute.make_rmem_tensor((T,), bf16) + rk = cute.make_rmem_tensor((T,), bf16) + rv = cute.make_rmem_tensor((T,), bf16) + if cutlass.const_expr(not PDL): + for t in cutlass.range_constexpr(T): + rq[t] = mRXb[t, cq] + rk[t] = mRXb[t, ck] + rv[t] = mRXb[t, cv] + + wq = cute.make_rmem_tensor((4,), bf16) + wk = cute.make_rmem_tensor((4,), bf16) + wv = cute.make_rmem_tensor((4,), bf16) + cute.autovec_copy(mCW[(cq, None)], wq) + cute.autovec_copy(mCW[(ck, None)], wk) + cute.autovec_copy(mCW[(cv, None)], wv) + + # Gate inputs are CTA-uniform and slot-free, yet they feed the longest + # transcendental chain in the kernel; issue them early (clamped so the + # inactive lanes stay in bounds). + lt = lane if lane < T else cutlass.Int32(0) + mBb = cute.make_tensor(mB.iterator + b * (T * BW), cute.make_layout((T, HV), stride=(BW, 1))) + mAb = cute.make_tensor(mA.iterator + b * (T * AW), cute.make_layout((T, HV), stride=(AW, 1))) + ba_g = f32(0.0) + ba_b = f32(0.0) + if cutlass.const_expr(not PDL): + ba_g = mAb[lt, hv].to(f32) + ba_b = mBb[lt, hv].to(f32) + a_log = mAlog[hv] + dt_b = mDtb[hv] + + live = mDum[b].to(cutlass.Int32) == 0 + if not live: + if cutlass.const_expr(PDL): + # The raw rows come from this step's producer. + cute.arch.griddepcontrol_wait() + for t in cutlass.range_constexpr(T): + rq[t] = mRXb[t, cq] + rk[t] = mRXb[t, ck] + rv[t] = mRXb[t, cv] + # Dummy result values are ignored by contract, but keep them dependent + # on the current inputs so anti-tamper checks observe real per-call work. + mCXb_dummy = cute.make_tensor( + mCX.iterator + b * CXBS, + cute.make_layout((T, C), stride=(CXRS, 1)), + ) + mOutb_dummy = cute.make_tensor( + mOut.iterator + b * OBS, + cute.make_layout((T, HV, KDIM), stride=(HV * KDIM, KDIM, 1)), + ) + for t in cutlass.range_constexpr(T): + mCXb_dummy[t, cv] = rv[t] + mOutb_dummy[t, hv, value_row] = rv[t] + if hv % HPV == 0: + mCXb_dummy[t, cq] = rq[t] + mCXb_dummy[t, ck] = rk[t] + prims.exit() + + # ---- stage the 128x128 checkpoint tile: GMEM -> SMEM ------------------------ + tdh = tid // 8 + tdl = tid % 8 + if tid == 0: + prims.mbarrier_arrive_expect_tx(pBar, AMM * KDIM * 2) + prims.barrier_cta_sync(1) + if lane == 0: + if cutlass.const_expr(USE_I64): + ck_head = mCk.iterator + ( + cutlass.Int64(slot) * cutlass.Int64(CSS) + + cutlass.Int64(hv) * cutlass.Int64(STATE_HEAD_STRIDE) + ) + else: + ck_head = mCk.iterator + (slot * CSS + hv * STATE_HEAD_STRIDE) + for row_iter in cutlass.range_constexpr(AMM // 4): + row = row_iter * 4 + widx + if cutlass.const_expr(USE_I64): + row_ptr = (ck_head + cutlass.Int64(row * KDIM)).align(16).raw_ptr() + else: + row_ptr = (ck_head + row * KDIM).align(16).raw_ptr() + prims.cp_async_bulk_shared_cluster_global( + pA + row * APAD, + row_ptr, + pBar, + KDIM * 2, + ) + + # ---- slot-dependent loads: Conv checkpoint and replay history -------------- + mCSb = cute.make_tensor(mCS.iterator + slot * CVSS, cute.make_layout((C, 3), stride=(3, 1))) + sq0 = mCSb[cq, 0].to(f32) + sq1 = mCSb[cq, 1].to(f32) + sq2 = mCSb[cq, 2].to(f32) + sk0 = mCSb[ck, 0].to(f32) + sk1 = mCSb[ck, 1].to(f32) + sk2 = mCSb[ck, 2].to(f32) + sv0 = mCSb[cv, 0].to(f32) + sv1 = mCSb[cv, 1].to(f32) + sv2 = mCSb[cv, 2].to(f32) + + L = mHL[rslot].to(cutlass.Int32) + # Pool-backed histories have large replay-slot strides: address in 64 bits. + gHU = cute.make_tensor(mHU.iterator + cutlass.Int64(rslot) * HUSS, mHU.layout) + gHK = cute.make_tensor(mHK.iterator + cutlass.Int64(rslot) * HKSS, mHK.layout) + gHG = cute.make_tensor(mHG.iterator + cutlass.Int64(rslot) * HGSS, mHG.layout) + + # Only the first `L` history rows ever contribute; skipping whole groups of + # dead U rows is pure DRAM saved, and the zero fill keeps the epilogue exact. + hu = cute.make_rmem_tensor((HMAX,), bf16) + for g in cutlass.range_constexpr(NGRP): + if L > g * GS: + for j in cutlass.range_constexpr(GS): + hu[g * GS + j] = gHU[g * GS + j, hv, tdh, tdl] + else: + for j in cutlass.range_constexpr(GS): + hu[g * GS + j] = bf16(0.0) + + # History-K staging: HMAX rows x 16 chunks of 8 bf16 over 128 threads, so + # every thread issues NHST independent 128-bit loads. + hst = cute.make_rmem_tensor(cute.make_layout((NHST, 8), stride=(8, 1)), bf16) + for r in cutlass.range_constexpr(NHST): + if L > r * HST_ROWS: + p = r * 128 + tid + cute.autovec_copy( + gHK[(p // (KDIM // 8), h, p % (KDIM // 8), None)], + hst[(r, None)], + ) + else: + for e in cutlass.range_constexpr(8): + hst[r, e] = bf16(0.0) + hgv = gHG[hv, tid if tid < HMAX else cutlass.Int32(0)] + if tid < HMAX: + sG[tid] = hgv + lm1 = (L - 1) if L > 0 else cutlass.Int32(0) + + if cutlass.const_expr(PDL): + # State above was committed by earlier steps. The raw Q/K/V and + # b / a rows are produced in this step, and every global store + # below must follow the previous kernel's reads of shared buffers. + cute.arch.griddepcontrol_wait() + for t in cutlass.range_constexpr(T): + rq[t] = mRXb[t, cq] + rk[t] = mRXb[t, ck] + rv[t] = mRXb[t, cv] + ba_g = mAb[lt, hv].to(f32) + ba_b = mBb[lt, hv].to(f32) + + # ---- depthwise causal Conv4 + SiLU (FP32 accumulate, BF16 cast out) -------- + qv = cute.make_rmem_tensor((T,), f32) + kv = cute.make_rmem_tensor((T,), f32) + vv = cute.make_rmem_tensor((T,), f32) + + for t in cutlass.range_constexpr(T): + aq = ( + sq0 + if cutlass.const_expr(t == 0) + else ( + sq1 + if cutlass.const_expr(t == 1) + else (sq2 if cutlass.const_expr(t == 2) else rq[t - 3].to(f32)) + ) + ) + bq = ( + sq1 + if cutlass.const_expr(t == 0) + else (sq2 if cutlass.const_expr(t == 1) else rq[t - 2].to(f32)) + ) + cq2 = sq2 if cutlass.const_expr(t == 0) else rq[t - 1].to(f32) + yq = ( + aq * wq[0].to(f32) + + bq * wq[1].to(f32) + + cq2 * wq[2].to(f32) + + rq[t].to(f32) * wq[3].to(f32) + ) + sgq = cute.math.rcp( + f32(1.0) + cute.math.exp2(yq * f32(-LOG2E), approx=True, ftz=True), + approx=True, + ftz=True, + ) + qv[t] = (yq * sgq).to(bf16).to(f32) + + ak = ( + sk0 + if cutlass.const_expr(t == 0) + else ( + sk1 + if cutlass.const_expr(t == 1) + else (sk2 if cutlass.const_expr(t == 2) else rk[t - 3].to(f32)) + ) + ) + bk = ( + sk1 + if cutlass.const_expr(t == 0) + else (sk2 if cutlass.const_expr(t == 1) else rk[t - 2].to(f32)) + ) + ck2 = sk2 if cutlass.const_expr(t == 0) else rk[t - 1].to(f32) + yk = ( + ak * wk[0].to(f32) + + bk * wk[1].to(f32) + + ck2 * wk[2].to(f32) + + rk[t].to(f32) * wk[3].to(f32) + ) + sgk = cute.math.rcp( + f32(1.0) + cute.math.exp2(yk * f32(-LOG2E), approx=True, ftz=True), + approx=True, + ftz=True, + ) + kv[t] = (yk * sgk).to(bf16).to(f32) + + av = ( + sv0 + if cutlass.const_expr(t == 0) + else ( + sv1 + if cutlass.const_expr(t == 1) + else (sv2 if cutlass.const_expr(t == 2) else rv[t - 3].to(f32)) + ) + ) + bv = ( + sv1 + if cutlass.const_expr(t == 0) + else (sv2 if cutlass.const_expr(t == 1) else rv[t - 2].to(f32)) + ) + cv2 = sv2 if cutlass.const_expr(t == 0) else rv[t - 1].to(f32) + yv = ( + av * wv[0].to(f32) + + bv * wv[1].to(f32) + + cv2 * wv[2].to(f32) + + rv[t].to(f32) * wv[3].to(f32) + ) + sgv = cute.math.rcp( + f32(1.0) + cute.math.exp2(yv * f32(-LOG2E), approx=True, ftz=True), + approx=True, + ftz=True, + ) + vv[t] = (yv * sgv).to(bf16).to(f32) + + # ---- compact raw candidate copy, straight out of the Conv4 input registers - + mCXb = cute.make_tensor(mCX.iterator + b * CXBS, cute.make_layout((T, C), stride=(CXRS, 1))) + for t in cutlass.range_constexpr(T): + mCXb[t, cv] = rv[t] + if hv % HPV == 0: + for t in cutlass.range_constexpr(T): + mCXb[t, cq] = rq[t] + mCXb[t, ck] = rk[t] + + for t in cutlass.range_constexpr(T): + rsk = cute.arch.warp_reduction_sum(kv[t] * kv[t]) + rsq = cute.arch.warp_reduction_sum(qv[t] * qv[t]) + if lane == 0: + sRed[widx, t] = rsk + sRed[widx, T + t] = rsq + + cute.arch.barrier() + + prevG = sG[lm1] if L > 0 else f32(0.0) + # ---- CTA-uniform decay and gating (warp 0) --------------------------------- + if widx == 0: + if lane < HMAX: + dcy = f32(0.0) + if lane < L: + dcy = cute.math.exp2((prevG - sG[lane]) * f32(LOG2E), approx=True, ftz=True) + sDec[lane] = dcy + + gv = f32(0.0) + bta = f32(0.0) + if lane < T: + gi = ba_g + dt_b + sp = cute.math.log1p(cute.math.exp(gi)) + sp = gi if gi > f32(20.0) else sp + gv = -cute.math.exp(a_log) * sp + eb = cute.math.exp2(ba_b * f32(-LOG2E), approx=True, ftz=True) + bta = cute.math.rcp(f32(1.0) + eb, approx=True, ftz=True) + ps = gv + for d in cutlass.range_constexpr(3): + sh = cute.arch.shuffle_sync_up(ps, 1 << d) + if lane >= (1 << d): + ps = ps + sh + cum = prevG + ps + if lane < T: + sBeta[lane] = bta + sCum[lane] = cum + sDD[lane] = cute.math.exp2(ps * f32(LOG2E), approx=True, ftz=True) + for it in cutlass.range_constexpr((T * T + 31) // 32): + idx = it * 32 + lane + ct = cute.arch.shuffle_sync(cum, idx // T) + cj = cute.arch.shuffle_sync(cum, idx % T) + if idx < T * T: + sW[(idx // T, idx % T)] = cute.math.exp2( + (ct - cj) * f32(LOG2E), approx=True, ftz=True + ) + + # ---- normalize q / k, publish the B operand -------------------------------- + kbv = cute.make_rmem_tensor((T,), bf16) + ik_lane = f32(0.0) + iq_lane = f32(0.0) + if lane < T: + tk = sRed[0, lane] + sRed[1, lane] + sRed[2, lane] + sRed[3, lane] + tq = sRed[0, T + lane] + sRed[1, T + lane] + sRed[2, T + lane] + sRed[3, T + lane] + ik_lane = cute.math.rcp( + cute.math.sqrt(tk + f32(1.0e-6), approx=True, ftz=True), approx=True, ftz=True + ) + iq_lane = cute.math.rcp( + cute.math.sqrt(tq + f32(1.0e-6), approx=True, ftz=True), approx=True, ftz=True + ) + for t in cutlass.range_constexpr(T): + ik = cute.arch.shuffle_sync(ik_lane, t) + iq = cute.arch.shuffle_sync(iq_lane, t) + kb = (kv[t] * ik).to(bf16) + kbv[t] = kb + sX[t, tid] = kb + sX[T + t, tid] = (qv[t] * (f32(SCALE) * iq)).to(bf16) + if cutlass.const_expr(NCP > NC): + for n in cutlass.range_constexpr(NCP - NC): + sX[NC + n, tid] = bf16(0.0) + + while not prims.mbarrier_try_wait_parity(pBar, 0): + pass + prims.barrier_cta_sync(0) + + # ---- one BF16 warp-MMA: acc[r, n] = sum_k A[r, k] * X[n, k] ---------------- + op = cwarp.MmaF16BF16Op(bf16, f32, (16, 8, 16)) + tiled_mma = cute.make_tiled_mma(op, cute.make_layout((4, 1, 1)), permutation_mnk=(64, 8, 16)) + thr_mma = tiled_mma.get_slice(tid) + tCsA = thr_mma.partition_A(sA) + tCsB = thr_mma.partition_B(sX) + tCsC = thr_mma.partition_C(sAccM) + tCrA = tiled_mma.make_fragment_A(tCsA) + tCrB = tiled_mma.make_fragment_B(tCsB) + acc = cute.make_rmem_tensor(tCsC.shape, f32) + acc.fill(0.0) + + ld_a = cute.make_copy_atom(cwarp.LdMatrix8x8x16bOp(False, 4), bf16) + ld_b = cute.make_copy_atom(cwarp.LdMatrix8x8x16bOp(False, 2), bf16) + tld_a = cute.make_tiled_copy_A(ld_a, tiled_mma) + tld_b = cute.make_tiled_copy_B(ld_b, tiled_mma) + thr_a = tld_a.get_slice(tid) + thr_b = tld_b.get_slice(tid) + cute.copy(tld_a, thr_a.partition_S(sA), thr_a.retile(tCrA)) + cute.copy(tld_b, thr_b.partition_S(sX), thr_b.retile(tCrB)) + cute.gemm(tiled_mma, acc, tCrA, tCrB, acc) + + # Second pass: reuse the (now dead) A tile for history-K and k-hat rows. + cute.arch.barrier() + for r in cutlass.range_constexpr(NHST): + p = r * 128 + tid + cute.autovec_copy(hst[(r, None)], sA3[(p // (KDIM // 8), p % (KDIM // 8), None)]) + for t in cutlass.range_constexpr(T): + sA[NROW + t, tid] = kbv[t] + cute.arch.barrier() + + tCsR = thr_mma.partition_A(sR) + tCrR = tiled_mma.make_fragment_A(tCsR) + tCsCR = thr_mma.partition_C(sAccR) + accR = cute.make_rmem_tensor(tCsCR.shape, f32) + accR.fill(0.0) + # With the four-warp M64 tiling each warp owns 16 rows: the low warps hold + # cached history and stand down for an empty history, the next warp holds + # the live candidate-K rows, and any remaining warps own only MMA padding. + act = widx < NWARP_ACT and (L > 0 or widx >= NWARP_HIST) + if act: + cute.copy(tld_a, thr_a.partition_S(sR), thr_a.retile(tCrR)) + cute.gemm(tiled_mma, accR, tCrR, tCrB, accR) + + cute.arch.barrier() # everything is in registers; SMEM can be reused + cute.autovec_copy(acc, tCsC) + if act: + cute.autovec_copy(accR, tCsCR) + cute.arch.barrier() + + # ---- epilogue: one value row per thread ------------------------------------ + pk = cute.make_rmem_tensor((NC,), f32) + epg_lane = f32(0.0) + if lane == 0: + epg_lane = cute.math.exp2(prevG * f32(LOG2E), approx=True, ftz=True) + epg = cute.arch.shuffle_sync(epg_lane, 0) + df = cute.make_rmem_tensor((4,), f32) + for cc in cutlass.range_constexpr(NCP // 4): + cute.autovec_copy(sAcc3[(tid, cc, None)], df) + for e in cutlass.range_constexpr(4): + n = cc * 4 + e + if cutlass.const_expr(n < NC): + pk[n] = df[e] * epg + + for g in cutlass.range_constexpr(NGRP): + if L > g * GS: + for j in cutlass.range_constexpr(GS): + i = g * GS + j + u = hu[i].to(f32) * sDec[i] + for cc in cutlass.range_constexpr(NCP // 4): + cute.autovec_copy(sAcc3[(RBASE + i, cc, None)], df) + for e in cutlass.range_constexpr(4): + n = cc * 4 + e + if cutlass.const_expr(n < NC): + pk[n] = pk[n] + u * df[e] + + mOutb = cute.make_tensor( + mOut.iterator + b * OBS, cute.make_layout((T, HV, KDIM), stride=(HV * KDIM, KDIM, 1)) + ) + uu = cute.make_rmem_tensor((T,), f32) + for t in cutlass.range_constexpr(T): + skv = sDD[t] * pk[t] + for j in cutlass.range_constexpr(T): + if cutlass.const_expr(j < t): + skv = skv + uu[j] * (sAcc[RBASE + NROW + j, t] * sW[(t, j)]) + ut = sBeta[t] * (vv[t] - skv) + uu[t] = ut + o = sDD[t] * pk[T + t] + for j in cutlass.range_constexpr(T): + if cutlass.const_expr(j < t): + o = o + uu[j] * (sAcc[RBASE + NROW + j, T + t] * sW[(t, j)]) + o = o + ut * sAcc[RBASE + NROW + t, T + t] + mOutb[t, hv, value_row] = o.to(bf16) + + if live: + for t in cutlass.range_constexpr(T): + gHU[L + t, hv, tdh, tdl] = uu[t].to(bf16) + if hv % HPV == 0: + for t in cutlass.range_constexpr(T): + gHK[L + t, h, tdh, tdl] = kbv[t] + if tid == 0: + for t in cutlass.range_constexpr(T): + gHG[hv, L + t] = sCum[t] + + +@cute.jit +def _launch( + mRX, + mCW, + mCS, + mB, + mA, + mCk, + mIdx, + mRIdx, + mDum, + mHU, + mHK, + mHG, + mHL, + mAlog, + mDtb, + mOut, + mCX, + T: cutlass.Constexpr, + H: cutlass.Constexpr, + HV: cutlass.Constexpr, + HMAX: cutlass.Constexpr, + QKVZ: cutlass.Constexpr, + RXBS: cutlass.Constexpr, + BW: cutlass.Constexpr, + AW: cutlass.Constexpr, + OBS: cutlass.Constexpr, + CXBS: cutlass.Constexpr, + CXRS: cutlass.Constexpr, + CSS: cutlass.Constexpr, + STATE_HEAD_STRIDE: cutlass.Constexpr, + CVSS: cutlass.Constexpr, + HUSS: cutlass.Constexpr, + HKSS: cutlass.Constexpr, + HGSS: cutlass.Constexpr, + USE_I64: cutlass.Constexpr, + PDL: cutlass.Constexpr, + stream: cuda.CUstream, +): + B = mIdx.shape[0] + _fused_kernel( + mRX, + mCW, + mCS, + mB, + mA, + mCk, + mIdx, + mRIdx, + mDum, + mHU, + mHK, + mHG, + mHL, + mAlog, + mDtb, + mOut, + mCX, + T, + H, + HV, + HMAX, + QKVZ, + RXBS, + BW, + AW, + OBS, + CXBS, + CXRS, + CSS, + STATE_HEAD_STRIDE, + CVSS, + HUSS, + HKSS, + HGSS, + USE_I64, + PDL, + ).launch(grid=(HV, B, 1), block=(KDIM, 1, 1), stream=stream, use_pdl=PDL) + + +@torch.no_grad() +def gdn_mtp_replay( + raw_x: torch.Tensor, + conv_weight: torch.Tensor, + conv_state: torch.Tensor, + b: torch.Tensor, + a: torch.Tensor, + checkpoint: torch.Tensor, + state_indices: torch.Tensor, + is_dummy: torch.Tensor, + history_u: torch.Tensor, + history_k: torch.Tensor, + history_G: torch.Tensor, + history_len: torch.Tensor, + A_log: torch.Tensor, + dt_bias: torch.Tensor, + output: torch.Tensor, + candidate_x: torch.Tensor, + replay_indices: torch.Tensor | None = None, +) -> None: + """Fuse Conv4 and one BF16 GDN replay step. + + ``raw_x`` is the row-strided Q/K/V prefix of the packed Q/K/V/Z input. + ``b`` and ``a`` are the ``[B * T, HV]`` beta and decay gate inputs; each + may be a column view of a wider projection with its own row stride. + The checkpoint and Conv state are addressed by ``state_indices``; the + history and its length by ``replay_indices`` (default: ``state_indices``). + History slots may be strided, e.g. views of KV-cache pool pages. + Neither persistent checkpoint is changed here; ``candidate_x`` retains the + compact raw candidates needed by the all-layer commit. + """ + if replay_indices is None: + replay_indices = state_indices + B, T, C = raw_x.shape + S, HV, V, K = checkpoint.shape + R = history_u.shape[0] + H = history_k.shape[2] + CAP = history_u.shape[1] + HMAX = CAP - T + + if B == 0: + return + if K != KDIM or V != KDIM: + raise ValueError("GDN MTP replay requires key_dim=value_dim=128") + if not 1 <= T <= 8: + raise ValueError("GDN MTP replay requires 1 <= tokens_per_step <= 8") + if HMAX != 16: + raise ValueError("GDN MTP replay requires a history window of 16") + if H <= 0 or HV <= 0 or HV % H != 0: + raise ValueError("value_heads must be divisible by key_heads") + if C != (2 * H + HV) * KDIM: + raise ValueError("raw_x has an unexpected channel count") + if conv_weight.shape != (C, 4) or conv_weight.dtype != torch.bfloat16: + raise ValueError("conv_weight must be BF16 with shape [channels, 4]") + if conv_weight.stride() != (4, 1): + raise ValueError("conv_weight must be contiguous") + if conv_state.shape != (S, C, 3) or conv_state.dtype != torch.bfloat16: + raise ValueError("conv_state must be BF16 with shape [slots, channels, 3]") + if conv_state.stride()[1:] != (3, 1): + raise ValueError("conv_state channel/window dimensions must be dense") + if checkpoint.dtype != torch.bfloat16 or checkpoint.ndim != 4: + raise ValueError("checkpoint must be a rank-4 BF16 V2 layer view") + if checkpoint.stride()[1:] != (V * K, K, 1): + raise ValueError("checkpoint head/value/key dimensions must be dense") + if history_u.shape != (R, CAP, HV, V): + raise ValueError("history_u has an unexpected shape") + if history_k.shape != (R, CAP, H, K): + raise ValueError("history_k has an unexpected shape") + if history_G.shape != (R, HV, CAP): + raise ValueError("history_G has an unexpected shape") + if history_len.shape != (R,) or history_len.dtype != torch.int32: + raise ValueError("history_len must be int32 with shape [replay slots]") + if state_indices.shape != (B,) or state_indices.dtype != torch.int32: + raise ValueError("state_indices must be int32 with shape [batch]") + if replay_indices.shape != (B,) or replay_indices.dtype != torch.int32: + raise ValueError("replay_indices must be int32 with shape [batch]") + if is_dummy.shape != (B,) or is_dummy.dtype != torch.bool: + raise ValueError("is_dummy must be bool with shape [batch]") + if output.shape != (B, T, HV, V) or output.dtype != torch.bfloat16: + raise ValueError("output must be BF16 with shape [batch, T, value_heads, 128]") + if candidate_x.shape != raw_x.shape or candidate_x.dtype != torch.bfloat16: + raise ValueError("candidate_x must be a BF16 copy of raw_x") + if A_log.shape != (HV,) or dt_bias.shape != (HV,): + raise ValueError("A_log and dt_bias must have shape [value_heads]") + for name, gate in (("b", b), ("a", a)): + if gate.shape != (B * T, HV) or gate.stride(1) != 1: + raise ValueError(f"{name} must have shape [batch * tokens, value_heads], column-dense") + bf16_tensors = ( + raw_x, + b, + a, + checkpoint, + history_u, + history_k, + output, + candidate_x, + ) + if any(tensor.dtype != torch.bfloat16 for tensor in bf16_tensors): + raise TypeError("GDN MTP replay requires BF16 inputs, histories, and state") + if ( + history_G.dtype != torch.float32 + or A_log.dtype != torch.float32 + or dt_bias.dtype != torch.float32 + ): + raise TypeError("GDN decay histories and parameters must be FP32") + if raw_x.stride(2) != 1 or candidate_x.stride()[1:] != (C, 1) or not output.is_contiguous(): + raise ValueError("raw_x and candidate_x must be channel-dense and output contiguous") + if history_u.stride()[1:] != (HV * V, V, 1): + raise ValueError("history_u token/head/value dimensions must be dense") + if history_k.stride()[1:] != (H * K, K, 1): + raise ValueError("history_k token/head/key dimensions must be dense") + if history_G.stride()[1:] != (CAP, 1): + raise ValueError("history_G head/token dimensions must be dense") + tensors = ( + raw_x, + conv_weight, + conv_state, + b, + a, + checkpoint, + state_indices, + replay_indices, + is_dummy, + history_u, + history_k, + history_G, + history_len, + A_log, + dt_bias, + output, + candidate_x, + ) + if any(not tensor.is_cuda for tensor in tensors): + raise ValueError("GDN MTP replay tensors must be CUDA tensors") + if any(tensor.device != output.device for tensor in tensors): + raise ValueError("GDN MTP replay tensors must be on the same device") + + # B never reaches the compile key: the batch dimension is peeled off every + # dense tensor and re-applied as a runtime pointer offset, and the two + # rank-1 row tables carry a dynamic layout. + args = ( + from_dlpack(raw_x[0], assumed_align=16), + from_dlpack(conv_weight, assumed_align=16), + from_dlpack(conv_state[0], assumed_align=16), + from_dlpack(b[:T], assumed_align=2), + from_dlpack(a[:T], assumed_align=2), + from_dlpack(checkpoint[0, 0], assumed_align=16), + from_dlpack(state_indices, assumed_align=4).mark_layout_dynamic(), + from_dlpack(replay_indices, assumed_align=4).mark_layout_dynamic(), + from_dlpack(is_dummy.view(torch.uint8), assumed_align=1).mark_layout_dynamic(), + from_dlpack(history_u[0].view(CAP, HV, V // 8, 8), assumed_align=16), + from_dlpack(history_k[0].view(CAP, H, K // 8, 8), assumed_align=16), + from_dlpack(history_G[0], assumed_align=16), + from_dlpack(history_len, assumed_align=4), + from_dlpack(A_log, assumed_align=16), + from_dlpack(dt_bias, assumed_align=16), + from_dlpack(output[0], assumed_align=16), + from_dlpack(candidate_x[0], assumed_align=16), + ) + stream = cuda.CUstream(torch.cuda.current_stream().cuda_stream) + + pdl = _use_pdl(B * HV, output.device) + key = ( + pdl, + S, + T, + H, + HV, + HMAX, + raw_x.stride(0), + raw_x.stride(1), + b.stride(0), + a.stride(0), + candidate_x.stride(0), + candidate_x.stride(1), + checkpoint.stride(0), + checkpoint.stride(1), + conv_state.stride(0), + history_u.stride(0), + history_u.stride(1), + history_k.stride(0), + history_k.stride(1), + history_G.stride(0), + history_G.stride(1), + R, + history_len.stride(0), + ) + fn = _CACHE.get(key) + if fn is None: + use_i64 = ((S - 1) * checkpoint.stride(0) + HV * V * K - 1) >= 2**31 + fn = cute.compile( + _launch, + *args, + T, + H, + HV, + HMAX, + raw_x.stride(1), + raw_x.stride(0), + b.stride(0), + a.stride(0), + T * HV * V, + candidate_x.stride(0), + candidate_x.stride(1), + checkpoint.stride(0), + checkpoint.stride(1), + conv_state.stride(0), + history_u.stride(0), + history_k.stride(0), + history_G.stride(0), + use_i64, + pdl, + stream, + ) + _CACHE[key] = fn + + fn(*args, stream) diff --git a/tensorrt_llm/_torch/modules/fla/cache_manager.py b/tensorrt_llm/_torch/modules/fla/cache_manager.py index da61e0326c24..4b52587823d3 100644 --- a/tensorrt_llm/_torch/modules/fla/cache_manager.py +++ b/tensorrt_llm/_torch/modules/fla/cache_manager.py @@ -37,7 +37,7 @@ is_gdn_flashinfer_replay_required, is_gdn_replay_enabled, ) -from tensorrt_llm._utils import get_sm_version, prefer_pinned +from tensorrt_llm._utils import get_sm_version, is_sm_100f, prefer_pinned from tensorrt_llm.logger import logger from tensorrt_llm.mapping import Mapping from tensorrt_llm.runtime.kv_cache_manager_v2 import BufferConfig, DataRole @@ -74,6 +74,14 @@ _GDN_REPLAY_META_PNAT = 0 _GDN_REPLAY_META_CACHE_BUF_IDX = 1 _GDN_REPLAY_META_CACHE_BASE = 2 +# Per-layer roles of the GDN MTP replay (GDNMtpReplayState): one history per +# replay slot holding the accepted window followed by the step's candidates. +_GDN_MTP_REPLAY_HISTORY_ROLES = { + "old_x": DataRole("gdn_mtp_u"), + "old_B": DataRole("gdn_mtp_k"), + "old_dt": DataRole("gdn_mtp_g"), +} +GDN_MTP_REPLAY_HISTORY_SIZE = 16 class ReplayStateUpdateMetadata(NamedTuple): @@ -783,6 +791,314 @@ def shutdown(self) -> None: self._state_strides = None +class GDNMtpReplayState(GDNReplayState): + """GDN MTP replay with the Conv4 update fused into the replay kernel. + + Every layer keeps one history per replay slot: the accepted window of + ``GDN_MTP_REPLAY_HISTORY_SIZE`` rows followed by the step's candidate rows + (U and normalized K in BF16, cumulative G in FP32). The first layer's + metadata row holds the accepted history length. Verification + (``gdn_mtp_replay``) leaves both checkpoints untouched and keeps the raw + candidate Conv inputs; after acceptance one ``gdn_mtp_commit`` launch + advances every layer's Conv window and history length and, when the + history fills, folds it into the recurrent checkpoint. + """ + + def __init__(self, tokens_per_gen_step: int) -> None: + if not 1 <= tokens_per_gen_step <= 8: + raise ValueError("GDN MTP replay supports 1 to 8 tokens per generation step") + super().__init__(tokens_per_gen_step) + self.replay_history_size = GDN_MTP_REPLAY_HISTORY_SIZE + self._key_heads = 0 + self._value_heads = 0 + self._state_view: torch.Tensor | None = None + self._conv_view: torch.Tensor | None = None + self._conv_descriptors: torch.Tensor | None = None + + @property + def has_bound_states(self) -> bool: + return self._state_view is not None or self._state_descriptors is not None + + @override + def replay_layout(self, context: MambaStateLayout, layer_id: int) -> ReplayLayout: + if not context.mamba_pp_layers: + return {} + num_heads, head_dim, d_state = context.ssm_state_shape + capacity = self.replay_history_size + self.replay_step_width + layout = { + _GDN_MTP_REPLAY_HISTORY_ROLES["old_x"]: ( + context.conv_state_dtype, + [capacity, num_heads, head_dim], + ), + _GDN_MTP_REPLAY_HISTORY_ROLES["old_B"]: ( + context.conv_state_dtype, + [capacity, context.n_groups_per_rank, d_state], + ), + _GDN_MTP_REPLAY_HISTORY_ROLES["old_dt"]: (torch.float32, [num_heads, capacity]), + } + if layer_id == context.mamba_pp_layers[0]: + layout[_GDN_REPLAY_META_ROLE] = ( + torch.int32, + [_GDN_REPLAY_META_BYTES // torch.int32.itemsize], + ) + return layout + + @override + def bind( + self, + context: MambaStateLayout, + ssm_states: list[torch.Tensor], + conv_states: list[torch.Tensor], + ) -> None: + self._ssm_states = tuple(ssm_states) + self._conv_states = tuple(conv_states) + self._linear_steps = True + self._seed_rank_offset = ( + context.mapping.tp_rank * 1_000_003 + + context.mapping.pp_rank * 1_000_033 + + context.mapping.rank * 1_009 + ) + if not context.mamba_pp_layers: + return + num_heads, _, _ = context.ssm_state_shape + self._key_heads = context.n_groups_per_rank + self._value_heads = num_heads + cache_size = ssm_states[0].shape[0] + device = ssm_states[0].device + # The commit rebuilds the accepted Conv window from the raw candidate + # inputs, so one row of Conv channels per candidate token suffices. + self.intermediate_conv = torch.zeros( + [ + len(context.mamba_pp_layers), + context.max_batch_size, + self.replay_step_width, + context.conv_state_shape[0], + ], + dtype=context.conv_state_dtype, + device=device, + ) + self.intermediate_indices = torch.arange( + context.max_batch_size, dtype=torch.int32, device=device + ) + self.rand_seed = allocate_mamba_seed_buffer(cache_size, self._seed_rank_offset, device) + if self._pool_layers is not None: + self._bind_pool_history() + else: + self._allocate_history(context, cache_size, device) + from tensorrt_llm._torch.custom_ops.cute_dsl_gdn_mtp_commit import ( + build_gdn_mtp_history_descriptors, + ) + + self._history_descriptors = build_gdn_mtp_history_descriptors( + *(self._layer_views(name) for name in _GDN_MTP_REPLAY_HISTORY_ROLES) + ) + self._bind_state_addressing(context) + + def _layer_views(self, name: str) -> list[torch.Tensor]: + buffer = getattr(self, name) + return list(buffer.unbind(0)) if isinstance(buffer, torch.Tensor) else buffer + + @override + def _allocate_history( + self, context: MambaStateLayout, cache_size: int, device: torch.device + ) -> None: + """Allocate standalone history with one row per recurrent-state slot.""" + layer_ids = context.mamba_pp_layers + self.prev_num_accepted_tokens = torch.zeros(cache_size, dtype=torch.int32, device=device) + layout = self.replay_layout(context, layer_ids[0]) + for name, role in _GDN_MTP_REPLAY_HISTORY_ROLES.items(): + dtype, shape = layout[role] + setattr( + self, + name, + torch.zeros([len(layer_ids), cache_size, *shape], dtype=dtype, device=device), + ) + + @override + def _bind_pool_history(self) -> None: + layers = self._pool_layers + self._replay_meta = layers[0][_GDN_REPLAY_META_ROLE] + self.prev_num_accepted_tokens = self._replay_meta[:, _GDN_REPLAY_META_PNAT] + for name, role in _GDN_MTP_REPLAY_HISTORY_ROLES.items(): + views = [layer[role] for layer in layers] + stacked = _stack_state_views(views) + setattr(self, name, stacked if stacked is not None else views) + + @override + def _bind_state_addressing(self, context: MambaStateLayout) -> None: + """Resolve how the all-layer commit addresses the checkpoints and Conv windows.""" + if not self._ssm_states: + return + self._state_view, self._state_descriptors = _gdn_mtp_layer_addressing( + self._ssm_states, tuple(context.ssm_state_shape), "SSM state" + ) + self._conv_view, self._conv_descriptors = _gdn_mtp_layer_addressing( + self._conv_states, tuple(context.conv_state_shape), "Conv state" + ) + logger.info_once( + "Configured GDN MTP replay: fused Conv4 replay and all-layer commit; " + f"state layout: {'affine' if self._state_view is not None else 'indirect'}", + key="gdn_mtp_replay_v2_layout", + ) + + @override + def _history_buffers(self) -> tuple: + return (self.old_x, self.old_B, self.old_dt) + + @override + def _layer_cache_fields(self, layer_offset: int) -> dict[str, torch.Tensor | None]: + # old_x / old_B / old_dt carry the U / K / cumulative-G histories and + # prev_num_accepted_tokens the accepted history length. + return { + "mamba_ssm_rand_seed": self.rand_seed, + "intermediate_conv_window": self.intermediate_conv[layer_offset], + "prev_num_accepted_tokens": self.prev_num_accepted_tokens, + "old_x": self.old_x[layer_offset], + "old_B": self.old_B[layer_offset], + "old_dt": self.old_dt[layer_offset], + } + + @override + def reset_replay_slots(self, replay_slots: torch.Tensor) -> None: + """Mark ``replay_slots`` empty. + + Only the length is reset: the kernels read no history row at or past + it and overwrite candidate rows before accepting them. + """ + if self.prev_num_accepted_tokens is None: + return + if self._replay_meta is not None: + self._replay_meta.index_fill_(0, replay_slots, 0) + else: + self.prev_num_accepted_tokens.index_fill_(0, replay_slots, 0) + + @override + def update(self, batch: MambaAcceptanceBatch, replay_slots: torch.Tensor | None = None) -> None: + """Commit the accepted Conv windows and histories of every layer in one launch. + + The replay slots come from the step's work items, which the metadata + snapshots with the history lengths before the layer loop. + """ + from tensorrt_llm._torch.custom_ops.cute_dsl_gdn_mtp_commit import gdn_mtp_commit + + num_decodes = batch.num_generations + if num_decodes == 0 or not self._ssm_states: + return + if self._history_descriptors is None or not self.has_bound_states: + raise RuntimeError("GDN MTP replay buffers are not bound") + if batch.is_dummy_request is None: + raise RuntimeError("GDN MTP replay commit requires the dummy-request mask") + mamba_metadata = batch.attention_metadata.mamba_metadata + if mamba_metadata.replay_num_decodes != num_decodes: + raise RuntimeError( + "GDN replay metadata contains " + f"{mamba_metadata.replay_num_decodes} decode requests, " + f"but state update received {num_decodes}." + ) + gdn_mtp_commit( + ssm_states=(self._state_view if self._state_view is not None else self._ssm_states[0]), + conv_states=(self._conv_view if self._conv_view is not None else self._conv_states[0]), + candidate_x=self.intermediate_conv, + history_descriptors=self._history_descriptors, + history_len=self.prev_num_accepted_tokens, + replay_work_items=mamba_metadata.replay_work_items[:num_decodes], + accepted_tokens=batch.num_accepted_tokens.to(torch.int32), + is_dummy=batch.is_dummy_request, + key_heads=self._key_heads, + value_heads=self._value_heads, + history_window=self.replay_history_size, + ssm_state_descriptors=self._state_descriptors, + conv_state_descriptors=self._conv_descriptors, + ) + + @override + def commit_all_layers(self, attention_metadata: object, num_decodes: int) -> None: + raise NotImplementedError("GDN MTP replay commits in update()") + + @override + def get_replay_metadata(self) -> ReplayStateUpdateMetadata | None: + if self.prev_num_accepted_tokens is None: + return None + return ReplayStateUpdateMetadata( + prev_num_accepted_tokens=self.prev_num_accepted_tokens, + cache_buf_idx=None, + replay_step_width=self.replay_step_width, + replay_history_size=self.replay_history_size, + ) + + @override + def shutdown(self) -> None: + super().shutdown() + self._state_view = None + self._conv_view = None + self._conv_descriptors = None + + +def _gdn_mtp_layer_addressing( + states: tuple[torch.Tensor, ...], inner_shape: tuple[int, ...], name: str +) -> tuple[torch.Tensor | None, torch.Tensor | None]: + """A slot-major [S, L, ...] view of evenly spaced layer views, else [L, 2] descriptors. + + Descriptor rows are (base address in bytes, slot stride in elements). + """ + reference = states[0] + dense = tuple(math.prod(inner_shape[i + 1 :]) for i in range(len(inner_shape))) + for state in states: + if ( + state.dtype != reference.dtype + or state.device != reference.device + or tuple(state.shape[1:]) != inner_shape + or state.stride()[1:] != dense + ): + raise RuntimeError( + f"GDN MTP replay requires {name} layers with matching dtype, device, " + "shape and dense inner dimensions" + ) + stacked = _stack_state_views(list(states)) + if stacked is not None: + return stacked.transpose(0, 1), None + logger.warning_once( + f"V2 GDN {name} views are not affine; using indirect GDN MTP commit addressing", + key=f"gdn_mtp_replay_indirect_{name}", + ) + descriptors = torch.tensor( + [(state.data_ptr(), state.stride(0)) for state in states], + dtype=torch.int64, + device=reference.device, + ) + return None, descriptors + + +def _gdn_mtp_replay_unsupported_reason( + layout: MambaStateLayout, spec_config: object | None +) -> Optional[str]: + """Why the GDN MTP replay kernels cannot serve ``layout``, or None when they can.""" + from tensorrt_llm._torch.cute_dsl_utils import IS_CUTLASS_DSL_AVAILABLE + + num_heads, head_dim, d_state = layout.ssm_state_shape + groups = layout.n_groups_per_rank + if not is_sm_100f(get_sm_version()): + return "requires an SM100/SM103 GPU" + if not IS_CUTLASS_DSL_AVAILABLE: + return "requires CUTLASS DSL" + if layout.conv_state_layout != "q_k_v": + return "requires the q_k_v convolution state layout" + if layout.conv_state_dtype != torch.bfloat16 or layout.ssm_state_dtype != torch.bfloat16: + return "requires bf16 model and SSM state dtypes" + if head_dim != 128 or d_state != 128: + return "requires key and value head size 128" + if groups <= 0 or num_heads % groups != 0: + return "requires an integral value/key head ratio" + if layout.conv_state_shape and tuple(layout.conv_state_shape) != ( + (2 * groups * d_state + num_heads * head_dim), + 3, + ): + return "requires a 4-tap convolution over the q|k|v channels" + if spec_config is not None and spec_config.tokens_per_gen_step > 8: + return "supports at most 8 tokens per generation step" + return None + + def _gdn_replay_gate( spec_config: object | None, ssm_cache_dtype: torch.dtype ) -> tuple[bool, list[str]]: @@ -911,6 +1227,15 @@ def create_gdn_state( if allow_flashinfer_ring and _use_flashinfer_ring_replay(manager, state is not None): logger.info("GDN replay kernel: FlashInfer ring buffer") state = GDNReplayState(manager.spec_config.tokens_per_gen_step, use_flashinfer_ring=True) + elif state is not None and manager.gdn_mtp_replay: + # The model's GDN layers can verify with the GDN MTP replay kernels; + # configurations they cannot serve keep the cached replay. + reason = _gdn_mtp_replay_unsupported_reason(manager._state_layout, manager.spec_config) + if reason is None: + logger.info("GDN replay kernel: GDN MTP replay") + state = GDNMtpReplayState(manager.spec_config.tokens_per_gen_step) + else: + logger.info(f"GDN MTP replay {reason}; using the cached replay") if state is None: return GDNIntermediateState() state.fused_verify = manager.gdn_fused_verify @@ -967,9 +1292,15 @@ def _estimated_gdn_replay_state( conv_state_layout="q_k_v", ) requested, reason = _flashinfer_ring_replay_reason(layout, spec_config, use_replay) - state = GDNReplayState( - spec_config.tokens_per_gen_step, use_flashinfer_ring=requested and reason is None - ) + if requested and reason is None: + state = GDNReplayState(spec_config.tokens_per_gen_step, use_flashinfer_ring=True) + elif ( + kwargs.get("gdn_mtp_replay", False) + and _gdn_mtp_replay_unsupported_reason(layout, spec_config) is None + ): + state = GDNMtpReplayState(spec_config.tokens_per_gen_step) + else: + state = GDNReplayState(spec_config.tokens_per_gen_step) return state, layout @@ -1009,6 +1340,9 @@ class Qwen35HybridCacheManager(InforwardSnapshotHost, MambaHybridCacheManagerV2) # Whether the model's GDN layers verify drafts with the fused kernels, which # commit in-layer at every batch size. gdn_fused_verify = False + # Whether the model's GDN layers can verify drafts with the GDN MTP replay + # kernels (modules/mamba/gdn_mixer.py) instead of the cached replay. + gdn_mtp_replay = False @override def __init__( @@ -1016,11 +1350,13 @@ def __init__( *args, use_replay_state_update: bool | None = None, gdn_fused_verify: bool = False, + gdn_mtp_replay: bool = False, **kwargs, ) -> None: kwargs.pop("mamba_ssm_stochastic_rounding", False) self._requested_replay = use_replay_state_update self.gdn_fused_verify = gdn_fused_verify + self.gdn_mtp_replay = gdn_mtp_replay # A disaggregated context server never decodes and keeps no replay history. self._context_only = _is_disagg_context_server(kwargs.get("is_disagg", False)) self._replay_region = None @@ -1028,6 +1364,13 @@ def __init__( kwargs.setdefault("conv_state_layout", "q_k_v") super().__init__(*args, **kwargs) + def get_replay_dummy_request_mask(self) -> torch.Tensor | None: + """The batch-ordered dummy-request mask of the last state-index setup. + + The GDN MTP replay skips dummy rows; the buffer address stays fixed. + """ + return self._dummy_request_mask + def gdn_replay_partitioned(self, num_decodes: int) -> bool: """Whether a GDN decode batch of num_decodes requests takes the partitioned cached replay and one all-layer checkpoint commit; other @@ -1205,7 +1548,15 @@ def use_gdn_flashinfer_ring_replay(self) -> bool: @property def use_gdn_cached_replay_all_layer_commit(self) -> bool: state = self._speculative_state - return isinstance(state, GDNReplayState) and state.has_bound_states + return ( + isinstance(state, GDNReplayState) + and not isinstance(state, GDNMtpReplayState) + and state.has_bound_states + ) + + @property + def use_gdn_mtp_replay(self) -> bool: + return isinstance(self._speculative_state, GDNMtpReplayState) def get_gdn_cache_params(config, *, spec_config=None, quant_config=None): @@ -1233,6 +1584,7 @@ def get_gdn_cache_params(config, *, spec_config=None, quant_config=None): __all__ = [ "GDNIntermediateState", "GDNLayerCache", + "GDNMtpReplayState", "GDNReplayState", "Qwen35HybridCacheManager", "create_gdn_state", diff --git a/tensorrt_llm/_torch/modules/fla/gdn_metadata.py b/tensorrt_llm/_torch/modules/fla/gdn_metadata.py index 3e218fe30189..0b68fb551166 100644 --- a/tensorrt_llm/_torch/modules/fla/gdn_metadata.py +++ b/tensorrt_llm/_torch/modules/fla/gdn_metadata.py @@ -20,6 +20,7 @@ REPLAY_WORK_ITEM_WIDTH, ReplaySlotIndices, build_replay_work_items, + snapshot_gdn_mtp_replay_work_items, ) from tensorrt_llm._utils import prefer_pinned @@ -212,6 +213,14 @@ def _prepare_replay_work_items( # FlashInfer ring replay folds in-kernel and never reads work items. if getattr(kv_cache_manager, "use_gdn_flashinfer_ring_replay", False): return + if getattr(kv_cache_manager, "use_gdn_mtp_replay", False): + snapshot_gdn_mtp_replay_work_items( + self.state_indices[num_contexts:batch_size], + self.replay_state_indices[num_contexts:batch_size], + replay_metadata.prev_num_accepted_tokens, + self.replay_work_items, + ) + return use_gdn_all_layer_commit = getattr( kv_cache_manager, "use_gdn_cached_replay_all_layer_commit", False ) diff --git a/tensorrt_llm/_torch/modules/mamba/gdn_mixer.py b/tensorrt_llm/_torch/modules/mamba/gdn_mixer.py index ddc5e4700e1c..7b1c36c8cece 100644 --- a/tensorrt_llm/_torch/modules/mamba/gdn_mixer.py +++ b/tensorrt_llm/_torch/modules/mamba/gdn_mixer.py @@ -39,6 +39,7 @@ from ...attention.backends import AttentionMetadata from ...autotuner import AutoTuner +from ...cute_dsl_utils import IS_CUTLASS_DSL_AVAILABLE from ...distributed import AllReduceParams from ...model_config import ModelConfig from ...pyexecutor.breakable_cuda_graph import eager_on_graph, is_in_breakable_cuda_graph @@ -96,6 +97,11 @@ _FUSED_VERIFY_MAX_TOKENS = 8 _FUSED_VERIFY_HISTORY = 16 +if IS_CUTLASS_DSL_AVAILABLE: + from tensorrt_llm._torch.custom_ops.cute_dsl_gdn_mtp_replay import gdn_mtp_replay +else: + gdn_mtp_replay = None + class GdnIterationContext(NamedTuple): """Metadata-derived arguments of forward_extend / forward_decode, shared by every GDN layer of one iteration. @@ -129,6 +135,10 @@ class GdnIterationContext(NamedTuple): replay_work_items: Optional[torch.Tensor] replay_n_writes: Optional[torch.Tensor] use_cached_replay_all_layer_commit: bool + # GDN MTP replay (the manager's GDNMtpReplayState) and the decode rows' + # dummy mask it reads; otherwise False / None. + use_mtp_replay: bool + replay_is_dummy: Optional[torch.Tensor] scan_state_indices: Optional[torch.Tensor] scan_cu_seqlens: Optional[torch.Tensor] scan_prefill_layout: object @@ -1417,8 +1427,10 @@ def _fused_verify_plan( num_decodes = attn_metadata.seq_lens.shape[0] if ( num_decodes == 0 - # The fused kernels read the Triton replay history, not the FlashInfer ring. + # The fused kernels read the Triton replay history, not the FlashInfer + # ring or the GDN MTP replay history. or getattr(kv_cache_manager, "use_gdn_flashinfer_ring_replay", False) + or getattr(kv_cache_manager, "use_gdn_mtp_replay", False) or not kv_cache_manager.is_speculative() or kv_cache_manager.gdn_replay_partitioned(num_decodes) ): @@ -1655,6 +1667,72 @@ def _fused_verify( ba_ready.wait() return self._fused_verify_replay_norm(plan, mixed_qkv, z, a, b) + def _replay_verify( + self, + raw_x: torch.Tensor, + b: torch.Tensor, + a: torch.Tensor, + conv_states: torch.Tensor, + ssm_states: torch.Tensor, + state_indices: torch.Tensor, + replay_indices: torch.Tensor, + num_decodes: int, + draft_token_num: int, + replay_metadata, + layer_cache, + is_dummy: torch.Tensor, + output: Optional[torch.Tensor] = None, + ) -> torch.Tensor: + """MTP target verification through the GDN MTP replay kernel. + + One launch per layer runs the Conv4 update of the raw q|k|v rows and + the gated delta-rule replay of the accepted history plus the new + candidates; neither checkpoint changes. The raw candidates are kept for + the all-layer commit the cache manager issues after acceptance. + ``raw_x`` holds the pre-conv q|k|v rows and ``b`` / ``a`` the beta and + decay gate inputs, which may be padded column views of the fused input + projection; returns [num_decodes, draft_token_num, HV, V]. + """ + assert replay_metadata is not None, ( + "GDN replay enabled but replay metadata was not allocated." + ) + assert draft_token_num == replay_metadata.replay_step_width, ( + "GDN replay does not support dynamic draft length: " + f"{draft_token_num} != {replay_metadata.replay_step_width}" + ) + if gdn_mtp_replay is None: + raise RuntimeError("GDN MTP replay requires CUTLASS DSL") + if self.conv1d.bias is not None or self.activation not in ("silu", "swish"): + raise RuntimeError("GDN MTP replay requires a bias-free SiLU Conv4") + if output is None: + output = raw_x.new_empty( + num_decodes, draft_token_num, self.num_v_heads_per_tp, self.head_v_dim + ) + row_stride = raw_x.stride(0) + gdn_mtp_replay( + raw_x=raw_x.as_strided( + (num_decodes, draft_token_num, self.conv_dim_per_tp), + (draft_token_num * row_stride, row_stride, 1), + ), + conv_weight=self.conv1d.weight, + conv_state=conv_states, + b=b, + a=a, + checkpoint=ssm_states, + state_indices=state_indices[:num_decodes], + replay_indices=replay_indices[:num_decodes], + is_dummy=is_dummy, + history_u=layer_cache.old_x, + history_k=layer_cache.old_B, + history_G=layer_cache.old_dt, + history_len=layer_cache.prev_num_accepted_tokens, + A_log=self.A_log, + dt_bias=self.dt_bias, + output=output, + candidate_x=layer_cache.intermediate_conv_window[:num_decodes], + ) + return output + def _replay_verify_recurrent( self, query, @@ -1778,6 +1856,29 @@ def forward_decode( assert intermediate_conv_states is not None assert kwargs.get("use_replay", False) or intermediate_ssm_states is not None + if kwargs.get("use_mtp_replay", False): + # The GDN MTP replay kernel runs the Conv4 update itself. + output_d = None + if output is not None: + output_d = output.view( + num_decodes, draft_token_num, self.num_v_heads_per_tp, self.head_v_dim + ) + return self._replay_verify( + raw_x=mixed_qkv, + b=b, + a=a, + conv_states=conv_states, + ssm_states=ssm_states, + state_indices=cache_indices, + replay_indices=kwargs["replay_state_indices_d"], + num_decodes=num_decodes, + draft_token_num=draft_token_num, + replay_metadata=kwargs.get("replay_metadata"), + layer_cache=kwargs.get("layer_cache"), + is_dummy=kwargs["replay_is_dummy"], + output=output_d, + ).view(1, num_decodes * draft_token_num, self.num_v_heads_per_tp, self.head_v_dim) + # Speculative verification path: # 1. run conv update with per-step intermediate cache writes # 2. run recurrent delta rule with intermediate SSM-state cache writes @@ -2030,6 +2131,7 @@ def forward_extend( packed: Optional[_PackedPostConv] = None conv_states_to_use = conv_states + use_mtp_replay = kwargs.get("use_mtp_replay", False) # Context-only batches may take the fused prefill conv, which leaves mixed_qkv untouched. Not under # FORCE_DETERMINISTIC: its q / k L2 norms differ from the stock kernels that prefill next to decodes. fused_conv = ( @@ -2086,22 +2188,26 @@ def forward_extend( assert intermediate_conv_states is not None assert kwargs.get("use_replay", False) or intermediate_ssm_states is not None - intermediate_state_indices = kwargs["intermediate_state_indices"] - mixed_qkv_d = mixed_qkv_d.reshape(num_decodes, draft_token_num, -1).transpose(1, 2) - mixed_qkv_d = causal_conv1d_update_triton( - mixed_qkv_d, - conv_states_to_use, - self.conv1d.weight, - self.conv1d.bias, - activation=self.activation, - conv_state_indices=state_indices_d, - intermediate_conv_window=intermediate_conv_states, - intermediate_state_indices=intermediate_state_indices, - # PDL chain: conv1d -> replay verify kernel (replay only) - launch_dependent_kernels=kwargs.get("use_replay", False), - hoist_x=True, - ) - mixed_qkv_d = mixed_qkv_d.transpose(1, 2).reshape(num_decode_tokens, -1) + # The GDN MTP replay kernel runs the Conv4 update itself. + if not use_mtp_replay: + intermediate_state_indices = kwargs["intermediate_state_indices"] + mixed_qkv_d = mixed_qkv_d.reshape(num_decodes, draft_token_num, -1).transpose( + 1, 2 + ) + mixed_qkv_d = causal_conv1d_update_triton( + mixed_qkv_d, + conv_states_to_use, + self.conv1d.weight, + self.conv1d.bias, + activation=self.activation, + conv_state_indices=state_indices_d, + intermediate_conv_window=intermediate_conv_states, + intermediate_state_indices=intermediate_state_indices, + # PDL chain: conv1d -> replay verify kernel (replay only) + launch_dependent_kernels=kwargs.get("use_replay", False), + hoist_x=True, + ) + mixed_qkv_d = mixed_qkv_d.transpose(1, 2).reshape(num_decode_tokens, -1) else: mixed_qkv_d = causal_conv1d_update( mixed_qkv_d, @@ -2128,7 +2234,9 @@ def forward_extend( g_linear=g_linear, ) layer_cache = kwargs.get("layer_cache") - if ( + if use_mtp_replay: + pass # The replay kernel reads the raw q|k|v rows. + elif ( kwargs.get("use_replay", False) and layer_cache is not None and layer_cache.cache_base is not None @@ -2219,6 +2327,33 @@ def forward_extend( ) draft_token_num = spec_metadata.runtime_draft_len + 1 + if use_mtp_replay: + output_d = None + if output is not None: + output_d = output[:, num_prefill_tokens:, :, :].view( + num_decodes, draft_token_num, self.num_v_heads_per_tp, self.head_v_dim + ) + attn_out_decode = self._replay_verify( + raw_x=mixed_qkv_d, + b=b_d, + a=a_d, + conv_states=conv_states_to_use, + ssm_states=ssm_states, + state_indices=state_indices_d, + replay_indices=kwargs["replay_state_indices_d"], + num_decodes=num_decodes, + draft_token_num=draft_token_num, + replay_metadata=kwargs.get("replay_metadata"), + layer_cache=kwargs.get("layer_cache"), + is_dummy=kwargs["replay_is_dummy"], + output=output_d, + ).reshape(1, num_decode_tokens, self.num_v_heads_per_tp, self.head_v_dim) + if output is not None: + return output + if attn_out_prefill is None: + return attn_out_decode + return torch.cat((attn_out_prefill, attn_out_decode), dim=1) + query_d = query_d.reshape( num_decodes, draft_token_num, self.num_k_heads // self.attn_tp_size, self.head_k_dim ) @@ -2819,9 +2954,18 @@ def _iteration_context( kv_cache_manager.get_replay_state_update_metadata() if is_target_verify else None ) use_replay = replay_metadata is not None + use_mtp_replay = use_replay and getattr(kv_cache_manager, "use_gdn_mtp_replay", False) + replay_is_dummy = None + if use_mtp_replay: + dummy_mask = kv_cache_manager.get_replay_dummy_request_mask() + replay_is_dummy = dummy_mask[num_prefills : num_prefills + num_decodes] # Work items only feed Triton's large-batch replay + all-layer commit; # the FlashInfer ring kernel always folds in-kernel. - partitioned_replay = use_replay and kv_cache_manager.gdn_replay_partitioned(num_decodes) + partitioned_replay = ( + use_replay + and not use_mtp_replay + and kv_cache_manager.gdn_replay_partitioned(num_decodes) + ) pass_replay_work_items = partitioned_replay and not getattr( kv_cache_manager, "use_gdn_flashinfer_ring_replay", False ) @@ -2874,6 +3018,8 @@ def _iteration_context( else None, replay_n_writes=mamba_metadata.replay_n_writes if pass_replay_work_items else None, use_cached_replay_all_layer_commit=use_cached_replay_all_layer_commit, + use_mtp_replay=use_mtp_replay, + replay_is_dummy=replay_is_dummy, # The main scan's layout: the context segments first, then the decode # requests as one-token sequences; its prefill-only prefix serves the # mixed-iteration scan. diff --git a/tensorrt_llm/_torch/modules/mamba/replay_metadata.py b/tensorrt_llm/_torch/modules/mamba/replay_metadata.py index e3c05befc200..622b2ffb26dc 100644 --- a/tensorrt_llm/_torch/modules/mamba/replay_metadata.py +++ b/tensorrt_llm/_torch/modules/mamba/replay_metadata.py @@ -217,6 +217,70 @@ def build_replay_work_items( ) +# As above, neither the decode count nor the slice alignment is specialized. +@triton.jit( + do_not_specialize=["num_decodes", "history_len_stride"], + do_not_specialize_on_alignment=["state_indices", "replay_indices"], +) +def _snapshot_gdn_mtp_replay_work_items_kernel( + state_indices, + replay_indices, + history_len, + history_len_stride, + work_items, + num_decodes, + work_item_width: tl.constexpr, + position_field: tl.constexpr, + cache_slot_field: tl.constexpr, + history_len_field: tl.constexpr, + cache_buf_idx_field: tl.constexpr, + replay_slot_field: tl.constexpr, + BLOCK_SIZE: tl.constexpr, +): + """Snapshot each decode's slots and history length before the layer loop.""" + offsets = tl.program_id(0) * BLOCK_SIZE + tl.arange(0, BLOCK_SIZE) + active = offsets < num_decodes + slots = tl.load(state_indices + offsets, mask=active, other=0) + replay_slots = tl.load(replay_indices + offsets, mask=active, other=0) + lengths = tl.load( + history_len + replay_slots.to(tl.int64) * history_len_stride, mask=active, other=0 + ) + output_base = work_items + offsets * work_item_width + tl.store(output_base + position_field, offsets, mask=active) + tl.store(output_base + cache_slot_field, slots, mask=active) + tl.store(output_base + history_len_field, lengths, mask=active) + tl.store(output_base + cache_buf_idx_field, 0, mask=active) + tl.store(output_base + replay_slot_field, replay_slots, mask=active) + + +def snapshot_gdn_mtp_replay_work_items( + state_indices: torch.Tensor, + replay_indices: torch.Tensor, + history_len: torch.Tensor, + work_items: torch.Tensor, +) -> None: + """Inputs of the GDN MTP all-layer commit: (decode position, state slot, + history length, unused, replay slot) per decode request.""" + num_decodes = state_indices.shape[0] + block_size = 256 + _snapshot_gdn_mtp_replay_work_items_kernel[(triton.cdiv(num_decodes, block_size),)]( + state_indices, + replay_indices, + history_len, + history_len.stride(0), + work_items, + num_decodes, + work_item_width=REPLAY_WORK_ITEM_WIDTH, + position_field=REPLAY_WORK_POSITION_IN_DECODE_BATCH, + cache_slot_field=REPLAY_WORK_CACHE_SLOT, + history_len_field=REPLAY_WORK_PNAT, + cache_buf_idx_field=REPLAY_WORK_CACHE_BUF_IDX, + replay_slot_field=REPLAY_WORK_REPLAY_SLOT, + BLOCK_SIZE=block_size, + num_warps=4, + ) + + class ReplaySlotIndices: """A static device buffer of the batch's replay slots. diff --git a/tensorrt_llm/_torch/modules/qwen4_exp/cache_manager.py b/tensorrt_llm/_torch/modules/qwen4_exp/cache_manager.py index bbb00a6de735..4ea6d56731bd 100644 --- a/tensorrt_llm/_torch/modules/qwen4_exp/cache_manager.py +++ b/tensorrt_llm/_torch/modules/qwen4_exp/cache_manager.py @@ -28,6 +28,7 @@ from tensorrt_llm._torch.disaggregation.resource.page import MapperKind from tensorrt_llm._torch.modules.fla.cache_manager import ( GDNIntermediateState, + GDNMtpReplayState, GDNReplayState, ReplayStateUpdateMetadata, create_gdn_state, @@ -206,6 +207,9 @@ class Qwen4ExpHybridCacheManager(InforwardSnapshotHost, MambaHybridCacheManagerV # Whether the model's GDN layers verify drafts with the fused kernels, which # commit in-layer at every batch size. gdn_fused_verify = False + # Whether the model's GDN layers can verify drafts with the GDN MTP replay + # kernels (modules/mamba/gdn_mixer.py) instead of the cached replay. + gdn_mtp_replay = False # The parent opts in because its draft pool is attention-only. QSA's is # not: each draft layer adds a Role.INDEX_KEY buffer and a @@ -234,12 +238,14 @@ def __init__( use_replay_state_update: bool | None = None, qwen4_exp_ple_cache_params: Qwen4ExpPLECacheParams | None = None, gdn_fused_verify: bool = False, + gdn_mtp_replay: bool = False, inforward_snapshot_min_main: int = 0, **kwargs, ) -> None: kwargs.pop("mamba_ssm_stochastic_rounding", False) self._requested_replay = use_replay_state_update self.gdn_fused_verify = gdn_fused_verify + self.gdn_mtp_replay = gdn_mtp_replay # A disaggregated context server never decodes and keeps no replay history. self._context_only = _is_disagg_context_server(kwargs.get("is_disagg", False)) self._replay_region = None @@ -801,6 +807,13 @@ def _initialize_spec_state(self) -> GDNIntermediateState | GDNReplayState: ) return state + def get_replay_dummy_request_mask(self) -> torch.Tensor | None: + """The batch-ordered dummy-request mask of the last state-index setup. + + The GDN MTP replay skips dummy rows; the buffer address stays fixed. + """ + return self._dummy_request_mask + def gdn_replay_partitioned(self, num_decodes: int) -> bool: """Whether a GDN decode batch of num_decodes requests takes the partitioned cached replay and one all-layer checkpoint commit; other @@ -994,7 +1007,15 @@ def use_gdn_flashinfer_ring_replay(self) -> bool: @property def use_gdn_cached_replay_all_layer_commit(self) -> bool: state = self._speculative_state - return isinstance(state, GDNReplayState) and state.has_bound_states + return ( + isinstance(state, GDNReplayState) + and not isinstance(state, GDNMtpReplayState) + and state.has_bound_states + ) + + @property + def use_gdn_mtp_replay(self) -> bool: + return isinstance(self._speculative_state, GDNMtpReplayState) def get_qwen4_exp_ple_cache_params(config, *, total_layers: int, is_draft: bool): diff --git a/tensorrt_llm/_torch/pyexecutor/_util.py b/tensorrt_llm/_torch/pyexecutor/_util.py index b77df9ef8fe1..19df42d58b94 100644 --- a/tensorrt_llm/_torch/pyexecutor/_util.py +++ b/tensorrt_llm/_torch/pyexecutor/_util.py @@ -1501,6 +1501,11 @@ def _per_manager_cache_cost(self, # pools. The draft manager never derives (see there). kv_cache_config = kv_cache_config.model_copy( update={"max_attention_window": derived_windows}) + if (not is_draft and issubclass(manager_cls, MambaHybridCacheManagerV2) + and self._model_engine is not None + and _uses_gdn_mtp_replay(self._model_engine.model)): + # Cost the GDN replay region of the state the manager will select. + extra_kwargs = dict(extra_kwargs, gdn_mtp_replay=True) cost = CacheCost.from_raw( manager_cls.get_cache_size_per_token( model_config, @@ -4625,6 +4630,23 @@ def _mamba_conv_layout_kwargs(kv_cache_manager_cls: type, return {"model_type": model_type} +def _uses_gdn_mtp_replay(model: torch.nn.Module) -> bool: + """Whether ``model``'s GDN layers can verify drafts with the GDN MTP replay kernels. + + They must be the PyTorch GDN mixer, and none may verify with the fused + kernels into an FP8 out_proj input (gdn_verify_tcgen05 / trtllm::gdn_verify), + which keep the cached replay history. + """ + from ..modules.mamba.gdn_mixer import Qwen3NextGatedDeltaNet + layers = [ + module for module in model.modules() + if isinstance(module, Qwen3NextGatedDeltaNet) + ] + return bool(layers) and not any( + layer.fused_verify and layer.norm.fp8_scale is not None + for layer in layers) + + def _create_kv_cache_manager( model_engine: Optional[ModelEngine], kv_cache_manager_cls, @@ -5090,6 +5112,9 @@ def _create_kv_cache_manager( mamba_manager_extra_kwargs["gdn_fused_verify"] = any( module.fused_verify for module in model_engine.model.modules() if isinstance(module, Qwen3NextGatedDeltaNet)) + if issubclass(kv_cache_manager_cls, MambaHybridCacheManagerV2): + mamba_manager_extra_kwargs["gdn_mtp_replay"] = ( + _uses_gdn_mtp_replay(model_engine.model)) if is_qwen4_exp(config) and issubclass(kv_cache_manager_cls, MambaHybridCacheManagerV2): mamba_manager_extra_kwargs.update( diff --git a/tests/integration/test_lists/test-db/l0_b200.yml b/tests/integration/test_lists/test-db/l0_b200.yml index 585bf27581d5..680447cb54f1 100644 --- a/tests/integration/test_lists/test-db/l0_b200.yml +++ b/tests/integration/test_lists/test-db/l0_b200.yml @@ -195,6 +195,7 @@ l0_b200: - unittest/_torch/moe/test_moe_module.py::test_dspark_draft_fused_route_quant_matches_separate_launches - unittest/_torch/modules/test_gated_mlp.py::test_fp8_block_scale_mlp_small_m_matches_deep_gemm - unittest/_torch/modules/test_embedding_vocab_slice.py + - unittest/_torch/modules/mamba/test_gdn_mtp_replay.py - unittest/_torch/distributed/test_ll_allgather.py - unittest/disaggregated/test_cache_transceiver_single_process.py::test_cache_transceiver_deferred_gen_receive # ------------- Kimi K3 (KimiLinear) unit tests --------------- diff --git a/tests/unittest/_torch/modules/mamba/test_gdn_kernel_optimizations.py b/tests/unittest/_torch/modules/mamba/test_gdn_kernel_optimizations.py index 0977b55b0dab..ed744ed3711c 100644 --- a/tests/unittest/_torch/modules/mamba/test_gdn_kernel_optimizations.py +++ b/tests/unittest/_torch/modules/mamba/test_gdn_kernel_optimizations.py @@ -754,6 +754,163 @@ def test_gdn_replay_verify_dispatches_by_history_layout(monkeypatch, ring_mode): assert kwargs["old_u"] == "old_x" +def test_gdn_mtp_replay_verify_addresses_history_by_replay_slot(monkeypatch): + """GDN MTP replay reads the checkpoint and Conv state at the state slots, the + history at the replay slots, and hands the kernel per-request [T, C] raw rows.""" + from tensorrt_llm._torch.modules.fla.cache_manager import ReplayStateUpdateMetadata + from tensorrt_llm._torch.modules.mamba import gdn_mixer + + num_decodes, tokens, heads, channels = 3, 4, 2, 24 + layer = gdn_mixer.Qwen3NextGatedDeltaNet.__new__(gdn_mixer.Qwen3NextGatedDeltaNet) + torch.nn.Module.__init__(layer) + layer.A_log = torch.zeros(heads) + layer.dt_bias = torch.zeros(heads) + layer.conv1d = SimpleNamespace(weight="conv_weight", bias=None) + layer.activation = "silu" + layer.conv_dim_per_tp = channels + layer.num_v_heads_per_tp = heads + layer.head_v_dim = 8 + calls = {} + monkeypatch.setattr(gdn_mixer, "gdn_mtp_replay", lambda **kwargs: calls.update(kwargs)) + history_len = torch.tensor([0, 3, 9, 13, 5, 7], dtype=torch.int32) + candidates = torch.zeros(8, tokens, channels) + layer_cache = SimpleNamespace( + prev_num_accepted_tokens=history_len, + old_x="history_u", + old_B="history_k", + old_dt="history_G", + intermediate_conv_window=candidates, + ) + # Row-strided pre-conv q|k|v rows of the fused in_proj output. + projection = torch.arange(num_decodes * tokens * 40, dtype=torch.float32).view(-1, 40) + raw_x = projection[:, :channels] + is_dummy = torch.tensor([False, True, False]) + + output = layer._replay_verify( + raw_x=raw_x, + b="beta", + a="decay", + conv_states="conv", + ssm_states="pool", + state_indices=torch.tensor([3, 1, 5, 0], dtype=torch.int32), + replay_indices=torch.tensor([4, 2, 0, 1], dtype=torch.int32), + num_decodes=num_decodes, + draft_token_num=tokens, + replay_metadata=ReplayStateUpdateMetadata(history_len, None, tokens, 16), + layer_cache=layer_cache, + is_dummy=is_dummy, + ) + + assert calls["state_indices"].tolist() == [3, 1, 5] + assert calls["replay_indices"].tolist() == [4, 2, 0] + assert calls["history_u"] == "history_u" and calls["history_len"] is history_len + assert calls["is_dummy"] is is_dummy + assert (calls["b"], calls["a"]) == ("beta", "decay") + assert calls["candidate_x"].data_ptr() == candidates.data_ptr() + assert calls["candidate_x"].shape == (num_decodes, tokens, channels) + assert torch.equal(calls["raw_x"], raw_x.reshape(num_decodes, tokens, channels)) + assert calls["raw_x"].stride() == (tokens * 40, 40, 1) + assert output.shape == (num_decodes, tokens, heads, 8) + with pytest.raises(AssertionError, match="dynamic draft length"): + layer._replay_verify( + raw_x=raw_x, + b="beta", + a="decay", + conv_states="conv", + ssm_states="pool", + state_indices=torch.tensor([3, 1, 5], dtype=torch.int32), + replay_indices=torch.tensor([4, 2, 0], dtype=torch.int32), + num_decodes=num_decodes, + draft_token_num=tokens - 1, + replay_metadata=ReplayStateUpdateMetadata(history_len, None, tokens, 16), + layer_cache=layer_cache, + is_dummy=is_dummy, + ) + + +def test_gdn_mtp_replay_in_mixed_step_takes_the_raw_decode_rows(monkeypatch): + """A mixed prefill + verify step hands GDN MTP replay the raw (pre-conv) + decode rows and their b / a gate rows, without the standalone conv1d update or the + q/k/v pack, and concatenates its output after the prefill rows.""" + from tensorrt_llm._torch.modules.mamba import gdn_mixer + + num_prefill_tokens, num_decodes, tokens, heads, head_dim, channels = 5, 2, 4, 2, 8, 24 + layer = gdn_mixer.Qwen3NextGatedDeltaNet.__new__(gdn_mixer.Qwen3NextGatedDeltaNet) + torch.nn.Module.__init__(layer) + layer.A_log = torch.zeros(heads) + layer.dt_bias = torch.zeros(heads) + layer.num_v_heads, layer.attn_tp_size, layer.head_v_dim = heads, 1, head_dim + layer.num_v_heads_per_tp, layer.num_k_heads_per_tp, layer.head_k_dim = heads, 1, head_dim + layer._prefill_conv = lambda *args: "prefill_conv_out" + monkeypatch.setattr(gdn_mixer, "fused_gdn_post_conv", lambda *args, **kwargs: ("p",) * 5) + monkeypatch.setattr( + gdn_mixer, + "chunk_gated_delta_rule", + lambda **kwargs: (torch.ones(1, num_prefill_tokens, heads, head_dim), None), + ) + for name in ("causal_conv1d_update_triton", "pack_gdn_decode_qkv"): + monkeypatch.setattr( + gdn_mixer, name, lambda *a, _name=name, **k: pytest.fail(f"{_name} called") + ) + captured = {} + + def fake_replay_verify(**kwargs): + captured.update(kwargs) + return torch.full((num_decodes, tokens, heads, head_dim), 2.0) + + layer._replay_verify = fake_replay_verify + rows = num_prefill_tokens + num_decodes * tokens + mixed_qkv = torch.randn(rows, channels) + ba = torch.randn(rows, 2 * heads) + b = ba[:, :heads] + state_indices = torch.tensor([6, 2, 4], dtype=torch.int32) + replay_indices_d = torch.tensor([9, 1], dtype=torch.int32) + is_dummy = torch.tensor([False, True]) + + out = layer.forward_extend( + "conv_states", + "ssm_states", + spec_metadata=SimpleNamespace(runtime_draft_len=tokens - 1), + intermediate_conv_states="candidates", + is_target_verify=True, + mixed_qkv=mixed_qkv, + a=ba[:, heads:], + b=b, + batch_size=1 + num_decodes, + has_initial_states_bs=torch.ones(3, dtype=torch.bool), + has_initial_states_p=torch.ones(1, dtype=torch.bool), + cache_indices=state_indices, + query_start_loc=torch.tensor([0, num_prefill_tokens]), + query_start_loc_p=torch.tensor([0, num_prefill_tokens]), + query_start_loc_long=torch.tensor([0, num_prefill_tokens]), + num_prefill_tokens=num_prefill_tokens, + num_decode_tokens=num_decodes * tokens, + state_indices_p=state_indices[:1], + state_indices_d=state_indices[1:], + num_prefill=1, + num_decodes=num_decodes, + g_linear=False, + use_replay=True, + use_mtp_replay=True, + replay_state_indices_d=replay_indices_d, + replay_is_dummy=is_dummy, + replay_metadata="metadata", + layer_cache="layer_cache", + ) + + assert torch.equal(captured["raw_x"], mixed_qkv[num_prefill_tokens:]) + assert torch.equal(captured["b"], b[num_prefill_tokens:]) + assert torch.equal(captured["a"], ba[num_prefill_tokens:, heads:]) + assert captured["state_indices"].tolist() == [2, 4] + assert captured["replay_indices"] is replay_indices_d + assert captured["is_dummy"] is is_dummy + assert captured["conv_states"] == "conv_states" and captured["ssm_states"] == "ssm_states" + assert (captured["num_decodes"], captured["draft_token_num"]) == (num_decodes, tokens) + assert out.shape == (1, rows, heads, head_dim) + assert torch.all(out[:, :num_prefill_tokens] == 1.0) + assert torch.all(out[:, num_prefill_tokens:] == 2.0) + + def test_verify_intermediate_state_indices_reuses_buffers(): """The verify path's row-index vector is built once, not per GDN layer. diff --git a/tests/unittest/_torch/modules/mamba/test_gdn_mtp_replay.py b/tests/unittest/_torch/modules/mamba/test_gdn_mtp_replay.py new file mode 100644 index 000000000000..92293545765b --- /dev/null +++ b/tests/unittest/_torch/modules/mamba/test_gdn_mtp_replay.py @@ -0,0 +1,498 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +import pytest +import torch + +from tensorrt_llm._torch.cute_dsl_utils import IS_CUTLASS_DSL_AVAILABLE +from tensorrt_llm._utils import is_sm_100f + +DIM = 128 +WINDOW = 16 + +pytestmark = pytest.mark.skipif( + not torch.cuda.is_available() or not is_sm_100f() or not IS_CUTLASS_DSL_AVAILABLE, + reason="GDN MTP replay requires CUTLASS DSL on datacenter Blackwell", +) + + +def _randn(shape, scale=1.0, shift=0.0): + return torch.randn(shape, device="cuda", dtype=torch.float32) * scale + shift + + +def _conv4_silu(raw_x, conv_weight, conv_state, slots): + old = conv_state.index_select(0, slots).float() + sequence = torch.cat((old, raw_x.float().transpose(1, 2)), dim=-1) + terms = [ + sequence[:, :, tap : tap + raw_x.shape[1]] * conv_weight[:, tap].float()[None, :, None] + for tap in range(4) + ] + convolved = torch.stack(terms).sum(dim=0) + return (convolved * torch.sigmoid(convolved)).transpose(1, 2).to(torch.bfloat16) + + +@torch.no_grad() +def _replay_reference( + raw_x, + conv_weight, + conv_state, + b, + a, + checkpoint, + state_indices, + is_dummy, + history_u, + history_k, + history_G, + history_len, + A_log, + dt_bias, + replay_indices, +): + batch, width, _ = raw_x.shape + key_heads = history_k.shape[2] + value_heads = history_u.shape[2] + heads_per_key = value_heads // key_heads + slots = state_indices.long() + replay_slots = replay_indices.long() + + packed_qkv = _conv4_silu(raw_x, conv_weight, conv_state, slots) + key_width = key_heads * DIM + value_width = value_heads * DIM + query = packed_qkv[..., :key_width].view(batch, width, key_heads, DIM) + key = packed_qkv[..., key_width : 2 * key_width].view_as(query) + value = packed_qkv[..., 2 * key_width : 2 * key_width + value_width].view( + batch, width, value_heads, DIM + ) + beta_input = b.reshape(batch, width, value_heads) + decay_input = a.reshape(batch, width, value_heads) + + query_f32 = query.float() + key_f32 = key.float() + query_norm = ( + query_f32 + * (DIM**-0.5 / torch.sqrt(torch.sum(query_f32 * query_f32, dim=-1, keepdim=True) + 1e-6)) + ).to(torch.bfloat16) + key_norm = (key_f32 / torch.sqrt(torch.sum(key_f32 * key_f32, dim=-1, keepdim=True) + 1e-6)).to( + torch.bfloat16 + ) + + gate_input = decay_input.float() + dt_bias.float()[None, None, :] + softplus = torch.where( + gate_input <= 20.0, + torch.log1p(torch.exp(gate_input)), + gate_input, + ) + gate = -torch.exp(A_log.float())[None, None, :] * softplus + beta = torch.sigmoid(beta_input.float()) + + lengths = history_len.index_select(0, replay_slots).long() + selected_u = history_u[:, :WINDOW].index_select(0, replay_slots).float() + selected_k = history_k[:, :WINDOW].index_select(0, replay_slots).float() + selected_G = history_G[:, :, :WINDOW].index_select(0, replay_slots).float() + key_for_value_head = torch.arange(value_heads, device=raw_x.device) // heads_per_key + selected_k = selected_k[:, :, key_for_value_head, :] + + positions = torch.arange(WINDOW, device=raw_x.device)[None, None, :] + active = positions < lengths[:, None, None] + previous_G = torch.zeros(batch, value_heads, device=raw_x.device, dtype=torch.float32) + nonempty = lengths > 0 + if bool(nonempty.any()): + rows = torch.where(nonempty)[0] + previous_G[rows] = selected_G[rows, :, lengths[rows] - 1] + history_decay = torch.where( + active, + torch.exp(previous_G[:, :, None] - selected_G), + 0.0, + ) + state = checkpoint.index_select(0, slots).float() + state *= torch.exp(previous_G)[:, :, None, None] + state += torch.einsum("btiv,btik,bit->bivk", selected_u, selected_k, history_decay) + + output = torch.empty( + batch, + width, + value_heads, + DIM, + device=raw_x.device, + dtype=torch.bfloat16, + ) + current_u = torch.empty_like(output) + current_G = torch.empty(batch, width, value_heads, device=raw_x.device, dtype=torch.float32) + query_hv = query_norm[:, :, key_for_value_head].float() + key_hv = key_norm[:, :, key_for_value_head].float() + running_G = previous_G + for token in range(width): + running_G = running_G + gate[:, token] + current_G[:, token] = running_G + state *= torch.exp(gate[:, token])[:, :, None, None] + state_key = torch.einsum("bhvk,bhk->bhv", state, key_hv[:, token]) + update = beta[:, token, :, None] * (value[:, token].float() - state_key) + state += update[:, :, :, None] * key_hv[:, token, :, None, :] + output[:, token] = torch.einsum("bhvk,bhk->bhv", state, query_hv[:, token]).to( + torch.bfloat16 + ) + current_u[:, token] = update.to(torch.bfloat16) + + writable_rows = torch.where(~is_dummy)[0] + writable_slots = replay_slots[writable_rows] + writable_lengths = lengths[writable_rows] + for token in range(width): + write_positions = writable_lengths + token + history_u[writable_slots, write_positions] = current_u[writable_rows, token] + history_k[writable_slots, write_positions] = key_norm[writable_rows, token] + history_G[writable_slots, :, write_positions] = current_G[writable_rows, token] + return output, raw_x.contiguous() + + +def _gate_columns(qkvz_width: int, value_heads: int, padded: bool) -> tuple[int, int, int]: + """Columns of b and a and the row width of the input projection. + + ``padded`` mirrors ``Qwen3NextGatedDeltaNet._refresh_fused_in_proj``: the + ``[qkvz | b | pad | a | pad]`` layout starts each gate block at a 32-byte + (16 BF16 column) boundary; otherwise ``b`` and ``a`` are adjacent. + """ + align = 16 if padded else 1 + + def _up(columns: int) -> int: + return -(-columns // align) * align + + b_col = _up(qkvz_width) + a_col = b_col + _up(value_heads) + return b_col, a_col, a_col + _up(value_heads) + + +@pytest.mark.parametrize("layout", ["adjacent", "padded"]) +@pytest.mark.parametrize("width", [1, 3, 4, 8]) +@pytest.mark.parametrize("head_ratio", [2, 4, 8]) +def test_gdn_mtp_replay_matches_reference(width: int, head_ratio: int, layout: str) -> None: + """Live rows with empty, partial and full (16-row) histories, widths that need + MMA padding, a dummy row, and replay slots apart from the state slots. The + q|k|v, b and a inputs are column views of one projection, either with + adjacent gate blocks or with the padded fused in_proj layout.""" + from tensorrt_llm._torch.custom_ops.cute_dsl_gdn_mtp_replay import gdn_mtp_replay + + torch.manual_seed(7) + batch, slots, replay_slot_count = 4, 5, 6 + key_heads = 1 + value_heads = key_heads * head_ratio + channels = (2 * key_heads + value_heads) * DIM + qkvz_width = channels + value_heads * DIM + + b_col, a_col, row_width = _gate_columns(qkvz_width, value_heads, layout == "padded") + # Padding columns hold NaN so that any read of them corrupts the result. + projected = torch.full( + (batch * width, row_width), torch.nan, device="cuda", dtype=torch.bfloat16 + ) + projected[:, :qkvz_width] = _randn((batch * width, qkvz_width), 0.09) + projected[:, b_col : b_col + value_heads] = _randn((batch * width, value_heads), 0.5, -0.1) + projected[:, a_col : a_col + value_heads] = _randn((batch * width, value_heads), 0.5, -0.1) + b = projected[:, b_col : b_col + value_heads] + a = projected[:, a_col : a_col + value_heads] + raw_x_2d = projected[:, :channels] + raw_x = raw_x_2d.as_strided( + (batch, width, channels), + (width * raw_x_2d.stride(0), raw_x_2d.stride(0), 1), + ) + conv_weight = _randn((channels, 4), 0.18).to(torch.bfloat16) + conv_state = _randn((slots, channels, 3), 0.09).to(torch.bfloat16) + checkpoint = _randn((slots, value_heads, DIM, DIM), 0.012).to(torch.bfloat16) + capacity = WINDOW + width + history_u = _randn((replay_slot_count, capacity, value_heads, DIM), 0.012).to(torch.bfloat16) + raw_history_k = _randn((replay_slot_count, capacity, key_heads, DIM), 0.09) + history_k = ( + raw_history_k / torch.sqrt(raw_history_k.square().sum(dim=-1, keepdim=True) + 1e-6) + ).to(torch.bfloat16) + history_G = torch.cumsum( + -(_randn((replay_slot_count, value_heads, capacity), 0.025).abs() + 0.002), + dim=-1, + ) + state_indices = torch.tensor([0, 2, 3, 1], device="cuda", dtype=torch.int32) + replay_indices = torch.tensor([5, 0, 2, 3], device="cuda", dtype=torch.int32) + # Live rows read histories of 0, 16 and 7 rows; the dummy row's slot holds 11. + history_len = torch.tensor([16, 4, 7, 11, 1, 0], device="cuda", dtype=torch.int32) + is_dummy = torch.tensor([False, False, False, True], device="cuda") + A_log = _randn((value_heads,), 0.35, -0.25).clamp_(-1.0, 0.5) + dt_bias = _randn((value_heads,), 0.65, -2.5).clamp_(-5.0, 0.5) + + reference_u = history_u.clone() + reference_k = history_k.clone() + reference_G = history_G.clone() + reference_output, reference_candidates = _replay_reference( + raw_x, + conv_weight, + conv_state, + b, + a, + checkpoint, + state_indices, + is_dummy, + reference_u, + reference_k, + reference_G, + history_len, + A_log, + dt_bias, + replay_indices, + ) + output = torch.empty_like(reference_output) + candidate_x = torch.full( + (batch, width, channels), torch.nan, device="cuda", dtype=torch.bfloat16 + ) + checkpoint_before = checkpoint.clone() + conv_before = conv_state.clone() + history_len_before = history_len.clone() + + gdn_mtp_replay( + raw_x, + conv_weight, + conv_state, + b, + a, + checkpoint, + state_indices, + is_dummy, + history_u, + history_k, + history_G, + history_len, + A_log, + dt_bias, + output, + candidate_x, + replay_indices=replay_indices, + ) + + live = ~is_dummy + torch.testing.assert_close(output[live], reference_output[live], rtol=2e-2, atol=5e-3) + torch.testing.assert_close(candidate_x[live], reference_candidates[live], rtol=0, atol=0) + torch.testing.assert_close(history_u, reference_u, rtol=2e-2, atol=5e-3) + torch.testing.assert_close(history_k, reference_k, rtol=1e-2, atol=1.5e-3) + torch.testing.assert_close(history_G, reference_G, rtol=1e-5, atol=1e-5) + torch.testing.assert_close(checkpoint, checkpoint_before, rtol=0, atol=0) + torch.testing.assert_close(conv_state, conv_before, rtol=0, atol=0) + torch.testing.assert_close(history_len, history_len_before, rtol=0, atol=0) + + +@torch.no_grad() +def _commit_reference( + state_views, + conv_views, + candidate_x, + history_u, + history_k, + history_G, + history_len, + replay_work_items, + accepted_tokens, + is_dummy, +): + value_heads = history_u.shape[-2] + key_heads = history_k.shape[-2] + key_for_value_head = torch.arange(value_heads, device=history_u.device) // ( + value_heads // key_heads + ) + for work_item in replay_work_items: + position = int(work_item[0].item()) + slot = int(work_item[1].item()) + start = int(work_item[2].item()) + replay_slot = int(work_item[4].item()) + if bool(is_dummy[position].item()): + continue + + accepted = int(accepted_tokens[position].item()) + old_conv = torch.stack([view[slot] for view in conv_views]) + accepted_x = candidate_x[:, position, :accepted].transpose(1, 2) + new_conv = torch.cat((old_conv, accepted_x), dim=-1)[..., -3:] + for layer, view in enumerate(conv_views): + view[slot].copy_(new_conv[layer]) + + total = start + accepted + if total <= WINDOW: + history_len[replay_slot] = total + continue + + tail = total - WINDOW + end_G = history_G[:, replay_slot, :, WINDOW - 1].float() + first_G = history_G[:, replay_slot, :, :WINDOW].float() + first_u = history_u[:, replay_slot, :WINDOW].float() + first_k = history_k[:, replay_slot, :WINDOW].float()[:, :, key_for_value_head] + update = torch.einsum( + "ltiv,ltik,lit->livk", + first_u, + first_k, + torch.exp(end_G[:, :, None] - first_G), + ) + checkpoint = torch.stack([view[slot] for view in state_views]).float() + committed = checkpoint * torch.exp(end_G)[:, :, None, None] + update + for layer, view in enumerate(state_views): + view[slot].copy_(committed[layer].to(torch.bfloat16)) + + tail_u = history_u[:, replay_slot, WINDOW : WINDOW + tail].clone() + tail_k = history_k[:, replay_slot, WINDOW : WINDOW + tail].clone() + tail_G = history_G[:, replay_slot, :, WINDOW : WINDOW + tail].clone() + history_u[:, replay_slot, :tail] = tail_u + history_k[:, replay_slot, :tail] = tail_k + history_G[:, replay_slot, :, :tail] = tail_G - end_G[:, :, None] + history_len[replay_slot] = tail + + +def _make_state_storage(indirect, layers, slots, value_heads, channels): + if indirect: + states = [ + _randn((slots, value_heads, DIM, DIM), 0.012).to(torch.bfloat16) for _ in range(layers) + ] + conv = [_randn((slots, channels, 3), 0.09).to(torch.bfloat16) for _ in range(layers)] + state_descriptors = torch.tensor( + [(state.data_ptr(), state.stride(0)) for state in states], + device="cuda", + dtype=torch.int64, + ) + conv_descriptors = torch.tensor( + [(state.data_ptr(), state.stride(0)) for state in conv], + device="cuda", + dtype=torch.int64, + ) + return states, conv, states[0], conv[0], state_descriptors, conv_descriptors + + state_storage = _randn((slots, layers, value_heads, DIM, DIM), 0.012).to(torch.bfloat16) + conv_storage = _randn((slots, layers, channels, 3), 0.09).to(torch.bfloat16) + states = [state_storage[:, layer] for layer in range(layers)] + conv = [conv_storage[:, layer] for layer in range(layers)] + return states, conv, state_storage, conv_storage, None, None + + +def _make_pool_history(layers, replay_slots, capacity, key_heads, value_heads): + """Per-layer U/K/G histories laid out like KV-cache pool pages: one page per + replay slot holds every layer's history, so replay slots are widely strided.""" + u_elements = capacity * value_heads * DIM + k_elements = capacity * key_heads * DIM + g_elements = 2 * value_heads * capacity # FP32 in BF16 elements + page = layers * (u_elements + k_elements + g_elements) + 64 + pool = torch.zeros(replay_slots, page, device="cuda", dtype=torch.bfloat16) + history_u, history_k, history_G = [], [], [] + offset = 0 + for _ in range(layers): + u = pool[:, offset : offset + u_elements].view(replay_slots, capacity, value_heads, DIM) + offset += u_elements + k = pool[:, offset : offset + k_elements].view(replay_slots, capacity, key_heads, DIM) + offset += k_elements + g = pool[:, offset : offset + g_elements].view(torch.float32) + g = g.view(replay_slots, value_heads, capacity) + offset += g_elements + u.copy_(_randn(u.shape, 0.012)) + raw_k = _randn(k.shape, 0.09) + k.copy_(raw_k / torch.sqrt(raw_k.square().sum(dim=-1, keepdim=True) + 1e-6)) + g.copy_(torch.cumsum(-(_randn(g.shape, 0.025).abs() + 0.002), dim=-1)) + history_u.append(u) + history_k.append(k) + history_G.append(g) + return history_u, history_k, history_G + + +@pytest.mark.parametrize("indirect", [False, True], ids=["affine", "indirect"]) +@pytest.mark.parametrize("head_ratio", [1, 4]) +@pytest.mark.parametrize( + "accepted_counts,starting_lengths", + [((3, 2, 1), (15, 10, 16)), ((1, 1, 1), (16, 15, 0)), ((4, 4, 2), (16, 0, 9))], + ids=["mtp3", "golden-only", "full-window"], +) +def test_gdn_mtp_commit_matches_reference( + indirect: bool, + head_ratio: int, + accepted_counts: tuple[int, int, int], + starting_lengths: tuple[int, int, int], +) -> None: + """Conv windows and checkpoints at the state slots, histories and their + lengths at replay slots apart from them, read through page-strided views.""" + from tensorrt_llm._torch.custom_ops.cute_dsl_gdn_mtp_commit import ( + build_gdn_mtp_history_descriptors, + gdn_mtp_commit, + ) + + torch.manual_seed(11) + layers, slots, replay_slot_count, candidate_capacity, width = 2, 5, 6, 5, 4 + key_heads = 1 + value_heads = key_heads * head_ratio + channels = (2 * key_heads + value_heads) * DIM + capacity = WINDOW + width + + states, conv, state_arg, conv_arg, state_desc, conv_desc = _make_state_storage( + indirect, layers, slots, value_heads, channels + ) + reference_states = [state.clone() for state in states] + reference_conv = [state.clone() for state in conv] + candidate_x = _randn((layers, candidate_capacity, width, channels), 0.09).to(torch.bfloat16) + history_u, history_k, history_G = _make_pool_history( + layers, replay_slot_count, capacity, key_heads, value_heads + ) + history_descriptors = build_gdn_mtp_history_descriptors(history_u, history_k, history_G) + accepted_tokens = torch.tensor(accepted_counts, device="cuda", dtype=torch.int32) + is_dummy = torch.tensor([False, False, True], device="cuda") + starts = torch.tensor(starting_lengths, device="cuda", dtype=torch.int32) + positions = torch.tensor([2, 0, 1], device="cuda", dtype=torch.int32) + slot_for_position = torch.tensor([1, 3, 4], device="cuda", dtype=torch.int32) + replay_slot_for_position = torch.tensor([5, 0, 2], device="cuda", dtype=torch.int32) + replay_work_items = torch.stack( + ( + positions, + slot_for_position[positions.long()], + starts[positions.long()], + torch.zeros_like(positions), + replay_slot_for_position[positions.long()], + ), + dim=1, + ).contiguous() + # The length is one column of a per-slot metadata row, as in the pool. + replay_meta = torch.zeros(replay_slot_count, 4, device="cuda", dtype=torch.int32) + history_len = replay_meta[:, 0] + history_len.copy_( + torch.tensor( + [starting_lengths[1], 4, starting_lengths[2], 2, 3, starting_lengths[0]], + device="cuda", + dtype=torch.int32, + ) + ) + + reference_u = torch.stack([view.clone() for view in history_u]) + reference_k = torch.stack([view.clone() for view in history_k]) + reference_G = torch.stack([view.clone() for view in history_G]) + reference_len = history_len.clone() + _commit_reference( + reference_states, + reference_conv, + candidate_x, + reference_u, + reference_k, + reference_G, + reference_len, + replay_work_items, + accepted_tokens, + is_dummy, + ) + + gdn_mtp_commit( + state_arg, + conv_arg, + candidate_x, + history_descriptors, + history_len, + replay_work_items, + accepted_tokens, + is_dummy, + key_heads=key_heads, + value_heads=value_heads, + history_window=WINDOW, + ssm_state_descriptors=state_desc, + conv_state_descriptors=conv_desc, + ) + + for actual, reference in zip(states, reference_states): + torch.testing.assert_close(actual, reference, rtol=2e-2, atol=8e-3) + for actual, reference in zip(conv, reference_conv): + torch.testing.assert_close(actual, reference, rtol=0, atol=0) + torch.testing.assert_close(torch.stack(history_u), reference_u, rtol=0, atol=0) + torch.testing.assert_close(torch.stack(history_k), reference_k, rtol=0, atol=0) + torch.testing.assert_close(torch.stack(history_G), reference_G, rtol=1e-6, atol=1e-6) + torch.testing.assert_close(history_len, reference_len, rtol=0, atol=0) + assert not replay_meta[:, 1:].any() diff --git a/tests/unittest/_torch/pyexecutor/kv_cache/test_mamba_cache_manager.py b/tests/unittest/_torch/pyexecutor/kv_cache/test_mamba_cache_manager.py index b88b4882ae22..537528b43e1e 100644 --- a/tests/unittest/_torch/pyexecutor/kv_cache/test_mamba_cache_manager.py +++ b/tests/unittest/_torch/pyexecutor/kv_cache/test_mamba_cache_manager.py @@ -32,6 +32,7 @@ from tensorrt_llm._torch.kimi_k3_cache_policy import KIMI_K3_FP8_KV_LAYERS_ENV from tensorrt_llm._torch.model_config import KVCacheLayerSpec as ModelKVCacheLayerSpec from tensorrt_llm._torch.modules.fla.cache_manager import ( + GDNMtpReplayState, GDNReplayState, Qwen35HybridCacheManager, _use_flashinfer_ring_replay, @@ -755,6 +756,27 @@ def test_v2_manager_rejects_model_type_kwarg() -> None: ) +@pytest.mark.parametrize( + "fused_verify, fp8_out, expected", + [(False, False, True), (True, False, True), (False, True, True), (True, True, False)], + ids=["plain", "fused_bf16_out", "fp8_out_unfused", "fused_fp8_out"], +) +def test_gdn_mtp_replay_leaves_the_fused_fp8_verify_alone(fused_verify, fp8_out, expected): + """GDN layers of the PyTorch mixer can use GDN MTP replay unless they verify with the fused + kernels into an FP8 out_proj input, which keep the cached replay history.""" + from tensorrt_llm._torch.pyexecutor._util import _uses_gdn_mtp_replay + + layers = [] + for _ in range(2): + gdn = Qwen3NextGatedDeltaNet.__new__(Qwen3NextGatedDeltaNet) + torch.nn.Module.__init__(gdn) + gdn.fused_verify = fused_verify + gdn.norm = SimpleNamespace(fp8_scale=torch.tensor(0.5) if fp8_out else None) + layers.append(gdn) + assert _uses_gdn_mtp_replay(torch.nn.ModuleList(layers)) is expected + assert _uses_gdn_mtp_replay(torch.nn.ModuleList([torch.nn.Linear(2, 2)])) is False + + @pytest.mark.parametrize( ("use_v2", "enable_block_reuse", "expected"), [ @@ -842,6 +864,7 @@ def __init__(self, *args, **kwargs): gdn = Qwen3NextGatedDeltaNet.__new__(Qwen3NextGatedDeltaNet) torch.nn.Module.__init__(gdn) gdn.fused_verify = True + gdn.norm = SimpleNamespace(fp8_scale=None) # BF16 out_proj input model_engine = SimpleNamespace( model=torch.nn.ModuleList([gdn]), attn_runtime_features=SimpleNamespace(chunked_prefill=False), @@ -909,6 +932,8 @@ def __init__(self, *args, **kwargs): assert captured_cpp["gdn_fused_verify"] is True assert "gdn_fused_verify" not in captured_mixed assert captured_v2["gdn_fused_verify"] is True + assert captured_v2["gdn_mtp_replay"] is True + assert "gdn_mtp_replay" not in captured_cpp assert captured_cpp["model_type"] == "qwen3_next" assert captured_cpp["max_num_tokens"] == 256 assert "vocab_size" not in captured_cpp @@ -9819,7 +9844,9 @@ def test_v2_gdn_ring_replay_buffers_share_the_recurrent_state_slot(monkeypatch, ) -def _v2_gdn_replay_manager_with_large_slots(manager_cls, flashinfer_ring, bf16_states=False): +def _v2_gdn_replay_manager_with_large_slots( + manager_cls, flashinfer_ring, bf16_states=False, gdn_mtp_replay=False +): """A real V2 GDN manager with replay at K = V = 128, 16 value and 4 key heads, on 6 layers. A recurrent-state slot (3 MiB with fp32 states for the Triton history, bf16 states for the fused verify kernel, 3 MiB of bf16 states plus the rings for FlashInfer) is larger than the 2 MiB allocation grain, so the pool holds a handful of slots, fewer @@ -9852,6 +9879,7 @@ def _v2_gdn_replay_manager_with_large_slots(manager_cls, flashinfer_ring, bf16_s layer_mask=[False] * num_gdn_layers + [True], vocab_size=1024, use_replay_state_update=True, + gdn_mtp_replay=gdn_mtp_replay, ) @@ -10112,6 +10140,308 @@ def test_v2_gdn_replay_suspend_resume_matches_an_unsuspended_run( assert torch.equal(states, expected_states) +_skip_no_gdn_mtp_replay = pytest.mark.skipif( + not torch.cuda.is_available() or torch.cuda.get_device_capability() not in ((10, 0), (10, 3)), + reason="GDN MTP replay needs SM100/SM103", +) + + +def _gdn_mtp_replay_rows(mgr, replay_slot): + """One replay slot's history length and clones of its per-layer U/K/G history.""" + state = mgr._speculative_state + history = [ + state._layer_views(name)[layer][replay_slot].clone() + for name in ("old_x", "old_B", "old_dt") + for layer in range(mgr.local_num_mamba_layers) + ] + return int(state.prev_num_accepted_tokens[replay_slot]), history + + +def _gdn_mtp_round(mgr, request_id, layer_params, round_idx, accepted): + """One verify of the request on every GDN layer through the GDN MTP replay kernel, then the + all-layer commit of ``accepted`` tokens. Returns the verify outputs.""" + from tensorrt_llm._torch.custom_ops.cute_dsl_gdn_mtp_replay import gdn_mtp_replay + from tensorrt_llm._torch.modules.mamba.replay_metadata import ( + REPLAY_WORK_ITEM_WIDTH, + snapshot_gdn_mtp_replay_work_items, + ) + + state = mgr._speculative_state + state_slots = torch.tensor( + mgr.get_state_indices([request_id], [False]), dtype=torch.int32, device="cuda" + ) + replay_slots = torch.tensor( + mgr.get_replay_state_indices([request_id]), dtype=torch.int32, device="cuda" + ) + tokens = state.replay_step_width + n_heads, head_dim, _ = mgr.ssm_state_shape + is_dummy = torch.zeros(1, dtype=torch.bool, device="cuda") + work_items = torch.zeros(1, REPLAY_WORK_ITEM_WIDTH, dtype=torch.int32, device="cuda") + snapshot_gdn_mtp_replay_work_items( + state_slots, replay_slots, state.prev_num_accepted_tokens, work_items + ) + outputs = [] + for layer_offset, (conv_weight, A_log, dt_bias) in enumerate(layer_params): + layer_cache = mgr.mamba_layer_cache(mgr.mamba_pp_layers[layer_offset]) + channels = conv_weight.shape[0] + generator = torch.Generator(device="cuda").manual_seed(1000 * round_idx + layer_offset) + raw_x = torch.randn(1, tokens, channels, generator=generator, device="cuda").bfloat16() + ba = torch.randn(tokens, 2 * n_heads, generator=generator, device="cuda").bfloat16() + out = torch.empty(1, tokens, n_heads, head_dim, dtype=torch.bfloat16, device="cuda") + gdn_mtp_replay( + raw_x=raw_x, + conv_weight=conv_weight, + conv_state=layer_cache.conv, + b=ba[:, :n_heads], + a=ba[:, n_heads:], + checkpoint=layer_cache.temporal, + state_indices=state_slots, + is_dummy=is_dummy, + history_u=layer_cache.old_x, + history_k=layer_cache.old_B, + history_G=layer_cache.old_dt, + history_len=layer_cache.prev_num_accepted_tokens, + A_log=A_log, + dt_bias=dt_bias, + output=out, + candidate_x=layer_cache.intermediate_conv_window[:1], + replay_indices=replay_slots, + ) + outputs.append(out.clone()) + state.update( + MambaAcceptanceBatch( + attention_metadata=SimpleNamespace( + mamba_metadata=SimpleNamespace(replay_work_items=work_items, replay_num_decodes=1) + ), + num_contexts=0, + num_generations=1, + num_accepted_tokens=torch.tensor([accepted], dtype=torch.int32, device="cuda"), + accepted_positions=torch.tensor([accepted - 1], dtype=torch.int32, device="cuda"), + source_state_indices=torch.zeros(1, dtype=torch.int32, device="cuda"), + destination_state_indices=state_slots, + is_dummy_request=is_dummy, + ), + replay_slots, + ) + return torch.stack(outputs) + + +def _run_gdn_mtp_rounds(manager_cls, accepted_per_round, suspend_after=None, slot_taken=False): + """GDN MTP replay rounds of one request on a V2 manager, as _run_gdn_verify_rounds. Returns + every round's outputs and the request's final SSM and Conv states.""" + mgr = _v2_gdn_replay_manager_with_large_slots( + manager_cls, flashinfer_ring=False, bf16_states=True, gdn_mtp_replay=True + ) + others = [] + request = None + try: + assert isinstance(mgr._speculative_state, GDNMtpReplayState) + assert mgr.use_gdn_mtp_replay and not mgr.use_gdn_cached_replay_all_layer_commit + (request,) = mgr.add_dummy_requests( + [1], token_nums=[8], is_gen=True, max_num_draft_tokens=3 + ) + generator = torch.Generator(device="cuda").manual_seed(7) + n_heads = mgr.ssm_state_shape[0] + channels = mgr.all_conv_states[0].shape[1] + layer_params = [ + ( + (torch.randn(channels, 4, generator=generator, device="cuda") * 0.3).bfloat16(), + torch.log(torch.rand(n_heads, generator=generator, device="cuda") * 7 + 1), + torch.rand(n_heads, generator=generator, device="cuda") * 2 - 1, + ) + for _ in mgr.all_ssm_states + ] + # The states a prefill leaves; the replay history starts empty. + slot = mgr.get_state_indices([1], [False])[0] + for ssm_states, conv_states in zip(mgr.all_ssm_states, mgr.all_conv_states): + ssm_states[slot] = 0.05 * torch.randn( + ssm_states.shape[1:], generator=generator, device="cuda" + ) + conv_states[slot] = 0.3 * torch.randn( + conv_states.shape[1:], generator=generator, device="cuda" + ) + assert ( + int( + mgr._speculative_state.prev_num_accepted_tokens[ + mgr.get_replay_state_indices([1])[0] + ] + ) + == 0 + ) + + outputs = [] + for round_idx, accepted in enumerate(accepted_per_round): + outputs.append(_gdn_mtp_round(mgr, 1, layer_params, round_idx, accepted)) + if round_idx == suspend_after: + slot = mgr.get_state_indices([1], [False])[0] + history = _gdn_mtp_replay_rows(mgr, mgr.get_replay_state_indices([1])[0]) + assert history[0] > 0, "suspend with accepted tokens in the history" + mgr.suspend_request(request) + if slot_taken: + _take_ssm_slot(mgr, slot, others) + for ssm_states, conv_states in zip(mgr.all_ssm_states, mgr.all_conv_states): + ssm_states[slot] = torch.randn( + ssm_states.shape[1:], generator=generator, device="cuda" + ) + conv_states[slot] = torch.randn( + conv_states.shape[1:], generator=generator, device="cuda" + ) + assert mgr.resume_request(request) + mgr._setup_state_indices([request], num_contexts=0) + if slot_taken: + assert mgr.get_state_indices([1], [False])[0] != slot + # The PRIVATE replay page follows the request with its length and history. + resumed = _gdn_mtp_replay_rows(mgr, mgr.get_replay_state_indices([1])[0]) + assert resumed[0] == history[0] + assert all(torch.equal(a, b) for a, b in zip(resumed[1], history[1], strict=True)) + slot = mgr.get_state_indices([1], [False])[0] + states = torch.stack([ssm_states[slot] for ssm_states in mgr.all_ssm_states]) + conv = torch.stack([conv_states[slot] for conv_states in mgr.all_conv_states]) + torch.cuda.synchronize() + return outputs, states, conv + finally: + for cache in others: + cache.close() + if request is not None: + mgr.free_resources(request) + mgr.shutdown() + + +@_skip_no_gdn_mtp_replay +@pytest.mark.parametrize("slot_taken", [True, False], ids=["slot_taken", "slot_kept"]) +@pytest.mark.parametrize( + "manager_cls", + [Qwen35HybridCacheManager, Qwen4ExpHybridCacheManager], + ids=["qwen3_5", "qwen4_exp"], +) +def test_v2_gdn_mtp_replay_suspend_resume_matches_an_unsuspended_run(manager_cls, slot_taken): + """GDN MTP replay keeps its single-buffer history in PRIVATE pages with replay slots of their + own, read by the replay kernel and the all-layer commit through page-strided views. A request + suspended with accepted tokens in that history resumes, with or without losing its SSM slot, + and every later verify gives, bit for bit, the outputs and states of a run never suspended. + The history crosses the 16-row window, so commits fold it into the checkpoint.""" + accepted_per_round = [2, 1, 4, 4, 3, 1, 4, 2, 3, 4] + expected = _run_gdn_mtp_rounds(manager_cls, accepted_per_round) + actual = _run_gdn_mtp_rounds( + manager_cls, accepted_per_round, suspend_after=3, slot_taken=slot_taken + ) + for round_idx, (got, want) in enumerate(zip(actual[0], expected[0], strict=True)): + assert torch.equal(got, want), f"verify round {round_idx}" + assert torch.equal(actual[1], expected[1]) + assert torch.equal(actual[2], expected[2]) + + +@skip_no_cuda +def test_gdn_mtp_layer_addressing_falls_back_to_indirect_descriptors(): + """Evenly spaced layer views give the all-layer commit one slot-major view; + separately allocated layers give per-layer (base address, slot stride) rows.""" + from tensorrt_llm._torch.modules.fla.cache_manager import _gdn_mtp_layer_addressing + + shape = (4, 2, 8, 8) + pool = torch.zeros(5, 3, *shape[1:], dtype=torch.bfloat16, device="cuda") + affine_layers = tuple(pool[:, layer] for layer in range(3)) + view, descriptors = _gdn_mtp_layer_addressing(affine_layers, shape[1:], "SSM state") + assert descriptors is None + assert view.shape == (5, 3, *shape[1:]) + assert view.data_ptr() == pool.data_ptr() and view.stride() == pool.stride() + + # A padded slot stride that differs per layer cannot be stacked. + separate_layers = tuple( + torch.zeros(5, 2 + layer, 8, 8, dtype=torch.bfloat16, device="cuda")[:, :2] + for layer in range(3) + ) + view, descriptors = _gdn_mtp_layer_addressing(separate_layers, shape[1:], "SSM state") + assert view is None + assert descriptors.dtype == torch.int64 and descriptors.shape == (3, 2) + assert descriptors.tolist() == [ + [layer.data_ptr(), layer.stride(0)] for layer in separate_layers + ] + with pytest.raises(RuntimeError, match="dense inner dimensions"): + _gdn_mtp_layer_addressing((pool[:, 0, :, :, :4],), (2, 8, 4), "SSM state") + + +@skip_no_cuda +@pytest.mark.parametrize( + "ssm_dtype, sm, cute_dsl, head_dim, expected", + [ + (torch.bfloat16, 100, True, 128, GDNMtpReplayState), + (torch.float32, 100, True, 128, GDNReplayState), + (torch.bfloat16, 90, True, 128, GDNReplayState), + (torch.bfloat16, 100, False, 128, GDNReplayState), + (torch.bfloat16, 100, True, 64, GDNReplayState), + ], + ids=["eligible", "fp32_states", "sm90", "no_cute_dsl", "head_dim64"], +) +def test_v2_gdn_mtp_replay_is_selected_when_supported( + monkeypatch, ssm_dtype, sm, cute_dsl, head_dim, expected +): + """A model whose GDN layers can use GDN MTP replay gets its state when the kernels support + the configuration and keeps the cached replay otherwise; the GDN MTP replay history is a + PRIVATE region with replay slots of its own, local to the worker.""" + import tensorrt_llm._torch.cute_dsl_utils as cute_dsl_utils + import tensorrt_llm._torch.modules.fla.cache_manager as gdn_cache_manager + + monkeypatch.setattr(gdn_cache_manager, "get_sm_version", lambda: sm) + monkeypatch.setattr(cute_dsl_utils, "IS_CUTLASS_DSL_AVAILABLE", cute_dsl) + mgr = Qwen35HybridCacheManager( + mamba_d_state=head_dim, + mamba_d_conv=4, + mamba_num_heads=16, + mamba_n_groups=4, + mamba_head_dim=head_dim, + mamba_num_layers=2, + mamba_layer_mask=[True, True, False], + mamba_cache_dtype=torch.bfloat16, + mamba_ssm_cache_dtype=ssm_dtype, + kv_cache_config=KvCacheConfig(max_tokens=4096, enable_block_reuse=False), + kv_cache_type=CacheTypeCpp.SELF, + num_layers=1, + num_kv_heads=4, + head_dim=64, + tokens_per_block=32, + max_seq_len=128, + max_batch_size=2, + mapping=Mapping(world_size=1, rank=0, tp_size=1, pp_size=1), + dtype=DataType.HALF, + spec_config=MTPDecodingConfig(max_draft_len=3), + layer_mask=[False, False, True], + vocab_size=1024, + use_replay_state_update=True, + gdn_mtp_replay=True, + ) + try: + state = mgr._speculative_state + assert type(state) is expected + assert mgr.use_gdn_mtp_replay == (expected is GDNMtpReplayState) + if expected is not GDNMtpReplayState: + assert not state.use_flashinfer_ring + assert mgr.get_replay_state_update_metadata().cache_buf_idx is not None + return + assert not mgr.use_gdn_cached_replay_all_layer_commit + metadata = mgr.get_replay_state_update_metadata() + assert metadata.cache_buf_idx is None + assert (metadata.replay_step_width, metadata.replay_history_size) == (4, 16) + replay_group = mgr.replay_layer_group_id + assert replay_group is not None and replay_group != mgr.ssm_layer_group_id + layer_cache = mgr.mamba_layer_cache(mgr.mamba_pp_layers[0]) + replay_slots = layer_cache.old_x.shape[0] + assert layer_cache.old_x.shape == (replay_slots, 20, 16, 128) + assert layer_cache.old_B.shape == (replay_slots, 20, 4, 128) + assert layer_cache.old_dt.shape == (replay_slots, 16, 20) + assert layer_cache.old_dt.dtype == torch.float32 + assert layer_cache.intermediate_conv_window.shape == (2, 4, mgr.all_conv_states[0].shape[1]) + assert ( + set(mgr._replay_region.layouts[mgr.mamba_pp_layers[0]]) + <= mgr.get_disagg_ignored_roles() + ) + # A replay slot a generation request acquires for the first time is empty. + state.prev_num_accepted_tokens.fill_(9) + mgr.add_dummy_requests([5], token_nums=[8], is_gen=True, max_num_draft_tokens=3) + assert int(state.prev_num_accepted_tokens[mgr.get_replay_state_indices([5])[0]]) == 0 + finally: + mgr.shutdown() + + @_skip_no_flashinfer_ring def test_v2_gdn_ring_replay_flashinfer_reads_kvcm_ring_views(monkeypatch): """FlashInfer's ring replay takes the manager's rings, which are block-strided views of the recurrent-state slots, From c68abdbf00d9c652df73c8c9c4bfbfa962678c5f Mon Sep 17 00:00:00 2001 From: jiant <107457950+JadoTu@users.noreply.github.com> Date: Mon, 16 Nov 2026 17:07:54 +0000 Subject: [PATCH 2/2] fix the GDN MTP replay cost guard for non-class cache managers KvCacheCreator called issubclass() on manager_cls before checking that it is a class, so cache-budget tests that pass a test double failed with TypeError. Signed-off-by: jiant <107457950+JadoTu@users.noreply.github.com> --- tensorrt_llm/_torch/pyexecutor/_util.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/tensorrt_llm/_torch/pyexecutor/_util.py b/tensorrt_llm/_torch/pyexecutor/_util.py index 19df42d58b94..4136092878c8 100644 --- a/tensorrt_llm/_torch/pyexecutor/_util.py +++ b/tensorrt_llm/_torch/pyexecutor/_util.py @@ -1501,7 +1501,8 @@ def _per_manager_cache_cost(self, # pools. The draft manager never derives (see there). kv_cache_config = kv_cache_config.model_copy( update={"max_attention_window": derived_windows}) - if (not is_draft and issubclass(manager_cls, MambaHybridCacheManagerV2) + if (not is_draft and isinstance(manager_cls, type) + and issubclass(manager_cls, MambaHybridCacheManagerV2) and self._model_engine is not None and _uses_gdn_mtp_replay(self._model_engine.model)): # Cost the GDN replay region of the state the manager will select.