Skip to content

[MTP] Cut spec-v2 host-seam overhead in hybrid-linear MTP decode - #32219

Merged
BBuf merged 7 commits into
sgl-project:mainfrom
yuan-luo:mtp_decode_perf_opt
Jul 28, 2026
Merged

BBuf merged 7 commits into
sgl-project:mainfrom
yuan-luo:mtp_decode_perf_opt

Conversation

@yuan-luo

@yuan-luo yuan-luo commented Jul 23, 2026 •

Copy link
Copy Markdown
Collaborator

Motivation

With MTP (NEXTN) speculative decoding under spec-v2 overlap scheduling, each decode step consists of three CUDA graphs:

[draft graph]   NEXTN draft model, k autoregressive passes -> draft-token chain
[verify graph]  target model, one forward over the draft tokens (TARGET_VERIFY)
[extend graph]  draft model backfills KV for the accepted tokens (DRAFT_EXTEND)

Between the graphs live eager "seams": accept sampling, cache-slot assignment, attention-metadata rebuild, next-step draft input preparation. At low concurrency (bs=1 to small batches) these seams, host-side Python dispatch and per-step synchronization the GPU cannot overlap, become GPU idle time.

Host run-ahead, and what pins it

image

sglang's event_loop_overlap is designed so that while the GPU executes step N, the host is already assembling and enqueuing step N+1; the host stays off the critical path iff host loop time < GPU step time. The FutureMap keeps cross-step data (next tokens, new_seq_lens, draft seeds) GPU-resident, relayed by pool index between graphs, so the host can launch the next step without ever seeing accept results, launch-queue depth grows to ~1 full step of run-ahead:

image

Several per-step host costs, however, still pin the host to the GPU's progress and shrink that run-ahead back toward lockstep:

  1. A blocking per-step seq_lens D2H stream sync for KDA hybrids. KDAAttnBackend never declared needs_cpu_seq_lens, inheriting the base-class True, which forces FutureMap.resolve_seq_lens_cpu onto the blocking path (fwd_prepare_d2h_stream.synchronize() every step). In bs=1 MTP traces of a KDA-hybrid model this stall measured ~0.5 ms/step median — the host waits for the previous verify to finish on GPU, zeroing run-ahead. GDN / Mamba2 / ShortConv siblings already declare False and run the same base-class metadata code.
  2. Hybrid wrappers drop the verify-buffer hooks. HybridLinearAttnBackend never forwarded get/update_verify_buffers_to_fill_after_draft, so every hybrid-linear MTP model takes the [None, None] fallback: the draft stage cannot write the tree mask / positions straight into the full-attn child's captured verify buffers and instead allocates a fresh custom_mask each step — sized bs * max_context_len once the GPU-only seq_lens path nulls seq_lens_sum.
  3. An eager end-offset add in verify prep. eagle_prepare_for_verify extends every row by exactly draft_token_num tokens, yet materialized seq_lens + draft_token_num on the host (a fresh tensor + a dispatch per step) for the generic cache-locs kernel, which then re-derived per-row output offsets with O(bs) cross-row prefix-sum loads.
  4. A 5-7 dispatch replay-prep chain. _replay_metadata refreshed state_indices_list via separate aten ops (zero padded req_pool_indices rows → mapping gather → v2p translate → -1 padding sentinel → copy_ into the static buffer) on every mamba-backend CUDA-graph replay.

The host seam is a serial chain — single-point savings do not add up: remove A and the CPU immediately hits B. What ultimately hides the host is the combination plus the overlap scheduling itself, not any single item. The latency payoff therefore lands as a bundle; each fix is nonetheless independently correct and independently revertible.

Effects

Before PR, GPU bubbles between draft_extend/draft/target_verify are significant:
image

After PR, GPU bubbles between these tree APIs are almost gone:
image

Whole picture before PR, no overlap, CUDA graph launch is sync:
image

After PR, the verify CUDA graph launch can be overlapped in the next draft_extend:
image

Provenance

These items were developed and measured in a bs=1 MTP decode optimization campaign on a KDA-hybrid MoE model (4× B200, TP4, NEXTN speculative decoding), whose end state reached ~90% GPU busy per step with the host fully hidden behind the GPU — the per-item trace measurements quoted in this PR (the ~0.5 ms/step D2H stall) come from that campaign. This PR upstreams the model-agnostic host-seam subset; every item passed the campaign's correctness gate (byte-exact 256-token greedy output + accept length invariance) before it stayed.

Modifications

One commit per item, bit-identical by construction (scheduling / fusion only — no numerical path changes):

  • Opt KDA backend out of the per-step seq_lens_cpu D2H sync — KDAAttnBackend declares needs_cpu_seq_lens = False, matching GDN/Mamba2/ShortConv. Safety: the shared MambaAttnBackendBase metadata never reads the spec-v2 CPU mirror for KDA — replay padding always comes from forward_batch.num_padding, and the replayssm track-flush mask reads are not is_kda-gated. With the full-attn siblings (trtllm_mla / fa3 / flashmla / triton) already False, the OR over spec-v2 backends can now stay False for KDA hybrids and the per-step stream sync disappears.
  • Forward verify-buffer hooks through HybridLinearAttnBackend — get delegates to the full-attn child (the linear side consumes no mask); the draft stage now writes directly into the captured verify buffers and the per-step mask allocation disappears. update forwards to both children with an explicit no-op on MambaAttnBackendBase (mamba plan-time metadata is draft-output independent); children without an implementation keep the fail-loud NotImplementedError, so an unvetted plan-stream combination fails loudly instead of silently reading stale buffers.
  • Fuse the uniform verify-prep cache-locs end offsets into the kernel — new assign_extend_cache_locs_uniform: end offset computed in-kernel (start + draft_token_num), output offset a direct pid * draft_token_num. NPU / CPU fall back to the end_offset-tensor reference path unchanged; the non-uniform call site (move_accept_tokens) keeps the reference kernel.
  • Fuse the mamba replay-prep state-indices chain into one launch — _fused_state_indices_kernel does the gather + sentinel + store in a single triton launch, preserving the reference chain's side effect of zeroing padded req_pool_indices rows (captured kernels gather with that buffer). Gated to CUDA + the static hybrid pool whose v2p translate is the identity + replayssm off; unified-pool / replayssm configs keep the reference chain.
  • Add bit-exact reference test for _fused_state_indices_kernel — see Accuracy Tests.

Compatibility: no API / flag changes; NPU, CPU, unified-memory pool, and replayssm behavior unchanged (explicit gates / fallbacks); plan-stream fail-loud contract preserved.

Accuracy Tests

  • New unit test test/registered/attention/unittests/hybrid_linear/test_fused_state_indices_kernel.py: fused kernel vs the reference aten chain on guard-padded buffers, bs ∈ {1, 2, 7, 32, 33} × num_padding sweep × 3 seeds + a non-injective-mapping case — asserts bit-identical state indices (incl. -1 sentinels), the req_pool_indices zeroing side effect, and untouched guard tails (out-of-range write protection for BS_UPPER > bs). Result on H20-3e: 2 tests, 45 subtests, all pass (8.8s).
  • e2e greedy byte-identity, branch vs base (b98a577f), H20-3e, tp=4 (greedy, 8 fixed prompts, 256 tokens each, ignore_eos):
    • Qwen3.5-35B-A3B + NEXTN MTP (--speculative-num-steps 3 --speculative-eagle-topk 1 --speculative-num-draft-tokens 4) — a GDN-hybrid spec-v2 config exercising items 2-4: output text byte-identical; per-prompt spec_verify_ct identical (113/91/71/83/84/83/85/80) — acceptance behavior unchanged.
    • Kimi-Linear-48B-A3B-Instruct plain CUDA-graph decode — a KDA config exercising item 4's fused replay path: output byte-identical.

Speed Tests and Profiling

These changes remove host-side work whose payoff is latency at low concurrency and compounds with sibling optimizations (serial chain):

  • Item 1 removes a measured ~0.5 ms/step median blocking stream sync (bs=1 MTP trace, KDA-hybrid lineage) once a KDA-hybrid spec-v2 config is active; it is inert (flag read only by decide_needs_cpu_seq_lens) for all other configs.
  • Item 2 removes a per-step bs * max_context_len bool-mask allocation for every hybrid-linear MTP model.
  • Items 3-4 replace 6-8 per-step host dispatches with 2 kernel launches.

Byte-identical outputs above double as the no-regression evidence. A bundle-level TPOT A/B on Blackwell for the KDA-hybrid MTP target is part of the follow-up series and will be reported there.

This is one part of hybrid-linear model optimazations, with which GPU utils increase from 67% to 95% in MTP.

Checklist


CI States

Latest PR Test (Base): 🚫 Run #30326134766
Latest PR Test (Extra): ✅ Run #30889987619

@gemini-code-assist

Copy link
Copy Markdown
Contributor

Caution

The consumer version of Gemini Code Assist on GitHub has been sunset. All code review activity has officially ceased.

@yuan-luo yuan-luo added speculative-decoding 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 Jul 23, 2026
@yuan-luo yuan-luo changed the title [Ling-3.0][MTP] Cut spec-v2 host-seam overhead in hybrid-linear MTP decode [MTP] Cut spec-v2 host-seam overhead in hybrid-linear MTP decode Jul 23, 2026
@yuan-luo
yuan-luo force-pushed the mtp_decode_perf_opt branch from 80e424d to f231f4e Compare July 23, 2026 14:01

@JustinTong0323 JustinTong0323 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.

Found one correctness issue in the plan-stream hybrid-linear verification path.

@JustinTong0323

Copy link
Copy Markdown
Collaborator

/rerun-failed-ci

luoyuan.luo added 3 commits July 28, 2026 11:19
KDAAttnBackend never declared needs_cpu_seq_lens and inherited the
base-class True, forcing FutureMap.resolve_seq_lens_cpu onto the
blocking path: a per-step fwd_prepare_d2h_stream.synchronize() that
stalls the scheduler ~0.5 ms (median 485 us over 30 traced steps, B200
bs=1 MTP) waiting for the previous verify to finish on GPU and publish
new_seq_lens, zeroing the spec-v2 host run-ahead.

KDA metadata never reads the spec-v2 seq_lens_cpu mirror: replay
padding comes from forward_batch.num_padding, and the replayssm
track-flush mask paths are gated `not is_kda`. GDNAttnBackend and
Mamba2AttnBackend already run the same base-class metadata code with
needs_cpu_seq_lens = False; this brings KDA into the same GPU-only
contract. With the full-attn siblings (trtllm_mla / fa3 / flashmla /
triton) all False, the OR over spec-v2 backends now stays False for
KDA hybrids (e.g. Kimi-Linear MTP) and the per-step stream sync
disappears entirely.
The hybrid wrapper never overrode the
get/update_verify_buffers_to_fill_after_draft hooks, so every
hybrid-linear MTP model (GDN / KDA) hit the base [None, None]: the
draft stage could not write the tree mask / positions straight into
the full-attn child's captured verify buffers and instead allocated a
fresh custom_mask every step -- sized bs * max_context_len once the
GPU-only seq_lens path (needs_cpu_seq_lens=False) nulls seq_lens_sum.

- get: delegate to the full-attn child (the linear side consumes no
  mask); the draft stage now writes into the captured verify buffers
  and the per-step mask allocation disappears.
- update: forward to both children. MambaAttnBackendBase gets an
  explicit no-op (mamba plan-time metadata -- state slot indices,
  per-bs static query_start_loc -- is draft-output independent);
  children without an implementation keep the fail-loud
  NotImplementedError, so an unvetted plan-stream combination fails
  loudly instead of silently reading stale buffers. The update site
  only fires under SGLANG_ENABLE_OVERLAP_PLAN_STREAM (default off).
eagle_prepare_for_verify extends every row by exactly draft_token_num
tokens, yet went through the generic assign_extend_cache_locs kernel:
the host eagerly materialized `seq_lens + draft_token_num` (a fresh
tensor + one dispatch per step on the bs=1 MTP inter-phase seam) and
the kernel re-derived per-row output offsets with O(bs) cross-row
prefix-sum loads.

Add assign_extend_cache_locs_uniform: the end offset is computed in
the kernel (start + draft_token_num) and the output offset is a direct
pid * draft_token_num. NPU / CPU fall back to the end_offset-tensor
reference path, unchanged. The non-uniform call site
(move_accept_tokens: seq_lens + num_correct_drafts + 1) keeps the
reference kernel.
luoyuan.luo added 3 commits July 28, 2026 11:19
_replay_metadata refreshed state_indices_list through a chain of
dispatched aten ops on the bs=1 MTP host critical path: zero padded
req_pool_indices rows, mamba mapping gather, v2p translate, -1
padding sentinel, copy_ into the static buffer (5 dispatches on the
static pool, more on the unified pool).

_fused_state_indices_kernel does the gather + sentinel + store in a
single triton launch, preserving the reference chain's side effect of
zeroing padded req_pool_indices rows (captured kernels gather with
them; dropping the zeroing would be a delayed illegal memory access).
Gated to CUDA + the static hybrid pool whose v2p translate is the
identity, and to replayssm off; the unified pool's allocator translate
is not a flat table gather, so those configs keep the reference chain.
Drives the fused single-launch replay-prep path and the reference aten
chain on guard-padded buffers across a bs x num_padding matrix
(non-power-of-two sizes exercise the BS_UPPER masking) and asserts
bit-identical results: state indices incl. the -1 padding sentinels,
the req_pool_indices zeroing side effect (captured kernels gather with
that buffer; a missed zeroing is a delayed illegal memory access, not
a visible diff), and untouched guard tails past total_bs. Also covers
non-injective mappings (requests sharing a mamba slot).
@yuan-luo
yuan-luo force-pushed the mtp_decode_perf_opt branch from 536a444 to ee7b6e2 Compare July 28, 2026 03:19
@yuan-luo
yuan-luo force-pushed the mtp_decode_perf_opt branch from ee7b6e2 to b908e69 Compare July 28, 2026 03:31
@BBuf
BBuf merged commit d9cf7b0 into sgl-project:main Jul 28, 2026
52 of 100 checks passed
@yuan-luo
yuan-luo deleted the mtp_decode_perf_opt branch July 28, 2026 15:56
@yuan-luo yuan-luo added the release-highlight Candidate PR for release note highlight label Aug 4, 2026
saturn-acc pushed a commit to saturn-acc/sglang that referenced this pull request Aug 16, 2026
Atituiset pushed a commit to Atituiset/sglang that referenced this pull request Sep 10, 2026
efschu pushed a commit to efschu/htsglang that referenced this pull request Sep 24, 2026
…es for mamba graph replay

Upstream d9cf7b0 (v0.5.20), only the part that reaches the 27B.

MambaAttnBackendBase._replay_metadata refreshes the captured
state_indices_list before every decode / target-verify graph replay; on the
27B's D group that is the DFLASH verify graph every step. The reference chain
(index-put of padded req rows, mapping gather, identity translate, -1 fill,
copy) is 4 launches of host overhead in the bs=1 seam; the fused Triton
kernel does it in one, bit-identically, including the padded-row zeroing of
the static req_pool_indices buffer.

Ported: srt/layers/attention/mamba/mamba_state_indices_triton.py (fork path
next to mamba_state_scatter_triton, not kernels/ops/mamba) and the fast path
in _replay_metadata.

