diff --git a/python/sglang/srt/layers/communicator.py b/python/sglang/srt/layers/communicator.py index c5e7878cf0..4595c53c86 100644 --- a/python/sglang/srt/layers/communicator.py +++ b/python/sglang/srt/layers/communicator.py @@ -394,6 +394,24 @@ class _LayerModeComputationContext: ) +def sparse_mlp_scatter_mode() -> ScatterMode: + """SCATTERED hands a sparse MLP this rank's own token shard; FULL and + MOE_FULL hand it a buffer gathered over the attn-TP or MoE-CP group.""" + if ( + # Token dispatch/combine will be handled outside of LayerCommunicator for these modes. + not get_moe_a2a_backend().is_none() + or should_use_flashinfer_cutlass_moe_fp4_allgather() + or enable_dwdp() + ): + return ScatterMode.SCATTERED + # DSA CP and MLA CP both don't support MOE_FULL yet; fall back to FULL. + if is_enable_moe_cp_allgather() and not ( + is_dsa_enable_prefill_cp() or is_mla_cp_enabled() + ): + return ScatterMode.MOE_FULL + return ScatterMode.FULL + + @dataclass class LayerScatterModes: layer_input_mode: ScatterMode @@ -423,19 +441,7 @@ class LayerScatterModes: @classmethod def _compute_mlp_mode(cls, context: _LayerModeComputationContext): if context.is_layer_sparse: - if ( - # Token dispatch/combine will be handled outside of LayerCommunicator for these modes. - not get_moe_a2a_backend().is_none() - or should_use_flashinfer_cutlass_moe_fp4_allgather() - or enable_dwdp() - ): - return ScatterMode.SCATTERED - # DSA CP and MLA CP both don't support MOE_FULL yet; fall back to FULL. - if is_enable_moe_cp_allgather() and not ( - is_dsa_enable_prefill_cp() or is_mla_cp_enabled() - ): - return ScatterMode.MOE_FULL - return ScatterMode.FULL + return sparse_mlp_scatter_mode() else: if enable_moe_dense_fully_dp(): return ScatterMode.SCATTERED diff --git a/python/sglang/srt/layers/moe/mega_moe.py b/python/sglang/srt/layers/moe/mega_moe.py index 783ac819ed..31e481aed1 100644 --- a/python/sglang/srt/layers/moe/mega_moe.py +++ b/python/sglang/srt/layers/moe/mega_moe.py @@ -221,7 +221,7 @@ def _run_mega_routed( hidden_states, router_logits, num_token_non_padded=( - forward_batch.num_token_non_padded + forward_batch.moe_num_token_non_padded() if forward_batch is not None else None ), diff --git a/python/sglang/srt/model_executor/forward_batch_info.py b/python/sglang/srt/model_executor/forward_batch_info.py index 57b33faf77..329c47aa33 100644 --- a/python/sglang/srt/model_executor/forward_batch_info.py +++ b/python/sglang/srt/model_executor/forward_batch_info.py @@ -1178,6 +1178,50 @@ class ForwardBatch(ForwardBatchDeepSeekMHAMixin): sharded=sharded, ) + def moe_num_token_non_padded(self) -> Optional[torch.Tensor]: + """Bound for masking a sparse MoE's padded rows, or None when the MoE + input is a gathered buffer whose real rows are not a prefix of it.""" + from sglang.srt.layers.communicator import ScatterMode, sparse_mlp_scatter_mode + + if self.num_token_non_padded is None: + return None + + mode = sparse_mlp_scatter_mode() + if mode == ScatterMode.SCATTERED: + # a2a dispatch, FP4 all-gather and dwdp all route the local shard. + return self.num_token_non_padded + if mode == ScatterMode.MOE_FULL and self._moe_input_gathered_across_moe_cp(): + return None + # DSA / MLA CP take the FULL mode but all-gather across CP on a prefill, + # which leaves the real rows zigzag-permuted rather than in a prefix. + if get_parallel().attn_cp_size > 1 and self._moe_input_gathered_across_cp(): + return None + if get_parallel().attn_dp_size != 1: + # dp_gather concatenates one padded slot per attention-DP rank. + return None + # A single attention-DP group all-reduces instead of gathering, so the + # buffer holds the whole sequence and the GLOBAL count bounds it. + if not self.attn_tp_sequence_sharded: + return self.num_token_non_padded + # None under cuda-graph replay: its static batch carries no GLOBAL count. + return self.global_num_token_non_padded + + def _moe_input_gathered_across_moe_cp(self) -> bool: + from sglang.srt.layers.dp_attention import get_moe_cp_size + + # Mirrors the communicator's MOE_FULL gather guard: decode stays FULL. + return ( + self.forward_mode.is_context_parallel_extend() + and self.attn_cp_metadata is not None + and get_moe_cp_size() > 1 + ) + + def _moe_input_gathered_across_cp(self) -> bool: + from sglang.srt.layers.attention.dsa.utils import dsa_use_prefill_cp + from sglang.srt.layers.cp.utils import is_mla_cp_active + + return dsa_use_prefill_cp(self) or is_mla_cp_active(self) + def mamba_track_aligned_lens(self) -> Optional[torch.Tensor]: """Tokens of this extend chunk covered by the tracked mamba state, floored to the mamba_cache_chunk_size boundary the scheduler snapshots at; diff --git a/python/sglang/srt/models/bailing_moe.py b/python/sglang/srt/models/bailing_moe.py index 36577fd597..06603253b1 100644 --- a/python/sglang/srt/models/bailing_moe.py +++ b/python/sglang/srt/models/bailing_moe.py @@ -476,7 +476,7 @@ class BailingMoESparseMoeBlock(nn.Module): hidden_states, router_logits, dynamic_expert_bias=dynamic_expert_bias, - num_token_non_padded=forward_batch.num_token_non_padded, + num_token_non_padded=forward_batch.moe_num_token_non_padded(), expert_location_dispatch_info=ExpertLocationDispatchInfo.init_new( layer_id=self.layer_id, ), diff --git a/python/sglang/srt/models/bailing_moe_v3.py b/python/sglang/srt/models/bailing_moe_v3.py index 6d04502115..4c1467031a 100644 --- a/python/sglang/srt/models/bailing_moe_v3.py +++ b/python/sglang/srt/models/bailing_moe_v3.py @@ -859,7 +859,7 @@ class BailingMoE(nn.Module): hidden_states, router_logits, dynamic_expert_bias=dynamic_expert_bias, - num_token_non_padded=forward_batch.num_token_non_padded, + num_token_non_padded=forward_batch.moe_num_token_non_padded(), expert_location_dispatch_info=ExpertLocationDispatchInfo.init_new( layer_id=self.layer_id, ), diff --git a/python/sglang/srt/models/deepseek_v2.py b/python/sglang/srt/models/deepseek_v2.py index c2356c907b..47361dd5ba 100644 --- a/python/sglang/srt/models/deepseek_v2.py +++ b/python/sglang/srt/models/deepseek_v2.py @@ -925,7 +925,9 @@ class DeepseekV2MoE(nn.Module): ) num_token_non_padded = ( - forward_batch.num_token_non_padded if forward_batch is not None else None + forward_batch.moe_num_token_non_padded() + if forward_batch is not None + else None ) if not self._enable_a2a_moe: if self._can_dual_stream_graph(hidden_states): @@ -1457,7 +1459,7 @@ class DeepseekV2MoE(nn.Module): topk_output = self.topk( hidden_states, router_logits, - num_token_non_padded=forward_batch.num_token_non_padded, + num_token_non_padded=forward_batch.moe_num_token_non_padded(), expert_location_dispatch_info=( ExpertLocationDispatchInfo.init_new( layer_id=self.layer_id, @@ -1851,7 +1853,7 @@ class DeepseekV2MoE(nn.Module): state.topk_output = self.topk( hidden_states=hidden_states, router_logits=router_logits, - num_token_non_padded=state.forward_batch.num_token_non_padded, + num_token_non_padded=state.forward_batch.moe_num_token_non_padded(), expert_location_dispatch_info=( ExpertLocationDispatchInfo.init_new( layer_id=self.layer_id, diff --git a/python/sglang/srt/models/deepseek_v4.py b/python/sglang/srt/models/deepseek_v4.py index 5ca658608a..422c59bf2a 100644 --- a/python/sglang/srt/models/deepseek_v4.py +++ b/python/sglang/srt/models/deepseek_v4.py @@ -3853,25 +3853,17 @@ class DeepseekV4DecoderLayer(nn.Module): if _use_cp and get_moe_a2a_backend().is_none() else nullcontext() ) - # The MoE sees DP-gathered rows, so this rank's local count cannot mask them. - # The standard dispatcher masks padding in the gathered buffer. - saved_num_token_non_padded = forward_batch.num_token_non_padded - if _use_tp_moe_gather: - forward_batch.num_token_non_padded = None - try: - with ( - get_forward().scoped(mlp_reduce_scatter=mlp_reduce_scatter), - gathered_rows, - ): - hidden_states = self.mlp( - hidden_states, - forward_batch, - input_ids=input_ids, - input_ids_global=input_ids_global, - skip_shared_experts=_do_shared_local, - ) - finally: - forward_batch.num_token_non_padded = saved_num_token_non_padded + with ( + get_forward().scoped(mlp_reduce_scatter=mlp_reduce_scatter), + gathered_rows, + ): + hidden_states = self.mlp( + hidden_states, + forward_batch, + input_ids=input_ids, + input_ids_global=input_ids_global, + skip_shared_experts=_do_shared_local, + ) if _use_cp and get_moe_a2a_backend().is_none(): hidden_states = dsa_cp_reduce_scatter_hidden_states(hidden_states) elif _use_tp_moe_gather: diff --git a/python/sglang/srt/models/dots3_common/modeling.py b/python/sglang/srt/models/dots3_common/modeling.py index 3253eab9ed..65d6142441 100644 --- a/python/sglang/srt/models/dots3_common/modeling.py +++ b/python/sglang/srt/models/dots3_common/modeling.py @@ -515,7 +515,7 @@ class Dots3MoE(nn.Module): topk_output = self.topk( hidden_states, router_logits, - num_token_non_padded=forward_batch.num_token_non_padded, + num_token_non_padded=forward_batch.moe_num_token_non_padded(), expert_location_dispatch_info=ExpertLocationDispatchInfo.init_new( layer_id=self.layer_id, ), @@ -577,7 +577,7 @@ class Dots3MoE(nn.Module): state.topk_weights_local, state.topk_idx_local, _ = self.topk( hidden_states=hidden_states, router_logits=router_logits, - num_token_non_padded=state.forward_batch.num_token_non_padded, + num_token_non_padded=state.forward_batch.moe_num_token_non_padded(), expert_location_dispatch_info=ExpertLocationDispatchInfo.init_new( layer_id=self.layer_id, ), diff --git a/python/sglang/srt/models/exaone_moe.py b/python/sglang/srt/models/exaone_moe.py index 1747e17c66..c87f0fd77c 100755 --- a/python/sglang/srt/models/exaone_moe.py +++ b/python/sglang/srt/models/exaone_moe.py @@ -227,7 +227,7 @@ class ExaoneMoESparseMoEBlock(nn.Module): topk_output = self.topk( hidden_states, router_logits, - num_token_non_padded=forward_batch.num_token_non_padded, + num_token_non_padded=forward_batch.moe_num_token_non_padded(), expert_location_dispatch_info=ExpertLocationDispatchInfo.init_new( layer_id=self.layer_id, ), diff --git a/python/sglang/srt/models/glm4_moe.py b/python/sglang/srt/models/glm4_moe.py index b24f069db9..59adfa0d8f 100644 --- a/python/sglang/srt/models/glm4_moe.py +++ b/python/sglang/srt/models/glm4_moe.py @@ -680,7 +680,7 @@ class Glm4MoeSparseMoeBlock(nn.Module): topk_output = self.topk( hidden_states, router_logits, - num_token_non_padded=forward_batch.num_token_non_padded, + num_token_non_padded=forward_batch.moe_num_token_non_padded(), expert_location_dispatch_info=ExpertLocationDispatchInfo.init_new( layer_id=self.layer_id, ), @@ -734,7 +734,7 @@ class Glm4MoeSparseMoeBlock(nn.Module): state.topk_output = self.topk( hidden_states=hidden_states, router_logits=router_logits, - num_token_non_padded=state.forward_batch.num_token_non_padded, + num_token_non_padded=state.forward_batch.moe_num_token_non_padded(), expert_location_dispatch_info=ExpertLocationDispatchInfo.init_new( layer_id=self.layer_id, ), diff --git a/python/sglang/srt/models/glm4_moe_lite.py b/python/sglang/srt/models/glm4_moe_lite.py index e30c2387ac..85cf6c15be 100644 --- a/python/sglang/srt/models/glm4_moe_lite.py +++ b/python/sglang/srt/models/glm4_moe_lite.py @@ -385,7 +385,7 @@ class Glm4MoeLiteSparseMoeBlock(nn.Module): topk_output = self.topk( hidden_states, router_logits, - num_token_non_padded=forward_batch.num_token_non_padded, + num_token_non_padded=forward_batch.moe_num_token_non_padded(), expert_location_dispatch_info=ExpertLocationDispatchInfo.init_new( layer_id=self.layer_id, ), @@ -446,7 +446,7 @@ class Glm4MoeLiteSparseMoeBlock(nn.Module): state.topk_output = self.topk( hidden_states=hidden_states, router_logits=router_logits, - num_token_non_padded=state.forward_batch.num_token_non_padded, + num_token_non_padded=state.forward_batch.moe_num_token_non_padded(), expert_location_dispatch_info=ExpertLocationDispatchInfo.init_new( layer_id=self.layer_id, ), diff --git a/python/sglang/srt/models/llada2.py b/python/sglang/srt/models/llada2.py index 01bd9c3fee..7a8dd4b03b 100644 --- a/python/sglang/srt/models/llada2.py +++ b/python/sglang/srt/models/llada2.py @@ -403,7 +403,7 @@ class LLaDA2MoeSparseMoeBlock(nn.Module): topk_output = self.topk( hidden_states, router_logits, - num_token_non_padded=forward_batch.num_token_non_padded, + num_token_non_padded=forward_batch.moe_num_token_non_padded(), expert_location_dispatch_info=ExpertLocationDispatchInfo.init_new( layer_id=self.layer_id, ), diff --git a/python/sglang/srt/models/mimo_v2.py b/python/sglang/srt/models/mimo_v2.py index 752c4f9d8c..26f9c8c88f 100644 --- a/python/sglang/srt/models/mimo_v2.py +++ b/python/sglang/srt/models/mimo_v2.py @@ -516,7 +516,7 @@ class MiMoV2MoE(nn.Module): topk_output = self.topk( hidden_states, router_logits, - num_token_non_padded=forward_batch.num_token_non_padded, + num_token_non_padded=forward_batch.moe_num_token_non_padded(), expert_location_dispatch_info=ExpertLocationDispatchInfo.init_new( layer_id=self.layer_id, ), @@ -549,7 +549,7 @@ class MiMoV2MoE(nn.Module): state.topk_output = self.topk( hidden_states=hidden_states, router_logits=router_logits, - num_token_non_padded=state.forward_batch.num_token_non_padded, + num_token_non_padded=state.forward_batch.moe_num_token_non_padded(), expert_location_dispatch_info=ExpertLocationDispatchInfo.init_new( layer_id=self.layer_id, ), diff --git a/python/sglang/srt/models/minimax_m2.py b/python/sglang/srt/models/minimax_m2.py index b0d470d6d1..cc3bd52710 100644 --- a/python/sglang/srt/models/minimax_m2.py +++ b/python/sglang/srt/models/minimax_m2.py @@ -618,7 +618,7 @@ class MiniMaxM2MoE(nn.Module): topk_output = self.topk( hidden_states, router_logits, - num_token_non_padded=forward_batch.num_token_non_padded, + num_token_non_padded=forward_batch.moe_num_token_non_padded(), expert_location_dispatch_info=ExpertLocationDispatchInfo.init_new( layer_id=self.layer_id, ), @@ -659,7 +659,7 @@ class MiniMaxM2MoE(nn.Module): state.topk_weights_local, state.topk_idx_local, _ = self.topk( hidden_states=hidden_states, router_logits=router_logits, - num_token_non_padded=state.forward_batch.num_token_non_padded, + num_token_non_padded=state.forward_batch.moe_num_token_non_padded(), expert_location_dispatch_info=ExpertLocationDispatchInfo.init_new( layer_id=self.layer_id, ), diff --git a/python/sglang/srt/models/minimax_m3.py b/python/sglang/srt/models/minimax_m3.py index eef7c270a3..7a6f2ea6d5 100644 --- a/python/sglang/srt/models/minimax_m3.py +++ b/python/sglang/srt/models/minimax_m3.py @@ -499,7 +499,7 @@ class MiniMaxM3MoE(nn.Module): topk_output = self.topk( hidden_states, router_logits, - num_token_non_padded=forward_batch.num_token_non_padded, + num_token_non_padded=forward_batch.moe_num_token_non_padded(), expert_location_dispatch_info=ExpertLocationDispatchInfo.init_new( layer_id=self.layer_id, ), diff --git a/python/sglang/srt/models/qwen2_moe.py b/python/sglang/srt/models/qwen2_moe.py index 7ebb60e9ae..b858f5061f 100644 --- a/python/sglang/srt/models/qwen2_moe.py +++ b/python/sglang/srt/models/qwen2_moe.py @@ -601,7 +601,7 @@ class Qwen2MoeSparseMoeBlock(nn.Module): topk_output = self.topk( hidden_states, router_logits, - num_token_non_padded=forward_batch.num_token_non_padded, + num_token_non_padded=forward_batch.moe_num_token_non_padded(), expert_location_dispatch_info=( ExpertLocationDispatchInfo.init_new( layer_id=self.layer_id, @@ -658,7 +658,7 @@ class Qwen2MoeSparseMoeBlock(nn.Module): hidden_states, router_logits, num_token_non_padded=( - forward_batch.num_token_non_padded + forward_batch.moe_num_token_non_padded() if forward_batch is not None else None ), diff --git a/python/sglang/srt/models/qwen3_moe.py b/python/sglang/srt/models/qwen3_moe.py index f4825ac4fb..6cdc9634c4 100644 --- a/python/sglang/srt/models/qwen3_moe.py +++ b/python/sglang/srt/models/qwen3_moe.py @@ -350,7 +350,7 @@ class Qwen3MoeSparseMoeBlock(nn.Module): topk_output = self.topk( hidden_states, router_logits, - num_token_non_padded=forward_batch.num_token_non_padded, + num_token_non_padded=forward_batch.moe_num_token_non_padded(), expert_location_dispatch_info=ExpertLocationDispatchInfo.init_new( layer_id=self.layer_id, ), @@ -389,7 +389,7 @@ class Qwen3MoeSparseMoeBlock(nn.Module): hidden_states, router_logits, num_token_non_padded=( - forward_batch.num_token_non_padded + forward_batch.moe_num_token_non_padded() if forward_batch is not None else None ), @@ -434,7 +434,7 @@ class Qwen3MoeSparseMoeBlock(nn.Module): state.topk_output = self.topk( hidden_states=hidden_states, router_logits=router_logits, - num_token_non_padded=state.forward_batch.num_token_non_padded, + num_token_non_padded=state.forward_batch.moe_num_token_non_padded(), expert_location_dispatch_info=ExpertLocationDispatchInfo.init_new( layer_id=self.layer_id, ), diff --git a/python/sglang/srt/models/sdar_moe.py b/python/sglang/srt/models/sdar_moe.py index c2ef190278..71b2f12f7f 100644 --- a/python/sglang/srt/models/sdar_moe.py +++ b/python/sglang/srt/models/sdar_moe.py @@ -159,7 +159,7 @@ class SDARMoeSparseMoeBlock(nn.Module): topk_output = self.topk( hidden_states, router_logits, - num_token_non_padded=forward_batch.num_token_non_padded, + num_token_non_padded=forward_batch.moe_num_token_non_padded(), expert_location_dispatch_info=ExpertLocationDispatchInfo.init_new( layer_id=self.layer_id ), diff --git a/python/sglang/srt/models/step3p5.py b/python/sglang/srt/models/step3p5.py index f2d62ad333..d9f68f3633 100644 --- a/python/sglang/srt/models/step3p5.py +++ b/python/sglang/srt/models/step3p5.py @@ -238,7 +238,7 @@ class Step3p5MoEMLP(nn.Module): topk_output = self.topk( hidden_states, router_logits, - num_token_non_padded=forward_batch.num_token_non_padded, + num_token_non_padded=forward_batch.moe_num_token_non_padded(), expert_location_dispatch_info=ExpertLocationDispatchInfo.init_new( layer_id=self.layer_id, ), @@ -270,7 +270,7 @@ class Step3p5MoEMLP(nn.Module): state.topk_output = self.topk( hidden_states=hidden_states, router_logits=router_logits, - num_token_non_padded=state.forward_batch.num_token_non_padded, + num_token_non_padded=state.forward_batch.moe_num_token_non_padded(), expert_location_dispatch_info=ExpertLocationDispatchInfo.init_new( layer_id=self.layer_id, ), diff --git a/python/sglang/srt/models/xllm.py b/python/sglang/srt/models/xllm.py index c22da55659..e09afdcb3d 100644 --- a/python/sglang/srt/models/xllm.py +++ b/python/sglang/srt/models/xllm.py @@ -1000,7 +1000,7 @@ class XllmSparseMoeBlock(nn.Module): topk_output = self.topk( hidden_states, router_logits, - num_token_non_padded=forward_batch.num_token_non_padded, + num_token_non_padded=forward_batch.moe_num_token_non_padded(), expert_location_dispatch_info=( ExpertLocationDispatchInfo.init_new(layer_id=self.layer_id) ), diff --git a/test/registered/unit/model_executor/test_num_token_non_padded_localization.py b/test/registered/unit/model_executor/test_num_token_non_padded_localization.py index b8446fc686..0d3ee96d86 100644 --- a/test/registered/unit/model_executor/test_num_token_non_padded_localization.py +++ b/test/registered/unit/model_executor/test_num_token_non_padded_localization.py @@ -9,17 +9,28 @@ localizer clamps ``real - chunk * attn_tp_rank`` into ``[0, chunk]``: a replicat identical whether the MoE runs TP or EP -- it is an attention-side quantity both backends consume. This table locks the exact per-rank counts and that the GPU tensor and host-int twin agree, so a change to the sharding math fails loudly. + +``ForwardBatch.moe_num_token_non_padded()`` decides whether that count may bound +a sparse MoE's input at all. Masking a gathered buffer with it truncates every +peer rank's rows, which collapsed gsm8k accuracy under DP attention with +``--moe-a2a-backend none``, where each rank sums its own partial output. The +second table locks that scatter mode x layout x CP decision. """ from sglang.test.ci.ci_register import register_cpu_ci -register_cpu_ci(est_time=7, suite="base-a-test-cpu") +register_cpu_ci(est_time=10, suite="base-a-test-cpu") import unittest +from unittest.mock import patch import torch +from sglang.srt.layers import communicator as comm +from sglang.srt.layers.communicator import ScatterMode from sglang.srt.model_executor.forward_batch_info import ( + ForwardBatch, + ForwardMode, compute_local_num_token_non_padded, compute_local_num_token_non_padded_cpu, ) @@ -66,5 +77,147 @@ class TestNumTokenNonPaddedLayoutTable(CustomTestCase): self.assertEqual(int(got_gpu), want) +LOCAL, GLOBAL = 7, 30 + + +def _forward_batch( + *, + sharded: bool, + local=LOCAL, + glob=GLOBAL, + forward_mode=ForwardMode.DECODE, + attn_cp_metadata=None, +) -> ForwardBatch: + empty = torch.empty(0, dtype=torch.int32) + batch = ForwardBatch( + forward_mode=forward_mode, + batch_size=1, + input_ids=empty, + req_pool_indices=empty, + seq_lens=empty, + out_cache_loc=empty, + seq_lens_sum=0, + ) + batch.num_token_non_padded = ( + None if local is None else torch.tensor(local, dtype=torch.int32) + ) + batch.global_num_token_non_padded = ( + None if glob is None else torch.tensor(glob, dtype=torch.int32) + ) + batch.attn_tp_sequence_sharded = sharded + batch.attn_cp_metadata = attn_cp_metadata + return batch + + +def _value(batch: ForwardBatch): + got = batch.moe_num_token_non_padded() + return None if got is None else int(got) + + +class TestMoeNumTokenNonPaddedTable(CustomTestCase): + # (label, mode, sharded, attn_dp_size, expected). Decode forwards, so the + # MOE_FULL rows follow the FULL layout: that config all-gathers over the + # MoE-CP group on a context-parallel extend only, which is the case below. + _TABLE = [ + ("scattered.replicated", ScatterMode.SCATTERED, False, 1, LOCAL), + ("scattered.sharded", ScatterMode.SCATTERED, True, 1, LOCAL), + ("scattered.dp", ScatterMode.SCATTERED, True, 4, LOCAL), + ("moe_full.decode.replicated", ScatterMode.MOE_FULL, False, 1, LOCAL), + ("moe_full.decode.sharded", ScatterMode.MOE_FULL, True, 1, GLOBAL), + ("moe_full.decode.dp", ScatterMode.MOE_FULL, True, 4, None), + ("full.dp_gathered", ScatterMode.FULL, True, 4, None), + ("full.dp_gathered.replicated", ScatterMode.FULL, False, 4, None), + ("full.tp_sharded", ScatterMode.FULL, True, 1, GLOBAL), + ("full.replicated", ScatterMode.FULL, False, 1, LOCAL), + ] + + def test_table(self): + for label, mode, sharded, attn_dp_size, expected in self._TABLE: + with ( + self.subTest(case=label), + get_parallel().override(attn_dp_size=attn_dp_size, attn_cp_size=1), + patch.object(comm, "sparse_mlp_scatter_mode", return_value=mode), + ): + self.assertEqual(_value(_forward_batch(sharded=sharded)), expected) + + def test_cp_gathered_full_is_unmasked(self): + """A CP prefill must route every row: DSA / MLA CP take the FULL mode + but all-gather across CP, which zigzag-permutes the real rows.""" + for sharded in (False, True): + for dsa_cp, mla_cp in ((True, False), (False, True)): + with ( + self.subTest(sharded=sharded, dsa_cp=dsa_cp), + get_parallel().override(attn_dp_size=1, attn_cp_size=2), + patch.object( + comm, "sparse_mlp_scatter_mode", return_value=ScatterMode.FULL + ), + patch( + "sglang.srt.layers.attention.dsa.utils.dsa_use_prefill_cp", + return_value=dsa_cp, + ), + patch( + "sglang.srt.layers.cp.utils.is_mla_cp_active", + return_value=mla_cp, + ), + ): + self.assertIsNone(_value(_forward_batch(sharded=sharded))) + + def test_moe_full_gathers_only_on_a_context_parallel_extend(self): + """A moe-cp config keeps its bound on every forward but the CP extend, + which is the only one that all-gathers over the MoE-CP group.""" + # get_moe_cp_size reads a live process group, so it is stubbed rather + # than reached through a topology published without distributed init. + for label, forward_mode, metadata, expected in [ + ("cp_extend", ForwardMode.EXTEND, object(), None), + ("extend_without_cp_metadata", ForwardMode.EXTEND, None, LOCAL), + ("decode", ForwardMode.DECODE, object(), LOCAL), + ]: + with ( + self.subTest(case=label), + get_parallel().override(attn_dp_size=1, attn_cp_size=2), + patch.object( + comm, "sparse_mlp_scatter_mode", return_value=ScatterMode.MOE_FULL + ), + patch("sglang.srt.layers.dp_attention.get_moe_cp_size", return_value=2), + patch( + "sglang.srt.layers.attention.dsa.utils.dsa_use_prefill_cp", + return_value=False, + ), + patch( + "sglang.srt.layers.cp.utils.is_mla_cp_active", return_value=False + ), + ): + got = _value( + _forward_batch( + sharded=False, + forward_mode=forward_mode, + attn_cp_metadata=metadata, + ) + ) + self.assertEqual(got, expected) + + def test_graph_replay_without_global_count_skips_masking(self): + """A captured batch carries the LOCAL buffer alone, so the attn-TP + sharded FULL case has no bound to mask with and must not use it.""" + with ( + get_parallel().override(attn_dp_size=1, attn_cp_size=1), + patch.object( + comm, "sparse_mlp_scatter_mode", return_value=ScatterMode.FULL + ), + ): + self.assertIsNone(_value(_forward_batch(sharded=True, glob=None))) + + def test_absent_local_count_stays_absent(self): + """Without expert parallelism the count is never filled, and routing + must not mask every row against the unfilled buffer.""" + for mode in (ScatterMode.SCATTERED, ScatterMode.FULL, ScatterMode.MOE_FULL): + with ( + self.subTest(mode=mode), + get_parallel().override(attn_dp_size=1, attn_cp_size=1), + patch.object(comm, "sparse_mlp_scatter_mode", return_value=mode), + ): + self.assertIsNone(_value(_forward_batch(sharded=False, local=None))) + + if __name__ == "__main__": unittest.main()