diff --git a/python/sglang/multimodal_gen/test/single_test_file/test_encoder_fold_srt_2_gpu.py b/python/sglang/multimodal_gen/test/single_test_file/test_encoder_fold_srt_2_gpu.py index 7266133318..53f9b7d654 100644 --- a/python/sglang/multimodal_gen/test/single_test_file/test_encoder_fold_srt_2_gpu.py +++ b/python/sglang/multimodal_gen/test/single_test_file/test_encoder_fold_srt_2_gpu.py @@ -15,6 +15,7 @@ from types import SimpleNamespace import torch from sglang.multimodal_gen.runtime.platforms import current_platform +from sglang.srt.distributed.utils import get_group_rank_size from sglang.test.test_utils import CustomTestCase _WORLD = 2 @@ -130,7 +131,10 @@ def _worker() -> int: fold_group = get_world_group() assert folded._encoder_tp_group is fold_group - assert folded.text_model.encoder.layers[0].mlp.fc2.tp_size == world_size + assert ( + get_group_rank_size(folded.text_model.encoder.layers[0].mlp.fc2.tp_group)[1] + == world_size + ) assert get_tp_group().world_size == 1 input_ids = torch.tensor([[1, 7, 11, 2]], device=device) diff --git a/python/sglang/multimodal_gen/test/single_test_file/test_encoder_fold_srt_linear_2_gpu.py b/python/sglang/multimodal_gen/test/single_test_file/test_encoder_fold_srt_linear_2_gpu.py index 5d7a3bea84..7489243eac 100644 --- a/python/sglang/multimodal_gen/test/single_test_file/test_encoder_fold_srt_linear_2_gpu.py +++ b/python/sglang/multimodal_gen/test/single_test_file/test_encoder_fold_srt_linear_2_gpu.py @@ -25,6 +25,9 @@ def _worker() -> int: init_distributed_environment, initialize_model_parallel, ) + from sglang.multimodal_gen.runtime.distributed.parallel_state import ( + use_tensor_parallel_group, + ) from sglang.multimodal_gen.runtime.models.encoders.base import ( EncoderTensorParallelMixin, ) @@ -51,14 +54,14 @@ def _worker() -> int: def __init__(self): super().__init__() self.bind_encoder_tp_group(get_world_group()) - self.proj = RowParallelLinear( - input_size=8, - output_size=6, - bias=False, - tp_rank=rank, - tp_size=world_size, - params_dtype=torch.float32, - ) + with use_tensor_parallel_group(get_world_group()): + self.proj = RowParallelLinear( + input_size=8, + output_size=6, + bias=False, + parallel_group="tp", + params_dtype=torch.float32, + ) def forward(self, inputs: torch.Tensor) -> torch.Tensor: local_inputs = inputs.chunk(world_size, dim=-1)[rank].contiguous() diff --git a/python/sglang/multimodal_gen/test/unit/test_qwen2_5vl_generation.py b/python/sglang/multimodal_gen/test/unit/test_qwen2_5vl_generation.py index c9711e83bb..6b76639708 100644 --- a/python/sglang/multimodal_gen/test/unit/test_qwen2_5vl_generation.py +++ b/python/sglang/multimodal_gen/test/unit/test_qwen2_5vl_generation.py @@ -24,6 +24,7 @@ from sglang.multimodal_gen.runtime.models.encoders.qwen2_5vl_vision import ( _vision_window_index, ) from sglang.multimodal_gen.runtime.pipelines.longcat_image import LongCatImagePipeline +from sglang.srt.distributed.utils import get_group_rank_size from sglang.srt.layers.linear import ( ColumnParallelLinear, ReplicatedLinear, @@ -87,11 +88,14 @@ def test_text_mlp_uses_single_rank_when_intermediate_size_is_not_tp_divisible( layer = qwen2_5vl.Qwen2_5_VLDecoderLayer(config, layer_idx=0) - assert layer.mlp.tp_size == 1 - assert layer.mlp.tp_rank == 0 + assert get_group_rank_size(layer.mlp.tp_group) == (0, 1) assert isinstance(layer.mlp.gate_proj, ColumnParallelLinear) assert isinstance(layer.mlp.up_proj, ColumnParallelLinear) - assert layer.mlp.gate_proj.tp_rank == layer.mlp.up_proj.tp_rank == 0 + assert ( + get_group_rank_size(layer.mlp.gate_proj.tp_group)[0] + == get_group_rank_size(layer.mlp.up_proj.tp_group)[0] + == 0 + ) assert isinstance(layer.mlp.down_proj, ReplicatedLinear) diff --git a/python/sglang/multimodal_gen/test/unit/test_qwen_vision_parallel_groups.py b/python/sglang/multimodal_gen/test/unit/test_qwen_vision_parallel_groups.py index 907b7e2c3b..8469a43525 100644 --- a/python/sglang/multimodal_gen/test/unit/test_qwen_vision_parallel_groups.py +++ b/python/sglang/multimodal_gen/test/unit/test_qwen_vision_parallel_groups.py @@ -9,10 +9,10 @@ import torch import torch.nn.functional as F from sglang.srt.layers.dp_attention import initialize_dp_attention_flags -from sglang.srt.layers.linear import QKVParallelLinear, ReplicatedLinear +from sglang.srt.layers.linear import QKVParallelLinear from sglang.srt.runtime_context import SpawnRanks, reset_context from sglang.srt.server_args import ServerArgs -from sglang.test.parallel_groups import parallel_scope, publish +from sglang.test.parallel_groups import parallel_scope, publish, rank_size class TestQwenGenerationParallelGroups(unittest.TestCase): @@ -20,39 +20,6 @@ class TestQwenGenerationParallelGroups(unittest.TestCase): reset_context() self.addCleanup(reset_context) - def test_generation_helpers_match_initialized_scope(self): - import sglang.multimodal_gen.runtime.models.encoders.qwen2_5vl as generation - - publish( - ServerArgs(model_path="dummy", device="cpu", tp_size=4), - role="test", - ranks=SpawnRanks(world_rank=3), - ) - for initialized in (False, True): - with patch.object( - generation, - "model_parallel_is_initialized", - return_value=initialized, - ): - for tensor_parallel in (False, True): - for maker in ( - generation._make_column_linear, - generation._make_row_linear, - ): - layer = maker( - 8, 8, bias=True, use_tensor_parallel=tensor_parallel - ) - expected = (3, 4) if initialized and tensor_parallel else (0, 1) - actual = ( - (0, 1) - if isinstance(layer, ReplicatedLinear) - else (layer.tp_rank, layer.tp_size) - ) - self.assertEqual(actual, expected) - self.assertEqual( - isinstance(layer, ReplicatedLinear), not tensor_parallel - ) - def test_native_vision_projection_math_and_reload(self): from sglang.multimodal_gen.runtime.layers.attention.selector import ( global_force_attn_backend_context_manager, @@ -81,10 +48,7 @@ class TestQwenGenerationParallelGroups(unittest.TestCase): tp = Mock(all_reduce=Mock(side_effect=lambda x: x * 2)) attn = Mock(all_reduce=Mock(side_effect=AssertionError("wrong group"))) for layer in (module.qkv_proj, module.proj): - rank, size = ( - getattr(layer, "tp_rank", 0), - getattr(layer, "tp_size", 1), - ) + rank, size = rank_size(layer) self.assertEqual((rank, size), (3, 4)) full = ( torch.arange(32 * 32, dtype=layer.weight.dtype).reshape(32, 32) diff --git a/python/sglang/srt/distributed/utils.py b/python/sglang/srt/distributed/utils.py index cbe3b65d40..171028791f 100644 --- a/python/sglang/srt/distributed/utils.py +++ b/python/sglang/srt/distributed/utils.py @@ -60,6 +60,11 @@ def get_global_tcp_store() -> Optional[TCPStore]: return store +def get_group_rank_size(group) -> Tuple[int, int]: + """Read rank and size from a retained owner; None denotes an unsharded layout.""" + return (0, 1) if group is None else (group.rank_in_group, group.world_size) + + def ensure_divisibility(numerator, denominator): """Ensure that numerator is divisible by the denominator.""" assert numerator % denominator == 0, "{} is not divisible by {}".format( diff --git a/python/sglang/srt/hardware_backend/npu/quantization/linear_method_npu.py b/python/sglang/srt/hardware_backend/npu/quantization/linear_method_npu.py index d7491e916a..3c905bf80d 100644 --- a/python/sglang/srt/hardware_backend/npu/quantization/linear_method_npu.py +++ b/python/sglang/srt/hardware_backend/npu/quantization/linear_method_npu.py @@ -105,7 +105,11 @@ class NPUW8A8Int8LinearMethod(_NPULinearMethodBase): ) # Only fuse bias add into GEMM for rank 0 (this ensures that # bias will not get added more than once in Attention TP>1 case) - if isinstance(layer, RowParallelLinear) and layer.tp_rank > 0: + if ( + isinstance(layer, RowParallelLinear) + and layer.tp_group is not None + and layer.tp_group.rank_in_group > 0 + ): quant_bias = None else: quant_bias = layer.quant_bias diff --git a/python/sglang/srt/hardware_backend/xpu/quantization/gptq_kernels.py b/python/sglang/srt/hardware_backend/xpu/quantization/gptq_kernels.py index a7928b260a..6c96a468dc 100644 --- a/python/sglang/srt/hardware_backend/xpu/quantization/gptq_kernels.py +++ b/python/sglang/srt/hardware_backend/xpu/quantization/gptq_kernels.py @@ -15,7 +15,6 @@ from sglang.srt.hardware_backend.xpu.quantization.int4pack_utils import ( xpu_int4pack_mm, ) from sglang.srt.layers.quantization.utils import replace_parameter -from sglang.srt.runtime_context import get_parallel if TYPE_CHECKING: from sglang.srt.layers.quantization.base_config import QuantizationConfig @@ -62,7 +61,14 @@ class GPTQXPULinearKernel: sorted_g = g_idx[act_perm].to(torch.int64) blocks = sorted_g.view(-1, group_size) if not torch.equal(blocks, blocks[:, :1].expand_as(blocks)): - tp_size = get_parallel().tp_size + from sglang.srt.layers.linear import LinearBase + + if isinstance(layer, LinearBase): + tp_size = ( + layer.tp_group.world_size if layer.tp_group is not None else 1 + ) + else: + tp_size = layer.tp_size tp_hint = ( f" Got tp_size={tp_size}; please use --tp-size 1." if tp_size > 1 diff --git a/python/sglang/srt/layers/attention/mamba/mamba.py b/python/sglang/srt/layers/attention/mamba/mamba.py index e47ee73fdf..555346c688 100644 --- a/python/sglang/srt/layers/attention/mamba/mamba.py +++ b/python/sglang/srt/layers/attention/mamba/mamba.py @@ -413,12 +413,19 @@ class MambaMixer2(torch.nn.Module): self.dt_bias = nn.Parameter(torch.ones(num_heads // self.tp_size)) self.use_rms_norm = use_rms_norm - set_weight_attrs(self.D, {"weight_loader": sharded_weight_loader(0)}) + set_weight_attrs( + self.D, + {"weight_loader": sharded_weight_loader(0, parallel_group=parallel_group)}, + ) a_weight_loader = composed_weight_loader( - sharded_weight_loader(0), lambda x: -torch.exp(x.float()) + sharded_weight_loader(0, parallel_group=parallel_group), + lambda x: -torch.exp(x.float()), ) set_weight_attrs(self.A, {"weight_loader": a_weight_loader}) - set_weight_attrs(self.dt_bias, {"weight_loader": sharded_weight_loader(0)}) + set_weight_attrs( + self.dt_bias, + {"weight_loader": sharded_weight_loader(0, parallel_group=parallel_group)}, + ) # By default the stage boundary reduces the output under DP attention. if reduce_results is None: diff --git a/python/sglang/srt/layers/attention/mamba/mamba1.py b/python/sglang/srt/layers/attention/mamba/mamba1.py index 1e9f9ef3f7..39a0cfbe48 100644 --- a/python/sglang/srt/layers/attention/mamba/mamba1.py +++ b/python/sglang/srt/layers/attention/mamba/mamba1.py @@ -168,8 +168,12 @@ class MambaMixer1(nn.Module): torch.empty(self.intermediate_size_per_tp, state_size, dtype=torch.float32) ) self.D = nn.Parameter(torch.ones(self.intermediate_size_per_tp)) - set_weight_attrs(self.A_log, {"weight_loader": sharded_weight_loader(0)}) - set_weight_attrs(self.D, {"weight_loader": sharded_weight_loader(0)}) + set_weight_attrs( + self.A_log, {"weight_loader": sharded_weight_loader(0, parallel_group="tp")} + ) + set_weight_attrs( + self.D, {"weight_loader": sharded_weight_loader(0, parallel_group="tp")} + ) # The time-step bias is folded into dt_proj.bias (applied before the # scan), so the selective_state_update kernel gets a zero dt_bias. Keep diff --git a/python/sglang/srt/layers/attention/mamba/mixer2_rms_norm_gated.py b/python/sglang/srt/layers/attention/mamba/mixer2_rms_norm_gated.py index c1b1fad4e5..96acc5dd8b 100644 --- a/python/sglang/srt/layers/attention/mamba/mixer2_rms_norm_gated.py +++ b/python/sglang/srt/layers/attention/mamba/mixer2_rms_norm_gated.py @@ -43,7 +43,14 @@ class Mixer2RMSNormGated(BaseFusedOp): if self.use_rms_norm: # Register norm weight only if we're actually applying RMSNorm self.weight = torch.nn.Parameter(torch.ones(self.per_rank_hidden_size)) - set_weight_attrs(self.weight, {"weight_loader": sharded_weight_loader(0)}) + set_weight_attrs( + self.weight, + { + "weight_loader": sharded_weight_loader( + 0, parallel_group="attn_tp" if self.use_attn_tp_group else "tp" + ) + }, + ) else: # Avoid checkpoint mismatch by skipping unused parameter self.register_parameter("weight", None) diff --git a/python/sglang/srt/layers/layernorm_sp.py b/python/sglang/srt/layers/layernorm_sp.py index 147d4cf44e..ea72e7941b 100644 --- a/python/sglang/srt/layers/layernorm_sp.py +++ b/python/sglang/srt/layers/layernorm_sp.py @@ -227,7 +227,7 @@ def row_parallel_gbar_matmul(linear, input_: torch.Tensor, bias) -> torch.Tensor exit gather). Uses the fused symm-mem kernel when eligible, else matmul + a plain reduce-scatter. """ - tp_size = linear.tp_size + tp_size = linear.tp_group.world_size if linear.tp_group is not None else 1 x = input_.contiguous() num_tokens = x.shape[0] padded = ceil_align(num_tokens, tp_size) diff --git a/python/sglang/srt/layers/linear.py b/python/sglang/srt/layers/linear.py index 102fcfb276..f5d93c1de8 100644 --- a/python/sglang/srt/layers/linear.py +++ b/python/sglang/srt/layers/linear.py @@ -24,6 +24,7 @@ from sglang.srt.distributed import ( from sglang.srt.distributed.device_communicators.pynccl_allocator import ( use_symmetric_memory, ) +from sglang.srt.distributed.utils import get_group_rank_size from sglang.srt.environ import envs from sglang.srt.layers import layernorm_sp from sglang.srt.layers.dp_attention import ( @@ -44,6 +45,7 @@ from sglang.srt.runtime_context import get_exec, get_forward, get_parallel from sglang.srt.utils import get_bool_env_var, is_cpu, is_hip, is_npu, set_weight_attrs if TYPE_CHECKING: + from sglang.srt.distributed.parallel_state import GroupCoordinator from sglang.srt.layers.quantization.base_config import ( QuantizationConfig, QuantizeMethodBase, @@ -79,51 +81,60 @@ LinearParallelGroup = ( def resolve_linear_parallel_group( parallel_group: LinearParallelGroup, ) -> Tuple[int, int]: - """Freeze a group's weight partition in the current construction scope.""" + """Read a group's partition in the current construction scope.""" + return get_group_rank_size(_resolve_linear_group(parallel_group)) + + +class _LogicalGroup(msgspec.Struct, frozen=True): + """Own a weight partition before distributed communication is initialized.""" + + rank_in_group: int + world_size: int + + +class _ReplicatedGroup(msgspec.Struct, frozen=True): + group: GroupCoordinator | _LogicalGroup + replica_size: int + + def __post_init__(self): + divide(self.group.world_size, self.replica_size) + + @property + def rank_in_group(self): + return self.group.rank_in_group // self.replica_size + + @property + def world_size(self): + return self.group.world_size // self.replica_size + + +def _resolve_linear_group( + parallel_group: Optional[LinearParallelGroup], +) -> GroupCoordinator | _LogicalGroup | _ReplicatedGroup | None: if isinstance(parallel_group, ReplicatedParallelGroup): - rank, size = resolve_linear_parallel_group(parallel_group.group) - return rank // parallel_group.replica_size, divide( - size, parallel_group.replica_size - ) - if parallel_group == "replicated": - return 0, 1 - if parallel_group == "shared_experts_tp": - group = get_parallel().shared_experts_tp_group + group = _resolve_linear_group(parallel_group.group) if group is None: - raise ValueError( - "The shared-expert TP group must exist before construction" - ) - return group.rank_in_group, group.world_size - if parallel_group not in ("tp", "attn_tp"): + if parallel_group.replica_size != 1: + raise ValueError("Cannot replicate a size-one group") + return None + return _ReplicatedGroup(group, parallel_group.replica_size) + if parallel_group == "replicated": + return None + name = "tp" if parallel_group is None else parallel_group + if name not in ("tp", "attn_tp", "shared_experts_tp"): raise ValueError(f"Unknown linear parallel_group: {parallel_group!r}") parallel = get_parallel() - if parallel_group == "attn_tp": - return parallel.attn_tp_rank, parallel.attn_tp_size - return parallel.tp_rank, parallel.tp_size - - -def _resolve_linear_partition( - parallel_group: Optional[LinearParallelGroup], - tp_rank: Optional[int], - tp_size: Optional[int], -) -> Tuple[int, int]: - """Resolve a layer's partition in its construction scope. - - Explicit integers remain available for layouts that do not correspond to a - process group. A group selection and explicit integers cannot be combined. - The returned values belong to the layer, including during later reloads. - """ - if parallel_group is not None: - if tp_rank is not None or tp_size is not None: - raise ValueError( - "parallel_group cannot be combined with tp_rank or tp_size" - ) - return resolve_linear_parallel_group(parallel_group) - if tp_rank is None: - tp_rank = get_parallel().tp_rank - if tp_size is None: - tp_size = get_parallel().tp_size - return tp_rank, tp_size + try: + group = getattr(parallel, f"{name}_group") + except RuntimeError: + group = None + if group is None: + if name == "shared_experts_tp": + raise ValueError(f"The {name} group must exist before construction") + size = getattr(parallel, f"{name}_size") + if size > 1: + return _LogicalGroup(getattr(parallel, f"{name}_rank"), size) + return group WEIGHT_LOADER_V2_SUPPORTED = [ @@ -233,6 +244,7 @@ class LinearBase(torch.nn.Module): # Module value under self._modules, which this default then shadows on read. # VocabParallelEmbedding and FusedMoE carry the same default. scheme = None + tp_group: GroupCoordinator | _LogicalGroup | _ReplicatedGroup | None = None def __init__( self, @@ -398,7 +410,6 @@ class ColumnParallelLinear(LinearBase): output_sizes: list of output sizes packed into one output, like for QKV the list would be size 3. parallel_group: Select TP, attention TP, or an unsharded partition. - Mutually exclusive with explicit tp_rank and tp_size. prefix: The name of the layer in the state dict, including all parents (e.g. model.layers.0.qkv_proj) """ @@ -414,13 +425,48 @@ class ColumnParallelLinear(LinearBase): quant_config: Optional[QuantizationConfig] = None, output_sizes: Optional[List[int]] = None, prefix: str = "", - tp_rank: Optional[int] = None, - tp_size: Optional[int] = None, + *, use_presharded_weights: bool = False, skip_block_quant_check: bool = False, - *, parallel_group: Optional[LinearParallelGroup] = None, ): + self._initialize_partition( + input_size=input_size, + output_size=output_size, + bias=bias, + gather_output=gather_output, + skip_bias_add=skip_bias_add, + params_dtype=params_dtype, + quant_config=quant_config, + output_sizes=output_sizes, + prefix=prefix, + use_presharded_weights=use_presharded_weights, + skip_block_quant_check=skip_block_quant_check, + parallel_group=parallel_group, + tp_group=_resolve_linear_group(parallel_group), + ) + + def _initialize_partition( + self, + input_size: int, + output_size: int, + bias: bool = True, + gather_output: bool = False, + skip_bias_add: bool = False, + params_dtype: Optional[torch.dtype] = None, + quant_config: Optional[QuantizationConfig] = None, + output_sizes: Optional[List[int]] = None, + prefix: str = "", + *, + tp_group: GroupCoordinator | _LogicalGroup | _ReplicatedGroup | None, + use_presharded_weights: bool = False, + skip_block_quant_check: bool = False, + parallel_group: Optional[LinearParallelGroup] = None, + ): + # Bind the selected group before quantization creates weight loaders. + self.tp_group = tp_group + self.parallel_group = parallel_group + _, tp_size = get_group_rank_size(tp_group) super().__init__( input_size, output_size, skip_bias_add, params_dtype, quant_config, prefix ) @@ -430,9 +476,6 @@ class ColumnParallelLinear(LinearBase): self.use_presharded_weights = use_presharded_weights # Divide the weight matrix along the last dimension. - tp_rank, tp_size = _resolve_linear_partition(parallel_group, tp_rank, tp_size) - self.parallel_group = parallel_group - self.tp_rank, self.tp_size = tp_rank, tp_size assert self.quant_method is not None self.output_size_per_partition = divide(self.output_size, tp_size) self.output_partition_sizes = [self.output_size_per_partition] @@ -490,10 +533,11 @@ class ColumnParallelLinear(LinearBase): param.weight_type = loaded_weight.item() # Materialize GGUF UninitializedParameter + tp_rank, tp_size = get_group_rank_size(self.tp_group) if is_gguf_weight and isinstance(param, UninitializedParameter): weight_shape = list(loaded_weight.shape) if output_dim is not None: - weight_shape[output_dim] = weight_shape[output_dim] // self.tp_size + weight_shape[output_dim] = weight_shape[output_dim] // tp_size param.materialize(tuple(weight_shape), dtype=loaded_weight.dtype) param_data = param.data @@ -502,7 +546,7 @@ class ColumnParallelLinear(LinearBase): use_bitsandbytes_4bit = getattr(param, "use_bitsandbytes_4bit", False) if output_dim is not None and not use_bitsandbytes_4bit: shard_size = param_data.shape[output_dim] - start_idx = self.tp_rank * shard_size + start_idx = tp_rank * shard_size if _is_cpu: from sglang.srt.model_loader.weight_utils import ( @@ -541,10 +585,11 @@ class ColumnParallelLinear(LinearBase): assert loaded_weight.numel() == 1 loaded_weight = loaded_weight.reshape(1) + tp_rank, _ = get_group_rank_size(self.tp_group) if isinstance(param, _ColumnvLLMParameter): param.load_column_parallel_weight( loaded_weight, - tp_rank=self.tp_rank, + tp_rank=tp_rank, use_presharded_weights=self.use_presharded_weights, ) else: @@ -554,7 +599,7 @@ class ColumnParallelLinear(LinearBase): try: param.load_column_parallel_weight( loaded_weight, - tp_rank=self.tp_rank, + tp_rank=tp_rank, use_presharded_weights=self.use_presharded_weights, ) except TypeError: @@ -567,7 +612,8 @@ class ColumnParallelLinear(LinearBase): # Megatron SP "g": the input is this rank's [M_pad/tp, K] sequence shard; # all-gather to the full sequence and matmul. Participants (qkv/gate_up) # have gather_output=False, so there is no output all-gather to reconcile. - if get_forward().sp_active and self.tp_size > 1: + _, tp_size = get_group_rank_size(self.tp_group) + if get_forward().sp_active and tp_size > 1: output = layernorm_sp.column_parallel_g_matmul(self, input_, bias) output_bias = self.bias if self.skip_bias_add else None return output, output_bias @@ -594,7 +640,8 @@ class ColumnParallelLinear(LinearBase): s = f"in_features={self.input_size}" s += f", output_features={self.output_size_per_partition}" s += f", bias={self.bias is not None}" - s += f", tp_size={self.tp_size}" + _, tp_size = get_group_rank_size(self.tp_group) + s += f", tp_size={tp_size}" s += f", gather_output={self.gather_output}" return s @@ -632,19 +679,17 @@ class MergedColumnParallelLinear(ColumnParallelLinear): params_dtype: Optional[torch.dtype] = None, quant_config: Optional[QuantizationConfig] = None, prefix: str = "", - tp_rank: Optional[int] = None, - tp_size: Optional[int] = None, - use_presharded_weights: bool = False, *, + use_presharded_weights: bool = False, parallel_group: Optional[LinearParallelGroup] = None, ): self.with_bias = bias self.output_sizes = output_sizes - tp_rank, tp_size = _resolve_linear_partition(parallel_group, tp_rank, tp_size) - self.tp_rank, self.tp_size = tp_rank, tp_size + tp_group = _resolve_linear_group(parallel_group) + _, tp_size = get_group_rank_size(tp_group) assert all(output_size % tp_size == 0 for output_size in output_sizes) self.use_presharded_weights = use_presharded_weights - super().__init__( + super()._initialize_partition( input_size=input_size, output_size=sum(output_sizes), bias=bias, @@ -653,11 +698,10 @@ class MergedColumnParallelLinear(ColumnParallelLinear): params_dtype=params_dtype, quant_config=quant_config, prefix=prefix, - tp_rank=tp_rank, - tp_size=tp_size, + tp_group=tp_group, + parallel_group=parallel_group, use_presharded_weights=use_presharded_weights, ) - self.parallel_group = parallel_group self.prefix = prefix def weight_loader( @@ -683,10 +727,11 @@ class MergedColumnParallelLinear(ColumnParallelLinear): param.shard_weight_type[loaded_shard_id] = loaded_weight.item() return + tp_rank, tp_size = get_group_rank_size(self.tp_group) if is_gguf_weight: output_dim = getattr(param, "output_dim", None) - shard_size = loaded_weight.size(output_dim) // self.tp_size - start_idx = self.tp_rank * shard_size + shard_size = loaded_weight.size(output_dim) // tp_size + start_idx = tp_rank * shard_size loaded_weight = loaded_weight.narrow(output_dim, start_idx, shard_size) @@ -717,7 +762,7 @@ class MergedColumnParallelLinear(ColumnParallelLinear): shard_offsets: List[Tuple[int, int, int]] = [] for i, output_size in enumerate(self.output_sizes): effective_size = ( - output_size // self.tp_size + output_size // tp_size if self.use_presharded_weights else output_size ) @@ -762,8 +807,8 @@ class MergedColumnParallelLinear(ColumnParallelLinear): assert loaded_shard_id < len(self.output_sizes) if output_dim is not None: - shard_offset = sum(self.output_sizes[:loaded_shard_id]) // self.tp_size - shard_size = self.output_sizes[loaded_shard_id] // self.tp_size + shard_offset = sum(self.output_sizes[:loaded_shard_id]) // tp_size + shard_size = self.output_sizes[loaded_shard_id] // tp_size # Special case for quantization. # If quantized, we need to adjust the offset and size to account # for the packing. @@ -790,7 +835,7 @@ class MergedColumnParallelLinear(ColumnParallelLinear): shard_offset = shard_offset // pack_factor param_data = param_data.narrow(output_dim, shard_offset, shard_size) - start_idx = self.tp_rank * shard_size + start_idx = tp_rank * shard_size if _is_cpu: from sglang.srt.model_loader.weight_utils import ( @@ -924,6 +969,7 @@ class MergedColumnParallelLinear(ColumnParallelLinear): ) # Load each shard + tp_rank, tp_size = get_group_rank_size(self.tp_group) for shard_id, (shard_block_offset, shard_block_size) in enumerate( zip(shard_block_offsets, shard_block_sizes) ): @@ -933,8 +979,8 @@ class MergedColumnParallelLinear(ColumnParallelLinear): ) # Calculate per-rank offset and size (considering TP) - rank_shard_offset = shard_block_offset // self.tp_size - rank_shard_size = shard_block_size // self.tp_size + rank_shard_offset = shard_block_offset // tp_size + rank_shard_size = shard_block_size // tp_size # Load into the parameter param.load_merged_column_weight( @@ -942,7 +988,7 @@ class MergedColumnParallelLinear(ColumnParallelLinear): shard_id=shard_id, shard_offset=rank_shard_offset, shard_size=rank_shard_size, - tp_rank=self.tp_rank, + tp_rank=tp_rank, use_presharded_weights=self.use_presharded_weights, ) @@ -952,6 +998,7 @@ class MergedColumnParallelLinear(ColumnParallelLinear): loaded_weight: torch.Tensor, loaded_shard_id: tuple[int, ...] | int | None = None, ): + tp_rank, tp_size = get_group_rank_size(self.tp_group) if loaded_shard_id is None or isinstance(loaded_shard_id, tuple): if isinstance(param, PerTensorScaleParameter): if loaded_weight.numel() != 1: @@ -973,7 +1020,7 @@ class MergedColumnParallelLinear(ColumnParallelLinear): param.load_merged_column_weight( loaded_weight=loaded_weight, shard_id=shard_id, - tp_rank=self.tp_rank, + tp_rank=tp_rank, ) return elif isinstance(param, BlockQuantScaleParameter): @@ -982,7 +1029,7 @@ class MergedColumnParallelLinear(ColumnParallelLinear): elif type(param) in (RowvLLMParameter, BasevLLMParameter): param.load_merged_column_weight( loaded_weight=loaded_weight, - tp_rank=self.tp_rank, + tp_rank=tp_rank, ) return output_sizes = ( @@ -1004,15 +1051,13 @@ class MergedColumnParallelLinear(ColumnParallelLinear): block_n = 1 if getattr(param, "format_ue8m0", False) else raw_block_n shard_offset = ( (sum(self.output_sizes[:loaded_shard_id]) + block_n - 1) // block_n - ) // self.tp_size + ) // tp_size shard_size = ( - (self.output_sizes[loaded_shard_id] + block_n - 1) - // block_n - // self.tp_size + (self.output_sizes[loaded_shard_id] + block_n - 1) // block_n // tp_size ) else: - shard_offset = sum(self.output_sizes[:loaded_shard_id]) // self.tp_size - shard_size = self.output_sizes[loaded_shard_id] // self.tp_size + shard_offset = sum(self.output_sizes[:loaded_shard_id]) // tp_size + shard_size = self.output_sizes[loaded_shard_id] // tp_size param.load_merged_column_weight( loaded_weight=loaded_weight, @@ -1020,7 +1065,7 @@ class MergedColumnParallelLinear(ColumnParallelLinear): shard_offset=shard_offset, shard_size=shard_size, use_presharded_weights=self.use_presharded_weights, - tp_rank=self.tp_rank, + tp_rank=tp_rank, ) @@ -1064,14 +1109,10 @@ class QKVParallelLinear(ColumnParallelLinear): params_dtype: Optional[torch.dtype] = None, quant_config: Optional[QuantizationConfig] = None, prefix: str = "", - tp_rank: Optional[int] = None, - tp_size: Optional[int] = None, + *, load_presharded_attn: bool = False, v_head_size: Optional[int] = None, skip_block_quant_check: bool = False, - kv_tp_rank: Optional[int] = None, - kv_tp_size: Optional[int] = None, - *, parallel_group: Optional[LinearParallelGroup] = None, kv_parallel_group: Optional[LinearParallelGroup] = None, ): @@ -1084,18 +1125,14 @@ class QKVParallelLinear(ColumnParallelLinear): total_num_kv_heads = total_num_heads self.total_num_kv_heads = total_num_kv_heads # Divide the weight matrix along the last dimension. - tp_rank, tp_size = _resolve_linear_partition(parallel_group, tp_rank, tp_size) - self.tp_rank, self.tp_size = tp_rank, tp_size - if kv_parallel_group is not None: - kv_tp_rank, kv_tp_size = _resolve_linear_partition( - kv_parallel_group, kv_tp_rank, kv_tp_size - ) - else: - if kv_tp_rank is None: - kv_tp_rank = tp_rank - if kv_tp_size is None: - kv_tp_size = tp_size - self.kv_tp_rank, self.kv_tp_size = kv_tp_rank, kv_tp_size + tp_group = _resolve_linear_group(parallel_group) + _, tp_size = get_group_rank_size(tp_group) + kv_tp_group = ( + _resolve_linear_group(kv_parallel_group) + if kv_parallel_group is not None + else tp_group + ) + _, kv_tp_size = get_group_rank_size(kv_tp_group) self.num_heads = divide(self.total_num_heads, tp_size) if kv_tp_size >= self.total_num_kv_heads: self.num_kv_heads = 1 @@ -1120,7 +1157,8 @@ class QKVParallelLinear(ColumnParallelLinear): self.use_presharded_weights = load_presharded_attn quant_config = None if _disable_hip_linear_quant else quant_config - super().__init__( + self.kv_tp_group = kv_tp_group + super()._initialize_partition( input_size=input_size, output_size=output_size, bias=bias, @@ -1129,12 +1167,11 @@ class QKVParallelLinear(ColumnParallelLinear): params_dtype=params_dtype, quant_config=quant_config, prefix=prefix, - tp_rank=tp_rank, - tp_size=tp_size, + tp_group=tp_group, + parallel_group=parallel_group, use_presharded_weights=self.use_presharded_weights, skip_block_quant_check=skip_block_quant_check, ) - self.parallel_group = parallel_group def _get_shard_offset_mapping(self, loaded_shard_id: str): shard_offset_mapping = { @@ -1212,6 +1249,8 @@ class QKVParallelLinear(ColumnParallelLinear): ("k", q_size, k_size), ("v", q_size + k_size, v_size), ] + kv_tp_rank, _ = get_group_rank_size(self.kv_tp_group) + tp_rank, _ = get_group_rank_size(self.tp_group) for shard_id, shard_offset, shard_size in shard_offsets: loaded_weight_shard = loaded_weight.narrow( param.output_dim, shard_offset, shard_size @@ -1224,7 +1263,7 @@ class QKVParallelLinear(ColumnParallelLinear): shard_id=shard_id, shard_offset=rank_shard_offset, shard_size=rank_shard_size, - tp_rank=(self.tp_rank if shard_id == "q" else self.kv_tp_rank), + tp_rank=(tp_rank if shard_id == "q" else kv_tp_rank), use_presharded_weights=self.use_presharded_weights, ) @@ -1272,13 +1311,15 @@ class QKVParallelLinear(ColumnParallelLinear): shard_offset = (shard_offset + block_n - 1) // block_n shard_size = (shard_size + block_n - 1) // block_n + kv_tp_rank, _ = get_group_rank_size(self.kv_tp_group) + tp_rank, _ = get_group_rank_size(self.tp_group) param.load_qkv_weight( loaded_weight=loaded_weight, num_heads=self.num_kv_head_replicas, shard_id=loaded_shard_id, shard_offset=shard_offset, shard_size=shard_size, - tp_rank=(self.tp_rank if loaded_shard_id == "q" else self.kv_tp_rank), + tp_rank=(tp_rank if loaded_shard_id == "q" else kv_tp_rank), use_presharded_weights=self.use_presharded_weights, ) @@ -1299,12 +1340,14 @@ class QKVParallelLinear(ColumnParallelLinear): param.shard_weight_type[loaded_shard_id] = loaded_weight.item() return + kv_tp_rank, kv_tp_size = get_group_rank_size(self.kv_tp_group) + tp_rank, tp_size = get_group_rank_size(self.tp_group) if is_gguf_weight: output_dim = getattr(param, "output_dim", None) shard_tp_rank, shard_tp_size = ( - (self.kv_tp_rank, self.kv_tp_size) + (kv_tp_rank, kv_tp_size) if loaded_shard_id in ("k", "v") - else (self.tp_rank, self.tp_size) + else (tp_rank, tp_size) ) shard_size = loaded_weight.size(output_dim) // shard_tp_size start_idx = shard_tp_rank * shard_size @@ -1451,9 +1494,9 @@ class QKVParallelLinear(ColumnParallelLinear): param_data = param_data.narrow(output_dim, shard_offset, shard_size) if loaded_shard_id == "q": - shard_id = self.tp_rank + shard_id = tp_rank else: - shard_id = self.kv_tp_rank // self.num_kv_head_replicas + shard_id = kv_tp_rank // self.num_kv_head_replicas start_idx = shard_id * shard_size if _is_cpu: @@ -1529,7 +1572,6 @@ class RowParallelLinear(LinearBase): params_dtype: Data type for the parameters. quant_config: Quantization configure. parallel_group: Select TP, attention TP, or an unsharded weight partition. - Mutually exclusive with explicit tp_rank and tp_size. Reduction and allocation policies remain independent. """ @@ -1544,13 +1586,13 @@ class RowParallelLinear(LinearBase): reduce_results: bool = True, quant_config: Optional[QuantizationConfig] = None, prefix: str = "", - tp_rank: Optional[int] = None, - tp_size: Optional[int] = None, + *, use_presharded_weights: bool = False, use_dp_attention_reduce: bool = False, - *, parallel_group: Optional[LinearParallelGroup] = None, ): + self.tp_group = _resolve_linear_group(parallel_group) + self.parallel_group = parallel_group quant_config = None if _disable_hip_linear_quant else quant_config super().__init__( input_size, output_size, skip_bias_add, params_dtype, quant_config, prefix @@ -1559,13 +1601,11 @@ class RowParallelLinear(LinearBase): self.with_bias = bias self.input_is_parallel = input_is_parallel self.reduce_results = reduce_results - self.parallel_group = parallel_group self.use_dp_attention_reduce = use_dp_attention_reduce # Divide the weight matrix along the last dimension. - tp_rank, tp_size = _resolve_linear_partition(parallel_group, tp_rank, tp_size) - self.tp_rank, self.tp_size = tp_rank, tp_size - self.input_size_per_partition = divide(input_size, self.tp_size) + _, tp_size = get_group_rank_size(self.tp_group) + self.input_size_per_partition = divide(input_size, tp_size) assert self.quant_method is not None self.use_presharded_weights = use_presharded_weights # Flag set by CpDecodeAttnTpContext to enable all_reduce during decode. @@ -1614,10 +1654,11 @@ class RowParallelLinear(LinearBase): param.weight_type = loaded_weight.item() # Materialize GGUF UninitializedParameter + tp_rank, tp_size = get_group_rank_size(self.tp_group) if is_gguf_weight and isinstance(param, UninitializedParameter): weight_shape = list(loaded_weight.shape) if input_dim: - weight_shape[input_dim] = weight_shape[input_dim] // self.tp_size + weight_shape[input_dim] = weight_shape[input_dim] // tp_size param.materialize(tuple(weight_shape), dtype=loaded_weight.dtype) param_data = param.data @@ -1629,7 +1670,7 @@ class RowParallelLinear(LinearBase): and not self.use_presharded_weights ): shard_size = param_data.shape[input_dim] - start_idx = self.tp_rank * shard_size + start_idx = tp_rank * shard_size if _is_cpu: from sglang.srt.model_loader.weight_utils import ( @@ -1674,12 +1715,13 @@ class RowParallelLinear(LinearBase): assert loaded_weight.numel() == 1 loaded_weight = loaded_weight.reshape(1) + tp_rank, _ = get_group_rank_size(self.tp_group) if isinstance(param, RowvLLMParameter): # This `BasevLLMParameter` is defined in sglang/srt/layers/parameter.py, # It supports additional parameters like tp_rank and use_presharded_weights. param.load_row_parallel_weight( loaded_weight, - tp_rank=self.tp_rank, + tp_rank=tp_rank, use_presharded_weights=self.use_presharded_weights, ) else: @@ -1689,7 +1731,7 @@ class RowParallelLinear(LinearBase): try: param.load_row_parallel_weight( loaded_weight, - tp_rank=self.tp_rank, + tp_rank=tp_rank, use_presharded_weights=self.use_presharded_weights, ) except TypeError: @@ -1703,19 +1745,18 @@ class RowParallelLinear(LinearBase): forward_batch=None, output_tensor=None, ): + tp_rank, tp_size = get_group_rank_size(self.tp_group) if self.input_is_parallel: input_parallel = input_ else: - splitted_input = split_tensor_along_last_dim( - input_, num_partitions=self.tp_size - ) - input_parallel = splitted_input[self.tp_rank].contiguous() + splitted_input = split_tensor_along_last_dim(input_, num_partitions=tp_size) + input_parallel = splitted_input[tp_rank].contiguous() # Matrix multiply. assert self.quant_method is not None # Only fuse bias add into GEMM for rank 0 (this ensures that # bias will not get added more than once in TP>1 case) - bias_ = None if (self.tp_rank > 0 or self.skip_bias_add) else self.bias + bias_ = None if (tp_rank > 0 or self.skip_bias_add) else self.bias # Megatron SP "g-bar": reduce-scatter along the token dim instead of # all-reduce, leaving the output sharded for the next SP LayerNorm region. @@ -1723,7 +1764,7 @@ class RowParallelLinear(LinearBase): # reduce_results=False, so under SP the linear owns the reduction. if ( get_forward().sp_active - and self.tp_size > 1 + and tp_size > 1 and not skip_all_reduce and output_tensor is None ): @@ -1757,7 +1798,7 @@ class RowParallelLinear(LinearBase): # mlp_reduce_scatter ForwardFlag published by the decoder — callers # should not thread it into modules. if ( - ((self.reduce_results and self.tp_size > 1) or self.use_decode_attn_tp) + ((self.reduce_results and tp_size > 1) or self.use_decode_attn_tp) and not skip_all_reduce and not should_skip_mlp_all_reduce() ): @@ -1789,7 +1830,8 @@ class RowParallelLinear(LinearBase): s = f"input_features={self.input_size_per_partition}" s += f", output_features={self.output_size}" s += f", bias={self.bias is not None}" - s += f", tp_size={self.tp_size}" + _, tp_size = get_group_rank_size(self.tp_group) + s += f", tp_size={tp_size}" s += f", reduce_results={self.reduce_results}" return s @@ -1818,10 +1860,11 @@ class MergedColumnParallelRepeatedLinear(LinearBase): params_dtype: Optional[torch.dtype] = None, quant_config: Optional[QuantizationConfig] = None, prefix: str = "", - tp_rank: Optional[int] = None, - tp_size: Optional[int] = None, + *, parallel_group: Optional[LinearParallelGroup] = None, ): + self.tp_group = _resolve_linear_group(parallel_group) + self.parallel_group = parallel_group output_size = sum(column_output_sizes) + sum(repeated_output_sizes) super().__init__( input_size=input_size, @@ -1832,12 +1875,10 @@ class MergedColumnParallelRepeatedLinear(LinearBase): prefix=prefix, ) self.num_column_parallel = len(column_output_sizes) - self.tp_rank, self.tp_size = _resolve_linear_partition( - parallel_group, tp_rank, tp_size - ) + _, tp_size = get_group_rank_size(self.tp_group) self.output_partition_sizes = [ - divide(x, self.tp_size) for x in column_output_sizes + divide(x, tp_size) for x in column_output_sizes ] + repeated_output_sizes self.quant_method.create_weights( layer=self, @@ -1863,8 +1904,9 @@ class MergedColumnParallelRepeatedLinear(LinearBase): shard_size = self.output_partition_sizes[loaded_shard_id] param_data = param.data.narrow(output_dim, shard_offset, shard_size) + tp_rank, _ = get_group_rank_size(self.tp_group) if loaded_shard_id < self.num_column_parallel: - start_idx = self.tp_rank * shard_size + start_idx = tp_rank * shard_size loaded_weight = loaded_weight.narrow(output_dim, start_idx, shard_size) param_data.copy_(loaded_weight) @@ -1889,16 +1931,14 @@ class ColumnParallelBatchedLinear(nn.Module): input_size: int, output_size: int, dtype: torch.dtype, - tp_rank: Optional[int] = None, - tp_size: Optional[int] = None, + *, parallel_group: Optional[LinearParallelGroup] = None, ): super().__init__() - self.tp_rank, self.tp_size = _resolve_linear_partition( - parallel_group, tp_rank, tp_size - ) + self.tp_group = _resolve_linear_group(parallel_group) + _, tp_size = get_group_rank_size(self.tp_group) self.weight = nn.Parameter( - torch.empty(batch, output_size // self.tp_size, input_size, dtype=dtype), + torch.empty(batch, output_size // tp_size, input_size, dtype=dtype), requires_grad=False, ) setattr(self.weight, "weight_loader", self.weight_loader) @@ -1910,6 +1950,7 @@ class ColumnParallelBatchedLinear(nn.Module): self, param: Parameter, loaded_weight: torch.Tensor, loaded_shard_id: int ) -> torch.Tensor: shard_size = self.weight.shape[-2] - start_idx = self.tp_rank * shard_size + tp_rank, _ = get_group_rank_size(self.tp_group) + start_idx = tp_rank * shard_size loaded_weight = loaded_weight.narrow(0, start_idx, shard_size) param.data[loaded_shard_id].copy_(loaded_weight) diff --git a/python/sglang/srt/layers/quantization/blockwise_int8.py b/python/sglang/srt/layers/quantization/blockwise_int8.py index 4323743548..26299bd3ad 100644 --- a/python/sglang/srt/layers/quantization/blockwise_int8.py +++ b/python/sglang/srt/layers/quantization/blockwise_int8.py @@ -22,10 +22,10 @@ from sglang.srt.layers.quantization.base_config import ( from sglang.srt.layers.quantization.int8_utils import apply_w8a8_block_int8_linear from sglang.srt.layers.quantization.unquant import UnquantizedLinearMethod from sglang.srt.layers.quantization.utils import is_layer_skipped -from sglang.srt.runtime_context import get_parallel from sglang.srt.utils import set_weight_attrs if TYPE_CHECKING: + from sglang.srt.layers.linear import LinearBase from sglang.srt.layers.moe.token_dispatcher import ( CombineInput, StandardDispatchOutput, @@ -138,7 +138,7 @@ class BlockInt8LinearMethod(LinearMethodBase): def create_weights( self, - layer: torch.nn.Module, + layer: LinearBase, input_size_per_partition: int, output_partition_sizes: List[int], input_size: int, @@ -149,7 +149,9 @@ class BlockInt8LinearMethod(LinearMethodBase): output_size_per_partition = sum(output_partition_sizes) weight_loader = extra_weight_attrs.get("weight_loader") - tp_size = get_parallel().tp_size + tp_group = layer.tp_group + + tp_size = tp_group.world_size if tp_group is not None else 1 block_n, block_k = ( self.quant_config.weight_block_size[0], @@ -271,7 +273,7 @@ class BlockInt8MoEMethod(FusedMoEMethodBase): if self.quant_config.is_checkpoint_int8_serialized: params_dtype = torch.int8 - tp_size = get_parallel().tp_size + tp_size = layer.moe_tp_size block_n, block_k = ( self.quant_config.weight_block_size[0], diff --git a/python/sglang/srt/layers/quantization/fp8.py b/python/sglang/srt/layers/quantization/fp8.py index 3d62fd5e1e..4291618b36 100644 --- a/python/sglang/srt/layers/quantization/fp8.py +++ b/python/sglang/srt/layers/quantization/fp8.py @@ -113,6 +113,7 @@ from sglang.srt.utils import ( ) if TYPE_CHECKING: + from sglang.srt.layers.linear import LinearBase from sglang.srt.layers.moe.moe_runner.aiter import AiterMoeQuantInfo from sglang.srt.layers.moe.token_dispatcher import CombineInput, DispatchOutput from sglang.srt.layers.quantization.w4afp8 import W4AFp8Config @@ -555,6 +556,7 @@ class Fp8LinearMethod(LinearMethodBase): @staticmethod def validate_block_quant_shapes( + layer: LinearBase, quant_config, input_size: int, input_size_per_partition: int, @@ -573,7 +575,8 @@ class Fp8LinearMethod(LinearMethodBase): "Skipping block quantization checks for weight partition." ) else: - tp_size = get_parallel().tp_size + tp_group = layer.tp_group + tp_size = tp_group.world_size if tp_group is not None else 1 # Required by row parallel if tp_size > 1 and input_size // input_size_per_partition == tp_size: if input_size_per_partition % block_k != 0: @@ -623,6 +626,7 @@ class Fp8LinearMethod(LinearMethodBase): if block_quant: block_n, block_k = quant_config.weight_block_size Fp8LinearMethod.validate_block_quant_shapes( + layer, quant_config, input_size, input_size_per_partition, @@ -1433,7 +1437,7 @@ class Fp8MoEMethod(FusedMoEMethodBase): if is_checkpoint_fp8_serialized: params_dtype = torch.uint32 if _use_hip_int4 else torch.float8_e4m3fn - tp_size = get_parallel().tp_size + tp_size = layer.moe_tp_size w13_num_shards = 2 if layer.moe_runner_config.is_gated else 1 w13_up_dim, w2_up_dim, weight_padded = get_moe_weight_sizes( diff --git a/python/sglang/srt/layers/quantization/fp8_utils.py b/python/sglang/srt/layers/quantization/fp8_utils.py index bf4f10134a..4dc8ea4e24 100755 --- a/python/sglang/srt/layers/quantization/fp8_utils.py +++ b/python/sglang/srt/layers/quantization/fp8_utils.py @@ -3,7 +3,7 @@ from __future__ import annotations import logging from enum import Enum from functools import lru_cache, partial -from typing import Callable, List, Optional, Tuple, Union +from typing import TYPE_CHECKING, Callable, List, Optional, Tuple, Union import torch @@ -32,7 +32,6 @@ from sglang.srt.layers import deep_gemm_wrapper from sglang.srt.layers.quantization.mxfp4_tensor import MXFP4QuantizeUtil from sglang.srt.runtime_context import ( get_exec, - get_parallel, get_platform, ) from sglang.srt.utils import ( @@ -55,6 +54,9 @@ from sglang.srt.utils import ( from sglang.srt.utils.common import torch_release from sglang.srt.utils.custom_op import register_custom_op +if TYPE_CHECKING: + from sglang.srt.layers.linear import LinearBase + logger = logging.getLogger(__name__) _is_hip = is_hip() @@ -2515,7 +2517,7 @@ def apply_fp8_ptpc_linear( def validate_fp8_block_shape( - layer: torch.nn.Module, + layer: LinearBase, input_size: int, output_size: int, input_size_per_partition: int, @@ -2524,9 +2526,9 @@ def validate_fp8_block_shape( ) -> None: """Validate block quantization shapes for tensor parallelism.""" - # Lazy: a ``getattr`` default would read the published bag even for a - # layer that carries its own tp_size. - tp_size = layer.tp_size if hasattr(layer, "tp_size") else get_parallel().tp_size + tp_group = layer.tp_group + + tp_size = tp_group.world_size if tp_group is not None else 1 block_n, block_k = block_size[0], block_size[1] # Required by row parallel diff --git a/python/sglang/srt/lora/layers.py b/python/sglang/srt/lora/layers.py index 9a314e580a..9e47c6c4b6 100644 --- a/python/sglang/srt/lora/layers.py +++ b/python/sglang/srt/lora/layers.py @@ -9,6 +9,7 @@ from sglang.srt.distributed import ( tensor_model_parallel_all_gather, tensor_model_parallel_all_reduce, ) +from sglang.srt.distributed.utils import get_group_rank_size from sglang.srt.environ import envs from sglang.srt.layers.linear import ( ColumnParallelLinear, @@ -79,9 +80,7 @@ class BaseLayerWithLoRA(nn.Module): def set_lora_info(self, *args): pass - # Weight slicing derives the shard rank from the wrapped base layer - # (base_layer.tp_rank): under DP attention, attention layers are built - # on the attn-TP group, so the outer/global TP rank would overshoot. + # LoRA slices follow the base layer's group; attention TP can differ from TP. def slice_lora_a_weights(self, A: torch.Tensor): pass @@ -520,7 +519,7 @@ class ColumnParallelLinearWithLoRA(BaseLayerWithLoRA): return A def slice_lora_b_weights(self, B: torch.Tensor): - local_tp_rank = self.base_layer.tp_rank + local_tp_rank = get_group_rank_size(self.base_layer.tp_group)[0] shard_size = self.base_layer.output_partition_sizes[0] start_idx = local_tp_rank * shard_size end_idx = (local_tp_rank + 1) * shard_size @@ -623,7 +622,7 @@ class MergedColumnParallelLinearWithLoRA(ColumnParallelLinearWithLoRA): return A def slice_lora_b_weights(self, B: torch.Tensor): - local_tp_rank = self.base_layer.tp_rank + local_tp_rank = get_group_rank_size(self.base_layer.tp_group)[0] partition_sizes = self.base_layer.output_partition_sizes output_sizes = self.base_layer.output_sizes slices = [] @@ -648,13 +647,13 @@ class InklingQKVRLinearWithLoRA(MergedColumnParallelLinearWithLoRA): def slice_lora_b_weights(self, B: torch.Tensor): bl = self.base_layer - tp_rank = bl.tp_rank + tp_rank = get_group_rank_size(bl.tp_group)[0] hd, nkv, nh, dr, tp = ( bl.inkling_head_dim, bl.inkling_num_kv_heads, bl.inkling_num_heads, bl.inkling_d_rel, - bl.inkling_tp_size, + get_group_rank_size(bl.tp_group)[1], ) q_size, kv_size, r_size = hd * nh, hd * nkv, dr * nh q_off, k_off, v_off, r_off = 0, q_size, q_size + kv_size, q_size + 2 * kv_size @@ -738,17 +737,18 @@ class QKVParallelLinearWithLoRA(ColumnParallelLinearWithLoRA): q_proj_shard_size = base_layer.q_proj_shard_size kv_proj_shard_size = base_layer.kv_proj_shard_size num_kv_head_replicas = base_layer.num_kv_head_replicas - local_tp_rank = base_layer.tp_rank + local_tp_rank = get_group_rank_size(base_layer.tp_group)[0] q_start_idx = q_proj_shard_size * local_tp_rank q_end_idx = q_start_idx + q_proj_shard_size - kv_shard_id = local_tp_rank // num_kv_head_replicas + kv_tp_rank, _ = get_group_rank_size(base_layer.kv_tp_group) + kv_shard_id = kv_tp_rank // num_kv_head_replicas kv_start_idx = kv_proj_shard_size * kv_shard_id kv_end_idx = kv_start_idx + kv_proj_shard_size - q_size = base_layer.output_sizes[0] - k_size = base_layer.output_sizes[1] // num_kv_head_replicas + q_size = base_layer.total_num_heads * base_layer.head_size + k_size = base_layer.total_num_kv_heads * base_layer.head_size B_q_shard = B[q_start_idx:q_end_idx, :] B_k_shard = B[q_size + kv_start_idx : q_size + kv_end_idx, :] B_v_shard = B[q_size + k_size + kv_start_idx : q_size + k_size + kv_end_idx, :] @@ -805,13 +805,12 @@ class RowParallelLinearWithLoRA(BaseLayerWithLoRA): self.lora_backend.start_lora_a_overlap(x, self.A_buffer) def forward(self, input_: torch.Tensor, skip_all_reduce=False, forward_batch=None): + tp_rank, tp_size = get_group_rank_size(self.base_layer.tp_group) if self.base_layer.input_is_parallel: input_parallel = input_ else: - splitted_input = split_tensor_along_last_dim( - input_, num_partitions=self.base_layer.tp_size - ) - input_parallel = splitted_input[self.base_layer.tp_rank].contiguous() + splitted_input = split_tensor_along_last_dim(input_, num_partitions=tp_size) + input_parallel = splitted_input[tp_rank].contiguous() lora_active = self.lora_active if lora_active: @@ -819,7 +818,7 @@ class RowParallelLinearWithLoRA(BaseLayerWithLoRA): bias_ = ( None - if (self.base_layer.tp_rank > 0 or self.base_layer.skip_bias_add) + if (tp_rank > 0 or self.base_layer.skip_bias_add) else self.base_layer.bias ) output_parallel = self.base_layer.quant_method.apply( @@ -828,7 +827,7 @@ class RowParallelLinearWithLoRA(BaseLayerWithLoRA): should_reduce = ( self.base_layer.reduce_results - and self.base_layer.tp_size > 1 + and tp_size > 1 and not skip_all_reduce and not should_skip_mlp_all_reduce() ) @@ -865,7 +864,7 @@ class RowParallelLinearWithLoRA(BaseLayerWithLoRA): return output_, output_bias def slice_lora_a_weights(self, A: torch.Tensor): - local_tp_rank = self.base_layer.tp_rank + local_tp_rank, _ = get_group_rank_size(self.base_layer.tp_group) shard_size = self.base_layer.input_size_per_partition start_idx = local_tp_rank * shard_size end_idx = (local_tp_rank + 1) * shard_size diff --git a/python/sglang/srt/lora/trtllm_lora_temp/attention.py b/python/sglang/srt/lora/trtllm_lora_temp/attention.py index 332325a4af..e7584c2903 100644 --- a/python/sglang/srt/lora/trtllm_lora_temp/attention.py +++ b/python/sglang/srt/lora/trtllm_lora_temp/attention.py @@ -14,6 +14,7 @@ from sglang.srt.distributed import ( tensor_model_parallel_all_gather, tensor_model_parallel_all_reduce, ) +from sglang.srt.distributed.utils import get_group_rank_size from sglang.srt.layers.moe.utils import should_skip_mlp_all_reduce from sglang.srt.lora.trtllm_lora_temp import ( get_lora_side_stream, @@ -25,7 +26,6 @@ from sglang.srt.lora.trtllm_lora_temp import ( lora_overlap_alloc_stream, supports_two_stream_dense_lora, ) -from sglang.srt.runtime_context import get_parallel def qkv_proj_lora_forward(self, input_: torch.Tensor): @@ -96,13 +96,11 @@ def row_parallel_lora_forward( """ # We need ``input_parallel`` to gate the per-batch decode check (its # token-count drives the threshold, not the unsplit ``input_``). + tp_rank, tp_size = get_group_rank_size(self.base_layer.tp_group) if self.base_layer.input_is_parallel: input_parallel = input_ else: - tp_rank = get_parallel().tp_rank - splitted_input = split_tensor_along_last_dim( - input_, num_partitions=self.base_layer.tp_size - ) + splitted_input = split_tensor_along_last_dim(input_, num_partitions=tp_size) input_parallel = splitted_input[tp_rank].contiguous() if ( @@ -113,9 +111,7 @@ def row_parallel_lora_forward( return get_original_row_forward()(self, input_, skip_all_reduce, forward_batch) bias_ = ( - None - if (self.base_layer.tp_rank > 0 or self.base_layer.skip_bias_add) - else self.base_layer.bias + None if (tp_rank > 0 or self.base_layer.skip_bias_add) else self.base_layer.bias ) side_stream = get_lora_side_stream() @@ -146,7 +142,7 @@ def row_parallel_lora_forward( should_reduce = ( self.base_layer.reduce_results - and self.base_layer.tp_size > 1 + and tp_size > 1 and not skip_all_reduce and not should_skip_mlp_all_reduce() ) diff --git a/python/sglang/srt/model_loader/weight_utils.py b/python/sglang/srt/model_loader/weight_utils.py index 3a9f2aa127..6b274b97af 100644 --- a/python/sglang/srt/model_loader/weight_utils.py +++ b/python/sglang/srt/model_loader/weight_utils.py @@ -19,6 +19,7 @@ import tempfile import threading from pathlib import Path from typing import ( + TYPE_CHECKING, Callable, Dict, Generator, @@ -1501,30 +1502,47 @@ def default_weight_loader(param: torch.Tensor, loaded_weight: torch.Tensor) -> N param.data.copy_(loaded_weight) +if TYPE_CHECKING: + from sglang.srt.layers.linear import LinearParallelGroup + + LoaderFunction = Callable[[torch.Tensor, torch.Tensor], torch.Tensor] def sharded_weight_loader( shard_axis: int, tp_rank_getter=None, + *, + parallel_group: Optional["LinearParallelGroup"] = None, ) -> LoaderFunction: - """Create a weight loader that shards the weights along the given axis""" + """Create a weight loader with placement frozen in its construction scope. - def loader(param: torch.Tensor, loaded_weight: torch.Tensor) -> None: + Without a group selection, retain the attention rank and legacy CPU padding + width. An explicit rank getter is evaluated once when creating the loader. + """ + if parallel_group is not None: + if tp_rank_getter is not None: + raise ValueError("parallel_group cannot be combined with tp_rank_getter") + from sglang.srt.layers.linear import resolve_linear_parallel_group + + tp_rank, tp_size = resolve_linear_parallel_group(parallel_group) + else: tp_rank = ( tp_rank_getter() if tp_rank_getter is not None else get_parallel().attn_tp_rank ) + tp_size = get_parallel().tp_size + def loader(param: torch.Tensor, loaded_weight: torch.Tensor) -> None: shard_size = param.data.shape[shard_axis] start_idx = tp_rank * shard_size if ( is_cpu() and ( - loaded_weight.size(0) % get_parallel().tp_size != 0 - or loaded_weight.size(0) < get_parallel().tp_size * shard_size + loaded_weight.size(0) % tp_size != 0 + or loaded_weight.size(0) < tp_size * shard_size ) and loaded_weight.dim() == 1 ): diff --git a/python/sglang/srt/models/bailing_moe_v3.py b/python/sglang/srt/models/bailing_moe_v3.py index 474654475d..3cdc40ea4c 100644 --- a/python/sglang/srt/models/bailing_moe_v3.py +++ b/python/sglang/srt/models/bailing_moe_v3.py @@ -330,13 +330,12 @@ class BailingMLP(nn.Module): parallel_group=parallel_group, ) - self.tp_size = self.gate_up_proj.tp_size + group = self.gate_up_proj.tp_group + tp_size = group.world_size if group is not None else 1 if self.padded_intermediate_size > self.intermediate_size: - self.padded_size_per_partition = ( - self.padded_intermediate_size // self.tp_size - ) - self.effective_size_per_partition = self.intermediate_size // self.tp_size + self.padded_size_per_partition = self.padded_intermediate_size // tp_size + self.effective_size_per_partition = self.intermediate_size // tp_size self.pad_size_per_partition = ( self.padded_size_per_partition - self.effective_size_per_partition ) diff --git a/python/sglang/srt/models/dflash.py b/python/sglang/srt/models/dflash.py index c8ce6af88a..3b0f16b998 100644 --- a/python/sglang/srt/models/dflash.py +++ b/python/sglang/srt/models/dflash.py @@ -295,7 +295,7 @@ class DFlashAttention(nn.Module): ) set_weight_attrs( self.attention_sink_bias, - {"weight_loader": sharded_weight_loader(0)}, + {"weight_loader": sharded_weight_loader(0, parallel_group="tp")}, ) elif draft_cfg.attention_sink_bias: # Per-head sink bias; each TP rank owns its slice of the @@ -306,7 +306,7 @@ class DFlashAttention(nn.Module): ) set_weight_attrs( self.attention_sink_bias, - {"weight_loader": sharded_weight_loader(0)}, + {"weight_loader": sharded_weight_loader(0, parallel_group="tp")}, ) self.attn = RadixAttention( num_heads=self.num_heads, diff --git a/python/sglang/srt/models/glm5_next.py b/python/sglang/srt/models/glm5_next.py index 4da28bdf3d..0ad1aa0f04 100644 --- a/python/sglang/srt/models/glm5_next.py +++ b/python/sglang/srt/models/glm5_next.py @@ -526,7 +526,7 @@ class Glm5NextLinearAttention(nn.Module): set_weight_attrs( self.dt_bias, - {"weight_loader": sharded_weight_loader(0)}, + {"weight_loader": sharded_weight_loader(0, parallel_group="attn_tp")}, ) self.qkv_conv1d = MergedColumnParallelLinear( @@ -546,7 +546,7 @@ class Glm5NextLinearAttention(nn.Module): ) set_weight_attrs( self.A_log, - {"weight_loader": sharded_weight_loader(2)}, + {"weight_loader": sharded_weight_loader(2, parallel_group="attn_tp")}, ) self.o_norm = FusedRMSNormGated( diff --git a/python/sglang/srt/models/granite.py b/python/sglang/srt/models/granite.py index c5102822d6..39dbcd8156 100644 --- a/python/sglang/srt/models/granite.py +++ b/python/sglang/srt/models/granite.py @@ -79,7 +79,9 @@ def build_attention_sinks(num_heads: int) -> nn.Parameter: attn_backend = get_exec().kernel.attention_backend sinks_dtype = torch.float32 if attn_backend == "trtllm_mha" else torch.bfloat16 sinks = nn.Parameter(torch.empty(num_heads, dtype=sinks_dtype), requires_grad=False) - set_weight_attrs(sinks, {"weight_loader": sharded_weight_loader(0)}) + set_weight_attrs( + sinks, {"weight_loader": sharded_weight_loader(0, parallel_group="tp")} + ) return sinks diff --git a/python/sglang/srt/models/inkling.py b/python/sglang/srt/models/inkling.py index ef999fa50f..92ab78a641 100644 --- a/python/sglang/srt/models/inkling.py +++ b/python/sglang/srt/models/inkling.py @@ -15,6 +15,7 @@ from sglang.srt.configs.inkling import ( InklingModelConfig, InklingVisionConfig, ) +from sglang.srt.distributed.utils import get_group_rank_size from sglang.srt.environ import envs from sglang.srt.layers.layernorm import RMSNorm from sglang.srt.layers.logits_processor import LogitsProcessor @@ -1434,6 +1435,7 @@ class InklingForConditionalGeneration(nn.Module): def load_weights(self, weights: Iterable[Tuple[str, torch.Tensor]]) -> Set[str]: params_dict = dict(self.named_parameters()) + modules_dict = dict(self.named_modules()) loaded_params: Set[str] = set() embed_tokens_weight: Optional[torch.Tensor] = None @@ -1454,19 +1456,12 @@ class InklingForConditionalGeneration(nn.Module): if any(name.endswith(suffix) for suffix in KV_REPLICATED_SUFFIXES): layer_id = get_layer_id(name) - if layer_id is not None: - num_kv_heads, head_dim = ( - ( - self.text_config.swa_num_key_value_heads, - self.text_config.swa_head_dim, - ) - if layer_id in set(self.text_config.local_layer_ids) - else ( - self.text_config.num_key_value_heads, - self.text_config.head_dim, - ) - ) - attn_tp_size = get_parallel().attn_tp_size + attention = modules_dict.get(name.rsplit(".", 2)[0]) + if layer_id is not None and attention is not None: + qkvr = getattr(attention.qkvr, "base_layer", attention.qkvr) + num_kv_heads = qkvr.inkling_num_kv_heads + head_dim = qkvr.inkling_head_dim + attn_tp_size = get_group_rank_size(qkvr.tp_group)[1] if ( attn_tp_size > num_kv_heads and loaded_weight.shape[0] == num_kv_heads * head_dim @@ -1480,7 +1475,9 @@ class InklingForConditionalGeneration(nn.Module): .reshape(attn_tp_size * head_dim, -1) ) else: - kv_head_idx = get_parallel().attn_tp_rank // replicas + kv_head_idx = ( + get_group_rank_size(qkvr.tp_group)[0] // replicas + ) loaded_weight = loaded_weight.narrow( 0, kv_head_idx * head_dim, head_dim ) @@ -1517,7 +1514,9 @@ class InklingForConditionalGeneration(nn.Module): param = params_dict[sgl_name] if loaded_weight.shape != param.data.shape: shard_size = param.data.shape[0] - start = get_parallel().attn_tp_rank * shard_size + projection = modules_dict[sgl_name.rsplit(".", 1)[0]] + projection = getattr(projection, "base_layer", projection) + start = get_group_rank_size(projection.tp_group)[0] * shard_size loaded_weight = loaded_weight.narrow(0, start, shard_size) if lora_compatible_layout_enabled(): # Local interleaved rows -> [gate||up] so contiguous swiglu and @@ -1908,6 +1907,7 @@ class InklingForConditionalGenerationMTP(nn.Module): def load_weights(self, weights: Iterable[Tuple[str, torch.Tensor]]) -> Set[str]: params_dict = dict(self.named_parameters()) + modules_dict = dict(self.named_modules()) loaded_params: Set[str] = set() for name, loaded_weight in weights: @@ -1954,7 +1954,9 @@ class InklingForConditionalGenerationMTP(nn.Module): param = params_dict[sgl_name] if loaded_weight.shape != param.data.shape: shard_size = param.data.shape[0] - start = get_parallel().attn_tp_rank * shard_size + projection = modules_dict[sgl_name.rsplit(".", 1)[0]] + projection = getattr(projection, "base_layer", projection) + start = get_group_rank_size(projection.tp_group)[0] * shard_size loaded_weight = loaded_weight.narrow(0, start, shard_size) default_weight_loader(param, loaded_weight) loaded_params.add(sgl_name) diff --git a/python/sglang/srt/models/inkling_common/attn.py b/python/sglang/srt/models/inkling_common/attn.py index f64c325a91..0a87b3a788 100644 --- a/python/sglang/srt/models/inkling_common/attn.py +++ b/python/sglang/srt/models/inkling_common/attn.py @@ -17,6 +17,7 @@ from sglang.kernels.ops.attention.score_mod import ( ) from sglang.kernels.ops.gemm.inkling_rel_proj import rel_proj_small_t from sglang.kernels.ops.memory.row_compact import row_compact_bf16 +from sglang.srt.distributed.utils import get_group_rank_size from sglang.srt.environ import envs from sglang.srt.layers.linear import MergedColumnParallelLinear, RowParallelLinear from sglang.srt.layers.quantization.base_config import QuantizationConfig @@ -276,7 +277,6 @@ class InklingQKVRLinear(MergedColumnParallelLinear): self.inkling_head_dim = inkling_head_dim self.inkling_num_heads = inkling_num_heads self.inkling_d_rel = inkling_d_rel - self.inkling_tp_size = self.tp_size class InklingAttention(nn.Module): @@ -1000,7 +1000,11 @@ class InklingAttention(nn.Module): ) if buf is not None and type(wo_ud.quant_method) is UnquantizedLinearMethod: torch.matmul(attn_output, wo_ud.weight.t(), out=buf) - bias_ = None if (wo_ud.tp_rank > 0 or wo_ud.skip_bias_add) else wo_ud.bias + bias_ = ( + None + if (get_group_rank_size(wo_ud.tp_group)[0] > 0 or wo_ud.skip_bias_add) + else wo_ud.bias + ) if bias_ is not None: buf.add_(bias_) if not reduce: diff --git a/python/sglang/srt/models/kimi_k3.py b/python/sglang/srt/models/kimi_k3.py index d1d31e6f42..689004c50a 100644 --- a/python/sglang/srt/models/kimi_k3.py +++ b/python/sglang/srt/models/kimi_k3.py @@ -1714,7 +1714,10 @@ class KimiK3DeltaAttention(nn.Module): self.dt_bias = nn.Parameter( torch.empty(divide(projection_size, self.attn_tp_size), dtype=torch.float32) ) - set_weight_attrs(self.dt_bias, {"weight_loader": sharded_weight_loader(0)}) + set_weight_attrs( + self.dt_bias, + {"weight_loader": sharded_weight_loader(0, parallel_group="attn_tp")}, + ) self.qkv_conv1d = MergedColumnParallelLinear( input_size=self.conv_size, diff --git a/python/sglang/srt/models/kimi_linear.py b/python/sglang/srt/models/kimi_linear.py index b76c405b56..9ad88d8a16 100644 --- a/python/sglang/srt/models/kimi_linear.py +++ b/python/sglang/srt/models/kimi_linear.py @@ -387,7 +387,10 @@ class KimiDeltaAttention(nn.Module): ) ) - set_weight_attrs(self.dt_bias, {"weight_loader": sharded_weight_loader(0)}) + set_weight_attrs( + self.dt_bias, + {"weight_loader": sharded_weight_loader(0, parallel_group=parallel_group)}, + ) self.qkv_conv1d = MergedColumnParallelLinear( input_size=self.conv_size, @@ -406,7 +409,10 @@ class KimiDeltaAttention(nn.Module): self.A_log = nn.Parameter( torch.empty(1, 1, self.local_num_heads, 1, dtype=torch.float32) ) - set_weight_attrs(self.A_log, {"weight_loader": sharded_weight_loader(2)}) + set_weight_attrs( + self.A_log, + {"weight_loader": sharded_weight_loader(2, parallel_group=parallel_group)}, + ) self.o_norm = FusedRMSNormGated( self.head_dim, eps=rms_norm_eps, activation="sigmoid" diff --git a/python/sglang/srt/models/lfm2.py b/python/sglang/srt/models/lfm2.py index d551014983..4bfbff8f6c 100644 --- a/python/sglang/srt/models/lfm2.py +++ b/python/sglang/srt/models/lfm2.py @@ -304,11 +304,15 @@ class Lfm2ShortConv(nn.Module): self.conv_weight = nn.Parameter( torch.empty(self.hidden_size_per_partition, self.conv_kernel) ) - set_weight_attrs(self.conv_weight, {"weight_loader": sharded_weight_loader(0)}) + set_weight_attrs( + self.conv_weight, + {"weight_loader": sharded_weight_loader(0, parallel_group="tp")}, + ) if self.use_bias: self.conv_bias = nn.Parameter(torch.empty(self.hidden_size_per_partition)) set_weight_attrs( - self.conv_bias, {"weight_loader": sharded_weight_loader(0)} + self.conv_bias, + {"weight_loader": sharded_weight_loader(0, parallel_group="tp")}, ) else: self.register_parameter("conv_bias", None) diff --git a/python/sglang/srt/models/lfm2_moe.py b/python/sglang/srt/models/lfm2_moe.py index edfe578304..c8864cc92a 100644 --- a/python/sglang/srt/models/lfm2_moe.py +++ b/python/sglang/srt/models/lfm2_moe.py @@ -319,11 +319,15 @@ class Lfm2MoeShortConv(nn.Module): self.conv_weight = nn.Parameter( torch.empty(self.hidden_size_per_partition, self.conv_kernel) ) - set_weight_attrs(self.conv_weight, {"weight_loader": sharded_weight_loader(0)}) + set_weight_attrs( + self.conv_weight, + {"weight_loader": sharded_weight_loader(0, parallel_group="tp")}, + ) if self.use_bias: self.conv_bias = nn.Parameter(torch.empty(self.hidden_size_per_partition)) set_weight_attrs( - self.conv_bias, {"weight_loader": sharded_weight_loader(0)} + self.conv_bias, + {"weight_loader": sharded_weight_loader(0, parallel_group="tp")}, ) else: self.register_parameter("conv_bias", None) diff --git a/python/sglang/srt/models/minicpm.py b/python/sglang/srt/models/minicpm.py index b28ab43924..e0f67c55f4 100644 --- a/python/sglang/srt/models/minicpm.py +++ b/python/sglang/srt/models/minicpm.py @@ -277,7 +277,8 @@ class MiniCPMLightningMixer(nn.Module): if self.use_output_norm: self.o_norm = RMSNorm(self.num_heads * self.head_dim, eps=self.rms_norm_eps) set_weight_attrs( - self.o_norm.weight, {"weight_loader": sharded_weight_loader(0)} + self.o_norm.weight, + {"weight_loader": sharded_weight_loader(0, parallel_group="tp")}, ) if self.use_output_gate: diff --git a/python/sglang/srt/models/qwen2_5_vl.py b/python/sglang/srt/models/qwen2_5_vl.py index 7b898d67de..62fe338447 100644 --- a/python/sglang/srt/models/qwen2_5_vl.py +++ b/python/sglang/srt/models/qwen2_5_vl.py @@ -54,7 +54,6 @@ from sglang.srt.layers.linear import ( MergedColumnParallelLinear, ReplicatedLinear, RowParallelLinear, - resolve_linear_parallel_group, ) from sglang.srt.layers.logits_processor import LogitsProcessor from sglang.srt.layers.pooler import Pooler, PoolingType @@ -151,7 +150,6 @@ class Qwen2_5_VLMLP(nn.Module): parallel_group = "replicated" elif parallel_group is None: parallel_group = "tp" - self.tp_rank, self.tp_size = resolve_linear_parallel_group(parallel_group) self.fuse_gate_up = fuse_gate_up if fuse_gate_up: self.gate_up_proj = MergedColumnParallelLinear( @@ -178,7 +176,11 @@ class Qwen2_5_VLMLP(nn.Module): **projection_kwargs, prefix=add_prefix("up_proj", prefix), ) - if not self.fuse_gate_up and self.tp_size == 1: + self.tp_group = ( + self.gate_up_proj if self.fuse_gate_up else self.gate_proj + ).tp_group + tp_size = self.tp_group.world_size if self.tp_group is not None else 1 + if not self.fuse_gate_up and tp_size == 1: self.down_proj = ReplicatedLinear( hidden_features, in_features, diff --git a/python/sglang/srt/models/qwen3_5.py b/python/sglang/srt/models/qwen3_5.py index 5ebbe76c8f..aebb547e09 100644 --- a/python/sglang/srt/models/qwen3_5.py +++ b/python/sglang/srt/models/qwen3_5.py @@ -421,8 +421,14 @@ class Qwen3_5GatedDeltaNet(nn.Module): torch.empty(self.num_v_heads // self.attn_tp_size, dtype=torch.float32), ) - set_weight_attrs(self.A_log, {"weight_loader": sharded_weight_loader(0)}) - set_weight_attrs(self.dt_bias, {"weight_loader": sharded_weight_loader(0)}) + set_weight_attrs( + self.A_log, + {"weight_loader": sharded_weight_loader(0, parallel_group="attn_tp")}, + ) + set_weight_attrs( + self.dt_bias, + {"weight_loader": sharded_weight_loader(0, parallel_group="attn_tp")}, + ) conv_weights = self.conv1d.weight.view( self.conv1d.weight.size(0), self.conv1d.weight.size(2) diff --git a/python/sglang/srt/models/qwen3_next.py b/python/sglang/srt/models/qwen3_next.py index 938f166eed..cf7444960a 100644 --- a/python/sglang/srt/models/qwen3_next.py +++ b/python/sglang/srt/models/qwen3_next.py @@ -192,8 +192,14 @@ class Qwen3GatedDeltaNet(nn.Module): torch.zeros(self.num_v_heads // self.attn_tp_size, dtype=torch.float32) ) - set_weight_attrs(self.A_log, {"weight_loader": sharded_weight_loader(0)}) - set_weight_attrs(self.dt_bias, {"weight_loader": sharded_weight_loader(0)}) + set_weight_attrs( + self.A_log, + {"weight_loader": sharded_weight_loader(0, parallel_group="attn_tp")}, + ) + set_weight_attrs( + self.dt_bias, + {"weight_loader": sharded_weight_loader(0, parallel_group="attn_tp")}, + ) self.norm = ( RMSNormGated( self.head_v_dim, @@ -283,9 +289,14 @@ class Qwen3GatedDeltaNet(nn.Module): # Fused checkpoint: weight is in packed (per-head-group) # format. Do contiguous TP slice like ColumnParallelLinear. output_dim = getattr(param, "output_dim", None) - if output_dim is not None and module.tp_size > 1: + group = module.tp_group + if ( + output_dim is not None + and group is not None + and group.world_size > 1 + ): shard_size = param.data.shape[output_dim] - start_idx = module.tp_rank * shard_size + start_idx = group.rank_in_group * shard_size if ( _is_cpu and _is_amx_available ) and start_idx + shard_size > loaded_weight.shape[output_dim]: diff --git a/python/sglang/srt/models/qwen3_vl.py b/python/sglang/srt/models/qwen3_vl.py index c1af8f286a..9e86550656 100644 --- a/python/sglang/srt/models/qwen3_vl.py +++ b/python/sglang/srt/models/qwen3_vl.py @@ -144,13 +144,13 @@ class Qwen3_VisionMLP(nn.Module): parallel_group = _resolve_vision_parallel_group( use_data_parallel=use_data_parallel, parallel_group=parallel_group ) - self.tp_rank, self.tp_size = resolve_linear_parallel_group(parallel_group) + _, tp_size = resolve_linear_parallel_group(parallel_group) # TODO: this layer shards over attention TP but reduces over the full TP # group without attention DP; reduce over the attention-TP group so # attention CP narrower than TP can run it. reject_attn_tp_shard_with_tp_reduce( type(self).__name__, - shard_tp_size=self.tp_size, + shard_tp_size=tp_size, reduces_over_attn_tp=is_dp_attention_enabled(), multimodal_encoder=True, hint=", or --mm-enable-dp-encoder where the model supports it", @@ -163,6 +163,7 @@ class Qwen3_VisionMLP(nn.Module): prefix=add_prefix("linear_fc1", prefix), parallel_group=parallel_group, ) + self.tp_group = self.linear_fc1.tp_group self.linear_fc2 = RowParallelLinear( hidden_features, in_features, @@ -319,13 +320,13 @@ class Qwen3VLMoeVisionPatchMerger(nn.Module): parallel_group = _resolve_vision_parallel_group( use_data_parallel=use_data_parallel, parallel_group=parallel_group ) - self.tp_rank, self.tp_size = resolve_linear_parallel_group(parallel_group) + _, tp_size = resolve_linear_parallel_group(parallel_group) # TODO: this layer shards over attention TP but reduces over the full TP # group without attention DP; reduce over the attention-TP group so # attention CP narrower than TP can run it. reject_attn_tp_shard_with_tp_reduce( type(self).__name__, - shard_tp_size=self.tp_size, + shard_tp_size=tp_size, reduces_over_attn_tp=is_dp_attention_enabled(), multimodal_encoder=True, hint=", or --mm-enable-dp-encoder where the model supports it", @@ -338,6 +339,7 @@ class Qwen3VLMoeVisionPatchMerger(nn.Module): prefix=add_prefix("linear_fc1", prefix), parallel_group=parallel_group, ) + self.tp_group = self.linear_fc1.tp_group self.act_fn = nn.GELU() self.linear_fc2 = RowParallelLinear( self.padded_context_dim, diff --git a/python/sglang/test/kits/attention_unittest/attention_methods/mamba2_attention.py b/python/sglang/test/kits/attention_unittest/attention_methods/mamba2_attention.py index 76cf4fa473..cf4589efc2 100644 --- a/python/sglang/test/kits/attention_unittest/attention_methods/mamba2_attention.py +++ b/python/sglang/test/kits/attention_unittest/attention_methods/mamba2_attention.py @@ -13,7 +13,7 @@ _parallel_override = get_parallel().override( tp_rank=0, attn_tp_size=1, attn_tp_rank=0, - tp_group=SimpleNamespace(world_size=1), + tp_group=SimpleNamespace(rank_in_group=0, world_size=1), ) _parallel_override.__enter__() diff --git a/python/sglang/test/layer_ut_utils.py b/python/sglang/test/layer_ut_utils.py index bd324e73be..0ce4916e26 100644 --- a/python/sglang/test/layer_ut_utils.py +++ b/python/sglang/test/layer_ut_utils.py @@ -47,8 +47,7 @@ def make_tp1_column_parallel_linear( params_dtype=torch.bfloat16, quant_config=quant_config, prefix=prefix, - tp_rank=0, - tp_size=1, + parallel_group="replicated", **kwargs, ).cuda() diff --git a/python/sglang/test/parallel_groups.py b/python/sglang/test/parallel_groups.py index 579960a1ca..840d75d245 100644 --- a/python/sglang/test/parallel_groups.py +++ b/python/sglang/test/parallel_groups.py @@ -49,3 +49,9 @@ def publish(*args, **kwargs): def parallel_scope(**values): with get_parallel().override(**_group_metadata(values)) as parallel: yield parallel + + +def rank_size(layer, *, kv=False): + """Read the retained query or KV partition used by a native linear layer.""" + group = layer.kv_tp_group if kv else layer.tp_group + return (0, 1) if group is None else (group.rank_in_group, group.world_size) diff --git a/test/registered/dcp/test_dcp_layout_unit.py b/test/registered/dcp/test_dcp_layout_unit.py index a9c4948d9b..2c3b7f34ec 100644 --- a/test/registered/dcp/test_dcp_layout_unit.py +++ b/test/registered/dcp/test_dcp_layout_unit.py @@ -26,7 +26,7 @@ from sglang.srt.layers.dcp.layout import ( filter_dcp_local_chunk_kv_indices, get_dcp_lens, ) -from sglang.srt.layers.linear import QKVParallelLinear +from sglang.srt.layers.linear import QKVParallelLinear, ReplicatedParallelGroup from sglang.srt.mem_cache.allocator.paged import PagedTokenToKVPoolAllocator from sglang.srt.mem_cache.kv_cache_configurator import KVCacheConfigurator from sglang.srt.mem_cache.memory_pool import HybridLinearKVPool, KVWriteLoc @@ -387,18 +387,39 @@ class TestGetDcpLens(CustomTestCase): v_weight = torch.arange(16, dtype=torch.float32).view(4, hidden_size) + 200 for tp_rank in range(4): - layer = QKVParallelLinear( - hidden_size=hidden_size, - head_size=head_size, - total_num_heads=8, - total_num_kv_heads=2, - bias=False, - params_dtype=torch.float32, - tp_rank=tp_rank, + group = SimpleNamespace(rank_in_group=tp_rank, world_size=4) + with rc.get_parallel().override( + tp_group=group, + attn_tp_group=group, tp_size=4, - kv_tp_rank=tp_rank // 2, - kv_tp_size=2, - ) + tp_rank=tp_rank, + attn_tp_rank=tp_rank, + moe_tp_rank=tp_rank, + attn_dp_rank=0, + attn_cp_rank=0, + moe_dp_rank=0, + moe_ep_rank=0, + dcp_rank=tp_rank % 2, + **rc.derive_parallel_widths( + tp_size=4, + attn_cp_size=1, + attn_dp_size=1, + moe_ep_size=1, + moe_dp_size=1, + dcp_size=2, + dcp_enabled=True, + ), + ): + layer = QKVParallelLinear( + hidden_size=hidden_size, + head_size=head_size, + total_num_heads=8, + total_num_kv_heads=2, + bias=False, + params_dtype=torch.float32, + parallel_group="attn_tp", + kv_parallel_group=ReplicatedParallelGroup("attn_tp", 2), + ) layer.weight_loader(layer.weight, q_weight, "q") layer.weight_loader(layer.weight, k_weight, "k") layer.weight_loader(layer.weight, v_weight, "v") diff --git a/test/registered/unit/layers/quantization/test_modelopt_nvfp4.py b/test/registered/unit/layers/quantization/test_modelopt_nvfp4.py index dcc443f18b..d49a6914ff 100644 --- a/test/registered/unit/layers/quantization/test_modelopt_nvfp4.py +++ b/test/registered/unit/layers/quantization/test_modelopt_nvfp4.py @@ -35,8 +35,7 @@ class TestModelOptNvfp4(CustomTestCase): input_size=16, output_sizes=[16, 16], bias=False, - tp_rank=0, - tp_size=1, + parallel_group="replicated", ) def _make_qkv_layer(self): @@ -46,8 +45,7 @@ class TestModelOptNvfp4(CustomTestCase): total_num_heads=2, total_num_kv_heads=2, bias=False, - tp_rank=0, - tp_size=1, + parallel_group="replicated", ) def test_fused_scalar_scale_load_fills_all_logical_slots(self): diff --git a/test/registered/unit/layers/quantization/test_nvfp4_linear_backends.py b/test/registered/unit/layers/quantization/test_nvfp4_linear_backends.py index 484603e14c..0b326fcd43 100644 --- a/test/registered/unit/layers/quantization/test_nvfp4_linear_backends.py +++ b/test/registered/unit/layers/quantization/test_nvfp4_linear_backends.py @@ -85,8 +85,7 @@ def _make_merged_layer(n_half: int, k: int): params_dtype=torch.bfloat16, quant_config=quant_config, prefix="model.layers.0.mlp.gate_up_proj", - tp_rank=0, - tp_size=1, + parallel_group="replicated", ).cuda() # process_weights_after_loading collapses shard scale_2 with max() without diff --git a/test/registered/unit/layers/test_attention_projection_parallel_groups.py b/test/registered/unit/layers/test_attention_projection_parallel_groups.py index 5582041c1d..95bfab019b 100644 --- a/test/registered/unit/layers/test_attention_projection_parallel_groups.py +++ b/test/registered/unit/layers/test_attention_projection_parallel_groups.py @@ -10,12 +10,13 @@ import torch.nn.functional as F from sglang.srt.layers.dp_attention import initialize_dp_attention_flags from sglang.srt.layers.linear import QKVParallelLinear, RowParallelLinear -from sglang.srt.runtime_context import SpawnRanks, get_parallel, publish, reset_context +from sglang.srt.runtime_context import SpawnRanks, get_parallel, reset_context from sglang.srt.server_args import ServerArgs from sglang.test.ci.ci_register import register_cuda_ci +from sglang.test.parallel_groups import parallel_scope, publish, rank_size from sglang.test.test_utils import CustomTestCase -register_cuda_ci(est_time=15, stage="base-b", runner_config="1-gpu-small") +register_cuda_ci(est_time=15, stage="nightly", runner_config="1-gpu-large") ATTENTION_CASES = ( ("bailing", "head_wise"), @@ -222,10 +223,10 @@ def values(rows, columns, layer, offset=0): def load_projection(layer): """Load at rank zero and return the checkpoint shard owned at construction.""" - rank, size = layer.tp_rank, layer.tp_size + rank, size = rank_size(layer)[0], rank_size(layer)[1] row = isinstance(layer, RowParallelLinear) bias_shard = None - with get_parallel().override(tp_rank=0, attn_tp_rank=0, attn_dp_rank=0): + with parallel_scope(tp_rank=0, attn_tp_rank=0, attn_dp_rank=0): if isinstance(layer, QKVParallelLinear): weights, biases = [], [] for i, shard_id in enumerate(("q", "k", "v")): @@ -303,11 +304,11 @@ class TestAttentionProjectionParallelGroups(CustomTestCase): ) if model == "mtp" and dp_size == 1: size = 4 - self.assertEqual( - (layer.tp_rank, layer.tp_size), (rank % size, size) - ) + self.assertEqual(rank_size(layer), (rank % size, size)) inputs = values(2, shard.shape[1], layer, 7) - used_bias = bias if not row or layer.tp_rank == 0 else None + used_bias = ( + bias if not row or rank_size(layer)[0] == 0 else None + ) expected = F.linear(inputs, shard, used_bias) if row and layer.reduce_results: expected *= 4 @@ -317,9 +318,7 @@ class TestAttentionProjectionParallelGroups(CustomTestCase): group.all_reduce.reset_mock() group.all_gather.reset_mock() with ( - get_parallel().override( - tp_group=tp, attn_tp_group=attn - ), + parallel_scope(tp_group=tp, attn_tp_group=attn), patch( "sglang.srt.layers.linear.is_allocation_symmetric", return_value=True, @@ -352,22 +351,6 @@ class TestAttentionProjectionParallelGroups(CustomTestCase): 0, ) - def test_disabled_mtp_start_projections(self): - publish(ServerArgs(model_path="dummy", device="cpu"), role="test") - for variant in ("attention", "moe"): - module, names = build_attention("mtp", variant, start=False) - self.assertFalse(names) - self.assertFalse(hasattr(module, "eh_proj")) - self.assertTrue(hasattr(module, "final_layernorm")) - - def test_xllm_keeps_quantization_rejection(self): - from sglang.srt.layers.quantization.fp8 import Fp8Config - - publish(ServerArgs(model_path="dummy", device="cpu"), role="test") - for variant in ("gated", "mova"): - with self.assertRaisesRegex(ValueError, "unquantized bf16/fp16"): - build_attention("xllm", variant, quant_config=Fp8Config()) - if __name__ == "__main__": unittest.main() diff --git a/test/registered/unit/layers/test_custom_projection_parallel_groups.py b/test/registered/unit/layers/test_custom_projection_parallel_groups.py index 54caa754d8..02bf83f3e2 100644 --- a/test/registered/unit/layers/test_custom_projection_parallel_groups.py +++ b/test/registered/unit/layers/test_custom_projection_parallel_groups.py @@ -1,6 +1,5 @@ """Custom projections retain frozen checkpoint shards and native math.""" -import inspect import unittest from contextlib import nullcontext from unittest.mock import Mock, patch @@ -12,12 +11,13 @@ from sglang.srt.layers import linear, mova from sglang.srt.models.inkling_common import dense_mlp from sglang.srt.models.inkling_common.attn import InklingAttention from sglang.srt.models.inkling_common.moe import _build_inkling_shared_experts -from sglang.srt.runtime_context import SpawnRanks, get_parallel, publish, reset_context +from sglang.srt.runtime_context import SpawnRanks, reset_context from sglang.srt.server_args import ServerArgs from sglang.test.ci.ci_register import register_cpu_ci +from sglang.test.parallel_groups import parallel_scope, publish, rank_size from sglang.test.test_utils import CustomTestCase -register_cpu_ci(est_time=15, suite="base-a-test-cpu") +register_cpu_ci(est_time=15, stage="weekly", runner_config="cpu") def values(shape, offset=0, *, device="cpu", dtype=torch.float32): @@ -51,9 +51,9 @@ def build_attention(kv_heads, *, width=32, head_dim=8, quant_config=None, bias=F def load_projection(layer): weights, biases = [], [] - r, s = layer.tp_rank, layer.tp_size + r, s = rank_size(layer)[0], rank_size(layer)[1] row = isinstance(layer, linear.RowParallelLinear) - with get_parallel().override(tp_rank=0, attn_tp_rank=0, attn_dp_rank=0): + with parallel_scope(tp_rank=0, attn_tp_rank=0, attn_dp_rank=0): if row: full = values( (layer.output_size, layer.input_size), @@ -93,23 +93,7 @@ def load_projection(layer): def build_batch(group=None, *, width=16, linearized=False, execution_group=None): - kwargs = {} - if group is not None: - if ( - "parallel_group" - in inspect.signature(dense_mlp.InklingBatchDenseMLP).parameters - ): - kwargs["parallel_group"] = group - else: - parallel = get_parallel() - rank, size = ( - (0, 1) - if group == "replicated" - else (parallel.attn_tp_rank, parallel.attn_tp_size) - if group == "attn_tp" - else (parallel.tp_rank, parallel.tp_size) - ) - kwargs.update(tp_rank=rank, tp_size=size) + kwargs = {} if group is None else dict(parallel_group=group) return dense_mlp.InklingBatchDenseMLP( 2, width, @@ -131,7 +115,7 @@ def load_batch(module): "w2": values((2, module.hidden_size, full_f), 2, device=device, dtype=dtype), } full13 = torch.stack([full["w1"], full["w3"]], dim=2).flatten(1, 2) - with get_parallel().override(tp_rank=0, attn_tp_rank=0, attn_dp_rank=0): + with parallel_scope(tp_rank=0, attn_tp_rank=0, attn_dp_rank=0): module.weight_loader_fused(module.w13_weight, full13, "w13.weight", "w13") module.weight_loader_fused(module.w2_weight, full["w2"], "w2.weight", "w2") shards = { @@ -159,18 +143,7 @@ def batch_reference(x, gamma, shards): def build_values(group="attn_tp", *, width=16): - kwargs = dict(parallel_group=group) - if "parallel_group" not in inspect.signature(mova.RoutedValueExperts).parameters: - parallel = get_parallel() - rank, size = ( - (0, 1) - if group == "replicated" - else (parallel.attn_tp_rank, parallel.attn_tp_size) - if group == "attn_tp" - else (parallel.tp_rank, parallel.tp_size) - ) - kwargs = dict(tp_rank=rank, tp_size=size) - return mova.RoutedValueExperts(2, width, width, **kwargs) + return mova.RoutedValueExperts(2, width, width, parallel_group=group) def load_values(module, rank, size): @@ -179,7 +152,7 @@ def load_values(module, rank, size): device=module.weight.device, dtype=module.weight.dtype, ) - with get_parallel().override(tp_rank=0, attn_tp_rank=0, attn_dp_rank=0): + with parallel_scope(tp_rank=0, attn_tp_rank=0, attn_dp_rank=0): module.weight_loader(module.weight, full) expected = full.chunk(size, dim=1)[rank] torch.testing.assert_close(module.weight, expected) @@ -204,7 +177,7 @@ class TestCustomProjectionParallelGroups(CustomTestCase): ) for kv_heads in (1, 4): module = build_attention(kv_heads, bias=True) - self.assertEqual(module.qkvr.inkling_tp_size, 4 // dp) + self.assertEqual(rank_size(module.qkvr)[1], 4 // dp) self.assertEqual(module.qkvr.inkling_num_kv_heads, kv_heads) for name in ("qkvr", "wo_ud"): layer = getattr(module, name) @@ -212,12 +185,10 @@ class TestCustomProjectionParallelGroups(CustomTestCase): torch.testing.assert_close(layer.weight, expected) x = values((2, expected.shape[1])) used_bias = ( - bias if name == "qkvr" or layer.tp_rank == 0 else None + bias if name == "qkvr" or rank_size(layer)[0] == 0 else None ) with ( - get_parallel().override( - tp_group=Mock(), attn_tp_group=Mock() - ), + parallel_scope(tp_group=Mock(), attn_tp_group=Mock()), patch.object( linear, "use_symmetric_memory", @@ -290,7 +261,7 @@ class TestCustomProjectionParallelGroups(CustomTestCase): ) execution = Mock() with ( - get_parallel().override(tp_group=execution), + parallel_scope(tp_group=execution), patch( "sglang.srt.models.inkling_common.moe.use_inkling_shared_fused_moe", return_value=False, diff --git a/test/registered/unit/layers/test_kimi_attention_parallel_groups.py b/test/registered/unit/layers/test_kimi_attention_parallel_groups.py index 85c3d0b1da..d05c72892a 100644 --- a/test/registered/unit/layers/test_kimi_attention_parallel_groups.py +++ b/test/registered/unit/layers/test_kimi_attention_parallel_groups.py @@ -11,12 +11,13 @@ import torch.nn.functional as F from sglang.srt.layers.dp_attention import initialize_dp_attention_flags from sglang.srt.layers.linear import QKVParallelLinear, RowParallelLinear from sglang.srt.models.kimi_k3 import KimiK3DeltaAttention, KimiK3MLAAttention -from sglang.srt.runtime_context import SpawnRanks, get_parallel, publish, reset_context +from sglang.srt.runtime_context import SpawnRanks, reset_context from sglang.srt.server_args import ServerArgs from sglang.test.ci.ci_register import register_cpu_ci +from sglang.test.parallel_groups import parallel_scope, publish, rank_size from sglang.test.test_utils import CustomTestCase -register_cpu_ci(est_time=15, suite="base-a-test-cpu") +register_cpu_ci(est_time=15, stage="weekly", runner_config="cpu") KIMI_CASES = tuple((kind, gate) for kind in ("delta", "mla") for gate in (False, True)) @@ -94,9 +95,9 @@ def values(rows, columns, layer, offset=0): def load_projection(layer): - rank, size = layer.tp_rank, layer.tp_size + rank, size = rank_size(layer)[0], rank_size(layer)[1] row = isinstance(layer, RowParallelLinear) - with get_parallel().override(tp_rank=0, attn_tp_rank=0, attn_dp_rank=0): + with parallel_scope(tp_rank=0, attn_tp_rank=0, attn_dp_rank=0): if isinstance(layer, QKVParallelLinear): shards = [] for i, shard_id in enumerate(("q", "k", "v")): @@ -169,7 +170,7 @@ class TestKimiAttentionParallelGroups(CustomTestCase): shard = load_projection(layer) torch.testing.assert_close(layer.weight, shard) self.assertEqual( - (layer.tp_rank, layer.tp_size), + rank_size(layer), (rank % (4 // dp), 4 // dp), ) if name == "qkv_conv1d": @@ -193,9 +194,7 @@ class TestKimiAttentionParallelGroups(CustomTestCase): for group in (tp, attn): group.all_reduce.reset_mock() with ( - get_parallel().override( - tp_group=tp, attn_tp_group=attn - ), + parallel_scope(tp_group=tp, attn_tp_group=attn), patch( "sglang.srt.layers.linear.is_allocation_symmetric", return_value=True, diff --git a/test/registered/unit/layers/test_kimi_mlp_parallel_groups.py b/test/registered/unit/layers/test_kimi_mlp_parallel_groups.py index a7f8d5cd72..135cfbd7ed 100644 --- a/test/registered/unit/layers/test_kimi_mlp_parallel_groups.py +++ b/test/registered/unit/layers/test_kimi_mlp_parallel_groups.py @@ -1,6 +1,5 @@ """Kimi dense and shared MLPs freeze placement without changing row policy.""" -import inspect import unittest from contextlib import nullcontext from types import SimpleNamespace @@ -12,31 +11,17 @@ import torch.nn.functional as F from sglang.srt.layers import linear from sglang.srt.layers.dp_attention import initialize_dp_attention_flags from sglang.srt.models import kimi_k3 -from sglang.srt.runtime_context import SpawnRanks, get_parallel, publish, reset_context +from sglang.srt.runtime_context import SpawnRanks, reset_context from sglang.srt.server_args import ServerArgs from sglang.test.ci.ci_register import register_cpu_ci +from sglang.test.parallel_groups import parallel_scope, publish, rank_size from sglang.test.test_utils import CustomTestCase -register_cpu_ci(est_time=15, suite="base-a-test-cpu") +register_cpu_ci(est_time=15, stage="weekly", runner_config="cpu") def build_mlp(group=None, *, width=16, quant_config=None, reduce=True): - kwargs = {} - if group is not None: - if "parallel_group" in inspect.signature(kimi_k3.KimiK3MLP).parameters: - kwargs["parallel_group"] = group - else: - parallel = get_parallel() - if group == "replicated": - rank, size = 0, 1 - elif group == "shared_experts_tp": - rank = parallel.shared_experts_tp_group.rank_in_group - size = parallel.shared_experts_tp_group.world_size - elif group == "attn_tp": - rank, size = parallel.attn_tp_rank, parallel.attn_tp_size - else: - rank, size = parallel.tp_rank, parallel.tp_size - kwargs.update(tp_rank=rank, tp_size=size) + kwargs = {} if group is None else dict(parallel_group=group) return kimi_k3.KimiK3MLP( width, 2 * width, @@ -101,8 +86,8 @@ def load_projection(layer): % 29 - 14 ).reshape(layer.output_size, layer.input_size).to(layer.weight.dtype) / 128 - rank, size = layer.tp_rank, layer.tp_size - with get_parallel().override( + rank, size = rank_size(layer)[0], rank_size(layer)[1] + with parallel_scope( tp_rank=0, attn_tp_rank=0, attn_dp_rank=0, shared_experts_tp_group=None ): layer.weight.weight_loader(layer.weight, full) @@ -135,7 +120,7 @@ class TestKimiMLPParallelGroups(CustomTestCase): publish(server, role="test", ranks=SpawnRanks(world_rank=rank)) initialize_dp_attention_flags(server) shared = SimpleNamespace(rank_in_group=rank % 2, world_size=2) - with get_parallel().override(shared_experts_tp_group=shared): + with parallel_scope(shared_experts_tp_group=shared): for group in ( None, "tp", @@ -158,9 +143,7 @@ class TestKimiMLPParallelGroups(CustomTestCase): self.assertEqual(module._dense_attn_tp, auto_attn) for name in ("gate_up_proj", "down_proj"): layer = getattr(module, name) - self.assertEqual( - (layer.tp_rank, layer.tp_size), (r, s) - ) + self.assertEqual(rank_size(layer), (r, s)) expected, _ = load_projection(layer) torch.testing.assert_close(layer.weight, expected) x = ( @@ -183,9 +166,7 @@ class TestKimiMLPParallelGroups(CustomTestCase): if row and reduce and s > 1: reference *= (4 // dp) if auto_attn else 4 with ( - get_parallel().override( - tp_group=tp, attn_tp_group=attn - ), + parallel_scope(tp_group=tp, attn_tp_group=attn), patch.object( linear, "use_symmetric_memory", @@ -223,7 +204,7 @@ class TestKimiMLPParallelGroups(CustomTestCase): (True, 2, False, 2), (True, None, True, 4), ): - with get_parallel().override( + with parallel_scope( shared_experts_tp_size=requested, enable_shared_experts_attn_tp=enabled, shared_experts_tp_group=shared, @@ -243,17 +224,17 @@ class TestKimiMLPParallelGroups(CustomTestCase): for name in ("gate_up_proj", "down_proj"): layer = getattr(module, name) self.assertEqual( - (layer.tp_rank, layer.tp_size), + rank_size(layer), (rank % expected_size, expected_size), ) expected, _ = load_projection(layer) torch.testing.assert_close(layer.weight, expected) self.assertFalse(module.down_proj.reduce_results) self.assertFalse(module.down_proj.use_dp_attention_reduce) - with get_parallel().override(shared_experts_tp_size=2): + with parallel_scope(shared_experts_tp_size=2): with self.assertRaisesRegex(ValueError, "requires an EP a2a"): build_shared_experts(ep_a2a=False) - with get_parallel().override( + with parallel_scope( shared_experts_tp_size=3, shared_experts_tp_group=SimpleNamespace( world_size=3, rank_in_group=rank % 3 @@ -264,16 +245,6 @@ class TestKimiMLPParallelGroups(CustomTestCase): _, disabled = build_shared_experts(shared=0) self.assertIsNone(disabled) - def test_shared_selector_requires_a_built_group(self): - publish( - ServerArgs(model_path="dummy", device="cpu"), - role="test", - ranks=SpawnRanks(world_rank=0), - ) - with get_parallel().override(shared_experts_tp_group=None): - with self.assertRaisesRegex(ValueError, "must exist before construction"): - linear.resolve_linear_parallel_group("shared_experts_tp") - if __name__ == "__main__": unittest.main() diff --git a/test/registered/unit/layers/test_linear_attention_parallel_groups.py b/test/registered/unit/layers/test_linear_attention_parallel_groups.py index f2ccebbbb3..0cce68272a 100644 --- a/test/registered/unit/layers/test_linear_attention_parallel_groups.py +++ b/test/registered/unit/layers/test_linear_attention_parallel_groups.py @@ -10,13 +10,14 @@ import torch.nn.functional as F from sglang.srt.layers.dp_attention import initialize_dp_attention_flags from sglang.srt.layers.linear import RowParallelLinear -from sglang.srt.runtime_context import SpawnRanks, get_parallel, publish, reset_context +from sglang.srt.runtime_context import SpawnRanks, get_parallel, reset_context from sglang.srt.server_args import ServerArgs from sglang.srt.utils import is_cpu from sglang.test.ci.ci_register import register_cpu_ci +from sglang.test.parallel_groups import parallel_scope, publish, rank_size from sglang.test.test_utils import CustomTestCase -register_cpu_ci(est_time=15, suite="base-a-test-cpu") +register_cpu_ci(est_time=15, stage="weekly", runner_config="cpu") def build_linear_attention( @@ -102,7 +103,7 @@ def checkpoint_values(rows, columns, layer, offset=0): def load_projection(module, name, n_groups=8, checkpoint="fused"): """Return an independently sliced checkpoint reference, including copied groups.""" layer = getattr(module, name) - rank, size = layer.tp_rank, layer.tp_size + rank, size = rank_size(layer)[0], rank_size(layer)[1] row = isinstance(layer, RowParallelLinear) mamba = hasattr(module, "intermediate_size") duplicate = mamba and n_groups == 1 and size > 1 @@ -147,7 +148,7 @@ def load_projection(module, name, n_groups=8, checkpoint="fused"): else: shard = torch.cat([piece.chunk(size)[rank] for piece in pieces]) bias_shard = None - with get_parallel().override(tp_rank=0, attn_dp_rank=0, attn_tp_rank=0): + with parallel_scope(tp_rank=0, attn_dp_rank=0, attn_tp_rank=0): if name.startswith("in_proj") and not mamba and checkpoint != "fused": if checkpoint == "tuple": indices = tuple(range(len(sizes) - 1)) @@ -230,9 +231,7 @@ class TestLinearAttentionParallelGroups(CustomTestCase): torch.testing.assert_close(layer.weight, shard) if bias is not None: torch.testing.assert_close(layer.bias, bias) - self.assertEqual( - (layer.tp_rank, layer.tp_size), (rank % size, size) - ) + self.assertEqual(rank_size(layer), (rank % size, size)) row = isinstance(layer, RowParallelLinear) if name == "conv1d": inputs = checkpoint_values( @@ -254,7 +253,9 @@ class TestLinearAttentionParallelGroups(CustomTestCase): continue inputs = checkpoint_values(2, shard.shape[1], layer, 7) used_bias = ( - bias if not row or layer.tp_rank == 0 else None + bias + if not row or rank_size(layer)[0] == 0 + else None ) expected = F.linear(inputs, shard, used_bias) if row and layer.reduce_results: @@ -264,9 +265,7 @@ class TestLinearAttentionParallelGroups(CustomTestCase): tp.all_reduce.reset_mock() attn.all_reduce.reset_mock() with ( - get_parallel().override( - tp_group=tp, attn_tp_group=attn - ), + parallel_scope(tp_group=tp, attn_tp_group=attn), patch( "sglang.srt.layers.linear.is_allocation_symmetric", return_value=True, @@ -310,20 +309,6 @@ class TestLinearAttentionParallelGroups(CustomTestCase): else: allocator.assert_not_called() - def test_projection_helpers_default_to_full_tp(self): - publish( - ServerArgs(model_path="dummy", device="cpu", tp_size=4, attn_dp_size=2), - role="test", - ranks=SpawnRanks(world_rank=3), - ) - for model in ("qwen_next", "qwen35"): - module, _ = build_linear_attention(model) - projections = [module.create_qkvz_proj(32, 64, 64, None, "")] - if model == "qwen35": - projections.append(module.create_ba_proj(32, 8, None, "")) - for layer in projections: - self.assertEqual((layer.tp_rank, layer.tp_size), (3, 4)) - if __name__ == "__main__": unittest.main() diff --git a/test/registered/unit/layers/test_linear_logical_groups.py b/test/registered/unit/layers/test_linear_logical_groups.py new file mode 100644 index 0000000000..f8e02ccd68 --- /dev/null +++ b/test/registered/unit/layers/test_linear_logical_groups.py @@ -0,0 +1,74 @@ +"""Offline linear layouts retain immutable partition ownership during reload.""" + +import unittest + +import torch +import torch.nn.functional as F + +from sglang.srt.layers.linear import ( + ColumnParallelLinear, + QKVParallelLinear, + ReplicatedParallelGroup, + RowParallelLinear, +) +from sglang.srt.runtime_context import SpawnRanks, get_parallel, publish, reset_context +from sglang.srt.server_args import ServerArgs +from sglang.test.ci.ci_register import register_cpu_ci +from sglang.test.parallel_groups import rank_size +from sglang.test.test_utils import CustomTestCase + +register_cpu_ci(est_time=5, suite="base-a-test-cpu") + + +class TestLinearLogicalGroups(CustomTestCase): + def setUp(self): + reset_context() + self.addCleanup(reset_context) + self.x = torch.arange(16, dtype=torch.float32).reshape(2, 8) / 16 + self.weight = torch.arange(64, dtype=torch.float32).reshape(8, 8) / 64 + + def test_group_less_layouts_keep_frozen_ownership(self): + reset_context() + publish( + ServerArgs(model_path="dummy", device="cpu", tp_size=4, attn_dp_size=2), + role="test", + ranks=SpawnRanks(world_rank=3), + ) + get_parallel().override_permanently(tp_group=None, attn_tp_group=None) + for selection, rank, size in (("tp", 3, 4), ("attn_tp", 1, 2)): + for cls, axis in ((ColumnParallelLinear, 0), (RowParallelLinear, 1)): + with self.subTest(group=selection, layer=cls.__name__): + kwargs = {"reduce_results": False} if axis == 1 else {} + layer = cls(8, 8, bias=False, parallel_group=selection, **kwargs) + owner = layer.tp_group + self.assertEqual( + (owner.rank_in_group, owner.world_size), (rank, size) + ) + with self.assertRaises(AttributeError): + owner.rank_in_group = 0 + with get_parallel().override( + tp_rank=0, attn_tp_rank=0, attn_dp_rank=0 + ): + layer.weight.weight_loader(layer.weight, self.weight) + shard = self.weight.chunk(size, dim=axis)[rank] + torch.testing.assert_close(layer.weight, shard, rtol=0, atol=0) + x = self.x if axis == 0 else self.x[:, : 8 // size] + torch.testing.assert_close(layer(x)[0], F.linear(x, shard)) + self.assertIs(layer.tp_group, owner) + self.assertFalse(hasattr(layer, "tp_rank")) + self.assertFalse(hasattr(layer, "tp_size")) + qkv = QKVParallelLinear( + 8, + 2, + 4, + 2, + bias=False, + parallel_group="tp", + kv_parallel_group=ReplicatedParallelGroup("tp", 2), + ) + self.assertEqual(rank_size(qkv), (3, 4)) + self.assertEqual(rank_size(qkv, kv=True), (1, 2)) + + +if __name__ == "__main__": + unittest.main() diff --git a/test/registered/unit/layers/test_linear_parallel_groups.py b/test/registered/unit/layers/test_linear_parallel_groups.py index 6482697b04..cb113f3d2d 100644 --- a/test/registered/unit/layers/test_linear_parallel_groups.py +++ b/test/registered/unit/layers/test_linear_parallel_groups.py @@ -12,12 +12,17 @@ from sglang.srt.layers.linear import ( ColumnParallelLinear, MergedColumnParallelLinear, QKVParallelLinear, + ReplicatedParallelGroup, RowParallelLinear, ) from sglang.srt.layers.parameter import ModelWeightParameter -from sglang.srt.runtime_context import SpawnRanks, get_parallel, publish, reset_context +from sglang.srt.runtime_context import ( + SpawnRanks, + reset_context, +) from sglang.srt.server_args import ServerArgs from sglang.test.ci.ci_register import register_cuda_ci +from sglang.test.parallel_groups import parallel_scope, publish, rank_size from sglang.test.test_utils import CustomTestCase register_cuda_ci(est_time=10, stage="base-b", runner_config="1-gpu-small") @@ -46,12 +51,12 @@ class TestLinearParallelGroups(CustomTestCase): shard = self.weight.chunk(size, dim=0)[rank] layer.weight.weight_loader(layer.weight, self.weight) torch.testing.assert_close(layer(self.x)[0], F.linear(self.x, shard)) - with get_parallel().override(tp_rank=0, attn_dp_rank=0, attn_tp_rank=0): + with parallel_scope(tp_rank=0, attn_dp_rank=0, attn_tp_rank=0): layer.weight.weight_loader(layer.weight, self.weight + 1) torch.testing.assert_close(layer.weight, shard + 1) - with get_parallel().override(tp_rank=0, attn_dp_rank=0, attn_tp_rank=0): - with get_parallel().override(tp_rank=1, attn_tp_rank=1): + with parallel_scope(tp_rank=0, attn_dp_rank=0, attn_tp_rank=0): + with parallel_scope(tp_rank=1, attn_tp_rank=1): layer = ColumnParallelLinear(8, 8, bias=False, parallel_group="attn_tp") layer.weight.weight_loader(layer.weight, self.weight) torch.testing.assert_close(layer.weight, self.weight[4:]) @@ -83,7 +88,7 @@ class TestLinearParallelGroups(CustomTestCase): ) expected = torch.cat((q[4:], k[kv_slice], v[kv_slice])) torch.testing.assert_close(qkv(self.x)[0], F.linear(self.x, expected)) - with get_parallel().override(tp_rank=0, attn_dp_rank=0, attn_tp_rank=0): + with parallel_scope(tp_rank=0, attn_dp_rank=0, attn_tp_rank=0): for name, weight in (("q", q), ("k", k), ("v", v)): qkv.weight.weight_loader(qkv.weight, weight + 1, name) torch.testing.assert_close(qkv.weight, expected + 1) @@ -114,9 +119,7 @@ class TestLinearParallelGroups(CustomTestCase): # Reload under another replica's scope. This model was # constructed on attention rank 1, so Q stays on that rank # and the one-head K/V layout remains replicated. - with get_parallel().override( - tp_rank=0, attn_dp_rank=0, attn_tp_rank=0 - ): + with parallel_scope(tp_rank=0, attn_dp_rank=0, attn_tp_rank=0): for name, weight in weights.items(): qkv.weight.weight_loader(qkv.weight, weight, name) if bias: @@ -163,19 +166,17 @@ class TestLinearParallelGroups(CustomTestCase): bias=bias, ) row = attention.o_proj - with get_parallel().override( - tp_rank=0, attn_dp_rank=0, attn_tp_rank=0 - ): + with parallel_scope(tp_rank=0, attn_dp_rank=0, attn_tp_rank=0): row.weight.weight_loader(row.weight, self.weight) if bias: row.bias.weight_loader(row.bias, torch.arange(8).float()) - self.assertEqual((row.tp_rank, row.tp_size), (1, 2)) + self.assertEqual(rank_size(row), (1, 2)) self.assertEqual(attention.q_size, row.input_size_per_partition) self.assertFalse(row.reduce_results) # The boundary reduces this partial result. Its allocation # still uses TP and the DP-padding condition. with ( - get_parallel().override(tp_group=tp, attn_tp_group=attn), + parallel_scope(tp_group=tp, attn_tp_group=attn), patch( "sglang.srt.layers.linear.is_allocation_symmetric", return_value=symmetric, @@ -224,13 +225,13 @@ class TestLinearParallelGroups(CustomTestCase): max_position_embeddings=16, ) row = attention.o_proj - with get_parallel().override(tp_rank=0, attn_dp_rank=0, attn_tp_rank=0): + with parallel_scope(tp_rank=0, attn_dp_rank=0, attn_tp_rank=0): row.weight.weight_loader(row.weight, self.weight) - self.assertEqual((row.tp_rank, row.tp_size), (1, 2)) + self.assertEqual(rank_size(row), (1, 2)) self.assertFalse(row.reduce_results) self.assertEqual(row.use_dp_attention_reduce, use_attention_allocation) with ( - get_parallel().override(tp_group=tp, attn_tp_group=attn), + parallel_scope(tp_group=tp, attn_tp_group=attn), patch( "sglang.srt.layers.linear.is_allocation_symmetric", return_value=False, @@ -294,9 +295,7 @@ class TestLinearParallelGroups(CustomTestCase): "k": self.weight[: kv_heads * 2] + 2, "v": self.weight[: kv_heads * 2] + 4, } - with get_parallel().override( - tp_rank=0, attn_dp_rank=0, attn_tp_rank=0 - ): + with parallel_scope(tp_rank=0, attn_dp_rank=0, attn_tp_rank=0): for name, weight in weights.items(): qkv.weight.weight_loader(qkv.weight, weight, name) if qkv.bias is not None: @@ -317,9 +316,7 @@ class TestLinearParallelGroups(CustomTestCase): gate_weight = ( self.weight if mode == "per-element" else self.weight[:4] ) - with get_parallel().override( - tp_rank=0, attn_dp_rank=0, attn_tp_rank=0 - ): + with parallel_scope(tp_rank=0, attn_dp_rank=0, attn_tp_rank=0): gate.weight.weight_loader(gate.weight, gate_weight) torch.testing.assert_close( gate(self.x)[0], F.linear(self.x, gate_weight.chunk(2)[1]) @@ -341,7 +338,7 @@ class TestLinearParallelGroups(CustomTestCase): ) # Reload while a different rank is current. The stored rank still owns # the latter half of Q and each MLP matrix, while K/V stay replicated. - with get_parallel().override(tp_rank=0, attn_dp_rank=0, attn_tp_rank=0): + with parallel_scope(tp_rank=0, attn_dp_rank=0, attn_tp_rank=0): column.weight.weight_loader(column.weight, self.weight) row.weight.weight_loader(row.weight, self.weight) merged.weight.weight_loader(merged.weight, self.weight, 0) @@ -365,7 +362,7 @@ class TestLinearParallelGroups(CustomTestCase): def test_gather_uses_the_selected_group(self): tp = SimpleNamespace(world_size=4, all_gather=Mock()) attn = SimpleNamespace(world_size=2, all_gather=Mock()) - with get_parallel().override(tp_group=tp, attn_tp_group=attn): + with parallel_scope(tp_group=tp, attn_tp_group=attn): for group, rank, size, selected, other in ( ("tp", 3, 4, tp, attn), ("attn_tp", 1, 2, attn, tp), @@ -399,7 +396,7 @@ class TestLinearParallelGroups(CustomTestCase): world_size=4, all_reduce=Mock(side_effect=AssertionError("wrong group")) ) with ( - get_parallel().override(tp_group=tp, attn_tp_group=attn), + parallel_scope(tp_group=tp, attn_tp_group=attn), patch( "sglang.srt.layers.linear.use_symmetric_memory", return_value=nullcontext(), @@ -426,7 +423,7 @@ class TestLinearParallelGroups(CustomTestCase): layer.reduce_results = False torch.testing.assert_close(layer(self.x)[0], partial) attn.all_reduce.assert_not_called() - with get_parallel().override(tp_rank=0, attn_dp_rank=0, attn_tp_rank=0): + with parallel_scope(tp_rank=0, attn_dp_rank=0, attn_tp_rank=0): layer.weight.weight_loader(layer.weight, self.weight + 1) torch.testing.assert_close(layer.weight, self.weight[:, 4:] + 1) @@ -460,16 +457,14 @@ class TestLinearParallelGroups(CustomTestCase): use_dp_attention_reduce=attention_reduce, reduce_results=reduce_results, ) - with get_parallel().override( + with parallel_scope( tp_rank=0, attn_dp_rank=0, attn_tp_rank=0 ): layer.weight.weight_loader(layer.weight, self.weight) shard = self.weight.chunk(size, dim=1)[rank] partial = F.linear(self.x.chunk(size, dim=1)[rank], shard) with ( - get_parallel().override( - tp_group=tp, attn_tp_group=attn - ), + parallel_scope(tp_group=tp, attn_tp_group=attn), patch( "sglang.srt.layers.linear.is_allocation_symmetric", return_value=symmetric, @@ -513,9 +508,7 @@ class TestLinearParallelGroups(CustomTestCase): allocator.assert_called_once_with( tp, disabled=not symmetric ) - self.assertEqual( - (layer.tp_rank, layer.tp_size), (rank, size) - ) + self.assertEqual(rank_size(layer), (rank, size)) def test_replicated_model_mlps_keep_weights_and_tp_output_allocation(self): from sglang.srt.models.exaone_moe import ExaoneMoEMLP @@ -557,9 +550,7 @@ class TestLinearParallelGroups(CustomTestCase): mlp.act_fn._forward_method = mlp.act_fn.forward_native up = getattr(mlp, "gate_up_proj", getattr(mlp, "up_proj", None)) down = mlp.down_proj - with get_parallel().override( - tp_rank=0, attn_dp_rank=0, attn_tp_rank=0 - ): + with parallel_scope(tp_rank=0, attn_dp_rank=0, attn_tp_rank=0): if cls is NemotronHMLP: up.weight.weight_loader(up.weight, self.weight) else: @@ -580,7 +571,7 @@ class TestLinearParallelGroups(CustomTestCase): if reduces: expected = expected * 2 with ( - get_parallel().override(tp_group=tp), + parallel_scope(tp_group=tp), patch( "sglang.srt.layers.linear.is_allocation_symmetric", return_value=True, @@ -596,43 +587,11 @@ class TestLinearParallelGroups(CustomTestCase): tp.all_reduce.assert_called_once() else: tp.all_reduce.assert_not_called() - self.assertEqual((up.tp_rank, up.tp_size), (rank, size)) - self.assertEqual((down.tp_rank, down.tp_size), (rank, size)) - - def test_step_shared_expert_constructs_a_replicated_mlp(self): - from sglang.srt.models import step3p5 - - config = SimpleNamespace( - hidden_size=8, - layer_types=["full_attention"], - yarn_only_types=[], - rope_theta=[10000], - max_position_embeddings=16, - head_dim=2, - moe_layers_enum="0", - num_attention_heads=4, - num_attention_groups=1, - num_hidden_layers=1, - swiglu_limits_shared=None, - partial_rotary_factors=[1.0], - rms_norm_eps=1e-6, - use_head_wise_attn_gate=False, - share_expert_dim=8, - ) - backend = Mock() - backend.is_deepep.return_value = True - with ( - patch.object(step3p5, "get_moe_a2a_backend", return_value=backend), - patch.object(step3p5, "Step3p5MoEMLP", return_value=torch.nn.Identity()), - patch.object(step3p5, "append_stages", return_value=(Mock(), Mock())), - ): - layer = step3p5.Step3p5DecoderLayer(config) - self.assertEqual(layer.share_expert.gate_up_proj.tp_size, 1) - self.assertEqual(layer.share_expert.down_proj.tp_size, 1) - self.assertFalse(layer.share_expert.down_proj.reduce_results) + self.assertEqual(rank_size(up), (rank, size)) + self.assertEqual(rank_size(down), (rank, size)) def test_replicated_layers_need_no_group_handle(self): - with get_parallel().override(tp_group=None, attn_tp_group=None): + with parallel_scope(tp_group=None, attn_tp_group=None): for cls, kwargs in ( (ColumnParallelLinear, dict(gather_output=True)), (RowParallelLinear, dict(input_is_parallel=False)), @@ -644,36 +603,81 @@ class TestLinearParallelGroups(CustomTestCase): layer(self.x)[0], F.linear(self.x, self.weight) ) - def test_legacy_arguments_remain_available_and_mixing_is_rejected(self): - constructors = ( - lambda **kwargs: ColumnParallelLinear(8, 8, bias=False, **kwargs), - lambda **kwargs: MergedColumnParallelLinear( - 8, [8, 4], bias=False, **kwargs - ), - lambda **kwargs: QKVParallelLinear(8, 2, 4, bias=False, **kwargs), - lambda **kwargs: RowParallelLinear(8, 8, bias=False, **kwargs), + def test_lora_slicing_reads_retained_query_and_kv_groups(self): + from sglang.srt.lora.layers import ( + ColumnParallelLinearWithLoRA, + MergedColumnParallelLinearWithLoRA, + QKVParallelLinearWithLoRA, + RowParallelLinearWithLoRA, ) - for build in constructors: - self.assertEqual((build().tp_rank, build().tp_size), (3, 4)) - explicit = build(tp_rank=0, tp_size=1) - self.assertEqual((explicit.tp_rank, explicit.tp_size), (0, 1)) - for kwargs in (dict(tp_rank=0), dict(tp_size=1)): - with self.assertRaisesRegex(ValueError, "cannot be combined"): - build(parallel_group="replicated", **kwargs) - with self.assertRaisesRegex(ValueError, "Unknown linear parallel_group"): - build(parallel_group="unknown") - for old_reduce in (False, True): - layer = RowParallelLinear( - 8, 8, parallel_group="attn_tp", use_dp_attention_reduce=old_reduce - ) - self.assertEqual((layer.tp_rank, layer.tp_size), (1, 2)) - self.assertEqual(layer.use_dp_attention_reduce, old_reduce) - legacy = RowParallelLinear( - 8, 8, tp_rank=1, tp_size=2, use_dp_attention_reduce=True + + column = ColumnParallelLinear(8, 8, bias=False) + merged = MergedColumnParallelLinear(8, [8, 4], bias=False) + qkv = QKVParallelLinear( + 8, + 2, + 4, + 2, + bias=False, + parallel_group="tp", + kv_parallel_group=ReplicatedParallelGroup("tp", 2), ) - self.assertTrue(legacy.use_dp_attention_reduce) - legacy.use_dp_attention_reduce = False - self.assertFalse(legacy.use_dp_attention_reduce) + row = RowParallelLinear(8, 8, bias=False, reduce_results=False) + for cls, layer, rows in ( + (ColumnParallelLinearWithLoRA, column, [6, 7]), + (MergedColumnParallelLinearWithLoRA, merged, [6, 7, 11]), + (QKVParallelLinearWithLoRA, qkv, [6, 7, 10, 11, 14, 15]), + ): + with self.subTest(wrapper=cls.__name__): + wrapped = cls.__new__(cls) + torch.nn.Module.__init__(wrapped) + wrapped.base_layer = layer + if isinstance(layer, QKVParallelLinear): + full_rows = ( + layer.total_num_heads + 2 * layer.total_num_kv_heads + ) * layer.head_size + else: + full_rows = layer.output_size + full = torch.arange(full_rows * 2, dtype=torch.float32).reshape(-1, 2) + with parallel_scope(tp_rank=0, attn_tp_rank=0, attn_dp_rank=0): + actual = wrapped.slice_lora_b_weights(full) + torch.testing.assert_close(actual, full[rows], rtol=0, atol=0) + wrapped = RowParallelLinearWithLoRA.__new__(RowParallelLinearWithLoRA) + torch.nn.Module.__init__(wrapped) + wrapped.base_layer = row + full = torch.arange(16, dtype=torch.float32).reshape(2, 8) + with parallel_scope(tp_rank=0, attn_tp_rank=0, attn_dp_rank=0): + actual = wrapped.slice_lora_a_weights(full) + torch.testing.assert_close(actual, full[:, 6:], rtol=0, atol=0) + + def test_two_stream_lora_row_gates_on_the_retained_input_partition(self): + from sglang.srt.lora.trtllm_lora_temp import attention + + for group, expected in (("attn_tp", self.x[:, 4:]), ("replicated", self.x)): + with self.subTest(group=group): + layer = RowParallelLinear( + 8, + 8, + input_is_parallel=False, + reduce_results=False, + parallel_group=group, + ) + wrapper = SimpleNamespace(base_layer=layer, lora_active=True) + fallback = Mock(return_value=(expected, None)) + with ( + parallel_scope(tp_rank=0, attn_tp_rank=0, attn_dp_rank=0), + patch.object( + attention, "is_two_stream_active", return_value=False + ) as gate, + patch.object( + attention, "get_original_row_forward", return_value=fallback + ), + ): + output, _ = attention.row_parallel_lora_forward(wrapper, self.x) + gate.assert_called_once() + torch.testing.assert_close(gate.call_args.args[0], expected) + self.assertIs(output, expected) + fallback.assert_called_once_with(wrapper, self.x, False, None) if __name__ == "__main__": diff --git a/test/registered/unit/layers/test_llama_inkling_parallel_groups.py b/test/registered/unit/layers/test_llama_inkling_parallel_groups.py index a0e541b410..e9db5287a8 100644 --- a/test/registered/unit/layers/test_llama_inkling_parallel_groups.py +++ b/test/registered/unit/layers/test_llama_inkling_parallel_groups.py @@ -1,6 +1,5 @@ """Dense MLP placement stays frozen while reduction uses its own policy.""" -import inspect import unittest from contextlib import nullcontext from unittest.mock import Mock, patch @@ -10,12 +9,13 @@ import torch.nn.functional as F from sglang.srt.models.inkling_common import dense_mlp from sglang.srt.models.llama import LlamaMLP -from sglang.srt.runtime_context import SpawnRanks, get_parallel, publish, reset_context +from sglang.srt.runtime_context import SpawnRanks, reset_context from sglang.srt.server_args import ServerArgs from sglang.test.ci.ci_register import register_cpu_ci +from sglang.test.parallel_groups import parallel_scope, publish, rank_size from sglang.test.test_utils import CustomTestCase -register_cpu_ci(est_time=10, suite="base-a-test-cpu") +register_cpu_ci(est_time=10, stage="weekly", runner_config="cpu") def build_mlp( @@ -44,18 +44,7 @@ def build_mlp( use_global_scale=True, layer_id=0, fused=fused, tp_group=execution_group ) if group is not None: - if "parallel_group" in inspect.signature(cls).parameters: - kwargs["parallel_group"] = group - else: - parallel = get_parallel() - rank, size = ( - (0, 1) - if group == "replicated" - else (parallel.attn_tp_rank, parallel.attn_tp_size) - if group == "attn_tp" - else (parallel.tp_rank, parallel.tp_size) - ) - kwargs.update(tp_rank=rank, tp_size=size) + kwargs["parallel_group"] = group with patch.object(dense_mlp, "lora_compatible_layout_enabled", return_value=lora): module = cls(**kwargs) return module @@ -71,11 +60,11 @@ def load_projection(layer): ).to(layer.weight.dtype) / 64 layer.weight.weight_loader(layer.weight, weight) if row: - expected = weight.chunk(layer.tp_size, dim=1)[layer.tp_rank] + expected = weight.chunk(rank_size(layer)[1], dim=1)[rank_size(layer)[0]] else: expected = torch.cat( [ - part.chunk(layer.tp_size)[layer.tp_rank] + part.chunk(rank_size(layer)[1])[rank_size(layer)[0]] for part in weight.split(layer.output_sizes) ] ) @@ -121,7 +110,7 @@ class TestLlamaInklingParallelGroups(CustomTestCase): "attn_tp": (1, 2), "replicated": (0, 1), }[expected_group] - with get_parallel().override( + with parallel_scope( tp_rank=0, attn_dp_rank=0, attn_tp_rank=0 ): a, b = load_projection(up), load_projection(down) @@ -141,9 +130,7 @@ class TestLlamaInklingParallelGroups(CustomTestCase): tp.all_reduce.reset_mock() attn.all_reduce.reset_mock() with ( - get_parallel().override( - tp_group=tp, attn_tp_group=attn - ), + parallel_scope(tp_group=tp, attn_tp_group=attn), patch( "sglang.srt.layers.linear.is_allocation_symmetric", return_value=False, @@ -179,8 +166,8 @@ class TestLlamaInklingParallelGroups(CustomTestCase): ) else: comm.assert_not_called() - self.assertEqual((up.tp_rank, up.tp_size), (rank, size)) - self.assertEqual((down.tp_rank, down.tp_size), (rank, size)) + self.assertEqual(rank_size(up), (rank, size)) + self.assertEqual(rank_size(down), (rank, size)) self.assertEqual(down.reduce_results, row_reduce) self.assertEqual(down.use_dp_attention_reduce, dp_reduce) @@ -202,7 +189,7 @@ class TestLlamaInklingParallelGroups(CustomTestCase): module.act_fn.forward = function._torchdynamo_orig_callable module.scattered_sconv = True with ( - get_parallel().override(tp_group=Mock()), + parallel_scope(tp_group=Mock()), patch( "sglang.srt.layers.linear.use_symmetric_memory", return_value=nullcontext(), diff --git a/test/registered/unit/layers/test_mla_parallel_groups.py b/test/registered/unit/layers/test_mla_parallel_groups.py index ebf21c2220..e0dcf4fe3f 100644 --- a/test/registered/unit/layers/test_mla_parallel_groups.py +++ b/test/registered/unit/layers/test_mla_parallel_groups.py @@ -8,12 +8,13 @@ from unittest.mock import Mock, patch import torch import torch.nn.functional as F -from sglang.srt.runtime_context import SpawnRanks, get_parallel, publish, reset_context +from sglang.srt.runtime_context import SpawnRanks, reset_context from sglang.srt.server_args import ServerArgs from sglang.test.ci.ci_register import register_cuda_ci +from sglang.test.parallel_groups import parallel_scope, publish, rank_size from sglang.test.test_utils import CustomTestCase -register_cuda_ci(est_time=15, stage="base-b", runner_config="1-gpu-small") +register_cuda_ci(est_time=15, stage="nightly", runner_config="1-gpu-large") def build_mla(model, variant, reduce_results=False, width=8, quant_config=None): @@ -164,7 +165,7 @@ class TestMLAParallelGroups(CustomTestCase): % 17 / 32 ).to(dtype) - with get_parallel().override( + with parallel_scope( tp_rank=0, attn_dp_rank=0, attn_tp_rank=0 ): layer.weight.weight_loader(layer.weight, weight) @@ -181,7 +182,7 @@ class TestMLAParallelGroups(CustomTestCase): expected *= 2 tp.all_reduce.reset_mock() with ( - get_parallel().override(tp_group=tp), + parallel_scope(tp_group=tp), patch( "sglang.srt.layers.linear.is_allocation_symmetric", return_value=True, @@ -202,7 +203,7 @@ class TestMLAParallelGroups(CustomTestCase): ) else: allocator.assert_not_called() - self.assertEqual((layer.tp_rank, layer.tp_size), (1, 2)) + self.assertEqual(rank_size(layer), (1, 2)) if is_row: self.assertFalse(layer.use_dp_attention_reduce) self.assertEqual( diff --git a/test/registered/unit/layers/test_mlp_parallel_groups.py b/test/registered/unit/layers/test_mlp_parallel_groups.py index 6c05c990d4..2067d32f35 100644 --- a/test/registered/unit/layers/test_mlp_parallel_groups.py +++ b/test/registered/unit/layers/test_mlp_parallel_groups.py @@ -10,12 +10,13 @@ from unittest.mock import Mock, patch import torch import torch.nn.functional as F -from sglang.srt.runtime_context import SpawnRanks, get_parallel, publish, reset_context +from sglang.srt.runtime_context import SpawnRanks, reset_context from sglang.srt.server_args import ServerArgs from sglang.test.ci.ci_register import register_cpu_ci +from sglang.test.parallel_groups import parallel_scope, publish, rank_size from sglang.test.test_utils import CustomTestCase -register_cpu_ci(est_time=15, suite="base-a-test-cpu") +register_cpu_ci(est_time=15, stage="weekly", runner_config="cpu") MODELS = { "bailing_moe": "BailingMoEMLP", @@ -87,7 +88,7 @@ class TestMLPParallelGroups(CustomTestCase): ) other = gate + 0.25 weight = gate.T.contiguous() + 0.5 - with get_parallel().override( + with parallel_scope( tp_rank=0, attn_dp_rank=0, attn_tp_rank=0 ): up.weight.weight_loader(up.weight, gate, 0) @@ -112,7 +113,7 @@ class TestMLPParallelGroups(CustomTestCase): expected = expected * 2 tp.all_reduce.reset_mock() with ( - get_parallel().override(tp_group=tp), + parallel_scope(tp_group=tp), patch( "sglang.srt.layers.linear.is_allocation_symmetric", return_value=True, @@ -129,8 +130,8 @@ class TestMLPParallelGroups(CustomTestCase): 1 if reduce and size > 1 else 0, ) torch.testing.assert_close(mlp(self.x[:0]), self.x[:0]) - self.assertEqual((up.tp_rank, up.tp_size), (rank, size)) - self.assertEqual((down.tp_rank, down.tp_size), (rank, size)) + self.assertEqual(rank_size(up), (rank, size)) + self.assertEqual(rank_size(down), (rank, size)) self.assertEqual(down.reduce_results, reduce) self.assertFalse(down.use_dp_attention_reduce) diff --git a/test/registered/unit/layers/test_qwen_vision_wrapper_parallel_groups.py b/test/registered/unit/layers/test_qwen_vision_wrapper_parallel_groups.py index 9c9683f20d..6a540f3936 100644 --- a/test/registered/unit/layers/test_qwen_vision_wrapper_parallel_groups.py +++ b/test/registered/unit/layers/test_qwen_vision_wrapper_parallel_groups.py @@ -1,6 +1,5 @@ """Qwen vision wrappers and generation helpers retain their placement policies.""" -import inspect import unittest from contextlib import nullcontext from unittest.mock import Mock, patch @@ -14,28 +13,17 @@ from sglang.srt.layers.linear import ( ReplicatedLinear, RowParallelLinear, ) -from sglang.srt.runtime_context import SpawnRanks, get_parallel, publish, reset_context +from sglang.srt.runtime_context import SpawnRanks, reset_context from sglang.srt.server_args import ServerArgs from sglang.test.ci.ci_register import register_cpu_ci +from sglang.test.parallel_groups import parallel_scope, publish, rank_size from sglang.test.test_utils import CustomTestCase -register_cpu_ci(est_time=10, suite="base-a-test-cpu") +register_cpu_ci(est_time=10, stage="weekly", runner_config="cpu") def group_kwargs(cls, group): - if group is None: - return {} - if "parallel_group" in inspect.signature(cls).parameters: - return dict(parallel_group=group) - p = get_parallel() - rank, size = ( - (0, 1) - if group == "replicated" - else (p.tp_rank, p.tp_size) - if group == "tp" - else (p.attn_tp_rank, p.attn_tp_size) - ) - return dict(tp_rank=rank, tp_size=size) + return {} if group is None else dict(parallel_group=group) def build_qwen(model, group=None, *, replicated=False, width=32, quant_config=None): @@ -86,7 +74,7 @@ def build_qwen(model, group=None, *, replicated=False, width=32, quant_config=No def load_projection(layer): """Load known full weights under rank zero, returning the expected owned shard.""" - rank, size = getattr(layer, "tp_rank", 0), getattr(layer, "tp_size", 1) + rank, size = rank_size(layer)[0], rank_size(layer)[1] row = isinstance(layer, RowParallelLinear) dtype, device = layer.weight.dtype, layer.weight.device @@ -100,7 +88,7 @@ def load_projection(layer): / 128 ).to(dtype) - with get_parallel().override(tp_rank=0, attn_dp_rank=0, attn_tp_rank=0): + with parallel_scope(tp_rank=0, attn_dp_rank=0, attn_tp_rank=0): if isinstance(layer, QKVParallelLinear): weights, biases = [], [] for offset, shard_id in enumerate(("q", "k", "v")): @@ -204,6 +192,9 @@ class TestQwenVisionWrapperGroups(CustomTestCase): if selected == "tp" else (3 % (4 // dp), 4 // dp) ) + self.assertIs(module.tp_group, layers[0].tp_group) + self.assertFalse(hasattr(module, "tp_rank")) + self.assertFalse(hasattr(module, "tp_size")) for index, layer in enumerate(layers): weight, bias = load_projection(layer) row = isinstance(layer, RowParallelLinear) @@ -222,9 +213,7 @@ class TestQwenVisionWrapperGroups(CustomTestCase): tp.all_reduce.reset_mock() attn.all_reduce.reset_mock() with ( - get_parallel().override( - tp_group=tp, attn_tp_group=attn - ), + parallel_scope(tp_group=tp, attn_tp_group=attn), patch( "sglang.srt.layers.linear.is_allocation_symmetric", return_value=False, @@ -254,8 +243,8 @@ class TestQwenVisionWrapperGroups(CustomTestCase): ) self.assertEqual( ( - getattr(layer, "tp_rank", 0), - getattr(layer, "tp_size", 1), + rank_size(layer)[0], + rank_size(layer)[1], ), (expected_rank, expected_size), ) @@ -265,30 +254,6 @@ class TestQwenVisionWrapperGroups(CustomTestCase): expected_size == 1, ) - def test_wrapper_conflict_guard_and_disabled_merger(self): - publish( - ServerArgs(model_path="dummy", device="cpu", tp_size=4, attn_cp_size=2), - role="test", - ranks=SpawnRanks(world_rank=3), - ) - for model in ("qwen25_fused", "qwen3_mlp", "qwen3_merger"): - with self.assertRaisesRegex( - ValueError, "cannot be combined with data parallel" - ): - build_qwen(model, "replicated", replicated=True) - from sglang.srt.models.qwen3_vl import Qwen3VLMoeVisionPatchMerger - - reset_context() - merger = Qwen3VLMoeVisionPatchMerger( - 32, - 32, - 64, - disable_merger_proj=True, - **group_kwargs(Qwen3VLMoeVisionPatchMerger, "replicated"), - ) - self.assertFalse(hasattr(merger, "linear_fc1")) - self.assertFalse(hasattr(merger, "tp_size")) - if __name__ == "__main__": unittest.main() diff --git a/test/registered/unit/layers/test_repeated_batched_parallel_groups.py b/test/registered/unit/layers/test_repeated_batched_parallel_groups.py index 086a7d20c2..f8dac66610 100644 --- a/test/registered/unit/layers/test_repeated_batched_parallel_groups.py +++ b/test/registered/unit/layers/test_repeated_batched_parallel_groups.py @@ -1,6 +1,5 @@ """Repeated and batched projections retain native checkpoint partitions.""" -import inspect import unittest from contextlib import nullcontext from types import SimpleNamespace @@ -11,12 +10,13 @@ import torch.nn.functional as F from sglang.srt.layers import linear from sglang.srt.layers.quantization.fp8 import Fp8Config -from sglang.srt.runtime_context import SpawnRanks, get_parallel, publish, reset_context +from sglang.srt.runtime_context import SpawnRanks, reset_context from sglang.srt.server_args import ServerArgs from sglang.test.ci.ci_register import register_cpu_ci +from sglang.test.parallel_groups import parallel_scope, publish, rank_size from sglang.test.test_utils import CustomTestCase -register_cpu_ci(est_time=15, suite="base-a-test-cpu") +register_cpu_ci(est_time=15, stage="weekly", runner_config="cpu") CASES = ( ("glm", "fused"), @@ -93,8 +93,8 @@ def values(rows, columns, layer, offset=0): def load_projection(layer): - rank, size = getattr(layer, "tp_rank", 0), getattr(layer, "tp_size", 1) - with get_parallel().override(tp_rank=0, attn_tp_rank=0, attn_dp_rank=0): + rank, size = rank_size(layer)[0], rank_size(layer)[1] + with parallel_scope(tp_rank=0, attn_tp_rank=0, attn_dp_rank=0): if isinstance(layer, linear.MergedColumnParallelRepeatedLinear): shards = [] for i, local_size in enumerate(layer.output_partition_sizes): @@ -167,13 +167,7 @@ class TestRepeatedBatchedParallelGroups(CustomTestCase): linear.MergedColumnParallelRepeatedLinear, linear.ColumnParallelBatchedLinear, ): - kwargs = {} - if group is not None: - kwargs = ( - dict(parallel_group=group) - if "parallel_group" in inspect.signature(cls).parameters - else dict(tp_rank=rank, tp_size=size) - ) + kwargs = {} if group is None else dict(parallel_group=group) layer = ( cls(8, [16, 8], [4], **kwargs) if cls is linear.MergedColumnParallelRepeatedLinear @@ -181,7 +175,7 @@ class TestRepeatedBatchedParallelGroups(CustomTestCase): ) expected = load_projection(layer) torch.testing.assert_close(layer.weight, expected) - self.assertEqual((layer.tp_rank, layer.tp_size), (rank, size)) + self.assertEqual(rank_size(layer), (rank, size)) if cls is linear.MergedColumnParallelRepeatedLinear: x = values(2, 8, layer, 3) actual = layer(x) @@ -242,8 +236,8 @@ class TestRepeatedBatchedParallelGroups(CustomTestCase): local_rank = rank % size self.assertEqual( ( - getattr(layer, "tp_rank", 0), - getattr(layer, "tp_size", 1), + rank_size(layer)[0], + rank_size(layer)[1], ), (local_rank, size), ) @@ -292,7 +286,7 @@ class TestRepeatedBatchedParallelGroups(CustomTestCase): else nullcontext() ) with ( - get_parallel().override( + parallel_scope( tp_group=tp, attn_tp_group=attn ), patch( diff --git a/test/registered/unit/layers/test_replicated_attention_parallel_groups.py b/test/registered/unit/layers/test_replicated_attention_parallel_groups.py index 96b187b509..c86a431b55 100644 --- a/test/registered/unit/layers/test_replicated_attention_parallel_groups.py +++ b/test/registered/unit/layers/test_replicated_attention_parallel_groups.py @@ -10,12 +10,13 @@ import torch.nn.functional as F from sglang.srt.layers import linear from sglang.srt.layers.layer_boundary.factories import layer_stack -from sglang.srt.runtime_context import SpawnRanks, get_parallel, publish, reset_context +from sglang.srt.runtime_context import SpawnRanks, reset_context from sglang.srt.server_args import ServerArgs from sglang.test.ci.ci_register import register_cuda_ci +from sglang.test.parallel_groups import parallel_scope, publish, rank_size from sglang.test.test_utils import CustomTestCase -register_cuda_ci(est_time=20, stage="base-b", runner_config="1-gpu-small") +register_cuda_ci(est_time=20, stage="nightly", runner_config="1-gpu-large") def build_attention(model, variant, *, width=32, head_dim=8, quant_config=None): @@ -79,8 +80,8 @@ def values(rows, columns, layer, offset=0): def load_projection(layer): - rank, size = layer.tp_rank, layer.tp_size - with get_parallel().override(tp_rank=0, attn_tp_rank=0, attn_dp_rank=0): + rank, size = rank_size(layer)[0], rank_size(layer)[1] + with parallel_scope(tp_rank=0, attn_tp_rank=0, attn_dp_rank=0): if isinstance(layer, linear.QKVParallelLinear): shards = [] for i, name in enumerate(("q", "k", "v")): @@ -89,11 +90,7 @@ def load_projection(layer): ) dim = layer.v_head_size if name == "v" else layer.head_size full = values(heads * dim, layer.input_size, layer, i) - r, s = ( - (rank, size) - if name == "q" - else (layer.kv_tp_rank, layer.kv_tp_size) - ) + r, s = (rank, size) if name == "q" else rank_size(layer, kv=True) pieces = s if name == "q" else min(heads, s) index = r if name == "q" else r // max(s // heads, 1) layer.weight.weight_loader(layer.weight, full, name) @@ -143,7 +140,7 @@ class TestReplicatedAttentionParallelGroups(CustomTestCase): else: size, expected_rank = attn_size, attn_rank self.assertEqual( - (layer.tp_rank, layer.tp_size), + rank_size(layer), (expected_rank, size), ) if isinstance(layer, linear.QKVParallelLinear): @@ -151,7 +148,7 @@ class TestReplicatedAttentionParallelGroups(CustomTestCase): dcp if model == "qwen" and not variant[0] else 1 ) self.assertEqual( - (layer.kv_tp_rank, layer.kv_tp_size), + rank_size(layer, kv=True), (expected_rank // factor, size // factor), ) shard, _ = load_projection(layer) @@ -159,9 +156,7 @@ class TestReplicatedAttentionParallelGroups(CustomTestCase): x = values(2, shard.shape[1], layer, 7) tp, attn = Mock(), Mock() with ( - get_parallel().override( - tp_group=tp, attn_tp_group=attn - ), + parallel_scope(tp_group=tp, attn_tp_group=attn), patch.object( linear, "use_symmetric_memory", @@ -214,31 +209,13 @@ class TestReplicatedAttentionParallelGroups(CustomTestCase): parallel_group="attn_tp", kv_parallel_group=selection, ) - self.assertEqual((qkv.tp_rank, qkv.tp_size), (3, 4)) - self.assertEqual((qkv.kv_tp_rank, qkv.kv_tp_size), (rank, size)) + self.assertEqual(rank_size(qkv), (3, 4)) + self.assertEqual(rank_size(qkv, kv=True), (rank, size)) expected, _ = load_projection(qkv) torch.testing.assert_close(qkv.weight, expected) x = values(2, 8, qkv, 3) torch.testing.assert_close(qkv(x)[0], F.linear(x, expected)) - def test_invalid_replica_factors_and_conflicting_kv_placement(self): - from sglang.srt.layers.linear import ReplicatedParallelGroup - - for factor in (0, -1, True, 1.5): - with self.assertRaises(ValueError): - ReplicatedParallelGroup("attn_tp", factor) - with self.assertRaises(ValueError): - ReplicatedParallelGroup("invalid", 1) - publish( - ServerArgs(model_path="dummy", device="cpu", tp_size=4), - role="test", - ranks=SpawnRanks(world_rank=0), - ) - with self.assertRaises(AssertionError): - linear.resolve_linear_parallel_group(ReplicatedParallelGroup("tp", 3)) - with self.assertRaisesRegex(ValueError, "cannot be combined"): - linear.QKVParallelLinear(8, 2, 8, 4, kv_parallel_group="tp", kv_tp_size=4) - if __name__ == "__main__": unittest.main() diff --git a/test/registered/unit/layers/test_sharded_loader_parallel_groups.py b/test/registered/unit/layers/test_sharded_loader_parallel_groups.py new file mode 100644 index 0000000000..34784d5884 --- /dev/null +++ b/test/registered/unit/layers/test_sharded_loader_parallel_groups.py @@ -0,0 +1,209 @@ +"""Auxiliary checkpoint loaders retain their constructed owner layout.""" + +import unittest +from contextlib import nullcontext +from types import SimpleNamespace +from unittest.mock import Mock, patch + +import torch + +from sglang.srt.layers.linear import ReplicatedParallelGroup +from sglang.srt.model_loader import weight_utils +from sglang.srt.runtime_context import SpawnRanks, get_parallel, reset_context +from sglang.srt.server_args import ServerArgs +from sglang.test.ci.ci_register import register_cuda_ci +from sglang.test.parallel_groups import parallel_scope, publish +from sglang.test.test_utils import CustomTestCase + +register_cuda_ci(est_time=15, stage="nightly", runner_config="1-gpu-large") + + +def values(shape, *, device="cpu", dtype=torch.float32, offset=0): + count = 1 + for size in shape: + count *= size + return ( + (((torch.arange(count, device=device) + offset) % 23 - 11) / 128) + .reshape(shape) + .to(dtype) + ) + + +def loading_scope(changed): + return ( + parallel_scope(tp_rank=0, attn_tp_rank=0, attn_dp_rank=0, moe_tp_rank=0) + if changed + else nullcontext() + ) + + +def full_tp_parameters(kind, width=32, heads=8): + if kind == "mamba1": + from sglang.srt.layers.attention.mamba.mamba1 import MambaMixer1 + + module = MambaMixer1( + hidden_size=width, + intermediate_size=2 * width, + state_size=4, + conv_kernel=3, + time_step_rank=4, + use_conv_bias=True, + use_bias=False, + ) + return module, [(module.A_log, 0), (module.D, 0)] + if kind in ("lfm", "lfm_moe"): + from sglang.srt.models.lfm2 import Lfm2ShortConv + from sglang.srt.models.lfm2_moe import Lfm2MoeShortConv + + cls = Lfm2ShortConv if kind == "lfm" else Lfm2MoeShortConv + module = cls( + SimpleNamespace(hidden_size=width, conv_L_cache=3, conv_bias=True), 0 + ) + return module, [(module.conv_weight, 0), (module.conv_bias, 0)] + if kind == "granite": + from sglang.srt.models.granite import build_attention_sinks + + parameter = build_attention_sinks(heads // get_parallel().tp_size) + return None, [(parameter, 0)] + if kind == "minicpm": + from sglang.srt.models.minicpm import MiniCPMLightningMixer + + module = MiniCPMLightningMixer( + width, heads, heads, width // heads, use_rope=False, use_output_norm=True + ) + return module, [(module.o_norm.weight, 0)] + if kind == "dflash": + from transformers import LlamaConfig + + from sglang.srt.models.dflash import DFlashAttention + + config = LlamaConfig( + hidden_size=width, + num_attention_heads=heads, + num_key_value_heads=heads, + head_dim=width // heads, + num_hidden_layers=1, + intermediate_size=2 * width, + ) + config.dflash_config = {"attention_sink_bias": True} + module = DFlashAttention(config, 0) + return module, [(module.attention_sink_bias, 0)] + raise ValueError(kind) + + +def load_parameters(parameters, rank, size, *, changed=False, transform=None): + for offset in (0, 7): + for param, axis in parameters: + shape = list(param.shape) + shape[axis] *= size + full = values(shape, device=param.device, dtype=param.dtype, offset=offset) + with loading_scope(changed): + param.weight_loader(param, full) + expected = full.chunk(size, dim=axis)[rank] + if transform is not None: + expected = transform(param, expected) + torch.testing.assert_close(param, expected, rtol=0, atol=0) + + +class TestShardedLoaderParallelGroups(CustomTestCase): + def setUp(self): + reset_context() + self.addCleanup(reset_context) + + def exercise_full_tp(self, changed=False, dps=(1,)): + for dp in dps: + for rank in range(4): + reset_context() + publish( + ServerArgs( + model_path="dummy", device="cpu", tp_size=4, attn_dp_size=dp + ), + role="test", + ranks=SpawnRanks(world_rank=rank), + ) + for kind in ( + "mamba1", + "lfm", + "lfm_moe", + "granite", + "minicpm", + "dflash", + ): + _, parameters = full_tp_parameters(kind) + load_parameters(parameters, rank, 4, changed=changed) + + def test_full_tp_owners_after_scope_exit_and_with_attention_dp(self): + self.exercise_full_tp(True, (1, 2)) + + def test_generic_groups_axes_and_frozen_reload(self): + publish( + ServerArgs(model_path="dummy", device="cpu", tp_size=4, attn_dp_size=2), + role="test", + ranks=SpawnRanks(world_rank=3), + ) + for group, rank, size in ( + (None, 1, 2), + ("tp", 3, 4), + ("attn_tp", 1, 2), + ("replicated", 0, 1), + (ReplicatedParallelGroup("tp", 2), 1, 2), + ): + for axis in (0, 1, 2): + shape = [2, 2, 2] + param = torch.nn.Parameter(torch.empty(shape), requires_grad=False) + loader = weight_utils.sharded_weight_loader( + axis, **({} if group is None else {"parallel_group": group}) + ) + shape[axis] *= size + full = values(shape) + with loading_scope(True): + loader(param, full) + torch.testing.assert_close( + param, full.chunk(size, dim=axis)[rank], rtol=0, atol=0 + ) + callback = Mock(side_effect=lambda: get_parallel().tp_rank) + loader = weight_utils.sharded_weight_loader(0, callback) + param = torch.nn.Parameter(torch.empty(2), requires_grad=False) + with loading_scope(True): + loader(param, torch.arange(8, dtype=torch.float32)) + torch.testing.assert_close(param, torch.tensor([6.0, 7.0])) + callback.assert_called_once() + with self.assertRaisesRegex(ValueError, "cannot be combined"): + weight_utils.sharded_weight_loader(0, callback, parallel_group="tp") + + def test_cpu_uneven_padding_uses_frozen_width(self): + publish( + ServerArgs(model_path="dummy", device="cpu", tp_size=3), + role="test", + ranks=SpawnRanks(world_rank=2), + ) + loader = weight_utils.sharded_weight_loader(0, parallel_group="tp") + param = torch.nn.Parameter(torch.full((3,), -1.0), requires_grad=False) + with ( + parallel_scope( + tp_size=1, + tp_rank=0, + tp_group=None, + attn_tp_size=1, + attn_tp_rank=0, + attn_tp_group=None, + attn_dp_size=1, + attn_dp_rank=0, + attn_cp_size=1, + attn_cp_rank=0, + moe_tp_size=1, + moe_tp_rank=0, + moe_ep_size=1, + moe_ep_rank=0, + moe_ep_group=None, + moe_dp_size=1, + moe_dp_rank=0, + ), + patch.object(weight_utils, "is_cpu", return_value=True), + ): + loader(param, torch.arange(7, dtype=torch.float32)) + torch.testing.assert_close(param, torch.tensor([6.0, 0.0, 0.0])) + + +if __name__ == "__main__": + unittest.main() diff --git a/test/registered/unit/layers/test_vision_parallel_groups.py b/test/registered/unit/layers/test_vision_parallel_groups.py index 43f647f637..078d5f72a7 100644 --- a/test/registered/unit/layers/test_vision_parallel_groups.py +++ b/test/registered/unit/layers/test_vision_parallel_groups.py @@ -12,16 +12,14 @@ from sglang.srt.layers.dp_attention import initialize_dp_attention_flags from sglang.srt.layers.linear import QKVParallelLinear, RowParallelLinear from sglang.srt.runtime_context import ( SpawnRanks, - get_disagg, - get_parallel, - publish, reset_context, ) from sglang.srt.server_args import ServerArgs from sglang.test.ci.ci_register import register_cpu_ci +from sglang.test.parallel_groups import parallel_scope, publish, rank_size from sglang.test.test_utils import CustomTestCase -register_cpu_ci(est_time=15, suite="base-a-test-cpu") +register_cpu_ci(est_time=15, stage="weekly", runner_config="cpu") VISION_MODELS = ( "vision_packed", @@ -140,7 +138,7 @@ def build_vision(model, use_data_parallel=False, width=32, quant_config=None): def load_projection(layer): """Load known full weights under rank zero, returning the expected owned shard.""" - rank, size = layer.tp_rank, layer.tp_size + rank, size = rank_size(layer)[0], rank_size(layer)[1] row = isinstance(layer, RowParallelLinear) dtype, device = layer.weight.dtype, layer.weight.device @@ -154,7 +152,7 @@ def load_projection(layer): / 128 ).to(dtype) - with get_parallel().override(tp_rank=0, attn_dp_rank=0, attn_tp_rank=0): + with parallel_scope(tp_rank=0, attn_dp_rank=0, attn_tp_rank=0): if isinstance(layer, QKVParallelLinear): weights, biases = [], [] for offset, shard_id in enumerate(("q", "k", "v")): @@ -269,9 +267,7 @@ class TestVisionParallelGroups(CustomTestCase): ) ) for layer in layers: - self.assertEqual( - (layer.tp_rank, layer.tp_size), (rank, size) - ) + self.assertEqual(rank_size(layer), (rank, size)) shard, bias = load_projection(layer) torch.testing.assert_close(layer.weight, shard) if bias is not None: @@ -295,9 +291,7 @@ class TestVisionParallelGroups(CustomTestCase): tp.all_reduce.reset_mock() attn.all_reduce.reset_mock() with ( - get_parallel().override( - tp_group=tp, attn_tp_group=attn - ), + parallel_scope(tp_group=tp, attn_tp_group=attn), patch( "sglang.srt.layers.linear.is_allocation_symmetric", return_value=False, @@ -330,47 +324,13 @@ class TestVisionParallelGroups(CustomTestCase): ) else: allocator.assert_not_called() - self.assertEqual( - (layer.tp_rank, layer.tp_size), (rank, size) - ) + self.assertEqual(rank_size(layer), (rank, size)) if hasattr(module, "tp_rank"): self.assertEqual( (module.tp_rank, module.tp_size), (rank, size) ) reset_context() - def test_guard_and_moonvit_dense_path(self): - from sglang.srt.layers.attention.vision import VisionAttention - from sglang.srt.models.kimi_vl_moonvit import MLP2 - - publish( - ServerArgs( - model_path="dummy", - device="cpu", - tp_size=4, - attn_dp_size=2, - mm_attention_backend="sdpa", - ), - role="test", - ranks=SpawnRanks(world_rank=3), - ) - with self.assertRaisesRegex(ValueError, "shards over the attention TP group"): - VisionAttention(32, 8, 32, True, qkv_backend="sdpa") - with get_disagg().override(language_model_only=True): - offloaded = VisionAttention(32, 8, 32, True, qkv_backend="sdpa") - self.assertEqual((offloaded.proj.tp_rank, offloaded.proj.tp_size), (1, 2)) - self.assertFalse(offloaded.proj.use_dp_attention_reduce) - for data_parallel, tensor_parallel in ((False, False), (True, True)): - module = MLP2( - [32, 64, 32], - torch.nn.GELU(), - use_data_parallel=data_parallel, - use_tensor_parallel=tensor_parallel, - ) - self.assertIsInstance(module.fc0, torch.nn.Linear) - self.assertIsInstance(module.fc1, torch.nn.Linear) - self.assertEqual(module(torch.zeros(2, 32)).shape, (2, 32)) - if __name__ == "__main__": unittest.main() diff --git a/test/registered/unit/models/test_inkling_linear_loader_layout.py b/test/registered/unit/models/test_inkling_linear_loader_layout.py new file mode 100644 index 0000000000..111924eda2 --- /dev/null +++ b/test/registered/unit/models/test_inkling_linear_loader_layout.py @@ -0,0 +1,286 @@ +"""Model checkpoint preprocessing uses the constructed projection's layout.""" + +import unittest +from contextlib import nullcontext +from types import SimpleNamespace +from unittest.mock import Mock, patch + +import torch +from torch import nn + +from sglang.srt.lora.layers import BaseLayerWithLoRA +from sglang.srt.models import inkling +from sglang.srt.models.inkling_common.attn import InklingAttention +from sglang.srt.models.inkling_common.dense_mlp import InklingDenseMLP +from sglang.srt.runtime_context import SpawnRanks, reset_context +from sglang.srt.server_args import ServerArgs +from sglang.test.ci.ci_register import register_cpu_ci +from sglang.test.parallel_groups import parallel_scope, publish, rank_size +from sglang.test.test_utils import CustomTestCase + +register_cpu_ci(est_time=15, stage="weekly", runner_config="cpu") + + +def values(shape, offset=0, *, device="cpu", dtype=torch.float32): + count = 1 + for size in shape: + count *= size + return ( + (((torch.arange(count, device=device) + offset) % 29 - 14) / 128) + .reshape(shape) + .to(dtype) + ) + + +def base(module): + return module.base_layer if isinstance(module, BaseLayerWithLoRA) else module + + +def loading_scope(changed): + if not changed: + return nullcontext() + return parallel_scope( + tp_rank=0, + tp_size=1, + tp_group=None, + attn_tp_rank=0, + attn_tp_size=1, + attn_tp_group=None, + attn_dp_rank=0, + attn_dp_size=1, + attn_cp_rank=0, + attn_cp_size=1, + moe_tp_rank=0, + moe_tp_size=1, + moe_ep_rank=0, + moe_ep_size=1, + moe_ep_group=None, + moe_dp_rank=0, + moe_dp_size=1, + ) + + +def build_attention_model( + kv_heads, *, local=False, wrapped=False, width=32, head_dim=8, quant_config=None +): + model = inkling.InklingForConditionalGeneration.__new__( + inkling.InklingForConditionalGeneration + ) + nn.Module.__init__(model) + model.audio = model.visual = None + model.text_config = SimpleNamespace( + num_key_value_heads=kv_heads, + head_dim=head_dim, + swa_num_key_value_heads=kv_heads, + swa_head_dim=head_dim, + local_layer_ids=[0] if local else [], + n_routed_experts=2, + ) + model.llm = nn.Module() + block = nn.Module() + block.attn = InklingAttention( + width, + 8, + kv_heads, + head_dim, + head_dim, + 8, + 4, + 1e-6, + local, + 0, + kv_conv=True, + sconv_kernel_size=3, + quant_config=quant_config, + ) + if wrapped: + block.attn.qkvr = BaseLayerWithLoRA(block.attn.qkvr, Mock()) + model.llm.layers = nn.ModuleList([block]) + return model, block.attn + + +def load_attention(model, attention, *, changed=False, offset=0): + qkvr = base(attention.qkvr) + rank, size = rank_size(qkvr) + device, dtype = qkvr.weight.device, qkvr.weight.dtype + heads, kv_heads, head_dim = ( + qkvr.inkling_num_heads, + qkvr.inkling_num_kv_heads, + qkvr.inkling_head_dim, + ) + weights, expected = [], [] + for i, (name, rows) in enumerate( + ( + ("wq_du", heads * head_dim), + ("wk_dv", kv_heads * head_dim), + ("wv_dv", kv_heads * head_dim), + ("wr_du", heads * qkvr.inkling_d_rel), + ) + ): + full = values((rows, qkvr.input_size), offset + i, device=device, dtype=dtype) + weights.append((f"model.llm.layers.0.attn.{name}.weight", full)) + if name in ("wk_dv", "wv_dv") and size > kv_heads: + begin = (rank // (size // kv_heads)) * head_dim + expected.append(full[begin : begin + head_dim]) + else: + expected.append(full.chunk(size)[rank]) + conv_expected = {} + for i, name in enumerate(("k_sconv", "v_sconv")): + full = values( + (kv_heads * head_dim, 1, 3), offset + i + 4, device=device, dtype=dtype + ) + weights.append((f"model.llm.layers.0.attn.{name}.weight", full)) + local_rows = attention.num_tp_kv_heads * head_dim + begin = ( + (rank // (size // kv_heads)) * head_dim + if size > kv_heads + else rank * local_rows + ) + conv_expected[name] = full[begin : begin + local_rows] + # Checkpoints can include a layer absent from this model; keep ignoring it. + weights.append(("model.llm.layers.999.attn.wk_dv.weight", weights[1][1])) + with loading_scope(changed): + loaded = model.load_weights(weights) + assert loaded == { + "llm.layers.0.attn.qkvr.weight", + "llm.layers.0.attn.k_sconv.weight", + "llm.layers.0.attn.v_sconv.weight", + } + expected = torch.cat(expected) + torch.testing.assert_close(qkvr.weight, expected) + for name, shard in conv_expected.items(): + torch.testing.assert_close(getattr(attention, name).weight, shard) + return expected, conv_expected + + +def build_dense_model( + *, mtp=False, wrapped=False, width=32, group="attn_tp", quant_config=None +): + cls = ( + inkling.InklingForConditionalGenerationMTP + if mtp + else inkling.InklingForConditionalGeneration + ) + model = cls.__new__(cls) + nn.Module.__init__(model) + mlp = InklingDenseMLP( + width, + 2 * width, + False, + 0, + fused=True, + parallel_group=group, + quant_config=quant_config, + ) + if wrapped: + mlp.gate_up_proj = BaseLayerWithLoRA(mlp.gate_up_proj, Mock()) + if mtp: + model.model = nn.Module() + model.model.mlp = mlp + else: + model.audio = model.visual = None + model.text_config = SimpleNamespace(n_routed_experts=2) + model.llm = nn.Module() + block = nn.Module() + block.mlp = mlp + model.llm.layers = nn.ModuleList([block]) + return model, mlp + + +def load_dense(model, mlp, *, mtp=False, changed=False, compatible=False, offset=0): + projection = base(mlp.gate_up_proj) + rank, size = rank_size(projection) + device, dtype = projection.weight.device, projection.weight.dtype + full = values( + (sum(projection.output_sizes), projection.input_size), + offset, + device=device, + dtype=dtype, + ) + expected = full.chunk(size)[rank] + if compatible and not mtp: + expected = torch.cat((expected[::2], expected[1::2])) + down = base(mlp.down_proj) + full_down = values( + (down.output_size, down.input_size), offset + 1, device=device, dtype=dtype + ) + prefix = "mtp.layers.0" if mtp else "llm.layers.0" + with ( + loading_scope(changed), + patch.object( + inkling, "lora_compatible_layout_enabled", return_value=compatible + ), + ): + loaded = model.load_weights( + [ + (f"model.{prefix}.mlp.w13_dn.weight", full), + (f"model.{prefix}.mlp.w2_md.weight", full_down), + ] + ) + torch.testing.assert_close(projection.weight, expected) + down_rank, down_size = rank_size(down) + expected_down = full_down.chunk(down_size, dim=1)[down_rank] + torch.testing.assert_close(down.weight, expected_down) + expected_prefix = "model" if mtp else "llm.layers.0" + assert loaded == { + f"{expected_prefix}.mlp.gate_up_proj.weight", + f"{expected_prefix}.mlp.down_proj.weight", + } + return expected, expected_down + + +class TestInklingLinearLoaderLayout(CustomTestCase): + def setUp(self): + reset_context() + self.addCleanup(reset_context) + + def exercise(self, changed, wrapped=False): + for dp in (1, 2): + for rank in range(4): + reset_context() + publish( + ServerArgs( + model_path="dummy", device="cpu", tp_size=4, attn_dp_size=dp + ), + role="test", + ranks=SpawnRanks(world_rank=rank), + ) + for kv_heads in (1, 2, 4): + for local in (False, True): + model, attention = build_attention_model( + kv_heads, local=local, wrapped=wrapped + ) + for offset in (0, 7): + expected, _ = load_attention( + model, attention, changed=changed, offset=offset + ) + x = values((2, attention.hidden_size), 3) + actual = base(attention.qkvr)(x)[0] + torch.testing.assert_close( + actual, torch.nn.functional.linear(x, expected) + ) + for mtp in (False, True): + for group in ("attn_tp", "replicated"): + model, mlp = build_dense_model( + mtp=mtp, group=group, wrapped=wrapped + ) + for compatible in (False, True): + for offset in (0, 7): + load_dense( + model, + mlp, + mtp=mtp, + changed=changed, + compatible=compatible, + offset=offset, + ) + + def test_checkpoint_layout_after_scope_exit(self): + self.exercise(True) + + def test_checkpoint_layout_through_lora_wrappers(self): + self.exercise(True, wrapped=True) + + +if __name__ == "__main__": + unittest.main()