Adapted: eligibility is asked per replay (_fused_state_indices_ok) instead of
cached at init, so a pool rebinding cannot leave a stale answer, and it also
requires get_mamba_indices to be the base flat gather (the kernel reads
req_index_to_mamba_index_mapping directly). Unified pool (non-identity v2p
translate), ReplaySSM (its cursor refresh reads the gathered ids) and
non-CUDA devices keep the reference chain.

Not ported (not applicable to DFLASH on this line):
- update_verify_buffers_to_fill_after_draft: tree verify (topk > 1) only;
- KDA needs_cpu_seq_lens: no KDA model here;
- eagle_utils assign_extend_cache_locs_uniform_func: EAGLE prepare_for_verify;
  DFLASH computes its verify cache locs in its own Triton prepare_block.

Tests (CPU, incg cgroup):
test/registered/unit/layers/attention/test_fused_replay_state_indices_32219.py
- the production kernel under TRITON_INTERPRET vs the reference chain over a
  bs x num_padding matrix (8 sizes incl. non-powers of two, 2 seeds): state
  indices, returned view, req_pool_indices side effect, guard tails -- all
  bit-identical;
- eligibility: static hybrid pool on CUDA -> fast path; unified translate,
  overridden gather, ReplaySSM, CPU device, foreign pool -> reference chain.
3 passed. Mutant (padded-row zeroing removed): bit-identity test red.
Metal: test/registered/attention/unittests/gdn/test_triton.py (cuda-graph
decode + verify cases) needs a GPU.
efschu pushed a commit to efschu/htsglang that referenced this pull request Sep 26, 2026
…-prefill-graph(-split/-tiny/-max-prefix), --p-deep-split-from

Picks der 27B-Linie in Reihenfolge (alle Schalter Default aus, P-Env/argv ohne Flag
byte-gleich): upstream-Ports bac77bc (sgl-project#37657) eb6d7d6 (sgl-project#34184) dc9fbf9
(sgl-project#32219 Teil) als Voraussetzung des Prefill-Graphen; 5fd4e77 5d8612b 02e218f
d24a17d 6b24aa6 3e093fe (P-Host-Overlap, #PGAP, P-NOSYNC); d32ddcb fb7ea2b
37ea1db 3e6ce57 (P-Prefill-Graph); 735db6a (+ 4e03821 als reine Verschiebung
durch die Auflösung erledigt) f49f2fd 51e39d4 dc128e3 18639ea.

Konfliktauflösungen:
- scheduler_pp_mixin: NF H49 PP-HOST-PERIOD und 27B P-HOST-OVERLAP komponiert (die im
  Inventar genannte Doppel-Instrumentierung): H49 note_launch/note_no_batch/note_sync
  bleiben, der d2h-Wait steht zusätzlich im #PGAP-Span, deferred publish + Lead-Bound
  nach dem Launch wie 27B. Beide Instrumente getrennt schaltbar (H49-Env / --p-host-overlap).
- unified_radix_cache: Chunk-Publish unter H2-sync_trace UND #PGAP-Span.
- launcher common_flags: p_chunked_prefill_tokens() = Graph-Bucket oder
  P_CHUNKED_PREFILL_TOKENS (NF-Env, Default = Konstante; 27B byte-gleich).
- argv_p: NF p_micro_batch_flags + 27B p_prefill_graph_flags() vor extra/H25-Strip.
- solve_p_cut: prefill_graph_pool_mib neben NF sgl-project#114 activation_reserve.
- --d-replayssm-spec der 27B-Hunks nicht doppelt registriert (NF-Form bleibt).

Tests (test27b.sh): 20 portierte Testdateien 204 passed, 2 skipped;
test_weg2_vision_prefill_graph_seam_0924 nicht gelaufen (Boot aktiv, incg-Schlange),
nachzufahren. dup_defs_gate: 0 neu.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

jit-kernel 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) speculative-decoding user-tps

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants