Repository navigation
[KDA] Add FlashKDA prefill backend for safe-gate KDA linear attention - #29472
Conversation
|
Warning You have reached your daily quota limit. Please wait up to 24 hours and I will start processing your requests again! |
b8zhong
left a comment
There was a problem hiding this comment.
When will it support decode?
FlashKDA hasn't added support for decode/MTP yet. We'll keep you updated on any progress. |
2929581 to
8f63981
Compare
8f63981 to
8456b83
Compare
|
Hi all, I'd like to share the Context Parallelism (CP) optimization we've implemented for FlashKDA, along with performance data and a question about integration. Background: Why CP is NeededFlashKDA's forward pass contains a serial state recurrence ( FlashKDA vs fla_chunk_kda (No CP, H20 GPU)
Key observation: At B=1, FlashKDA is 30-43% slower than fla_chunk_kda due to serial bottleneck. At B≥8 it's 2.2-2.4x faster. CP fixes the B=1 case by splitting long sequences into parallel sub-segments. CP Optimization Results (H20 GPU, B=1, H=16, D=128)
How It WorksThe approach exploits the linearity of state recurrence:
For production decay settings ( 📖 Detailed math: DeltaNet 状态递推与 Context Parallelism Full doc: cp_optimization.md on branch ❓ QuestionShould this CP optimization be integrated into sglang's FlashKDA implementation? It would be most beneficial for:
Would love to hear your thoughts! |
@yyq0210 Thanks for your progress. Let's put this enhancement in a separate PR. |
Add FlashKDA (MoonshotAI's fused CUTLASS Kimi Delta Attention kernel) as an opt-in KDA prefill/extend backend, selected via --linear-attn-prefill-backend flashkda. It wraps the external flash_kda package and replaces the multi-kernel Triton chunk_kda prefill with a single fused kernel (1.3-4.6x faster, cross-validated on H20-3e/sm90 and B200/sm100). FlashKDA implements only the safe/bounded KDA gate, so it activates only when layer.lower_bound is set; the unbounded-gate path, sequences <64 or >2048, and decode/target-verify all fall back to Triton chunk_kda. flash_kda is an optional, lazily-imported module with an actionable install error (not declared in pyproject), following sglang's optional-kernel pattern (lazy import + test skip, as with FA3 / deep_gemm). This lands the fast path as prerequisite infrastructure for safe-gate KDA models (kda_safe_gate=true) with zero risk to existing deployments.
95b31ee to
24dcc57
Compare
…sgl-project#29472) Co-authored-by: luoyuan.luo <[email protected]>
[KDA] Add FlashKDA prefill backend for safe-gate KDA linear attention
Summary
Adds FlashKDA (MoonshotAI's fused CUTLASS Kimi Delta Attention kernel) as an optional KDA prefill/extend backend, selectable via
--linear-attn-prefill-backend flashkda. It replaces the multi-kernel Tritonchunk_kdaprefill path with a single fused kernel that is 1.3–4.6× faster.This PR lands the kernel backend and its dispatch/fallback only — it is the prerequisite infrastructure for safe-gate KDA support. It is opt-in, off by default, depends on an optional package, and transparently falls back to Triton for anything it can't run, so it adds zero risk to existing deployments.
Background: FlashKDA
KDA (Kimi Delta Attention) is the per-channel-gated delta-rule linear attention used by recent KDA models (e.g. Kimi-Linear). The reference prefill (FLA's Triton
chunk_kda) runs the chunked delta rule as a sequence of kernels —chunk = 64with intra-chunk rescaling and high-precision accumulation — which is launch- and bandwidth-heavy.FlashKDA (MoonshotAI, open-sourced 2026-04) fuses the whole chunked delta rule into a CUTLASS kernel and trades the rescaling machinery for a numerically tighter design:
chunk = 16, recurrent state stored in bf16, the 16×16 intra-chunk inverse computed in fp16 via a Neumann series, base-2exp, and tensor-core tiles. The net result is a 1.3–4.6× speedup over the Triton path (cross-validated below on H20 and GB200). Upstream it is wired as FLA'sflashkdabackend, auto-dispatched fromchunk_kdawhen its preconditions hold.Why the safe gate (the hard precondition)
FlashKDA's speed comes from running the entire chunked recurrence in low precision (bf16 state, fp16 inverse) on small chunks without rescaling. That is only numerically valid if the gate's per-step log-decay is bounded below. KDA has two gate formulations, chosen at training time:
a = -exp(A_log)·softplus(g + bias),a ∈ (-∞, 0]. The cumulative chunk decayexp(cumsum(a))can span a huge dynamic range, so the kernel needs larger chunks + careful rescaling — i.e. the Triton path.a = lower_bound·sigmoid(exp(A_log)·(g + bias)),a ∈ (lower_bound, 0). Withlower_bound = -5andchunk = 16,cumsum ∈ [-80, 0], soexp(cumsum)stays inside bf16's representable range (no rescaling), the 16×16 inverse stays well-conditioned (entries in[-1,1], fp16-safe), and the tensor-core fast path is valid.In short: bounding the gate trades a sliver of expressiveness (memory can't fully zero out) for the numerical headroom that makes the fused low-precision kernel correct. It is baked into the checkpoint (safe-gate models init
A_log ≈ 0; unbounded initA_log = log(uniform(1,16))), so it cannot be toggled at inference — a model is one or the other.Foundation for safe-gate KDA support (why land it now)
FlashKDA only implements the safe gate, so it activates only when a model sets
layer.lower_bound. Landing the backend first, ahead of and independently of the model-side wiring, means:layer.lower_bound(kda_safe_gate=true,kda_lower_bound=-5, checkpointA_log ≈ 0) — selecting--linear-attn-prefill-backend flashkdaturns on the 1.3–4.6× path with no further kernel work.kda_safe_gate=true,lower_bound=-5)exp(A_log)∈[0.85,1.47]exp(A_log)up to 201Modifications
layers/attention/linear/utils.py—LinearAttnKernelBackend.FLASHKDA+is_flashkda()server_args.py—flashkdaadded toLINEAR_ATTN_KERNEL_BACKEND_CHOICESlayers/attention/linear/kda_backend.py— prefill dispatch branch →FlashKDAKernellayers/attention/linear/kernels/kda_flashkda.py— newFlashKDAKernel(prefill/extend-only) wrappingflash_kda.fwdMechanism
FlashKDAKernel.extendpasses raw tensors plusA_log/dt_bias/lower_boundtoflash_kda.fwd(the kernel fuses L2-norm / beta-sigmoid / gate internally; beta is inverted to logits since the model already applied sigmoid). The recurrent state layout[N, H, V, K]matches the existing KDA pool, so no transpose is needed; the final state is written back in place viassm_states[cache_indices].It falls back to Triton
chunk_kdawhen:lower_bound is None(unbounded-gate model), or< 64(chunk size), or> 2048(past the crossover where Triton wins).flash_kdais lazily imported, so the dependency is only needed when the backend is actually selected.Correctness
Validated against the production Triton
chunk_kdaon the safe-gate path (bf16, H=32, K=V=128, varlen), inputs cloned per path (chunk_kdamutatesg/vin place):[N,H,V,K]layout)Residual is bf16 cross-implementation accumulation (FlashKDA is a different CUTLASS kernel, not bit-exact with Triton — same as FLA's treatment of it).
Performance (FlashKDA vs Triton
chunk_kda, raw kernels, fresh clones)H20-3e (sm90):
B200 (sm100):
The B200
T=8192results (1.73× / 2.23× at H=64 / 96) match MoonshotAI's publishedBENCHMARK_GB200.md(1.70× / 2.31×), cross-validating the measurement.Requirements
flash_kdamodule installed:pip install sglang[flashkda](orpip install git+https://github.com/MoonshotAI/FlashKDA.git).K == V == 128,HV == H(no GVA), safe gate (lower_boundset).Usage
Testing
chunk_kda(single-token, full-sequence, final state) on H20-3e and B200.CI States
Latest PR Test (Base): ✅ Run #28530376386
Latest PR Test (Extra): ✅ Run #28858938282