Skip to content

[Feat] dsa: Add an arch-independent torch paged-MQA-logits backend with a fused Triton fast path - #31480

Open
vroomfondel wants to merge 2 commits into
sgl-project:mainfrom
vroomfondel:dsa-indexer-torch-triton-backend
Open

vroomfondel wants to merge 2 commits into
sgl-project:mainfrom
vroomfondel:dsa-indexer-torch-triton-backend

Conversation

@vroomfondel

@vroomfondel vroomfondel commented Jul 16, 2026 •

Copy link
Copy Markdown
Contributor

Problem

The DSA indexer's paged-MQA-logits kernel has no backend that runs outside the current three:

  • DEEPGEMM (the auto default): compiled C++ Unsupported architecture assert on SM120/SM121; DeepGEMM upstream declined SM12x support (deepgemm PR Requests not supported with HuggingFace Chat Templates #318).
  • CUTEDSL: gated behind is_sm100_supported(), and structurally SM100-only — _setup_mma uses tcgen05.MmaF8F6F4Op, a datacenter-Blackwell ISA op that does not exist on consumer Blackwell.
  • AITER: ROCm.

So every DSA model (DeepSeek-V3.2 family, GLM GlmMoeDsaForCausalLM) crashes on its first decode step on SM120/SM121 (DGX Spark GB10, RTX PRO Blackwell). The dsv4 path already solved this exact problem for DeepSeek-V4 (fp8_paged_mqa_logits_torch_sm120, #24692), but the generic dsa/dsa_indexer.py path has no equivalent.

Relation to SGLANG_FP8_PAGED_MQA_LOGITS_TORCH (#32947, merged after this PR was opened): that fallback is an env switch inside the DeepGEMM split path and only covers next_n == 1. This PR is an explicit backend selected by CLI flag that covers decode, target-verify and draft-extend (next_n >= 1) and the KPool path, never enters the DeepGEMM path or its schedule metadata, and adds the fused Triton kernel with early exit on the true sequence length under CUDA graphs. The two are independent; where #32947 applies, auto or deepgemm plus its env var works as before.

Changes

  1. New backend value torch in DSAPagedMQALogitsBackend + --dsa-paged-mqa-logits-backend torch. Opt-in only, NOT selected by auto — archs where DeepGEMM/CuteDSL work are unaffected.

  2. New module dsa/torch_paged_mqa_logits.py: a vectorized, cuda-graph-safe (no .item(), no data-dependent control flow) pure-torch implementation for the generic DSA path. It discards the DeepGEMM schedule metadata (the torch path does no SM-tiled scheduling), so the eager get_paged_mqa_logits_metadata() call sites in dsa_backend.py::init_forward_metadata and the graph-replay refresh helper are skipped for this backend.

  3. Dispatch in dsa_indexer.py::_get_topk_paged: pure pass-through for all modes this function serves (decode / target_verify / draft_extend_v2). No reshaping is needed: q/weights are already sliced per token, verify seqlens come from get_seqlens_expanded() (per-token), and init_forward_metadata already repeat_interleaves the page table to per-token rows for the multi-token modes.

  4. Fused Triton fast path dsa/triton_paged_mqa_logits.py (env SGLANG_DSA_INDEXER_TRITON, registered in environ.py, default on; falls back to torch when triton is unavailable or num_heads < 16): one program per (token, 64-token KV page), static launch grid over the full page-table width (cuda-graph-safe) with per-block early exit on the true seq_lens[b] read at replay time; fused fp8 load + inline-scale dequant + q·k dot + relu + weighted head-sum, no fp32 HBM intermediates. Motivation: under cuda-graph the page-table width is a capture-time constant and the pure-torch kernel pays the full width every step — measured 1.476 ms/layer-call at width 131072 regardless of the true seq len; the Triton kernel is numerically equivalent and 0.024 ms at the same shape (61x).

  5. KPool (GLM-5.3-Flash, index_kpool > 1): IndexerKPool._get_topk_paged has a torch arm that scores the pooled index keys with fp8_paged_mqa_logits_torch_dsa (Triton fast path included). The DeepGEMM schedule metadata is not built for this backend, neither in _get_kpool_decode_metadata nor in the KPool metadata builders (_build_kpool_paged_mqa_schedule_metadata returns False), so the CUDA-graph capture and replay paths allocate and refresh none. The torch backend takes precedence over the SM90 tilelang arm. Other backends are unchanged.

Evidence

Live-validated on a 4× DGX Spark (GB10, SM121) cluster serving GlmMoeDsaForCausalLM (504B REAP cut, NVFP4, TP4): decode/prefill/target-verify/draft-extend all healthy, MTP/NEXTN accept length ~2.1, GSM8K 2-shot n=20 conc 8 = 85% with 0 errors/restarts. This run predates the rebase onto current main (2026-11-30) and the KPool arm; neither has been re-run on SM12x hardware or with a GLM-5.3-Flash model yet.

Tests

test/registered/kernels/test_dsa_paged_mqa_logits.py (modeled on test_sm120_paged_mqa_logits.py from #24692; register_cuda_ci, runs on any CUDA GPU — no SM12x hardware required): torch vs loopy reference, Triton vs torch equivalence incl. identical -inf masks, both KV dtype views (uint8 / float8_e4m3fn), variable per-batch seq_lens, per-token expanded verify shapes (next_n >= 2) incl. a regression test that double-expanding the page table is caught by the shape assert, cuda-graph capture + replay incl. a seq-len change between capture and replay, and the num_heads < 16 fallback guard. 17/17 passed on GB10 (SM121) before the rebase. After the rebase onto current main, with 4 added KPool cases (torch arm for decode and next_n = 2 with padded rows against the loopy reference, unchanged DeepGEMM arm, schedule-metadata gate): 21/21 pass on an RTX 4090 (SM89); the KPool cases call the real _get_topk_paged with a stubbed indexer object.

Notes

  • Companion PR (the attention side for SM12x): the sparse-MLA routing PR — neither alone boots DSA on consumer Blackwell; they are independent to review/merge.
  • The kernel hardcodes the DSA index-cache layout (head_dim 128, 64-token pages, per-page [64*128 fp8][64*4 fp32 scales]) and asserts it with descriptive messages.

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 #46455835300

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

Companion PR (the attention side for SM12x): #31481 — neither alone boots DSA on consumer Blackwell; the two are independent to review and merge.

efschu added a commit to efschu/htsglang that referenced this pull request Aug 2, 2026
Risk sgl-project#1 of the Cut 1/2 report predicted boot 12 stops at the DSpark indexer,
and a card window is not spent on a wall we have already named. Closed here.

The paged-MQA-logits step of the DSpark layers (40-42, compress_ratio 4/128)
defaults to deep_gemm.fp8_paged_mqa_logits: Hopper and datacenter Blackwell
only. Not an Ampere-only problem -- DeepGEMM declined SM12x (deepgemm PR
sgl-project#318), so after Cut 2 gets TP0 through attention the 5090 would have hit this
exactly like the 3080s. All three ranks of this rig need it.

Upstream first: PR sgl-project#31480 solves the same thing for the sibling dsa/ package,
and its structure is what is adopted -- explicit backend selections stay
authoritative, the capability-driven choice goes underneath them, and the
DeepGEMM schedule metadata is skipped for any backend that does not consume
it. The parts that PR had to BUILD (a torch implementation, a metadata
bypass) already exist here from sgl-project#24692, so our delta is the dispatch half
only. This cut writes no kernel; saying otherwise would overstate it.

New dsv4/indexer_arch.py: deepgemm_indexer_supported (per_device_gate,
major in (9, 10)), resolve_paged_mqa_logits_backend, the companion
deepgemm_indexer_metadata_needed, and the named warning. The kernel choice
and the schedule choice must never disagree -- a rank with a schedule and no
DeepGEMM, or a kernel and no schedule, is a crash either way -- so that
invariant is pinned over the whole env x capability matrix rather than left
to two functions happening to agree.

The fn selection is lifted out of _forward_paged_indexer into module-level
select_paged_mqa_logits_fn(). It is the whole of this cut and the kind of
decision that goes quietly wrong on a heterogeneous group; inline in a
600-line method it was untestable. Also: _can_use_nonpaged_indexer now
refuses a card without DeepGEMM (that branch calls fp8_mqa_logits directly
and has no torch twin; the paged path is its fallback).

APPROXIMATION, NAMED, NOT SILENT: this substitution is not bit-identical.
DeepGEMM computes the logits as an FP8 tensor-core GEMM; the torch path
dequantises to float32 and accumulates with bmm. Same quantity, different
arithmetic. The logits feed a top-k, so a near-tie between two KV positions
can be broken differently and output can differ from a Hopper run of the same
checkpoint. Warned once per device, naming the capability and the mechanism.
It stays quiet when the user asked for the torch path explicitly -- then it
is not a surprise.

Two findings from writing the test, both worth the branch on their own:

  * The FP4 indexer has no fallback at all (68-byte vs 132-byte index cache
    layout), so it now REFUSES by name instead of being routed at the FP8
    torch path, which would have read the cache wrongly and returned
    plausible numbers. Our GGUF checkpoint is unaffected.
  * The two torch implementations are not interchangeable, and the difference
    is not architectural. The paged call site passes seq_lens with a trailing
    dim of 1; only the _sm120 variant squeezes it, the other asserts
    shape == (batch_size,). So the old is_sm120_supported() split at
    indexer.py:667 would have sent every non-SM120 card at an implementation
    that ASSERTS -- including anyone setting SGLANG_FP8_PAGED_MQA_LOGITS_TORCH
    on a Hopper box today. The dispatch now always takes the trimmed variant,
    which is additionally the one that walks ceil(max_seq_len/64) pages
    instead of the full capture-time page-table width.

TESTS (desk, CUDA_VISIBLE_DEVICES=99, no GPU touched)
  test_dsv4_indexer_arch_417.py  21 tests / 68 subtests green, incl.
    PagedIndexerMetadata constructed on a mocked Ampere card without ever
    importing DeepGEMM, and the Hopper branch still being taken (observable
    because DeepGEMM raises in this CPU environment).
    CAN-FAIL, three ways: _DEEPGEMM_MAJORS -> (8,9,10) gives 22 failed /
    17 passed; returning fp8_paged_mqa_logits_torch from the dispatch gives
    8 failed / 21 passed; making the FP4 branch fall back silently instead of
    refusing gives 1 failed / 20 passed.
  Regression: unit/layers + unit/utils, 47 failed / 731 passed on this branch
    vs 47 failed / 682 passed at a56f33aafd. Failing set diff EMPTY.
    This comparison earned its keep: it caught the first version of the
    non-paged DeepGEMM check reaching into a metadata field that
    test_dsv4_nonpaged_indexer's stub does not provide. Asking the CURRENT
    device instead is both what that test expects and the more correct
    question after set_device.
  ruff findings identical to base on the touched files (E712 x3 pre-existing
    in indexer.py), new files clean. codespell, black, isort, mypy clean.

Plan file updated: Cut 3 section, matrix rows 9/9b/9c/10, the GPU-window
request restated for Cuts 1-3 in path (all three cards, ~90 min,
SGLANG_OPT_USE_TOPK_V2=0 on any sm86 boot, plus a new gate 6 that sizes the
top-k divergence between ranks rather than asserting the warning is
harmless), and a 5-line ticket note for the ue8m0 subnormal divergence so it
is not lost -- registered separately, deliberately untouched here.
@vroomfondel
vroomfondel force-pushed the dsa-indexer-torch-triton-backend branch from d0b442f to 5480d1d Compare August 3, 2026 10:36
@vroomfondel
vroomfondel force-pushed the dsa-indexer-torch-triton-backend branch from 5480d1d to 685784f Compare August 3, 2026 12:40
@vroomfondel

Copy link
Copy Markdown
Contributor Author

Rebased onto current main; 17/17 kernel tests pass on GB10 (SM121).
Could a maintainer add the run-ci label and take a look? Companion PR: #31481.

@b8zhong b8zhong mentioned this pull request Aug 5, 2026
15 of 41 tasks
@vroomfondel
vroomfondel force-pushed the dsa-indexer-torch-triton-backend branch from 685784f to 68cf312 Compare August 15, 2026 10:11
@vroomfondel
vroomfondel force-pushed the dsa-indexer-torch-triton-backend branch from 68cf312 to 6b2e62e Compare August 28, 2026 10:47
@vroomfondel
vroomfondel force-pushed the dsa-indexer-torch-triton-backend branch from 6b2e62e to 8d3944a Compare September 10, 2026 13:09
…used Triton fast path

The DSA indexer's paged-MQA-logits kernel (dsa/dsa_indexer.py::_get_topk_paged)
has no backend that runs on consumer Blackwell (SM120/SM121) or, more
generally, any CUDA arch outside what DeepGEMM/CuTe DSL/aiter each cover:
DeepGEMM's compiled kernel asserts "Unsupported architecture" on SM120/121
(upstream declined support, deepseek-ai/DeepGEMM#318), CuTe DSL is gated to
SM100 and its _setup_mma uses a datacenter-Blackwell-only tensor-core op, and
aiter is ROCm-only. Every DSA model (DeepSeek-V3.2 family, GlmMoeDsaForCausalLM)
therefore has no working indexer logits kernel on those archs.

This adds a new opt-in backend value "torch" (--dsa-paged-mqa-logits-backend
torch; not selected by "auto", so unaffected archs keep their existing
default):

- dsa/paged_mqa_logits_backend.py, server_args.py: new enum member + CLI choice.
- dsa/torch_paged_mqa_logits.py (new): a vectorized, CUDA-graph-safe pure-torch
  port of the equivalent DeepSeek-V4 fallback (dsv4/indexer.py's
  fp8_paged_mqa_logits_torch_sm120, PR sgl-project#24692) for the generic DSA indexer
  path, which had no equivalent. Discards the DeepGEMM schedule metadata the
  same way, so dsa_backend.py's two eager metadata precompute call sites and
  the shared cuda-graph-replay refresh helper are skipped for this backend.
- dsa_backend.py, dsa/dsa_indexer.py: backend resolve + dispatch wiring.
  dsa_indexer.py's dispatch is a pure pass-through for every mode
  _get_topk_paged is invoked for (decode, target_verify, draft_extend_v2):
  q/weights are already per-token, seqlens are already expanded per-token for
  the speculative modes, and block_tables is already repeat_interleaved to
  per-token rows by dsa_backend.py before this is reached.
- dsa/triton_paged_mqa_logits.py (new): a fused Triton fast path (env
  SGLANG_DSA_INDEXER_TRITON, default on; falls back to the torch kernel when
  triton is unavailable or num_heads < 16). Under CUDA graph capture the
  pure-torch kernel pays the full page-table capture width every step
  regardless of the true sequence length; this kernel keeps the same static
  launch grid but early-exits per (request, KV-page) block on the true
  seq_lens read at replay time, so cost tracks the real context length.
- test/registered/kernels/test_dsa_paged_mqa_logits.py (new): modelled on the
  DSv4 SM120 precedent test (test_sm120_paged_mqa_logits.py, PR sgl-project#24692) --
  runs on any CUDA GPU. Covers the torch kernel against an independent
  un-vectorized reference, bit-exact-tolerance equivalence against the Triton
  kernel, both KV-cache dtype views, a page_table -1-sentinel case, per-token
  (flattened-batch) shapes with a dedicated double-expansion regression test,
  CUDA graph capture+replay across a seq_lens change, and the num_heads < 16
  Triton fallback guard.
@vroomfondel
vroomfondel force-pushed the dsa-indexer-torch-triton-backend branch from 8d3944a to 7815bd2 Compare November 30, 2026 15:55
@github-actions

This comment has been minimized.

…QA-logits backend

With --dsa-paged-mqa-logits-backend torch, IndexerKPool._get_topk_paged still
called deep_gemm.fp8_paged_mqa_logits and the KPool metadata builders still
called deep_gemm.get_paged_mqa_logits_metadata.

- dsa_indexer_kpool.py: add a torch arm that scores the pooled index keys with
  fp8_paged_mqa_logits_torch_dsa (Triton fast path included), take precedence
  over the SM90 tilelang arm, and skip the schedule-metadata build.
- dsa_backend_kpool.py: _build_kpool_paged_mqa_schedule_metadata returns False
  for the torch backend, which also covers the CUDA-graph capture and replay
  metadata (every copy site is guarded on the schedule being present).
- test_dsa_paged_mqa_logits.py: cover the KPool torch arm (decode, next_n=2
  per-token rows, padded rows) against the loopy reference, the unchanged
  DeepGEMM arm and the schedule-metadata gate.
@github-actions

This comment has been minimized.

@github-actions

This comment has been minimized.

@vroomfondel vroomfondel changed the title [DSA] Add an arch-independent torch paged-MQA-logits backend with a fused Triton fast path [Feat] dsa: Add an arch-independent torch paged-MQA-logits backend with a fused Triton fast path Dec 1, 2026

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

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant