Repository navigation
[ROCm] Support decode context parallel (DCP) for GLM-5 / DeepSeek-V3.2 - #42618
EricKing626 wants to merge 18 commits into
Conversation
8a07e5d to
42cb8a8
Compare
…k-V3.2 The DSA backend had no DCP path, so DSA models could not shard the KV cache across the DCP group. Reuse the existing DCP plumbing (widened allocator owner rule, Q all-gather, LSE merge) and add the DSA pieces: - Writes: MLA fp8 KV and indexer K only land on the owner rank. - Indexer decode: score the local index-K shard, take a local top-k and all-gather (score, global position) candidates to merge the global top-k. - Indexer prefill: rebuild the full-sequence index K from the shards. - Sparse decode: keep the owned top-k slots, attend with mla_gluon_decode and return the natural-log LSE for the cross-rank merge. - Sparse prefill: attend the all-gathered dcp_kv_buffer. - Disable fused top-k, the tilelang fused rope+cache path and MHA one-shot prefill under DCP; they assume the full KV is local. Scope: ROCm, qlen=1 decode; speculative decoding, hisparse and index kpool are rejected for now.
…ange, custom-AG LSE merge - Sparse decode under DCP uses the Triton split-K kernel instead of mla_gluon (mla_gluon asserts min_kv_seq_len > 784 and DCP shards are short). The reduce kernel optionally writes the natural-log LSE (STORE_LSE). - Owned slots are compacted to the front (dcp_compact_owned_slots) and the split kernel bounds its tiles by the per-row owned count. - dcp_exchange_topk: fused pack / merge Triton kernels; the global merge uses the DSA topk_func instead of torch.topk; gather as fp32 so ROCm takes the custom all-gather. - dcp_a2a_lse_reduce: on ROCm use the custom all-gather instead of RCCL a2a. - Add test/registered/dcp/test_dcp_dsa_unit.py.
42cb8a8 to
ab07236
Compare
…exer, owned top-k + LSE merge DCP prefill used to gather the whole KV and run absorbed MLA on every rank. Three changes, chosen per batch: - Short prompts (kv_len <= SGLANG_DSA_PREFILL_DENSE_ATTN_KV_LEN_THRESHOLD) take the MHA one-shot path under DCP too; the prefix comes through all_gather_kv_cache_for_mha_extend, which dequantizes the fp8 cache. Absorbed MLA costs ~3.4x the MHA FLOPs per q.k pair, which made short-context TTFT ~3x TP4. - The gathered-KV indexer splits query rows across ranks once the mean key length per query token reaches SGLANG_DCP_DSA_SPLIT_INDEXER_MIN_KV (default 8192): each rank scores 1/W of the rows against the all-gathered index K and the int32 top-k is all-gathered. Shorter batches score every row on every rank. - When the cached prefix is long next to the extend (SGLANG_DCP_DSA_OWNED_PREFILL_RATIO, default 3.0 x gathered heads x extend tokens), prefill runs like decode: each rank scores its own index-K shard, the top-k candidates go through the same exchange and merge as decode (global positions, identical on every rank), and attention reads only this rank's owned slots with an LSE merge (forward_batch.dcp_owned_prefill), so the prefix KV is never gathered. GLM-5.2 MXFP4, TP4 + DCP4 on MI355X: GSM8K 0.933, passkey 9/9 (8K-76K); with every prefill forced onto the owned path (ratio 0, dense threshold 0) GSM8K 0.924, passkey 9/9. Short extend on a cached 16K-128K prefix: 182-308 ms TTFT.
… target; HiCache with MTP DSA + DCP rejected speculative decoding. Chain EAGLE/NEXTN (--speculative-eagle-topk 1) now runs with the draft inheriting the target's DCP layout, as in vLLM: - The DSA draft KV pool shards like the target (KVCacheConfigurator.loc_space_scale is 1 for it), so it is 1/W the size of a replicated draft and its writes take the owner rule. - Draft prefill, draft decode and their CUDA graphs reuse the DCP prefill and decode paths. TARGET_VERIFY and DRAFT_EXTEND_V2 rows are one query per draft token, so the indexer exchanges top-k candidates and forward_extend attends this rank's owned slots and LSE-merges them like decode (is_dcp_mla_decode_phase includes DRAFT_EXTEND_V2). - The draft runner's extend and multi-step backends are bound to its KVIndexTranslator; the DCP planner reads it through get_attn_backend(). - MTP IndexShare (index_share_for_mtp_iteration) is off under DCP: each rank holds only its owned share of the top-k. - HiCache + DCP accepts EAGLE/NEXTN on DSA models; the draft packs into the target's host rows. The DSA indexer host pool pages the widened transfer indices (logical_page_size), which previously addressed index-K pages W times too far and faulted once slots passed the per-rank capacity.
The aiter custom all-gather moves W x the bytes the merge needs; it only wins while the exchange is latency bound. Above SGLANG_ROCM_DCP_LSE_AG_MAX_BYTES (default 1 MiB per rank) use the byte all-to-all, which is 2-3x faster at bs 32-64 verify sizes.
Drop SGLANG_ROCM_DCP_LSE_AG_MAX_BYTES and the ROCm custom all-gather branch; the LSE merge now always uses the byte all-to-all, which moves 1/W of the bytes the all-gather did.
…ens / tables DcpStep localizes out_cache_loc once per forward (target and draft) and memoizes the per-rank lens and index block tables, instead of recomputing them in every layer.
With kv_splits == 1 and return_lse the split partial already is the final result; write it and the natural-log LSE directly instead of round-tripping through the split-K workspace and the reduce kernel.
Gate the shared-file changes on DSA so dense MLA + DCP behaves as before: - is_dcp_mla_decode_phase takes use_dsa; draft extend and owned prefill count as the decode phase only for DSA attention. - The EAGLE v2 draft binds its swapped-in backends to the KV index translator only for a DSA draft under DCP. - dcp_forward_scope opens only for DSA models (target and NextN draft).
|
/rerun-failed-ci |
Jacob0226
left a comment
There was a problem hiding this comment.
The DSA+DCP algorithm and the measurements are clear. Three things block merging: (1) the new platform check and the draft-sharding predicate are not HIP-scoped, which breaks the existing NPU DSA+DCP path (#37787); (2) none of the new Triton kernels or the triton_sparse_mla_decode_splitk LSE/length paths run in CI; (3) per-forward state sits in a module global instead of attn_dcp_metadata. Details inline. The description still mentions SGLANG_ROCM_DCP_LSE_AG_MAX_BYTES, which 2546a14 removed.
PR body — Speed Tests and Profiling (non-blocking)
The Speed Tests table mostly shows DCP's cost, because the TP4 KV pool is not under pressure at those points. Your agentic benchmark shows DCP4 ahead of TP4 once concurrency goes above 16, which is the case this PR is for. Could you plot those results on InferenceX Curve and paste the chart here? It shows the high-concurrency benefit at a glance.
| if is_deepseek_dsa(hf_config) and getattr(cfg, "dcp_size", 1) > 1: | ||
| # DSA + DCP covers ROCm decode and chain EAGLE/MTP on the plain DSA | ||
| # pool; the draft shards its KV like the target. | ||
| if not get_platform().is_hip: |
There was a problem hiding this comment.
This rejects DSA + --dcp-size > 1 on every non-HIP platform, but NPU already supports DCP for DSA models only (#37787; model_hook.py raises for non-DSA NPU DCP). With this change NPU DSA+DCP no longer starts, and no CI job covers it. Scope the whole block, including the EAGLE-topk and hisparse checks, to get_platform().is_hip, and keep rejecting CUDA explicitly. Please also add an override_platform(is_npu=True) + DSA + dcp_size=4 case to test_deepseek_family_order_safe_declarations.
| def loc_space_scale(self) -> int: | ||
| dcp_size = get_parallel().attn_dcp_size | ||
| return dcp_size if (self.is_draft_worker and dcp_size > 1) else 1 | ||
| replicated_draft = self.is_draft_worker and not is_deepseek_dsa( |
There was a problem hiding this comment.
is_deepseek_dsa alone switches the draft to sharded on every platform. NPU's DSA draft is still replicated (AscendAttnBackend skips DCP when is_draft_worker), so its pool shrinks to 1/W while it indexes widened locs raw. The same unscoped predicate appears in resolve_hicache_dcp_compatibility, EAGLEWorkerV2.init_attention_backend and _init_dsa_index_share_state. Suggest one helper, e.g. dsa_draft_shards_under_dcp(hf_config) = HIP and DSA and dcp_size > 1, used at all four sites.
| from sglang.test.ci.ci_register import register_cpu_ci | ||
| from sglang.test.test_utils import CustomTestCase | ||
|
|
||
| register_cpu_ci(est_time=5, suite="base-a-test-cpu") |
There was a problem hiding this comment.
Registered on base-a-test-cpu, so every skipUnless(torch.cuda.is_available()) case is skipped in CI, and no CI run covers the new Triton kernels. Suggest two GPU files. Put dcp_compact_owned_slots and dcp_topk_pack/dcp_topk_merge (index math, any HIP GPU) on stage="jit-kernel-unit", runner_config="amd". Put triton_sparse_mla_decode_splitk(lengths=, return_lse=), including the one-split direct store, on stage="stage-b", runner_config="1-gpu-small-amd-mi35x", because the deployed fp8 path is optimize_gfx950_fp8. Compare out and LSE against a torch reference.
| return out | ||
|
|
||
|
|
||
| _STEP: Optional[DcpStep] = None |
There was a problem hiding this comment.
Per-forward state lives in a module global, opened by dcp_forward_scope and found again by tensor identity (_root, data_ptr, hit[0] is src). It also makes mem_cache/memory_pool.py import a DSA layer module. Per-forward DCP state already lives on forward_batch.attn_dcp_metadata, and this PR adds dsa_page_table_1 there. Could the localized loc, local lens, block tables and the dcp_owned_prefill/dcp_split_indexer flags live there too? That also removes the forward/_forward split in DeepseekV2Model.
| from sglang.srt.runtime_context import get_parallel | ||
|
|
||
|
|
||
| def _localize(loc: torch.Tensor) -> torch.Tensor: |
There was a problem hiding this comment.
This is a fourth copy of the owner rule. layout.remap_dcp_sparse_indices (NPU DSA) already has this contract: keep owned slots, map them to local rows, preserve score order, pad with a -1 tail. _set_mla_kv_buffer_impl resolves DCP_WORLD_SIZE/DCP_RANK inside the kernel. Suggest putting the Triton compact behind remap_dcp_sparse_indices, and passing dcp_world_size/dcp_rank to set_mla_kv_buffer_triton_fp8_quant like set_mla_kv_buffer_dcp_sharded_triton does, instead of a separate torch.where localize.
| local_logits, (0, topk - local_logits.shape[1]), value=-float("inf") | ||
| ) | ||
| local_idx = topk_func(local_logits, local_lens, topk) | ||
| if local_logits.is_cuda: |
There was a problem hiding this comment.
The non-CUDA branch runs only in tests, and it is a different algorithm (torch.topk, permute layout) from the dcp_topk_pack/dcp_topk_merge path that runs in production. So the CPU tests verify the fallback, not the shipped code. Drop the branch and cover the GPU path (see the test comment), or move the reference into the test.
| if get_parallel().dcp_enabled and not forward_batch.forward_mode.is_idle(): | ||
| if q_all is None: | ||
| q_all = torch.cat([q_nope, q_rope], dim=-1) | ||
| return self._forward_decode_dcp(q_all, kv_cache, page_table_1, layer) |
There was a problem hiding this comment.
Triton is the ROCm default, so this is fine by default. But an explicit --dsa-decode-backend aiter or tilelang is silently replaced by Triton split-K under DCP, because this returns before the dsa_impl dispatch. Please raise in _check_dsa_backend_constraints (it already takes dcp_size) when HIP + dcp_size > 1 and the decode backend is not triton.
TboForwardBatchPreparer.filter_batch walks every ForwardBatch field and rejects the ones it does not handle. A bool field is never None, so dcp_owned_prefill / dcp_split_indexer broke test_tbo_filter_batch_marker at their default value. They are per-batch DSA attention state, so keep them on the backend next to use_mha, which set_dsa_prefill_impl already resets on every call. Readers outside the backend go through dcp_dsa_owned_prefill() and dcp_dsa_split_indexer().
…atch" This reverts commit 1c7cf5c. The next commit carries the flags through TBO filter_batch instead, next to reuse_dsa_topk_indices, which is the same kind of forward-level DSA flag. That keeps the flags on ForwardBatch, where a per-batch value does not depend on the backend resetting instance state every forward.
ForwardBatch.dcp_owned_prefill and dcp_split_indexer default to False, not None, so filter_batch's completeness guard rejected every TBO split (test_tbo_filter_batch_marker failed on all cases). Both flags record the prefill path chosen once per forward; the TBO children run the same forward, so they inherit the parent's values like reuse_dsa_topk_indices.
DeepseekModelNextN.forward now reads self.decoder.self_attn.use_dsa to open the DCP forward scope. The mock model in test_deepseek_nextn_mm_embed had no decoder, so forward raised AttributeError before embedding; the test swallows forward errors, so test_no_mm_falls_back_to_embed_tokens saw no embed_tokens call and test_mm_sentinel_ids_do_not_cause_oob passed without checking anything. Add a non-DSA decoder to the mock.
forward_decode returns into _forward_decode_dcp before the dsa_impl dispatch, so an explicit --dsa-decode-backend aiter or tilelang was silently replaced by the Triton split-K kernel whenever --dcp-size > 1. Triton is the ROCm default, so the default config is unaffected. Raise in _check_dsa_backend_constraints, which already takes dcp_size.
NPU already runs DCP for DSA models (model_hook rejects it for every other architecture), and its draft keeps allocator-global cache slots and takes the non-DCP attention path. Two changes made that configuration ours: - The DSA + --dcp-size > 1 block rejected every non-HIP platform, so NPU no longer started. Reject CUDA, let NPU through, and keep the EAGLE and hisparse limits for HIP, where they come from. - loc_space_scale switched the draft to sharded on is_deepseek_dsa alone, so the NPU draft pool shrank to 1/W while it still indexed widened locs raw. Same unscoped predicate in the HiCache check, the EAGLE backend bind and the MTP index-share state. All four now go through dsa_draft_shards_under_dcp(hf_config, dcp_size).
|
|
Our GLM-5.2 PD audit found that the local split-indexer series (D14/D15/D18/D24/D30/D31) overlaps the local-top-k/all-gather/global-merge direction here. We will coordinate here rather than file a competing implementation. Historical isolated We opened separate, draft current-main candidates for pieces outside this PR's transport scope:
The local D26 change only suppresses an idle-rank Known limits: DP2×DCP2 graph outputs in the archived stack were still garbled and unbisected. Historical serving throughput used simulated MTP acceptance; no stack throughput is claimed as evidence for these patches. The October 27 PP-overlap/custom-all-reduce bisect also prevents using later combined-stack speed as patch-correctness evidence. |

[DSA][ROCm] Support decode context parallel (DCP) for GLM-5 / DeepSeek-V3.2
Motivation
Under pure TP, every rank of an MLA model stores a full copy of the KV cache. Decode context parallel (
--dcp-size) shards tokens across ranks to remove that duplication. SGLang already supports DCP for dense MLA, but not for DSA models: GLM-5 and DeepSeek-V3.2 run on thedsabackend, which has no DCP path.DSA picks the top 2048 tokens of the whole sequence before attention. Under DCP this adds three problems:
With this PR, each rank stores 1/W of both caches, in decode, prefill, MTP speculative decoding and HiCache. The algorithm reuses SGLang's existing DCP plumbing.
Modifications
The DSA-specific logic is in a new
layers/dcp/dsa.pyand a few Triton kernels inkernels/ops/attention/dcp_kernels.py. Other files get small hooks.slot % W == rank). The local write location, the per-rank sequence lengths and the local index-K block table are derived once per forward and shared by all layers.SGLANG_ROCM_DCP_LSE_AG_MAX_BYTES), and with an RCCL all-to-all above that.kv_len <= SGLANG_DSA_PREFILL_DENSE_ATTN_KV_LEN_THRESHOLD) use MHA one-shot on the all-gathered, dequantized prefix.SGLANG_DCP_DSA_SPLIT_INDEXER_MIN_KV(8192), each rank scores 1/W of the query rows and the int32 top-k is all-gathered.SGLANG_DCP_DSA_OWNED_PREFILL_RATIO, 3.0 × gathered heads × extend tokens), prefill runs like decode: owned top-k plus LSE merge, and the prefix KV is never gathered.--speculative-eagle-topk 1): the draft shards its KV like the target, so its pool is 1/W the size of a replicated draft. Draft prefill, draft decode and their CUDA graphs reuse the DCP prefill and decode paths. Target verify and draft extend run one query per draft token through the owned top-k plus LSE merge path. MTP IndexShare is off under DCP, because each rank holds only its owned share of the top-k.test/registered/dcp/test_dcp_dsa_unit.py,test/registered/dcp/test_dcp_layout_unit.py.Supported scope: ROCm,
interleave_size=1, HiCache without an L3 storage backend. Rejected for now:--speculative-eagle-topk > 1, other speculative algorithms,--enable-hisparseand index kpool.Accuracy Tests
GLM-5.2-MXFP4 on MI355X, fp8 KV cache. MTP uses 5 steps and 6 draft tokens.
Speed Tests and Profiling
Agentic test:
Same setup,
--max-running-requests 128, random prompts of fixed length, output length 256. TPUT per GPU = output tokens/s ÷ 4. Interactivity = 1000 / TPOT. TTFT, TPOT and ITL are medians. The TP4 and TP4 + MTP rows come from an earlier session with the same server arguments.Checklist
CI States
Latest PR Test (Base): Not run yet⚠️ Not enabled -- add
Latest PR Test (Extra):
run-ci-extralabel to opt in.Latest PR Test (AMD ROCm 10): ➖ No AMD PR run found for this commit.