Skip to content

[Perf] dsa: Add an opt-in FlashInfer Prims-TS sparse MLA backend - #48602

Merged
Fridge003 merged 14 commits into
sgl-project:mainfrom
nvpohanh:pohanh/k31-port-prims-ts
Nov 12, 2026
Merged

Fridge003 merged 14 commits into
sgl-project:mainfrom
nvpohanh:pohanh/k31-port-prims-ts

Conversation

@nvpohanh

@nvpohanh nvpohanh commented Nov 5, 2026 •

Copy link
Copy Markdown
Collaborator

[by Claude Code]

Original authors: @nvpohanh

Port of #48414

This port takes the Kimi-K3.1 branch's opt-in DSA backend --dsa-prefill-backend prims_ts / --dsa-decode-backend prims_ts. It runs FlashInfer's Prims-TS sparse MLA (BatchSparseMLADecodePagedTSWrapper: D576, native E4M3 KV, E4M3 query, FP8 MMA, natural-log LSE) instead of trtllm-gen, on the existing trtllm DSA route. The route stays the same end to end (raw FP8 MLA cache, q quantize/concat, KV store, top-k transforms, row plan, DCP page-table localization); only the attention kernel call changes. It is faster than trtllm-gen and FlashMLA at decode, and its cache needs fewer bytes per token than FlashMLA's (see Speed). The defaults do not change.

