Skip to content

[KDA] Add FlashKDA prefill backend for safe-gate KDA linear attention - #29472

Merged
BBuf merged 2 commits into
sgl-project:mainfrom
yuan-luo:flashkda-prefill-backend
Jul 2, 2026
Merged

BBuf merged 2 commits into
sgl-project:mainfrom
yuan-luo:flashkda-prefill-backend

Conversation

@yuan-luo

@yuan-luo yuan-luo commented Jun 27, 2026 •

Copy link
Copy Markdown
Collaborator

[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 Triton chunk_kda prefill 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 = 64 with 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-2 exp, 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's flashkda backend, auto-dispatched from chunk_kda when its preconditions hold.

Why the safe gate (the hard precondition)

image

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:

  • Unbounded (standard): a = -exp(A_log)·softplus(g + bias), a ∈ (-∞, 0]. The cumulative chunk decay exp(cumsum(a)) can span a huge dynamic range, so the kernel needs larger chunks + careful rescaling — i.e. the Triton path.
  • Safe / bounded: a = lower_bound·sigmoid(exp(A_log)·(g + bias)), a ∈ (lower_bound, 0). With lower_bound = -5 and chunk = 16, cumsum ∈ [-80, 0], so exp(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.
                  UNBOUNDED (standard)            SAFE / BOUNDED (FlashKDA)
  gate  a   =  −exp(A_log)·softplus(x)        lb·sigmoid(exp(A_log)·x),  lb=−5
  range of a    (−∞ , 0]   no floor               (−5 , 0]   floored
  exp(cumsum)  0 ◄────────► 1  (unbounded)     6.6e−3 ◄─► 1  (≤2 orders, chunk=16)
  bf16 ?        ✗ needs fp32 + rescale            ✓ fits, no rescale
  inverse       ill-conditioned                   |entries|≤1 → fp16 16×16 (Neumann)
  kernel        multi-kernel Triton chunk_kda     ONE fused CUTLASS  →  1.3–4.6×
  memory        can fully forget (0)              retains ≥ e^−5 ≈ 0.67%  (the price)

  why bound ⇒ fast:
      bound a ≥ −5
          ├─► cumsum bounded ─► exp(cumsum) fits bf16 ─► no rescale, bf16 state, chunk=16
          └─► (I+A) well-conditioned (|inv|≤1) ─► fp16 16×16 inverse
                                  │
                                  ▼
                   ONE fused CUTLASS kernel  →  1.3–4.6× vs Triton

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 init A_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:

  • The fast path is reviewed and benchmarked on its own (this PR), keeping the later model PR small.
  • Once a safe-gate KDA model threads its bound to layer.lower_bound (kda_safe_gate=true, kda_lower_bound=-5, checkpoint A_log ≈ 0) — selecting --linear-attn-prefill-backend flashkda turns on the 1.3–4.6× path with no further kernel work.
  • Until then it is inert (falls back to Triton), so there is no risk to current models.
model gate A_log (checkpoint) FlashKDA
FlashKDA target model safe (kda_safe_gate=true, lower_bound=-5) mean ≈ 0.1, exp(A_log)∈[0.85,1.47] target — applies once wired
Kimi-Linear-48B-A3B unbounded mean ≈ 2.28, exp(A_log) up to 201 falls back to Triton

Modifications

  • layers/attention/linear/utils.py — LinearAttnKernelBackend.FLASHKDA + is_flashkda()
  • server_args.py — flashkda added to LINEAR_ATTN_KERNEL_BACKEND_CHOICES
  • layers/attention/linear/kda_backend.py — prefill dispatch branch → FlashKDAKernel
  • layers/attention/linear/kernels/kda_flashkda.py — new FlashKDAKernel (prefill/extend-only) wrapping flash_kda.fwd

Mechanism

FlashKDAKernel.extend passes raw tensors plus A_log/dt_bias/lower_bound to flash_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 via ssm_states[cache_indices].

It falls back to Triton chunk_kda when:

  • lower_bound is None (unbounded-gate model), or
  • the shortest sequence < 64 (chunk size), or
  • the longest sequence > 2048 (past the crossover where Triton wins).

flash_kda is lazily imported, so the dependency is only needed when the backend is actually selected.

Correctness

Validated against the production Triton chunk_kda on the safe-gate path (bf16, H=32, K=V=128, varlen), inputs cloned per path (chunk_kda mutates g/v in place):

check result
single-token (hand-verifiable) bit-close, cos 1.0000, max|diff| 3e-4
full-sequence output cos 0.985
final recurrent state cos 0.9999 (confirms [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):

B T speedup
1 128 5.2×
1 512 2.2×
1 2048 1.24×
8 512 2.0×
16 512 2.1×
32 512 2.05×

B200 (sm100):

B T H speedup
1 128 32 4.61×
1 512 32 2.60×
1 2048 32 1.27×
16 512 32 2.69×
32 512 32 2.65×
1 8192 64 1.73×
1 8192 96 2.23×

The B200 T=8192 results (1.73× / 2.23× at H=64 / 96) match MoonshotAI's published BENCHMARK_GB200.md (1.70× / 2.31×), cross-validating the measurement.

Requirements

  • SM90+ GPU and the optional flash_kda module installed: pip install sglang[flashkda] (or pip install git+https://github.com/MoonshotAI/FlashKDA.git).
  • bf16, K == V == 128, HV == H (no GVA), safe gate (lower_bound set).
  • Prefill/extend only (decode / target-verify fall back).

Usage

--linear-attn-prefill-backend flashkda

Testing

  • Kernel correctness vs Triton chunk_kda (single-token, full-sequence, final state) on H20-3e and B200.
  • Perf benchmarks on H20-3e (sm90) and B200 (sm100), cross-validated against the upstream FlashKDA GB200 benchmark.

CI States

Latest PR Test (Base): ✅ Run #28530376386
Latest PR Test (Extra): ✅ Run #28858938282

@gemini-code-assist

Copy link
Copy Markdown
Contributor

Warning

You have reached your daily quota limit. Please wait up to 24 hours and I will start processing your requests again!

@github-actions github-actions Bot added the dependencies Pull requests that update a dependency file label Jun 27, 2026
@yuan-luo yuan-luo added run-ci CI: run the baseline test suite on this PR run-ci-extra CI: also run the extra suite (requires run-ci) linear-attention labels Jun 27, 2026
@yuan-luo
yuan-luo requested a review from yizhang2077 June 28, 2026 15:23
Comment thread python/pyproject.toml Resolved

@b8zhong b8zhong left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

When will it support decode?

@yuan-luo

Copy link
Copy Markdown
Collaborator Author

When will it support decode?

FlashKDA hasn't added support for decode/MTP yet. We'll keep you updated on any progress.

@yuan-luo
yuan-luo force-pushed the flashkda-prefill-backend branch from 2929581 to 8f63981 Compare June 29, 2026 15:20
Comment thread python/sglang/srt/server_args.py Resolved
@yuan-luo
yuan-luo force-pushed the flashkda-prefill-backend branch from 8f63981 to 8456b83 Compare June 30, 2026 16:58

@BBuf BBuf left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM

@yyq0210

yyq0210 commented Jul 1, 2026

Copy link
Copy Markdown
Contributor

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 Needed

FlashKDA's forward pass contains a serial state recurrence (S_t = A_t · S_{t-1} + b_t), which means the entire sequence must be processed chunk-by-chunk sequentially. This causes low GPU SM utilization for long sequences, especially at small batch sizes.

FlashKDA vs fla_chunk_kda (No CP, H20 GPU)

Batch SeqLen FlashKDA (ms) fla_chunk_kda (ms) vs fla
1 8K 1.235 0.907 0.73×
1 16K 2.429 1.710 0.70×
1 64K 9.509 6.626 0.70×
1 256K 37.860 26.484 0.70×
1 512K 75.675 52.968 0.70×
8 8K 2.871 6.380 2.22×
32 64K 21.161 51.703 2.44×

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)

SeqLen No CP With CP Speedup
4K 0.63ms 0.35ms 1.82x
8K 1.24ms 0.54ms 2.29x
16K 2.45ms 0.99ms 2.47x
32K 4.87ms 1.76ms 2.77x
64K 9.64ms 3.91ms 2.46x
  • Stable ~1.8x-2.8x speedup across all decay strengths (lb=-5.0 to -0.5)
  • Only ~5-10% overhead: warmup state_only + serial correction
  • Works for both fixed-length and variable-length sequences

How It Works

The approach exploits the linearity of state recurrence: S_final = mt · h0 + ht

  1. Warmup: Run only the last few chunks of each sub-segment to compute ht (data-driven terminal state)
  2. Correct: Chain-solve correct initial states: h0[i+1] = mt[i] · h0[i] + ht[i]
  3. Parallel Fwd: All sub-segments run full forward in parallel with corrected h0

For production decay settings (lb < -1.73), mt ≈ 0, so h0[i+1] ≈ ht[i] — just a slice assignment, no matrix multiply needed.

📖 Detailed math: DeltaNet 状态递推与 Context Parallelism

Full doc: cp_optimization.md on branch cp_optimization


❓ Question

Should this CP optimization be integrated into sglang's FlashKDA implementation?

It would be most beneficial for:

  • Long context inference (T ≥ 8K) at small batch sizes
  • Throughput-critical deployments where every ms matters
  • The overhead is minimal (~5-10%) and it's fully automatic (auto-detects when CP is beneficial)

Would love to hear your thoughts!

@yuan-luo

yuan-luo commented Jul 1, 2026

Copy link
Copy Markdown
Collaborator Author

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 Needed

FlashKDA's forward pass contains a serial state recurrence (S_t = A_t · S_{t-1} + b_t), which means the entire sequence must be processed chunk-by-chunk sequentially. This causes low GPU SM utilization for long sequences, especially at small batch sizes.

FlashKDA vs fla_chunk_kda (No CP, H20 GPU)

Batch SeqLen FlashKDA (ms) fla_chunk_kda (ms) vs fla
1 8K 1.235 0.907 0.73×
1 16K 2.429 1.710 0.70×
1 64K 9.509 6.626 0.70×
1 256K 37.860 26.484 0.70×
1 512K 75.675 52.968 0.70×
8 8K 2.871 6.380 2.22×
32 64K 21.161 51.703 2.44×
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)

SeqLen No CP With CP Speedup
4K 0.63ms 0.35ms 1.82x
8K 1.24ms 0.54ms 2.29x
16K 2.45ms 0.99ms 2.47x
32K 4.87ms 1.76ms 2.77x
64K 9.64ms 3.91ms 2.46x

  • Stable ~1.8x-2.8x speedup across all decay strengths (lb=-5.0 to -0.5)
  • Only ~5-10% overhead: warmup state_only + serial correction
  • Works for both fixed-length and variable-length sequences

How It Works

The approach exploits the linearity of state recurrence: S_final = mt · h0 + ht

  1. Warmup: Run only the last few chunks of each sub-segment to compute ht (data-driven terminal state)
  2. Correct: Chain-solve correct initial states: h0[i+1] = mt[i] · h0[i] + ht[i]
  3. Parallel Fwd: All sub-segments run full forward in parallel with corrected h0

For production decay settings (lb < -1.73), mt ≈ 0, so h0[i+1] ≈ ht[i] — just a slice assignment, no matrix multiply needed.

📖 Detailed math: DeltaNet 状态递推与 Context Parallelism

Full doc: cp_optimization.md on branch cp_optimization

❓ Question

Should this CP optimization be integrated into sglang's FlashKDA implementation?

It would be most beneficial for:

  • Long context inference (T ≥ 8K) at small batch sizes
  • Throughput-critical deployments where every ms matters
  • The overhead is minimal (~5-10%) and it's fully automatic (auto-detects when CP is beneficial)

Would love to hear your thoughts!

@yyq0210 Thanks for your progress. Let's put this enhancement in a separate PR.

luoyuan.luo added 2 commits July 1, 2026 23:53
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.
@yuan-luo
yuan-luo force-pushed the flashkda-prefill-backend branch from 95b31ee to 24dcc57 Compare July 1, 2026 15:53
@BBuf
BBuf merged commit eb23f9a into sgl-project:main Jul 2, 2026
248 of 295 checks passed
@yuan-luo
yuan-luo deleted the flashkda-prefill-backend branch July 2, 2026 03:40
@yuan-luo yuan-luo added the release-highlight Candidate PR for release note highlight label Jul 7, 2026
Chronostasys pushed a commit to MindLab-Research/sglang that referenced this pull request Aug 24, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

dependencies Pull requests that update a dependency file linear-attention release-highlight Candidate PR for release note highlight run-ci CI: run the baseline test suite on this PR run-ci-extra CI: also run the extra suite (requires run-ci)

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants