Repository navigation
[DCP] Support decode context parallelism on the trtllm_mla decode path - #33926
Conversation
1f4ce86 to
f54f050
Compare
dff0648 to
887e760
Compare
|
@kpham-sgl @thanhhao98 @merrymercy — can you guys take a look at this when you get a chance? and add the This PR adds DCP support to the Two correctness bugs turned up on during the way and are fixed here: the decode LSE was being rebased to base-2 a second time on trtllm-gen, and the fused bf16 KV-write lands on a row the DCP page table never points at. |
dff0648 to
197f35c
Compare
|
@kpham-sgl — I just saw your #34240 from a few days ago: rebased onto That PR moves the DCP LSE base out of the backends and onto the merge site: I've dropped mine in favour of the merge-site convention. Carrying both would have meant two registries for one correction, and the in-backend rebase would have re-entered the very double-rebase
That file was also the only conflict in the rebase. I'm re-running |
|
@kpham-sgl @thanhhao98 @merrymercy — following up with the numbers I promised above, now that the branch is rebased onto Two things here: the GSM8K arm that the #34240 conflict resolution actually decides, and a re-run of the full performance sweep on the rebased branch. GSM8K —
|
| flexible-extract | strict-match | |
|---|---|---|
dcp_size=1 |
0.3700 ± 0.0279 | 0.3667 ± 0.0279 |
dcp_size=8 |
0.3533 ± 0.0276 | 0.3500 ± 0.0276 |
The point of this arm is that a wrong LSE base is not a subtle failure. Getting it wrong scales the cross-rank merge weights by log2(e), which corrupts every merged attention output — accuracy collapses rather than drifting. Landing 1.7 points from the dcp_size=1 baseline is the signal that cutedsl_mla is now correctly picking up base-e at the merge site with no backend-side rebase.
On the gap itself: it's exactly 5 questions of 300, the same 5 in both metrics, against a ±2.8 point standard error. DCP also changes the order of the cross-rank reduction, so a handful of borderline generations flipping is expected. To be clear about what this does and doesn't establish — it rules out a broken merge, but at n=300 it would not resolve a small real regression. Happy to run the paired per-question comparison at full gsm8k if you'd like that tightened.
Performance — TP vs DCP4 vs DCP8, re-run post-rebase
trtllm_mla, DeepSeek-V2-Lite, B200x8, TP8, dcp_comm_backend=ag_rs, ISL 32K/64K/128K/256K, OSL 1K, concurrency 1→64.
DCP costs throughput at low concurrency, where the allgather and LSE merge aren't amortized, and wins once there is enough work to hide them. Both the entry cost and the crossover point improve monotonically with context, as the panels above show.
The clearest evidence for the capacity argument is where the TP baseline stops scaling. At 128K, TP flattens from cc=16 onward (647 → 682 → 667 tok/s) because it has run out of KV cache and is queueing rather than serving, while DCP8 keeps climbing (891 → 1034 → 1131). Same at 256K: TP pins at ~288 tok/s from cc=16, DCP8 goes 402 → 428 → 439. Removing that ceiling is the point of the feature, and it's visible directly in the sweep.
Repro
Branch 197f35c, container lmsysorg/sglang:nightly-dev-20260812-c7c03ec5, B200x8, --tp-size 8 --dcp-size {1,4,8} --attention-backend trtllm_mla --mem-fraction-static 0.85 --max-running-requests 256 --cuda-graph-max-bs-decode 256 --chunked-prefill-size 32768 --disable-radix-cache --random-seed 0 (page_size resolves to 64 on its own for trtllm_mla). The 256K arms need SGLANG_ALLOW_OVERWRITE_LONGER_CONTEXT_LEN=1 and --context-length 264192, since 256K exceeds V2-Lite's native 163840.
Could someone add the run-ci label? Only blackwell is on the PR right now, so CI hasn't run against the rebased branch yet.
|
/tag-and-rerun-ci |
|
@kpham-sgl could you pls help to review this pr too, thanks! |
|
@qtris123, could you please verify this again with tokenspeed + cutedsl and confirm that the accuracy is still good |
197f35c to
46c321c
Compare
|
@thanhhao98 — re-verified with GSM8K — DeepSeek-V2-Lite, B200x8, TP8, 5-shot, 300 questions
Both backends land within one standard error of their own Performance — TP vs DCP4 vs DCP8Same sweep as the
Same shape as ReproSame setup as the |
|
/tag-and-rerun-ci |
3d4a39c to
a0e1936
Compare
There was a problem hiding this comment.
Gate and counter sizing look right; one issue in the comments.
For DCP draft-extend proper the blocker is routing, not kernels: draft_utils.py L126 sends cutedsl_mla draft-extend to trtllm-gen, which flashinfer won't allow enable_dcp on. Nothing in CI covers trtllm_mla + DCP decode either.
(from Claude)
Review feedback on sgl-project#33926. The draft_extend_v2 branch put the global lengths in seq_lens_k, which every reader treats as rank-local, and never wrote global_seq_lens_k at all; init_forward_metadata skipped the same derivation for that mode. Both now match the branches beside them. The page table is rank-local in every mode, so the kernel was handed a global length against a table covering only this rank's slice.
|
@qtris123 can you resolve conflicts? |
…family The DCP metadata this test covers is kernel-agnostic and is about to move from TokenspeedMLABackend onto the shared TRTLLMMLABackend parent, so the test stops being tokenspeed-specific. Pure rename; the contents change in the next commit.
trtllm_mla had no DCP decode path: forward_decode used global sequence lengths and a global page table and returned a bare tensor, while the model under DCP expects a rank-local (out, lse) pair to merge across ranks. Since trtllm_mla is the auto-selected attention backend for DeepseekV3ForCausalLM on sm100, --dcp-size > 1 on Blackwell reached it without a guard. flashinfer only implements in-kernel DCP for the cute-dsl MLA kernel and rejects enable_dcp=True for every other backend, but a q_len == 1 decode does not need it. The kernel-side DCP arguments exist so a kernel can resolve a per-query global causal bound, which only varies when q_len > 1; with a single query token the cyclic owner rule already selects exactly the causally visible prefix, so rank-local lengths plus a rank-local page table fully describe the shard. trtllm-gen already supports return_lse, which is the remaining piece. The DCP metadata plumbing was duplicated between cutedsl_mla and tokenspeed_mla and is kernel-agnostic, so hoist it onto TRTLLMMLABackend and let all three share it. Speculative decoding under DCP still needs the global causal bound and stays rejected, now with an error that names the reason. Roadmap item: sgl-project/sglang issue 29736 (trtllm_mla decode path); related to issue 26432.
The DCP decode path rebased the kernel LSE from natural log to base-2 on the assumption that trtllm-gen, like cute-dsl, emits natural log. Measured on B200/SM100 with flashinfer 0.6.15.post1 against a torch.logsumexp reference, trtllm-gen already emits base-2: median lse/ln_ref = 1.442695 = log2(e), and the rebased reference matches to 4e-6. The rebase was therefore applying log2(e) a second time, inflating every LSE by ~44% and corrupting the cross-rank merge while each rank stayed individually correct. flashinfer's own trtllm-gen MLA test asserts only the LSE dtype, shape and finiteness, never its value, so no upstream test would have caught this. The base is also per instance rather than per class: TRTLLMMLABackend takes ``backend`` as a constructor argument and CuteDslMLABackend constructs it with "cute-dsl", so a class attribute cannot express both. Resolve it from a backend -> bool mapping in __init__ instead, defaulting to no rebase.
…de head count Under DCP the decode kernel runs on the query all-gathered across the DCP group, so it sees attn_dcp_size x this rank's heads: the model builds attn_mqa_for_dcp_decode with num_local_heads * attn_dcp_size, and the flashinfer MLA backend scales its head count the same way. TRTLLMMLABackend did not, and num_q_heads sizes the persistent multi-CTA KV counter buffer handed to the kernel, leaving it a factor of attn_dcp_size too small under DCP. Size that allocation from the decode head count instead. This is a latent out-of-bounds write rather than the cause of the current dcp_size=2 accuracy gap: a parity run with this fix applied was byte-identical to the run without it, so the remaining error is elsewhere.
set_mla_kv_concat_q takes no dcp_world_size/dcp_rank, unlike its fp8 sibling set_mla_kv_concat_q_fp8. Under DCP it therefore writes the KV row at the raw VIRTUAL out_cache_loc from every rank, while the reader create_mla_kv_page_table_for_dcp computes virtual_locs // DCP_SIZE // PHYSICAL_PAGE_SIZE and expects the compacted row written only by the owning rank. The fused write lands where no page table entry points and the page table points at rows nobody wrote, so each rank decoded correctly over corrupt KV. This, not the cross-rank merge, was the cause of the dcp_size=2 accuracy gap. An in-server check of the rank-local output against a torch reference passed on both ranks precisely because it read the same corrupt slots the kernel did. Fall back to the pool's DCP-aware set_mla_kv_buffer plus concat_mla_absorb_q_general when DCP is on. dcp_enabled is dcp_size > 1, so this is a no-op at dcp_size == 1 and the non-DCP fast path is untouched. Measured on 2xB200, DeepSeek-V2-Lite tp2, CUDA graph on. GSM8K over the full 1319 problems: dcp_size=1 scores 0.3806 +/- 0.0134, dcp_size=2 scores 0.3692 +/- 0.0133 -- a 1.14pp gap against a 1.89pp standard error on the difference (z = 0.60), so no detectable regression. Throughput at isl 4096 / osl 256 costs 9-19% output tok/s versus dcp_size=1; a control run at dcp_size=1 with the fused path forced off is marginally faster than stock, so the gate itself is free and the gap is DCP's own communication cost. The kernel gap is worth closing upstream: set_mla_kv_concat_q should either take dcp_world_size/dcp_rank like the fp8 variant or refuse under DCP, rather than silently writing to the wrong row.
…the base at the merge site Obsoletes 2e5e123 ("[DCP] Fix the decode LSE base for trtllm-gen; resolve it per backend"), which is superseded by the merge-site LSE convention that landed upstream in sgl-project#34240. 2e5e123 fixed a real bug: the decode LSE was rebased by log2(e) unconditionally, which is right for cute-dsl (natural log) but corrupts trtllm-gen, which already emits base-2. It fixed it inside the backend, resolving the base from a registry keyed on the flashinfer kernel string ("trtllm-gen" / "cute-dsl"). native LSE and the merge site decides, keyed on the sglang attention backend name instead: def is_mla_dcp_lse_base_on_e(attention_backend): return attention_backend in {"flashmla", "cutedsl_mla"} Keeping both would leave two registries for one correction, and the rebase in _run_decode_kernel would re-enter the very double-rebase 2e5e123 removed as soon as a cute-dsl call reached the base hook with return_lse=True. So drop the backend-side mechanism; the merge-site convention already gives the right answer across the family: - trtllm_mla -> merge assumes base-2; trtllm-gen emits base-2. - cutedsl_mla -> merge assumes base-e; cute-dsl emits natural log, and sgl-project#34240 removed its own rebase. - tokenspeed_mla -> merge assumes base-2; unaffected, it never passed a flashinfer backend string so it never rebased. _run_decode_kernel keeps only the return_lse passthrough that the DCP decode path needs and otherwise returns the kernel result unchanged, as upstream does.
…rn_lse FlashInfer MoE autotune under DCP overflowed the trtllm-gen workspace because TRTLLMMLABackend lacked Tokenspeed's dummy-run skip. CuteDsl's cp_world<=1 hook also dropped return_lse, so inherited DCP decode would unpack a bare tensor.
CI registration requires a __main__ entry so python3 file.py -f actually runs the cases, and black wanted the dummy-skip call on one line.
Review feedback on sgl-project#33926: drop the trtllm_mla DCP decode hook test, and put the decode layout properties in TestDcpDecodeLayout in test_trtllm_mla_family_dcp_metadata.py rather than adding a standalone file. Only the two properties not already covered are kept: the per-rank lengths summing to the global length, and a decode step growing exactly one rank. The third case duplicated TestGetDcpLens.test_start_none_matches_owner_count, and those two subsume it anyway -- the partition sum pins the base case at zero and the growth check pins rank (L-1) % n at every step, which determines the per-rank counts by induction. The new class sits outside the CUDA skipUnless that guards the metadata cases, since the length math needs no GPU. This does shift the two checks off the base-a CPU shard onto the base-b 4-gpu-b200 suite the file registers for; get_dcp_lens keeps CPU coverage through the existing TestGetDcpLens cases.
Review feedback on sgl-project#33926. The draft_extend_v2 branch put the global lengths in seq_lens_k, which every reader treats as rank-local, and never wrote global_seq_lens_k at all; init_forward_metadata skipped the same derivation for that mode. Both now match the branches beside them. The page table is rank-local in every mode, so the kernel was handed a global length against a table covering only this rank's slice.
The q_len / causal_seqs gate let a single-token draft-extend slip through: it reads as q_len == 1 with no causal_seqs but skips the cross-rank merge. Add `not return_lse` so every spec path under DCP is refused, and cover it with the decode-hook refusal tests. See the hook docstring for the rationale.
d46cb16 to
e1e71ee
Compare
|
Rebased onto latest main and resolved the conflict. Although it's small, #35245 touch the DCP decode page-table, I'm running a lightweight B200 checks to verify the changes. |
|
@kpham-sgl I ran a matched pre/post A/B on B200 (DeepSeek-V2-Lite, TP2 dcp2, fp8 KV, ISL 8K / OSL 128), identical config on both sides — only the code and the ABI-matched nightly image differ:
|
|
/rerun-failed-ci |
|
/rerun-test test/registered/dcp/* registered/radix_cache/unified_radix_tree/test_unified_radix_cache_kl_dcp.py |
|
Results for 🚀 🚀 🚀 |
|
/rerun-test test/registered/dcp/test_trtllm_mla_family_dcp_metadata.py |
|
Results for 🚀 |
Cut the explanatory prose added by this PR down to the invariants a reader would otherwise violate. No executable code changes: the AST of each touched file is unchanged once docstrings are stripped. Kept: the num_decode_q_heads sizing rule, the fused-KV/DCP loc mismatch, the max(local_max, 1) scheduling bound, the neutral (0, -inf) state for ranks owning no slice, and the q_len == 1 justification for the refusal. Dropped: the bulleted walkthrough of the three-clause refusal, the per-test rationale comments whose test names already say it, and the restatements of the global/rank-local hoist repeated at each site. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
The seq_lens_k assignments this comment refers to are the if/elif chain in init_forward_metadata itself, not a superclass -- super() is only called in the else branch, which never reaches the DCP block. The "parent stored" phrasing was correct in cutedsl_mla_backend.py before the hoist, and the previous commit reintroduced it by mistake. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
_call_trtllm_batch_decode_mla() passed return_lse=return_lse to flashinfer's trtllm_batch_decode_with_kv_cache_mla, but never declared return_lse as a parameter -- every call raised NameError. The outer _run_decode_kernel() does declare it but never forwarded it down. This makes trtllm_mla unusable end to end: plain decode, DCP decode, DCP target-verify, draft-extend, and varlen-absorbed prefill all route through this helper. In a PD-disaggregated deployment the crash surfaces on BOTH roles, since prefill's FlashInfer MoE-autotune warmup also drives a decode-shaped dummy forward through the same path -- so neither side of a fresh PD launch reaches "server is fired up". Root cause is a semantic merge conflict, not a defect on either parent: 055bf1c extracted the flashinfer call into this helper (2026-08-20); upstream sgl-project#33926 / f50b4ad later added return_lse=return_lse at the still-inline call site inside _run_decode_kernel, whose signature does declare it (2026-09-01). The two parents of 47ed7ec ("Merge branch 'main' into online_base_0903") are each independently clean under an AST walk; the merge kept the extracted-helper shape from one side and absorbed the other side's added line into it, without carrying over the matching signature change -- producing code that parses and compiles but always raises at runtime. Fix: declare return_lse: bool = False as a keyword-only parameter on _call_trtllm_batch_decode_mla, widen its return annotation to Union[Tensor, Tuple[Tensor, Tensor]] (it already returns a 2-tuple when return_lse=True, which the DCP decode and DCP target-verify call sites already unpack), and forward it from _run_decode_kernel. The two subclass overrides (cutedsl_mla, tokenspeed_mla) already declare return_lse in their own signatures and cutedsl already forwards it through super(), so neither needs a change -- they were only broken by inheriting this base helper. Verified via AST walk over the full tree: 1 unbound return_lse read before this change, 0 after; every call site's kwargs checked against the helper's actual signature; py_compile clean. Not verified against a live flashinfer/GPU run from this environment.
sgl-project#33926) Co-authored-by: kpham-sgl <[email protected]> Co-authored-by: Claude Opus 5 (1M context) <[email protected]>



Motivation
Draft for the unassigned
trtllm_mladecode path item in the DCP roadmap #29736 (also relevant to #26432).trtllm_mlahas no DCP decode path.forward_decodebuilds its page table andseq_lensfrom the global sequence lengths and returns a bare tensor, while under DCP the model routes decode throughattn_mqa_for_dcp_decodeand expects a rank-local(out, lse)pair. The DCP code already intrtllm_mla_backend.pycovers only speculativetarget_verify, and delegates to_run_decode_kernel, which the base rejected — only thecutedsl_mla/tokenspeed_mlasubclasses served it.This is reachable without asking for it:
arg_groups/overrides.pyauto-selectstrtllm_mlaon sm100 forDeepseekV3ForCausalLM, andforward_mla.pyroutes decode toattn_mqa_for_dcp_decodewheneverget_parallel().dcp_enabledis set, regardless of backend.The approach, and its main assumption
flashinfer implements in-kernel DCP only for the CuTeDSL MLA kernel and rejects it elsewhere (
_validate_mla_dcp_argsinflashinfer/mla/_core.py), so spec-decode × DCP ontrtllm_mlais blocked upstream and stays rejected here.The assumption this draft rests on is that a
q_len == 1decode does not need it:cp_world/cp_rank/causal_seqlens_kv_globalexist so a kernel can resolve a per-query global causal bound, and that bound only varies across query rows whenq_len > 1. With a single query token the cyclic owner rule should already select exactly the causally visible prefix, leaving the rank-local page table andseq_lenssufficient.trtllm-genalready supportsreturn_lse.Modifications
TRTLLMMLABackend. The rank-local length and page-table helpers were duplicated betweencutedsl_mla_backend.pyandtokenspeed_mla_backend.py; both carried a TODO to collapse them into the base. They are kernel-agnostic, so the base now owns them and both subclasses define only their kernel call and decode forward. Every branch is a no-op when DCP is off._run_decode_kernel: forwardsreturn_lse, and narrows the blanketcp_world > 1 or return_lserefusal tocp_world > 1 and causal_seqs is not None— callers needing a global causal bound signal it by passingcausal_seqs.forward_decode: new_forward_decode_dcpreturns the rank-local(out, lse), withfixup_zero_kv_rowsneutralizing ranks owning no slice of a request.__init__from abackend -> boolmapping rather than a class attribute.TRTLLMMLABackendtakesbackendas a constructor argument andCuteDslMLABackendconstructs the parent with"cute-dsl", so one class drives either kernel and a class attribute cannot express both:trtllm-genemits base-2 and needs no rebase,cute-dslemits natural log and does.set_mla_kv_concat_qtakes nodcp_world_size/dcp_rank, unlike its fp8 siblingset_mla_kv_concat_q_fp8, so under DCP it writes the KV row at the raw virtualout_cache_locfrom every rank — while the readercreate_mla_kv_page_table_for_dcpcomputesvirtual_locs // DCP_SIZE // PHYSICAL_PAGE_SIZEand expects the compacted rowloc // dcp_size, written only by the owning rank. The two disagree, so the fused write lands where no page table entry points. DCP runs now fall back to the pool's DCP-awareset_mla_kv_bufferplusconcat_mla_absorb_q_general.dcp_enabledisdcp_size > 1, so this is a no-op atdcp_size == 1and the non-DCP fast path is untouched.get_parallelin the tokenspeed module, which the hoist would otherwise have bypassed.Accuracy Tests
Metadata regression check (B200)
The DCP metadata tests pass on hardware for all three backends —
TRTLLMMLABackend,TokenspeedMLABackend,CuteDslMLABackend— andtest_dcp_layout_unit.pypasses identically on this branch and on its merge base. So the hoist does not change metadata behaviour for the two backends that already had working DCP, which was the main regression risk.The decode path, end to end (B200)
GSM8K via lm-eval, full 1319 problems, 5-shot, greedy.
deepseek-ai/DeepSeek-V2-Litewith--tp-size 8on 8×B200,--attention-backend trtllm_mla, CUDA graph on, servers identical apart from--dcp-size:dcp_size=1dcp_size=8Both columns score the same generations with different answer extractors: strict-match requires the canonical
#### <number>ending that the few-shot prompt demonstrates, while flexible-extract accepts the last number appearing anywhere in the output. The gap between the two reflects formatting compliance rather than reasoning.Speed Tests and Profiling
DeepSeek-V2-Lite on 8×B200,
--attention-backend trtllm_mla,--dcp-comm-backend ag_rs,--tp-size 8in every arm with--dcp-size1 / 4 / 8 — so all three arms use the same 8 GPUs and differ only in whether the KV cache is sharded across them. aiperf, synthetic, OSL 1024, concurrency 1–64, ISL 32K / 64K / 128K / 256K,--disable-radix-cache,--mem-fraction-static 0.85, CUDA graph on.Each point is one concurrency level, labelled on the marker; concurrency rises up and to the left. Left axis is per-GPU throughput, right axis the same curve as a total across the 8 GPUs.
DCP trades an all-gather plus reduce-scatter per decode layer for an N-way reduction in the KV bytes each rank reads per decode step. That trade is a loss at low concurrency, where the collective is pure overhead, and a win once there is enough KV traffic to amortize it — so the arms cross, and the crossing moves to lower concurrency as context grows: between concurrency 8 and 16 at 32K, 4 and 8 at 64K, 2 and 4 at 128K, and below 1 at 256K, where DCP leads at every level measured. At concurrency 64,
dcp_size=8is +57% at 32K, +57% at 64K, +68% at 128K and +52% at 256K.The other effect visible here is TP running out of KV capacity: at 128K and 256K the
dcp_size=1curve turns horizontal at the left, meaning added concurrency buys latency cost with no throughput in return. Numerically it goes 648 → 681 → 673 output tok/s across concurrency 16/32/64 at 128K, and is flat at ~286 from concurrency 16 onward at 256K. Both DCP arms are still climbing at concurrency 64 in every panel, so these are a lower bound on the gap rather than a measured saturation point.Raw per-point numbers are in the CSV behind this plot and can be posted on request.
Control for the fused-KV gate
The gate added in Modifications removes the fused bf16 KV-write from DCP runs, so a plain DCP-vs-TP comparison would otherwise charge DCP for that change. Running
dcp_size=1with the fused path forced off (isl 4096 / osl 256,--tp-size 2on 2×B200) shows it is worth nothing at this shape:dcp_size=1dcp_size=1, fused KV-write forced offThe control arm is marginally faster than stock, i.e. inside run-to-run noise. So the gate itself is free, and the DCP deltas above are DCP's own communication cost rather than an artifact of that code change.
Caveats
DeepSeek-V2-Liteis the smallest MLA model available, which maximises KV pressure per unit of compute but also makes the decode step cheap, so the per-layer collective is a larger share of the step than it would be on a production-scale MLA model. If anything this understates DCP.ag_rsonly;a2ais not covered.Checklist
CI States
Latest PR Test (Base): ❌ Run #33453586250
Latest PR Test (Extra): ⏳ Run #33466531470
Latest PR Test (AMD ROCm 7.2): 🚫 Run #33453586243