It needs FlashInfer 0.7.4 (#49771), which ships Prims-TS D576 native-FP8 sparse MLA: flashinfer-ai/flashinfer#7410 and flashinfer-ai/flashinfer#7984, plus flashinfer-ai/flashinfer#8186 for SM107.

It takes all of the branch's prims_ts code that main now has a base for. That includes Kimi-K3.1, under its sharded index-K DCP, now that main has that DCP and Kimi-K3.1's opt-in trtllm DSA backend. It also includes SM107 (Rubin) support.

What changed against the raw port:

  • Main's row plan. _forward_prims_ts restores rows with _restore_live_rows(row_plan), as main's _forward_trtllm does, as the branch now does too.

  • Tests. The branch's prims_ts tests lived in its sharded-DCP test file, which main does not have. Here they are a new file, test_dsa_prims_ts.py, with the same cases:

    • the DCP8 partial merge at 24 rows (exact plan) and 1025 rows (packed plan);
    • the combine's LSE base per DCP mode, patched at layers/dcp/layout.py, where main keeps is_mla_dcp_lse_base_on_e.

    The file is registered on B200 rather than 1-gpu-large (H100), since the kernel needs SM100/SM103/SM107. With FlashInfer 0.7.4 pinned, a planning failure on those GPUs now fails the test instead of skipping it.

  • Docs. The two DSA backend tables list prims_ts.

  • KV scale. _forward_prims_ts rejects a checkpoint KV scale (k_scale != 1). The raw FP8 store writes K/V unscaled, and trtllm applies k_scale to the logits only, so the branch's output scaling by k_scale would make prims_ts diverge from trtllm. Kimi-K3.1 has no KV scale.

  • Overlap check. DSAInterleaveCPIndexerOverlap._can_overlap unwraps TboAttnBackend and narrows the backend with isinstance(DeepseekSparseAttnBackend) instead of a getattr of dsa_prefill_impl.

  • The SM107 change. Its FlashInfer overlay in the branch's container image is not taken: main installs FlashInfer 0.7.4 as a package.

Left for the port of the branch's fused FP8 q builder (_trtllm_q_fp8): its no-head-padding mode for prims_ts (pad_heads=not use_prims_ts). Without the builder, prims_ts reads q from main's FP8 quantize path, which already keeps the layer's head count; main pads heads only right before trtllm-gen.

Left for the port of the branch's alt-stream decode absorb: its raw-FP8 branch in forward_mla.py, which skips the adjacent bf16 q buffer.

Modifications

  • layers/attention/dsa/prims_ts.py (new):
    • PrimsTSSparseMLA holds the planned launches. Plans are exact per row count up to 1024 rows and use power-of-two packed capacities above that.
    • Plans are made on eager calls; the CUDA-graph warmups plan every captured row count, and replays call run(validate=False).
    • check_prims_ts_sparse_mla_support is the startup check (D576 MLA, SM100/SM103/SM107, and an installed FlashInfer that can plan the kernel). If FlashInfer refuses, its reason is part of the error.
  • dsa_backend.py:
    • prims_ts joins _DSA_IMPL_T.
    • uses_raw_fp8_dsa_kv_layout(backend) (trtllm or prims_ts) replaces the == "trtllm" layout checks.
    • Backend init rejects a non-fp8_e4m3 KV cache, a GPU or FlashInfer that cannot run the kernel, and replicated index-K DCP (_validate_prims_ts_dcp). That DCP combine merges base-2 LSE partials, while Prims-TS returns a natural-log LSE. Under Kimi-K3.1's sharded index-K the combine merges non-trtllm partials base e, so prims_ts is accepted there.
    • _forward_trtllm(use_prims_ts=...) hands off to _forward_prims_ts once the q, KV store, row plan and page table are ready. Prims-TS runs any head count, so q is not padded.
    • Under DCP, _forward_prims_ts returns the partial and its LSE for the merge. A sharded-DCP decode partial keeps the owned-row lengths from the localized page table.
    • _forward_prims_ts rejects k_scale != 1 (see above).
  • arg_groups/fields/exec_.py: adds prims_ts as a choice for both DSA backend flags.
  • arg_groups/overrides.py:
    • prims_ts needs CUDA and --kv-cache-dtype fp8_e4m3.
    • Kimi-K3.1 admits prims_ts next to flashmla_kv and trtllm. It warns that the numerics differ from the reference fp8_ds_mla, and that PD peers must both use a raw-FP8-KV backend.
  • mem_cache/kv_cache_configurator.py, forward_mha.py, forward_mla.py (_fuse_rope_for_trtllm_mla), layers/cp/interleave.py: treat prims_ts like trtllm through uses_raw_fp8_dsa_kv_layout. The interleave overlap check narrows the backend by type.

An unset phase gets a layout-compatible backend:

  • For Kimi-K3.1, it follows the set phase.
  • On other Blackwell FP8 models, it defaults to trtllm, which uses the same 576 B/token layout.

In PD disaggregation, both servers need a raw-FP8-KV backend (trtllm or prims_ts).

Tests

At this head, on CPU only (no SM100 GPU in this environment):

  • test_dsa_prims_ts.py: 2 passed (the LSE base under sharded and replicated index-K), 2 skipped (GPU, "needs SM100/SM103/SM107").
  • Related unit tests: 248 passed.
    • test_dsa_tilelang_fp8_validation.py, test_dsa_dcp_backend_defaults.py, test_pool_configurator.py, test_dsa_backend_dp_padding.py, test_model_overrides.py, test_rocm_mla_absorb_fusion_gate.py.
    • test_page_interleave_shard.py also passes, apart from its Rust-core variants, which need a Cargo build this environment lacks.
  • Each touched module imports cleanly on its own, and pre-commit passes.
  • FlashInfer 0.7.4's BatchSparseMLADecodePagedTSWrapper.plan / run and get_prims_ts_sparse_mla_decode_workspace_size take the arguments prims_ts.py passes (checked against the v0.7.4 tag).

On the Kimi-K3.1 branch (#48414), on GB300, with Prims-TS from FlashInfer main copied onto 0.7.2:

This port has not been run on a GPU on main, and nothing has run on SM107 hardware: Rubin support goes only as far as flashinfer-ai/flashinfer#8186 and its tests. No model other than Kimi-K3.1 has been served with prims_ts. That includes DeepSeek-V3.2 and GLM-5, which this port admits without DCP. The GPU cases of test_dsa_prims_ts.py run in this PR's B200 CI.

Accuracy

All measured on the Kimi-K3.1 branch (#48414):

  • Kernel against an FP32 reference on its own inputs: 1.1-1.6% relative L2 (FlashMLA: 0.2%). The error comes from rounding the softmax probabilities to E4M3. The LSE matches to 2e-6.
  • Prims-TS against FlashMLA: 4.1-4.5% output error. There were no NaN/Inf mismatches. A row with no keys gives zero output and a -inf LSE.
  • GSM8K (all 1319 questions; only the backend flag changed): 0.9704 with Prims-TS vs 0.9697 with FlashMLA.

Speed

Kernel time per DSA layer (us), measured on the Kimi-K3.1 branch: GB300, 96 heads, about 256 keys per row (one DCP8 rank's share of 2048 top-k), 6 query rows per request, cold L2, CUDA graph.

Requests FlashMLA (flashmla_kv) Prims-TS (prims_ts) Speedup
1 16.0 11.7 1.37x
4 21.2 9.9 2.14x
16 35.2 14.5 2.43x
32 62.6 18.7 3.35x
64 97.8 29.5 3.32x
  • trtllm-gen takes 13-38 us over this range, so Prims-TS is 1.15-1.8x faster than it.
  • Compared with FlashMLA, the kernel reads the FP8 cache without dequantizing it, makes one pass for up to 128 heads, and is a single kernel from 24 rows up.
  • The raw cache takes 576 B per token instead of fp8_ds_mla's 656 B. On Kimi-K3.1 that gave about 9% more KV tokens.
  • End to end on Kimi-K3.1 (agg TP8/DCP8): sparse-MLA time per decode step fell from 891 us to 332 us, about 1.7% of a ~32 ms step.

Not yet covered:

  • An eager batch with an unseen row count (up to 1024 rows) plans and keeps one more plan. Its workspace is allocated after --mem-fraction-static has sized the KV pool.
  • The first use compiles the kernels (about 100 s extra in CUDA-graph capture). Point FLASHINFER_WORKSPACE_BASE at a persistent path to keep the cache.
  • Prefill speed against the other prefill backends has not been measured.

🤖 Generated with Claude Code


CI States

Latest PR Test (Base): ⏳ Run #43157175119
Latest PR Test (Extra): ❌ Run #43157174952
Latest PR Test (AMD ROCm 10): ⏳ Run #43157175002

Tip

Base CI only covers the core cases, and its workload may not exercise your change. Use /rerun-test to run the tests your change touches, or copy this prompt for an agent:

Find the registered tests this PR affects and run them with /rerun-test, following https://github.com/sgl-project/sglang/blob/main/.agents/skills/rerun-test/SKILL.md

nvpohanh and others added 4 commits November 5, 2026 00:16
… port)

Copy the backend-generic hunks of the FlashInfer Prims-TS sparse MLA DSA
backend from the Kimi-K3.1 branch (sgl-project#48414) byte for byte. The Kimi-K3.1-only
and sharded-DCP hunks are not taken. This commit does not build against main
yet; the next commits adapt it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…eturn

Main has no sharded index-K DCP, so its DSA DCP combine always merges base-2
LSE partials, while Prims-TS returns a natural-log LSE. _validate_prims_ts_dcp
drops shards_index_k and rejects any --dcp-size > 1, and _forward_prims_ts
drops partial / clamp_lengths: it always clamps the lengths to the top-k
width and returns the output alone.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…P rejection

A single-rank check of the exact (24 rows) and packed (1025 rows) plans
against an FP32 reference, and a CPU check that the DSA DCP combine merges
base 2, so prims_ts is rejected under DCP. Registered on B200, since the
kernel needs SM100/SM103; the GPU cases skip until FlashInfer ships Prims-TS
D576 native-FP8 sparse MLA.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@mintlify

mintlify Bot commented Nov 5, 2026 •

Copy link
Copy Markdown
Contributor

Preview approval required

This pull request comes from a fork, so Mintlify won't build a preview until someone with write access approves commit 753d3be.

Approve preview

@github-actions github-actions Bot added the documentation Improvements or additions to documentation label Nov 5, 2026
nvpohanh and others added 2 commits November 5, 2026 00:49
Cherry-pick the SGLang part of the Kimi-K3.1 branch's SM107 change:

- prims_ts.py: admit compute capability (10, 7) next to (10, 0) and (10, 3);
  SM107 needs flashinfer-ai/flashinfer#8186. When FlashInfer's probe refuses
  the device, its reason is now part of the startup error (on SM107 with a
  CuTe DSL older than 4.8 it names the CUTE_DSL_ARCH=sm_100f fallback).
- Update the --dsa-*-backend help text, the comment that points at the check,
  and the test's skip message.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@kpham-sgl

kpham-sgl commented Nov 12, 2026 •

Copy link
Copy Markdown
Collaborator

@nvpohanh i think this can be reviewed now

nvpohanh and others added 4 commits November 11, 2026 19:46
Main's _forward_trtllm now plans rows with _RowPlan; _forward_prims_ts takes row_plan and restores the output with _restore_live_rows in place of the removed DP-padding helpers.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…imi-K3.1

Main now has Kimi-K3.1's sharded index-K DCP (whose combine merges non-trtllm
DSA partials base e) and its opt-in trtllm DSA backend, so take the sgl-project#48414
hunks this port had left for them, copied from the branch:

- _validate_prims_ts_dcp takes shards_index_k again and rejects prims_ts
  only under replicated index-K DCP (base-2 combine).
- _forward_prims_ts takes partial / clamp_lengths again: under DCP it returns
  the natural-log LSE with the output, and a sharded-DCP decode partial keeps
  the owned-row lengths.
- Kimi-K3.1 admits prims_ts next to flashmla_kv and trtllm, with its layout
  error and PD warning.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…r DCP mode

Take the branch's tests now that main has sharded index-K DCP: per-rank
Prims-TS partials over the owned top-k rows merge to the single-rank result
(exact and packed plans, a rank owning none of a row's keys gives zero output
and -inf LSE), and the combine merges prims_ts base e under sharded index-K
while replicated index-K rejects it. FlashInfer 0.7.4 ships the kernel, so a
planning failure on SM100/SM103/SM107 now fails instead of skipping.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

@nvpohanh nvpohanh left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

[by Claude Code] This review is done by agents. Please feel free to disagree if they do not make sense.

nvpohanh and others added 4 commits November 11, 2026 20:43
The raw FP8 MLA store casts K/V unscaled, and the trtllm route applies k_scale to the logits only, while Prims-TS would also scale the output by it. Fail loudly on k_scale != 1 instead of diverging from trtllm.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…overlap check

Unwrap TboAttnBackend and check isinstance(DeepseekSparseAttnBackend) instead of a defensive getattr of dsa_prefill_impl.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@nvpohanh

Copy link
Copy Markdown
Collaborator Author

/tag-and-rerun-ci

@nvpohanh
nvpohanh marked this pull request as ready for review November 12, 2026 04:49

@claude claude Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Claude Code Review

This pull request is from a fork — automated review is disabled. A repository maintainer can comment @claude review to run a one-time review.

@nvpohanh

Copy link
Copy Markdown
Collaborator Author

[by Claude Code] I've started babysitting the NVIDIA CI of this PR. I'll check it every 30 minutes until all NV pipelines pass. If a relevant job fails, I may rerun it, merge the latest main into this branch, push a small test-only fix, fix the PR title if the title check fails, or post a note here.

Anyone can stop me at any time: just post a comment asking me to stop (for example, stop babysitting). I'll stop at my next check, within 30 minutes, and take no further action on this PR.

@nvpohanh

Copy link
Copy Markdown
Collaborator Author

/rerun-failed-ci

@Fridge003 Fridge003 added highest-priority CI: all three control labels, plus never batch-cancelled or stale-closed release-highlight Candidate PR for release note highlight labels Nov 12, 2026
@nvpohanh

Copy link
Copy Markdown
Collaborator Author

/rerun-failed-ci

@Fridge003
Fridge003 merged commit c7f3e2b into sgl-project:main Nov 12, 2026
393 of 462 checks passed
@nvpohanh nvpohanh mentioned this pull request Nov 12, 2026
5 tasks done
hnyls2002 added a commit that referenced this pull request Nov 12, 2026
# Conflicts:
#	python/sglang/srt/arg_groups/overrides.py
#	python/sglang/srt/layers/attention/dsa/prims_ts.py
#	python/sglang/srt/layers/attention/dsa_backend.py
#	python/sglang/srt/layers/cp/interleave.py
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

documentation Improvements or additions to documentation highest-priority CI: all three control labels, plus never batch-cancelled or stale-closed release-highlight Candidate PR for release note highlight run-ci CI: run the baseline test suite on this PR

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants