Repository navigation
[KDA] Add FlashInfer SM100 KDA decode + MTP (target_verify) backend - #30113
Conversation
There was a problem hiding this comment.
Code Review
This pull request introduces a FlashInfer-based KDA (Kimi Delta Attention) linear attention kernel (FlashInferKDAKernel) supporting SM100 decode and speculative-decode (MTP) operations, alongside integration into the KDA backend dispatcher and corresponding correctness tests. The review feedback focuses on improving robustness and precision compatibility, specifically recommending that hardcoded torch.bfloat16 casts be replaced with dynamic casting to q.dtype to support float16 models, and that .view() calls on potentially non-contiguous tensors be replaced with .reshape() to prevent runtime errors.
Important
The consumer version of Gemini Code Assist on GitHub is being sunset. Starting June 18, 2026, new organization installations will be blocked, and all code review activity will officially cease on July 17, 2026.
For more details on the timeline and next steps, please review the Help Documentation.
| def _beta_logit_to_prob(b: torch.Tensor) -> torch.Tensor: | ||
| # Triton KDA does beta = sigmoid(b); recurrent_kda wants beta pre-sigmoided. | ||
| # torch.sigmoid computes in fp32 internally, so a single sigmoid on the bf16 | ||
| # logit is enough (avoids an explicit fp32 upcast + downcast = 2 extra kernels). | ||
| return torch.sigmoid(b).to(torch.bfloat16) |
There was a problem hiding this comment.
Hardcoding the output dtype to torch.bfloat16 in _beta_logit_to_prob can cause runtime dtype mismatch errors if the model is running in float16 (or another precision), as the query, key, and value tensors will have a different dtype. Passing the target dtype dynamically ensures compatibility across different precision modes.
| def _beta_logit_to_prob(b: torch.Tensor) -> torch.Tensor: | |
| # Triton KDA does beta = sigmoid(b); recurrent_kda wants beta pre-sigmoided. | |
| # torch.sigmoid computes in fp32 internally, so a single sigmoid on the bf16 | |
| # logit is enough (avoids an explicit fp32 upcast + downcast = 2 extra kernels). | |
| return torch.sigmoid(b).to(torch.bfloat16) | |
| @staticmethod | |
| def _beta_logit_to_prob(b: torch.Tensor, dtype: torch.dtype) -> torch.Tensor: | |
| # Triton KDA does beta = sigmoid(b); recurrent_kda wants beta pre-sigmoided. | |
| # torch.sigmoid computes in fp32 internally, so a single sigmoid on the logit | |
| # is enough (avoids an explicit fp32 upcast + downcast = 2 extra kernels). | |
| return torch.sigmoid(b).to(dtype) |
| g_fi = a.reshape(1, batch_size, num_v_heads, head_k_dim).to(torch.bfloat16) | ||
| beta_fi = self._beta_logit_to_prob(b).reshape(1, batch_size, num_v_heads) |
There was a problem hiding this comment.
Cast g_fi and beta_fi to q.dtype instead of hardcoding torch.bfloat16 to prevent dtype mismatch crashes when running models in float16 precision.
| g_fi = a.reshape(1, batch_size, num_v_heads, head_k_dim).to(torch.bfloat16) | |
| beta_fi = self._beta_logit_to_prob(b).reshape(1, batch_size, num_v_heads) | |
| g_fi = a.reshape(1, batch_size, num_v_heads, head_k_dim).to(q.dtype) | |
| beta_fi = self._beta_logit_to_prob(b, q.dtype).reshape(1, batch_size, num_v_heads) |
| g_fi = a.reshape(1, seq_len, num_v_heads, head_k_dim).to(torch.bfloat16) | ||
| beta_fi = self._beta_logit_to_prob(b).reshape(1, seq_len, num_v_heads) |
There was a problem hiding this comment.
Cast g_fi and beta_fi to q.dtype instead of hardcoding torch.bfloat16 to prevent dtype mismatch crashes when running models in float16 precision.
| g_fi = a.reshape(1, seq_len, num_v_heads, head_k_dim).to(torch.bfloat16) | |
| beta_fi = self._beta_logit_to_prob(b).reshape(1, seq_len, num_v_heads) | |
| g_fi = a.reshape(1, seq_len, num_v_heads, head_k_dim).to(q.dtype) | |
| beta_fi = self._beta_logit_to_prob(b, q.dtype).reshape(1, seq_len, num_v_heads) |
| mixed_qkv_reshaped = mixed_qkv.view(batch_size, draft_token_num, -1).transpose( | ||
| 1, 2 | ||
| ) |
There was a problem hiding this comment.
Using .view() on mixed_qkv can raise a runtime error if the tensor is non-contiguous. Using .reshape() is safer and more robust as it automatically handles non-contiguous layouts.
| mixed_qkv_reshaped = mixed_qkv.view(batch_size, draft_token_num, -1).transpose( | |
| 1, 2 | |
| ) | |
| mixed_qkv_reshaped = mixed_qkv.reshape(batch_size, draft_token_num, -1).transpose( | |
| 1, 2 | |
| ) |
| state_pool = scratch.view( | ||
| scratch.shape[0] * draft_token_num, num_v_heads, head_v_dim, head_k_dim | ||
| ) |
There was a problem hiding this comment.
Using .view() on scratch can raise a runtime error if the tensor is non-contiguous. Using .reshape() is safer and more robust as it automatically handles non-contiguous layouts.
| state_pool = scratch.view( | |
| scratch.shape[0] * draft_token_num, num_v_heads, head_v_dim, head_k_dim | |
| ) | |
| state_pool = scratch.reshape( | |
| scratch.shape[0] * draft_token_num, num_v_heads, head_v_dim, head_k_dim | |
| ) |
2d17aad to
16675d0
Compare
kaixih
left a comment
There was a problem hiding this comment.
Could you add the full output from bench_kda_flashinfer_mtp.py to the PR description, or attach it as an artifact?
At B=64, recurrent_kda itself looks faster in the NCU profile, while the wrapper-level decode result is still 0.93x. A short breakdown of the work outside recurrent_kda would make this tradeoff much easier to understand. For example, input casts, sigmoid/cast for beta, dispatch, or other setup work.
This would also give us a clearer target for follow-up optimizations, such as fusing the surrounding ops or supporting more input dtypes.
16675d0 to
7cf7612
Compare
@kaixih Added full output. |
3bd1fde to
072778a
Compare
Add a FlashInfer (Blackwell / SM100) backend for KDA (Kimi Delta Attention) linear attention: single-token decode and the first numerically correct MTP / speculative-decode target_verify (topk=1) path for KDA, which KDA previously lacked entirely. Wraps flashinfer.kda_decode.recurrent_kda (the single KDA op covering both decode and fused spec-decode). Prefill stays on Triton / CuTe DSL (FlashInfer has no KDA chunk-prefill kernel). Opt in with --linear-attn-decode-backend flashinfer (requires --mamba-ssm-dtype bfloat16). KDA MTP is FlashInfer / SM100 only. The FlashInfer verify reproduces the non-speculative reference end to end (Kimi-Linear-48B gsm8k 0.895 vs 0.90 non-spec). The Triton KDA verify produces the correct per-draft-token attention output (unit-tested) but does not yet commit the right per-step checkpoint state for the central MTP rollback, so end-to-end accuracy collapses to ~0.60; it is kept as a per-token reference and a Hopper starting point but not wired into production -- target_verify() raises a clear error for the Triton / CuTe DSL decode backends.
124c5f4 to
bfde956
Compare
|
Sorry for the late reply. I can see the "Full output of the eager per-call microbench". But it seems flashinfer is slower than triton in every case. Do I read it correctly? |
This is eagle mode result, for CUDA graph mode, the decode FlashInfer is the same as triton, while the target_verify is still slightly slower than triton. |
### Summary This PR optimizes and simplifies the CuTe DSL recurrent-KDA implementation on Blackwell: - Uses a single register-tiled, one-warp kernel for D=64 and D=128. - Automatically selects measured 8-, 16-, or 32-row tiles and tree or dual-accumulator reductions. - Removes the legacy base/vtile kernels, dispatch branches, compilation caches, and environment overrides. - Supports loading speculative token 0 from a separate read-only committed-state pool. - Supports applying sigmoid to beta inside the kernel. - Simplifies the schedule tests and recurrent-KDA benchmark. ### Performance Benchmarks were run on B300/SM103 with PyTorch 2.11.0+cu130 using CUDA graphs. Latencies are in microseconds. #### FLA comparison `FLA/CuTe > 1` means FlashInfer is faster. | Config | Batch | CuTe T=1 | FLA T=1 | FLA/CuTe T=1 | CuTe T=4 | FLA T=4 | FLA/CuTe T=4 | |:---|---:|---:|---:|---:|---:|---:|---:| | H8-D64 | 1 | 2.6 | 3.4 | 1.32x | 4.6 | 7.2 | 1.58x | | H8-D64 | 2 | 2.5 | 3.4 | 1.39x | 4.7 | 7.2 | 1.55x | | H8-D64 | 4 | 2.5 | 3.4 | 1.37x | 4.8 | 7.2 | 1.52x | | H8-D64 | 8 | 2.6 | 3.5 | 1.33x | 4.9 | 7.4 | 1.51x | | H8-D64 | 16 | 2.8 | 3.9 | 1.37x | 5.6 | 8.7 | 1.56x | | H8-D64 | 32 | 3.3 | 4.9 | 1.49x | 6.4 | 11.2 | 1.75x | | H8-D64 | 64 | 4.1 | 7.5 | 1.85x | 8.0 | 19.7 | 2.46x | | H8-D64 | 128 | 5.1 | 11.5 | 2.26x | 13.8 | 33.1 | 2.40x | | H16-D128 | 1 | 2.5 | 3.6 | 1.44x | 6.8 | 8.4 | 1.25x | | H16-D128 | 2 | 2.6 | 3.8 | 1.47x | 6.6 | 8.2 | 1.24x | | H16-D128 | 4 | 2.7 | 4.6 | 1.68x | 7.9 | 10.0 | 1.28x | | H16-D128 | 8 | 3.3 | 5.7 | 1.72x | 9.1 | 13.2 | 1.45x | | H16-D128 | 16 | 4.4 | 8.8 | 2.01x | 17.3 | 23.6 | 1.36x | | H16-D128 | 32 | 7.5 | 13.2 | 1.77x | 23.8 | 44.2 | 1.86x | | H16-D128 | 64 | 12.9 | 24.7 | 1.92x | 52.2 | 83.0 | 1.59x | | H16-D128 | 128 | 23.7 | 54.8 | 2.31x | 97.5 | 156.2 | 1.60x | | H32-D128 | 1 | 2.6 | 3.8 | 1.46x | 7.0 | 8.6 | 1.23x | | H32-D128 | 2 | 2.8 | 4.2 | 1.53x | 7.5 | 9.7 | 1.29x | | H32-D128 | 4 | 3.4 | 5.8 | 1.72x | 9.1 | 13.2 | 1.45x | | H32-D128 | 8 | 4.4 | 8.7 | 1.99x | 17.2 | 23.2 | 1.35x | | H32-D128 | 16 | 7.7 | 13.1 | 1.71x | 24.2 | 44.7 | 1.84x | | H32-D128 | 32 | 12.9 | 23.7 | 1.84x | 51.0 | 82.0 | 1.61x | | H32-D128 | 64 | 23.9 | 52.2 | 2.18x | 97.4 | 155.9 | 1.60x | | H32-D128 | 128 | 53.9 | 99.4 | 1.85x | 185.9 | 299.4 | 1.61x | Geometric-mean speedup over the 24 configurations: - T=1: **1.68x** - T=4: **1.55x** #### SGLang Triton comparison This comparison uses the unchanged Triton implementation from [SGLang PR #30113](sgl-project/sglang#30113) at commit `f66df9cac0517755578a28620aecfe322d73d05d`. KDA decode, T=1: | B | Triton (us) | FlashInfer (us) | Speedup | Output max diff | State max diff | |---:|---:|---:|---:|---:|---:| | 1 | 4.15 | 4.13 | 1.00x | 2.98e-08 | 2.44e-04 | | 4 | 6.16 | 4.13 | 1.49x | 2.98e-08 | 2.44e-04 | | 16 | 6.18 | 6.18 | 1.00x | 1.91e-06 | 4.88e-04 | | 32 | 10.28 | 8.23 | 1.25x | 1.91e-06 | 4.88e-04 | | 64 | 18.46 | 14.37 | 1.28x | 1.91e-06 | 4.88e-04 | | 128 | 29.77 | 24.55 | 1.21x | 7.63e-06 | 9.77e-04 | Geometric-mean T=1 speedup: **1.195x**. KDA target verify, T=8: | B | Triton (us) | FlashInfer (us) | Speedup | Output max diff | State max diff | |---:|---:|---:|---:|---:|---:| | 1 | 16.42 | 12.32 | 1.33x | 1.53e-05 | 4.88e-04 | | 4 | 16.42 | 14.37 | 1.14x | 1.53e-05 | 9.77e-04 | | 16 | 24.60 | 24.62 | 1.00x | 3.05e-05 | 9.77e-04 | | 32 | 53.52 | 52.49 | 1.02x | 3.05e-05 | 9.77e-04 | | 64 | 99.40 | 97.76 | 1.02x | 6.10e-05 | 9.77e-04 | | 128 | 175.54 | 173.34 | 1.01x | 3.05e-05 | 9.77e-04 | Geometric-mean T=8 speedup: **1.081x**. ### Correctness and validation The accuracy tests, tolerances, and benchmark comparison paths were not changed to obtain these results. - `74 passed` in `tests/kda/test_recurrent_kda.py` - D=64 and D=128 - Standard and speculative decode - Precomputed, softplus, and lower-bound gate modes - Separate committed-state and in-place state sources - Padded and variable-length sequences - All active 8-, 16-, and 32-row schedules - Tree and dual-accumulator reductions - Ruff: all checks passed - `git diff --check`: passed <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit * **New Features** * Recurrent KDA decoding now supports initializing from a separate committed state source using corresponding state indices. * Added `beta_is_logit` to interpret beta inputs as logits. * Added recurrent KDA tracing support, including a new trace configuration example. * **Performance** * Updated recurrent KDA decoding to use an optimized tiled execution path with improved specialization/schedule selection. * **Bug Fixes** * Improved recurrent/spec decode correctness, including BF16 comparison behavior and padded output handling. * Correct handling for `T=1` with empty sequence rows (no token reads or state mutation). * **Documentation** * Refined recurrent KDA benchmark documentation for `T=1` vs `T>1`. <!-- end of auto-generated comment: release notes by coderabbit.ai -->
…gl-project#30113) Co-authored-by: luoyuan.luo <[email protected]>
来源提交(1 个):a086f66534 原标题:[KDA] Add FlashInfer SM100 KDA decode + MTP (target_verify) backend (sgl-project#30113) 作者:Yuan Luo,日期:2026-07-15 luno:- 开关:- 默认:无开关 改动规模:6 files changed, 1077 insertions(+), 39 deletions(-) 主要目录:python/sglang/srt/layers, benchmark/bench_linear_attention/bench_kda_flashinfer_mtp.py, python/sglang/srt/mem_cache, test/registered/attention/test_kda_decode_flashinfer.py
Summary
This PR adds a FlashInfer (Blackwell / SM100) backend for KDA (Kimi Delta Attention) linear attention, providing both single-token decode and the first numerically-correct MTP / speculative-decode
target_verify(topk=1) path for KDA — which KDA previously lacked entirely. Enable with--linear-attn-decode-backend flashinfer(SM100, requires--mamba-ssm-dtype bfloat16).Motivation
KDA had no
target_verifypath, so KDA models (e.g. Kimi-Linear, ling-v3) could not use speculative decoding (EAGLE / MTP / n-gram) at all. GDN already has the full decode + prefill + MTP story (including a FlashInfer backend); this PR brings KDA to parity for decode + MTP on Blackwell by wrapping FlashInfer'srecurrent_kda(the single KDA op that covers both standard decode and fused spec-decode). Prefill stays on Triton / CuTe DSL — FlashInfer has no KDA chunk-prefill kernel.Modifications
kernels/kda_flashinfer.py(new):FlashInferKDAKernel(LinearAttnKernelBase)wrappingflashinfer.kda_decode.recurrent_kda. Implementsdecode(in-place pool update) andtarget_verify(topk=1). Lazy import + SM100 guard;extendraises (no FlashInfer KDA prefill).kda_backend.py:KDAKernelDispatchergains anis_flashinfer()decode branch and atarget_verify()method;KDAAttnBackendgainsverify_intermediate_state_indicesand aforward_extend→_forward_target_verifypath (conv1d MTP with intermediate-window checkpointing + the central post-verify rollback), mirroring the GDN backend. KDA MTP is dispatched to FlashInfer only (see correctness note below); Triton / CuTe DSL decode backends leaveverify_kernel = Noneandtarget_verify()raises a clear error.kernels/kda_triton.py:TritonKDAKernel.target_verify(viafused_sigmoid_gating_delta_rule_update(is_kda=True, disable_state_update=True, ...)). Its per-draft-token attention output is correct and is used as the unit-test reference, but its end-to-end rollback checkpointing is not yet correct for KDA, so it is not wired into production (see limitations).mem_cache/memory_pool.py:conv_window_dedup_enabledgains anis_kdaguard — KDA keeps the dense conv-window layout (required; see below).test/registered/attention/test_kda_decode_flashinfer.py(new): 11 unit tests — FlashInferdecodeandtarget_verifymatch the Triton reference per-token across batch/spec shapes;target_verify's per-step checkpoint states match a sequential-decode reference (the correctness property the central MTP rollback depends on — an output-only check misses it, which is exactly how the Triton verify's e2e bug hides); plus a tree-spec-rejection guard.benchmark/bench_linear_attention/bench_kda_flashinfer_mtp.py(new): FlashInfer-vs-Triton decode + verify correctness and per-call latency.LinearAttnKernelBackend.FLASHINFER/ the"flashinfer"CLI choice already existed — noutils.py/server_args.pychanges needed.Key contract details
g = -exp(A_log) * softplus(a + dt_bias), so the wrapper callsrecurrent_kda(..., use_gate_in_kernel=True)to match the Triton reference exactly.sigmoidin-kernel);recurrent_kdawants pre-sigmoid beta, so the wrapper passessigmoid(b).[N, HV, V, K]everywhere (committed pool, speculativeintermediate_ssm, andrecurrent_kda), so no transpose is needed on the SSM side.recurrent_kdawrites each draft token's post-state into pool slots given byssm_state_indices; the wrapper points those at the speculativeintermediate_ssmscratch (slot =request*T + step) and seeds column 0 with the committed state, so the existing central rollback (update_mamba_state_after_mtp_verify) commits the accepted-length state unchanged.Correctness: conv-window layout must stay dense for KDA
KDA's conv-state pool is physically
[pool, width, dim], so the KDA backend.transpose(-1, -2)s the conv-window before the conv kernel (GDN's native layout is[.., dim, width]). The sliding-window conv-intermediate has a deduplicated layout — an overlappingas_stridedview that halves the footprint by aliasing physical columns across consecutive draft steps. That overlap is only idempotent when the window is written raw (as GDN does); it does not survive KDA's transpose (the per-draft-token windows land in the wrong physical columns → corrupt committed conv state → coherent first token then degenerate output). Fix:conv_window_dedup_enabled(..., is_kda)keeps KDA on the dense conv-window layout. Confirmed on Kimi-Linear MTP: dedup conv → garbage (gsm8k 0.03); dense conv + FlashInfer verify → gsm8k 0.895, matching the 0.90 non-spec reference.Validation (B200, SM100, Kimi-Linear-48B-A3B-Instruct, TP2)
Unit (kernel-level).
test_kda_decode_flashinfer— FlashInferdecodeandtarget_verifymatch the Triton reference per-token across batch sizes and spec lengths, andtarget_verify's per-step checkpoint states (what the rollback commits on accept) match a sequential-decode reference (11/11 pass on B200; output tol ~5e-2, state[V,K]layout confirmed).End-to-end (gsm8k, 200 questions, 5-shot, n-gram speculative decode). n-gram is used because Kimi-Linear has no MTP head (
num_nextn_predict_layers=0), so it exercisestarget_verifywithout a draft model. Same model / questions / dense conv for all rows:Performance
recurrent_kdain-kernelcu_seqlenspath; CUDA-graph, pure GPU): FlashInfer wins at large batch and is at parity/slower at small batch — B=1 0.67x, B=64 0.93x, B=128 ~1.0x (parity), B=256 1.35x (FlashInfer faster). ncu (B=64) puts therecurrent_kdadecode kernel at 29.6 us vs Tritonfused_sigmoid_gating_delta_rule_update36.8 us.Microbenchmark (
bench_kda_flashinfer_mtp.py, B200, bf16, K=V=128, H=HV=16)Full output of the eager per-call microbench (CUDA-event wall time, warmup 20 / iters 100):
How to enable
python3 -m sglang.launch_server \ --model-path <kimi_linear-or-other-KDA-model> \ --tp 2 --trust-remote-code \ --mamba-ssm-dtype bfloat16 \ --linear-attn-decode-backend flashinfer \ --speculative-algorithm NGRAM \ --speculative-num-draft-tokens 8 \ --speculative-ngram-min-bfs-breadth 1 --speculative-ngram-max-bfs-breadth 1Prefill stays on Triton. KDA MTP requires the FlashInfer decode backend (SM100); other decode backends raise a clear error if speculative decode is enabled.
Testing
python -m pytest test/registered/attention/test_kda_decode_flashinfer.py(SM100 +recurrent_kda-capable FlashInfer required; skipped otherwise).python benchmark/bench_linear_attention/bench_kda_flashinfer_mtp.py— FlashInfer-vs-Triton decode + verify correctness and latency (use CUDA-graph / ncu, not eager wall-clock which is CPU-dispatch-bound).CI States
Latest PR Test (Base): 🚫 Run #29301333959
Latest PR Test (Extra): ✅ Run #29847149276