Skip to content

[Feat] [NVIDIA] dsa: Enable sparse MLA decode+prefill on SM120/SM121 via flashinfer's packed sparse backend - #31481

Open
vroomfondel wants to merge 1 commit into
sgl-project:mainfrom
vroomfondel:dsa-sm12x-native-sparse-mla
Open

vroomfondel wants to merge 1 commit into
sgl-project:mainfrom
vroomfondel:dsa-sm12x-native-sparse-mla

Conversation

@vroomfondel

@vroomfondel vroomfondel commented Jul 16, 2026 •

Copy link
Copy Markdown
Contributor

Problem

attention_backend=dsa with dsa_decode_backend/dsa_prefill_backend=trtllm crashes on SM120/SM121 (DGX Spark GB10, RTX PRO Blackwell) with TllmGenFmhaRunner ... Unsupported architecture: _forward_trtllm hardcodes backend="trtllm-gen", which only exists for datacenter Blackwell (SM100/103).

flashinfer (>= 0.6.x) already ships a native SM120/121 sparse-MLA implementation (flashinfer/mla/_sparse_mla_sm120.py, @supported_compute_capability([120, 121]), DSv3.2/GLM model types, warp-spec decode kernels for num_tokens <= 64 plus a prefill orchestrator above), and its dispatcher trtllm_batch_decode_with_kv_cache_mla routes cc == 12 && sparse_mla_top_k > 0 to it automatically — but only with backend="auto". Three small changes make the whole DSA path (decode AND prefill) work on consumer Blackwell.

Scope after #26928 (updated 2026-11-30): for GlmMoeDsaForCausalLM on SM12x with fp8 KV, main now auto-selects flashinfer_sparse_mla and its validator rejects trtllm there, so GLM no longer reaches _forward_trtllm and does not need this PR. What this PR still fixes is dsa_decode_backend/dsa_prefill_backend=trtllm with fp8 KV on SM12x for non-GLM DSA architectures (DeepSeek-V3.2 family), which #26928's default and validator do not cover and which still hit trtllm-gen. The rebased code has not been run on SM12x hardware with a non-GLM DSA model.

Changes

All SM12x gating uses get_platform().is_sm120 (covers SM120 and SM121); SM100/SM103 behaviour is byte-identical (every conditional keeps the upstream value on the non-SM12x side).

  1. mem_cache/kv_cache_configurator.py::calculate_mla_kv_cache_dim — do not early-return the plain kv_lora_rank + qk_rope_head_dim layout for trtllm backends on SM12x. The SM120 sparse kernel consumes the 656-byte packed inline-scale layout (512 fp8 nope + 4× fp32 tile scales + 64 bf16 rope) that quantize_k_cache already writes; dsa_kv_cache_store_fp8 then derives True automatically. The opt-in Prims-TS backend ([Perf] dsa: Add an opt-in FlashInfer Prims-TS sparse MLA backend #48602) keeps its plain 576-byte layout on SM12x.
  2. dsa_backend.py::_forward_trtllm — on SM12x with the packed pool: backend="auto" (flashinfer picks the sparse backend), pass the KV cache as a uint8 view (required by the sm120 checker), kv_scale_format="arbitrary_fp32" (sglang's quantize_k_cache writes amax/448 arbitrary fp32 tile scales, not pow2/ue8m0 — the default "auto" would misread them as DSv3.2 pow2 scales), skip_softmax_threshold_scale_factor=None and multi_ctas_kv_counter_buffer=None (both trtllm-gen-only; the sparse backend raises on non-None values), and skip the fused rope+fp8-query-quantize branch — the sparse kernel requires a BF16 query and dequants KV itself via the inline scales. DSA prefill context-parallelism raises an explicit NotImplementedError on this path instead of silently mis-routing (its rope rebuild and KV all-gather live inside the skipped fp8 branch), and so do the DCP paths added on main since (dcp_partial, replicated_dcp). The sparse path is not taken when Prims-TS is selected, and the fused fp8-query prebuild (q_prebuilt) is skipped on it.
  3. deepseek_common/attention_forward_methods/forward_mla.py::_fuse_rope_for_trtllm_mla — return False for the dsa branch on SM12x when the backend stores the packed fp8 layout (dsa_kv_cache_store_fp8; raw layouts such as Prims-TS stay fused) so rope stays in forward_absorb_prepare and the query reaches _forward_trtllm in bf16.

Evidence

Historical, measured before #26928 with the GLM configuration that main now routes elsewhere (see Scope above); the kernel, layout and kwargs are the same ones this PR uses for non-GLM models. Live on a 4× DGX Spark (GB10, SM121) cluster serving GlmMoeDsaForCausalLM (504B REAP cut, NVFP4, TP4, fp8 KV): boot clean, decode graph capture 18 s, decode 8.4 tok/s single-stream with cuda-graph, prefill 873 tok/s input on a 7-seq/2240-token batch, GSM8K 2-shot n=20 conc 8 = 85% with 0 errors/restarts; MTP/NEXTN target-verify runs through the same kernel (accept length ~2.1). Kernel-level (real quantize_k_cache pool vs a torch dequant+softmax reference): decode bs=4 topk=2048 max|diff| 0.008 @ 0.072 ms/call; prefill 2400 extend tokens max|diff| 0.016; seq_lens > topk clamps safely; -1 padding skipped natively; cuda-graph capture+replay works directly.

Tests

  • test/registered/unit/mem_cache/test_dsa_kv_cache_dim_sm12x.py — layout matrix (sm12x+fp8+trtllm → 656 packed; sm12x+bf16 → 576; sm100+trtllm → 576; non-trtllm unaffected). Mocked arch — runs anywhere.
  • test/registered/unit/layers/attention/test_dsa_backend_trtllm_sm12x_kwargs.py — monkeypatches flashinfer.decode and calls the real _forward_trtllm, asserting kwarg selection on the SM12x path, unchanged upstream kwargs on the non-SM12x path, and the CP guard. Runs anywhere.
  • test/registered/unit/models/test_deepseek_mla_fuse_rope_trtllm_sm12x.py — isolated regression test for the "expects BF16 query, got float8_e4m3fn" crash. Runs anywhere.
  • test/registered/kernels/test_dsa_sparse_mla_sm12x.py — SM120/121-gated (skips elsewhere): builds a real packed pool via quantize_k_cache and compares flashinfer's sparse kernel vs a torch masked-softmax reference (decode small/overshoot/variable, prefill > 64 tokens, cuda-graph capture+replay).

11/11 CI-safe unit tests pass anywhere; 5/5 kernel tests pass on GB10 (SM121).

Re-validated after rebasing onto current main (flashinfer pin 0.6.15.post1, multi_ctas_kv_counter_buffer kwarg, config-namespace accessors): 11/11 unit tests, and 5/5 kernel tests on GB10 against flashinfer 0.6.16 — the sparse dispatch semantics are identical across 0.6.15.post1/0.6.16.

After the rebase onto current main (2026-11-30, conflicts with #48602, #51473 and the attention_kwargs refactor): the three CPU unit files pass (13 cases, including new ones for Prims-TS keeping the 576 layout and staying fused); the 5 SM12x-gated kernel tests were adapted to the renamed helpers (dequantize_k_cache_paged_dsa, dsa_quant_k_cache.quantize_k_cache) but not re-run on SM12x hardware.

Notes


CI States

Latest PR Test (Base): ⊘ Skipped -- a maintainer comments /tag-and-rerun-ci to run CI tests.
Latest PR Test (Extra): ⊘ Skipped -- a maintainer comments /tag-and-rerun-ci to run CI tests.
Latest PR Test (AMD ROCm 10): ⚠️ Run #46455849262

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

@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!

@vroomfondel

Copy link
Copy Markdown
Contributor Author

Rebased onto current main and re-validated: 11/11 CI-safe unit tests, 5/5 SM121 kernel tests on GB10 (kwarg semantics checked against the pinned flashinfer 0.6.15.post1 sources, live-tested on 0.6.16).
Could a maintainer add the run-ci label so the suites actually run? Review welcome.
Companion PR: #31480.

padthaitofuhot pushed a commit to littlecedar/sparkrun-recipe-registry that referenced this pull request Nov 10, 2026
Both lanes recorded SM121 sparse decode as blocked on a kernel that does not
exist. Desk audit 2026-11-10 against the pinned images and the upstream trees
says the kernel does exist, in FlashInfer, and that what blocks each arm is
engine wiring.

ERNIE: the pin is not the arg resolver and not a flag — `--dsa-*` is resolved
first and `Ernie5_5MlaAttnBackend.__init__` assigns over it after
`super().__init__()` (`ernie55_backend.py:83-85`), so `flashinfer_sparse_mla`
is refused by the parent GLM whitelist and every other value is discarded.
FlashMLA is SM100/103-only twice over (HEAD `setup.py:29`; `is_sm100f(){return
major == 10;}`, raise at `csrc_legacy/api/sparse_decode.cpp:386`) and patching
that gate would still hit the 227 KB `SharedMemoryPlan` assert against GB10
`smem_optin = 101376 B`, measured on `.30`. FlashInfer 0.7.3 in the same image
ships `mla/_sparse_mla_sm120` at `[120, 121]` with an `attn_sink` contract and
the DSv3.2 envelope ERNIE lands in exactly (576/512/656, 16 heads at TP4,
topk 2048), so the unlock is a five-site impl switch
(`sgl-project/sglang#31481`), not a recipe change.

arm-5: `trtllm-gen` is SM100/103-only in every release through `v0.7.4rc2`
(`flashinfer/mla/_core.py:1241-1244`, and `:1062` at `v0.6.18` is the recorded
error verbatim); SM12x has its own `sparse` backend, auto-selected since
`v0.7.0`. The fork hardcodes `backend="trtllm-gen"` at `:366,506`, passes the
pre-0.7 single `sparse_indices`/`sparse_topk_lens` shape, and monkeypatches
`_fi_core._get_trtllm_gen_multi_ctas_kv_counter_buffer`, which 0.7.3 dropped —
so the unlock is an ABI migration of those call sites. No local image can boot
it: every knapcio-adapter image is FlashInfer 0.6.18 and the only 0.7.3 image
has no `/opt/dsv41`.
…well) via flashinfer's packed sparse backend

attention_backend=dsa with dsa_decode_backend/dsa_prefill_backend=trtllm
crashes on SM120/SM121 (DGX Spark GB10, RTX PRO Blackwell) with
"TllmGenFmhaRunner ... Unsupported architecture": _forward_trtllm hardcodes
backend="trtllm-gen", which only exists for datacenter Blackwell (SM100/103).

flashinfer (>= 0.6.x) ships a native SM120/121 sparse-MLA implementation
(flashinfer/mla/_sparse_mla_sm120.py, @supported_compute_capability([120, 121]))
whose dispatcher (trtllm_batch_decode_with_kv_cache_mla) routes cc==12 +
sparse_mla_top_k>0 to it automatically, but only with backend="auto". Three
changes make the whole DSA path (decode and prefill) work on consumer
Blackwell, gated on the canonical is_sm120_supported() arch util so SM100/103
behavior stays byte-identical:

1. mem_cache/kv_cache_configurator.py::calculate_mla_kv_cache_dim - do not
   early-return the plain kv_lora_rank + qk_rope_head_dim layout for trtllm
   dsa backends on SM12x. The SM120 sparse kernel consumes the 656-byte
   packed inline-scale layout (512 fp8 nope + 4x fp32 tile scales + 64 bf16
   rope) that quantize_k_cache already writes; dsa_kv_cache_store_fp8 then
   derives True automatically.

2. layers/attention/dsa_backend.py::_forward_trtllm - gate on
   is_sm120_supported() and dsa_kv_cache_store_fp8:
   - backend="auto" instead of "trtllm-gen" (flashinfer picks "sparse"),
   - pass the KV cache as a uint8 view (the sm120 checker requires it),
   - kv_scale_format="arbitrary_fp32": sglang's quantize_k_cache writes
     amax/448 arbitrary fp32 tile scales, not pow2/ue8m0 - flashinfer's
     GLM_NSA scale semantics; the default "auto" (pow2) would misread them,
   - skip_softmax_threshold_scale_factor=None (unsupported by the sparse
     backend),
   - skip the fused rope+fp8-query-quantize branch - the sparse kernel
     requires a BF16 query and dequantizes KV itself via inline scales,
   - raise NotImplementedError if DSA prefill context parallelism is
     requested together with the SM12x sparse route: that combination has
     only been exercised against the trtllm-gen fp8-fused-rope path, which
     this route skips entirely, so silently mis-routing it would be wrong.

3. models/deepseek_common/attention_forward_methods/forward_mla.py::
   DeepseekMLAForwardMixin._fuse_rope_for_trtllm_mla - return False for the
   dsa/nsa branch on SM12x so rope stays in forward_absorb_prepare and the
   query reaches _forward_trtllm in bf16 (consequence of 2; the second call
   site sharing this gate for the extra cos_sin_cache args stays consistent).

All conditionals keep the upstream values on the non-SM12x side.

Tests (split CI-safe / hardware-bound per the sglang testing guide):
- test/registered/unit/mem_cache/test_dsa_kv_cache_dim_sm12x.py: mocks the
  module-level is_sm120_supported() cache to cover the
  sm12x+fp8+trtllm/sm12x+bf16/sm100+trtllm/sm12x+non-trtllm matrix.
- test/registered/unit/layers/attention/test_dsa_backend_trtllm_sm12x_kwargs.py:
  monkeypatches flashinfer.decode via sys.modules and calls _forward_trtllm
  against a lightweight fake backend, asserting the exact kwarg selection on
  both the sm12x-sparse and upstream-unchanged paths, plus the CP
  NotImplementedError guard.
- test/registered/unit/models/test_deepseek_mla_fuse_rope_trtllm_sm12x.py:
  covers the fuse-rope carve-out in isolation (regression guard for the
  "expects BF16 query, got torch.float8_e4m3fn" live-deploy crash).
- test/registered/kernels/test_dsa_sparse_mla_sm12x.py: SM120/121-gated
  (skipped elsewhere), builds a real packed pool via quantize_k_cache and
  compares flashinfer's sparse kernel against a torch dequant+masked-softmax
  reference for decode, seq_len>topk clamping, -1 padding, prefill (>64
  tokens), and cuda-graph capture+replay.

GPU-verified on DGX Spark GB10 (SM121, flashinfer 0.6.14, TP4,
0xSero/glm-5.2-reap-504B-v2 = GlmMoeDsaForCausalLM): boot clean, decode graph
capture 18s, decode 8.4 tok/s cuda-graph, prefill 873 tok/s input on a
7-seq/2240-token batch, GSM8K 2-shot n=20 conc 8 = 85%, 0 errors/restarts.
Kernel-level (real quantize_k_cache pool, torch dequant+softmax reference):
decode bs=4 topk=2048 max|diff| 0.008 @ 0.072ms/call; prefill 2400 extend
tokens max|diff| 0.016 @ 14.4ms/layer-call; cuda-graph capture+replay works
directly.
@vroomfondel
vroomfondel force-pushed the dsa-sm12x-native-sparse-mla branch from 7aa9049 to bcee4f9 Compare November 30, 2026 15:55
@github-actions

This comment has been minimized.

@github-actions

This comment has been minimized.

@vroomfondel vroomfondel changed the title [DSA] Enable sparse MLA decode+prefill on SM120/SM121 (consumer Blackwell) via flashinfer's packed sparse backend [Feat] [NVIDIA] dsa: Enable sparse MLA decode+prefill on SM120/SM121 via flashinfer's packed sparse backend Dec 1, 2026
xulunfan added a commit to xulunfan/sglang that referenced this pull request Dec 3, 2026
trtllm is the auto-selected DSA backend on every CUDA device with capability
>= 10, but it dispatches flashinfer's TRT-LLM-GEN MLA kernels, which the
pinned wheel builds for SM100/SM103/SM107 only. Resolution accepted the
combination, weights loaded, and the refusal surfaced mid-forward
(sgl-project#40558, sgl-project#40286).

- _check_dsa_backend_constraints now gates trtllm on exactly flashinfer's
  own dispatch condition, as an exact (major, minor) set -- the same rule
  0.7.2 applies in _resolve_dsv4_sparse_mla_backend. major == 10 alone
  would still let SM101/SM102/SM104 through to the same late failure.
- Nothing is re-routed. On SM11x/SM12x no DSA backend is established as
  usable for the non-GLM family (sgl-project#31481 is open, sgl-project#40286 records "no usable
  DSA backend on SM121"), so a default change would only pick a different
  late crash. This turns "accepted, then crashes" into "refused at startup".
- The refusal names the one route these checks do accept on SM12x -- tilelang
  for both phases with FP8 KV -- reported to start and decode on an RTX 5090
  with accuracy unvalidated, so the text is a pointer rather than a
  recommendation.
- The arch set tracks the pinned wheel, which bot-bump-flashinfer-version.yml
  moves on its own; moving it here stays a human edit, hence "the flashinfer
  pinned here" in the message.
- The ROCm-only hint said "trtllm on Blackwell" and now says SM10.x Blackwell.
- Tests: one CPU unit case over the accepted and rejected arch triples in the
  existing DCP constraint file, plus the end-to-end shape of sgl-project#40558 (no DSA
  flag, both KV dtypes, SM120) in the existing golden overrides file. Two
  pre-existing assertions that paired trtllm with an unsupported device now
  mock an accepted arch. A further case asserts that the SM12x route the
  message names really passes these checks, so the pointer cannot rot into
  advice the gate contradicts.

Refs: sgl-project#40558, sgl-project#40286

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant