# Copyright 2025 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import json import math import re from dataclasses import asdict, dataclass from typing import TYPE_CHECKING, List, Optional import jax.numpy as jnp import numpy as np from jax.sharding import Mesh from tpu_inference import envs, utils from tpu_inference.logger import init_logger if TYPE_CHECKING: from vllm.config import VllmConfig logger = init_logger(__name__) MESH_AXIS_NAMES = ("data", "attn_dp", "attn_dp_expert", "expert", "model", "dcp", "pcp") MESH_AXIS_NAMES_2D = ('data', 'model') class ShardingAxisNameBase: """Base class for sharding axis names.""" SEQUENCE = ( 'data', 'attn_dp', 'attn_dp_expert', ) ATTN_DATA = ('data', 'pcp', 'attn_dp', 'attn_dp_expert') ATTN_DATA_EXPERT = ('attn_dp_expert', 'expert') MLP_DATA = 'data' ATTN_HEAD = ('model', 'expert', 'dcp') # Q heads KV_HEAD = ('model', 'expert') ATTN_TENSOR = None MLP_TENSOR = ('attn_dp', 'attn_dp_expert', 'expert', 'model', 'dcp', 'pcp') MOE_TENSOR = ('attn_dp', 'model', 'dcp', 'pcp') EXPERT = ('attn_dp', 'attn_dp_expert', 'expert', 'model', 'dcp', 'pcp') EXPERT_DATA = ('data', 'attn_dp', 'attn_dp_expert', 'expert', 'model', 'dcp', 'pcp') VOCAB = ('attn_dp', 'attn_dp_expert', 'expert', 'model', 'dcp', 'pcp') MODEL_1 = 'model' MODEL_2 = 'expert' # Standard name for the model sharding axis. MODEL = 'model' # These axes are used in KV caches management. BATCH = ('data', 'attn_dp', 'attn_dp_expert') KV_CONTEXT = ('pcp', 'dcp') # PCP input sharding PREFILL_CONTEXT = 'pcp' # Vision encoder sharding axes VIT_BATCH = ('data', 'attn_dp', 'attn_dp_expert') VIT_MODEL = 'model' class ShardingAxisName2D: """Sharding axis names for 2D data parallelism scenarios. NOTE(wenxindongwork): The new MoE kernel expects a 2D mesh for now. We should use ShardingAxisNameBase once the new MoE kernel supports more general mesh shapes. For now, this is the default sharding axes. """ SEQUENCE = 'data' ATTN_DATA = 'data' MLP_DATA = 'data' ATTN_HEAD = 'model' KV_HEAD = 'model' ATTN_TENSOR = None MLP_TENSOR = 'model' MOE_TENSOR = 'model' EXPERT = 'model' EXPERT_DATA = ('data', 'model') VOCAB = ('data', 'model') BATCH = 'data' KV_CONTEXT = None PREFILL_CONTEXT = None MODEL = 'model' # Vision encoder sharding axes VIT_BATCH = 'data' VIT_MODEL = 'model' # Lazily initialize the ShardingAxisName so that we can decide which one to use based on the # propagated / updated environment variables in the multi-host setup. class LazyShardingAxisName: """Lazy loading for ShardingAxisName.""" def __init__(self): self._cls = None self._overrides: dict = {} def _initialize(self): if self._cls is None: try: _use_2d_tp_sharding = envs.USE_2D_TP _use_base_sharding = envs.NEW_MODEL_DESIGN if _use_2d_tp_sharding or _use_base_sharding: self._cls = ShardingAxisNameBase else: self._cls = ShardingAxisName2D except Exception: self._cls = ShardingAxisName2D def override(self, **kwargs): """Set runtime axis overrides.""" self._overrides.update(kwargs) def reset(self): """Clear all overrides, restoring base-class values.""" self._overrides.clear() def __getattr__(self, name): if name in self._overrides: return self._overrides[name] self._initialize() return getattr(self._cls, name) ShardingAxisName = LazyShardingAxisName() def is_attn_dp(mesh: Mesh) -> bool: """Whether attention data-parallelism is active on ``mesh``. True when the attention-data axes carry a factor beyond plain data parallelism (i.e. ``attn_dp`` * ``attn_dp_expert`` > 1), meaning attention is replicated over more data-parallel shards than the MLP/data axis alone. """ attn_dp_size = utils.get_mesh_shape_product(mesh, ShardingAxisName.ATTN_DATA) dp_size = utils.get_mesh_shape_product(mesh, ShardingAxisName.MLP_DATA) return (attn_dp_size // dp_size) > 1 def is_shared_expert_prefix(prefix: str) -> bool: """Whether a linear layer's prefix names a MoE shared expert. Covers both checkpoint namings: `.shared_expert.` (Qwen) and `.shared_experts.` (DeepSeek V2/V3 style). """ return re.search(r"\.shared_experts?\.", prefix) is not None def shared_expert_is_replicated(shared_experts) -> bool: """Whether every linear of the shared expert has replicated weights. VllmQuantLinearConfig replicates the shared expert under the sequence-parallel residual stream (`sharding.keeps_tokens_sharded`); it then runs on the local token slice and its output is already complete. Reads the linears' actual weight sharding, so it can't disagree with the linear configs. """ modules_fn = getattr(shared_experts, "modules", None) if not callable(modules_fn): return False configs = [ m.quant_method.linear_config for m in modules_fn() if getattr(getattr(m, "quant_method", None), "linear_config", None) is not None ] return bool(configs) and all( all(axis is None for axis in c.weight_sharding) for c in configs) def keeps_tokens_sharded(mesh: Mesh | None, enable_sp: bool, *, gmm_ep: bool) -> bool: """Whether the residual stream stays token-sharded over EXPERT_DATA. Sequence parallelism (`enable_sp`) under attention DP with GMM_EP (`expert_parallel_gmm`): the MoE consumes and produces tokens sharded over all devices (EXPERT_DATA), so instead of resharding to ATTN_DATA around every linear and the MoE, the activations outside attention stay token-sharded: column-parallel projections all-gather (FP8) tokens over the attention TP axis, row-parallel ones reduce-scatter, and router / shared expert / norms run on the local token slice. Only under attention DP with attention TP > 1 and GMM_EP; otherwise `enable_sp` keeps its MLP_TENSOR input / output sharding: - `gmm_ep`: the MoE backend must be GMM_EP. GMM_TP (expert parallelism off) and the other EP backends (USE_MOE_EP_KERNEL, USE_FUSED_EP_MOE_V2, USE_ROUTING_MOE) ignore `keep_token_sharding`. vLLM callers decide this with `select_moe_backend` via `vllm_keeps_tokens_sharded`. - The `expert` and `pcp` mesh axes must be size 1. The linears gather and reduce-scatter tokens over ATTN_HEAD (`model`, `expert`, `dcp`) inside each ATTN_DATA block, but EXPERT_DATA orders `expert` before `model` and puts `pcp` last, so with either axis > 1 the token rows would not line up with EXPERT_DATA. """ if not enable_sp or not gmm_ep: return False if mesh is None or not is_attn_dp(mesh): return False if any( utils.get_mesh_shape_product(mesh, axis) > 1 for axis in ("expert", "pcp")): return False return (utils.get_mesh_shape_product(mesh, ShardingAxisName.ATTN_HEAD) > 1 and utils.get_mesh_shape_product(mesh, ShardingAxisName.EXPERT_DATA) > 1) def sp_token_axes(mesh: Mesh, keep_tokens_sharded: bool, num_tokens: int): """EXPERT_DATA if `num_tokens` tokens stay sharded over it, else None. Requires the token count to divide EXPERT_DATA; otherwise the linears use the usual ATTN_DATA token sharding (XLA reshards around them). """ if not keep_tokens_sharded: return None if num_tokens % utils.get_mesh_shape_product(mesh, ShardingAxisName.EXPERT_DATA): return None return ShardingAxisName.EXPERT_DATA @dataclass class ShardingStrategy: """Defines the high-level parallelism strategy. This class specifies how many ways each type of parallelism (tensor, expert, sequence, data) should be distributed across the available devices. Attributes: tensor_parallelism: The degree of tensor parallelism (e.g., splitting weights of a single layer). expert_parallelism: The degree of expert parallelism for MoE models. sequence_parallelism: The degree of sequence parallelism (splitting activations along the sequence length dimension). data_parallelism: The degree of data parallelism (splitting the batch across devices). """ tensor_parallelism: int = 1 expert_parallelism: int = 1 sequence_parallelism: int = 1 data_parallelism: int = 1 attention_data_parallelism: int = 1 attention_data_expert_parallelism: int = 1 decode_context_parallelism: int = 1 prefill_context_parallelism: int = 1 class ShardingConfigManager: """Manages sharding configuration parsing and access from vLLM config. Usage: sharding_config = ShardingConfigManager.from_vllm_config(vllm_config) tp_size = sharding_config.tp_size During initialization, we set `vllm_config.sharding_config` to `ShardingConfigManager.from_vllm_config(vllm_config)`, so you can access `vllm_config.sharding_config.tp_size` directly. """ def __init__(self, sharding_strategy: ShardingStrategy, device_indexes: Optional[List] = None, mm_encoder_tp_mode: str = "weights"): self.sharding_strategy: ShardingStrategy = sharding_strategy self.device_indexes: Optional[List[int]] = device_indexes self._total_devices: int = int( math.prod(asdict(sharding_strategy).values())) if device_indexes: assert self._total_devices == len(device_indexes) self.mm_encoder_tp_mode = mm_encoder_tp_mode @classmethod def from_vllm_config(cls, vllm_config: 'VllmConfig') -> 'ShardingConfigManager': sharding_strategy = vllm_config.additional_config.get( "sharding", {}).get("sharding_strategy", {}) parallel_config = vllm_config.parallel_config # Currently tensor_parallelism is also used for other things like determining number of Ray workers. pc_tensor_parallelism = parallel_config.tensor_parallel_size ss_tensor_parallelsim = sharding_strategy.get("tensor_parallelism", None) data_parallelism = parallel_config.data_parallel_size enable_dp_attention = sharding_strategy.get("enable_dp_attention", False) if envs.TPU_MULTIPROCESS_DP: data_parallelism = 1 expert_parallelism = sharding_strategy.get("expert_parallelism", 1) sequence_parallelism = sharding_strategy.get("sequence_parallelism", 1) device_indexes = sharding_strategy.get("device_indexes", None) decode_context_parallelism = parallel_config.decode_context_parallel_size prefill_context_parallelism = parallel_config.prefill_context_parallel_size if pc_tensor_parallelism != ss_tensor_parallelsim and ss_tensor_parallelsim: # The user has explicitly set the tensor parallelism in the sharding config. tensor_parallelism = ss_tensor_parallelsim else: tensor_parallelism = pc_tensor_parallelism if tensor_parallelism % decode_context_parallelism != 0: raise ValueError( f"tensor_parallelism ({tensor_parallelism}) must be divisible by " f"decode_context_parallelism ({decode_context_parallelism})") # DCP reused TP axis tensor_parallelism = tensor_parallelism // decode_context_parallelism if enable_dp_attention: # Replicate attention layer when num_kv_heads < TP num_kv_heads = 1 if vllm_config.model_config.use_mla else vllm_config.model_config.get_total_num_kv_heads( ) cache_dtype = vllm_config.cache_config.cache_dtype if cache_dtype == 'auto': cache_dtype = vllm_config.model_config.dtype kv_dtype = utils.get_jax_dtype_from_str_dtype( cache_dtype) or jnp.bfloat16 packing = 4 // jnp.dtype(kv_dtype).itemsize # The default head dim is 128 but 64 is also supported as a special case. if vllm_config.model_config.get_head_size() == 64: packing *= 2 # When num_kv_heads * 2 / packing < TP, tensor parallelism would # duplicate KV heads across devices, wasting kv cache memory. # Use attention DP instead to reduce per-device num_kv_heads and # eliminate this waste. if envs.USE_BATCHED_RPA_KERNEL and envs.USE_BATCHED_RPA_SEQ_ON_LANE: num_kv_heads_per_device_in_kv_cache = max(1, num_kv_heads * 2) else: num_kv_heads_per_device_in_kv_cache = max( 1, (num_kv_heads * 2) / packing) attn_dp_size = sharding_strategy.get("attn_dp_size", None) if attn_dp_size is None: attn_dp = max( int(tensor_parallelism // num_kv_heads_per_device_in_kv_cache), 1) tensor_parallelism = tensor_parallelism // attn_dp else: attn_dp = attn_dp_size assert tensor_parallelism % attn_dp_size == 0 tensor_parallelism = tensor_parallelism // attn_dp # If Attention DP is active or TP perfectly saturates the KV heads limit, # prioritize TP for KV heads and shift all expert parallelism to attn_dp_expert. is_kv_fully_sharded_by_tp = (attn_dp > 1) or ( tensor_parallelism == num_kv_heads_per_device_in_kv_cache) if is_kv_fully_sharded_by_tp: attn_dp_expert = expert_parallelism expert_parallelism = 1 else: # Otherwise, shard KV heads over the expert axis. # Use the remaining KV heads per device as the divisor. shard_divisor = num_kv_heads_per_device_in_kv_cache // tensor_parallelism attn_dp_expert = max(1, int(expert_parallelism // shard_divisor)) expert_parallelism //= attn_dp_expert else: attn_dp = 1 attn_dp_expert = 1 sharding_strategy = ShardingStrategy( tensor_parallelism=tensor_parallelism, data_parallelism=data_parallelism, expert_parallelism=expert_parallelism, sequence_parallelism=sequence_parallelism, attention_data_parallelism=attn_dp, attention_data_expert_parallelism=attn_dp_expert, decode_context_parallelism=decode_context_parallelism, prefill_context_parallelism=prefill_context_parallelism) # Must override here to avoid vLLM spinning up multiple DP engines. if (not envs.TPU_MULTIPROCESS_DP and vllm_config.parallel_config.data_parallel_size > 1): vllm_config.parallel_config.data_parallel_size = 1 vllm_config.parallel_config.data_parallel_rank = 0 vllm_config.parallel_config.data_parallel_size_local = 1 # To enable data-parallel vision encoding, pass: # --additional_config='{"mm-encoder-tp-mode": "data"}' mm_encoder_tp_mode = vllm_config.additional_config.get( 'mm-encoder-tp-mode', 'weights') cls.validate(vllm_config, sharding_strategy) return cls(sharding_strategy, device_indexes, mm_encoder_tp_mode) @classmethod def validate(cls, vllm_config, sharding_strategy): total_dp_size = sharding_strategy.data_parallelism * sharding_strategy.attention_data_parallelism * sharding_strategy.attention_data_expert_parallelism if total_dp_size > 1: if vllm_config.lora_config is not None: raise ValueError( f"LoRA is not supported with data parallelism " f"(DP size: {total_dp_size}). Please disable LoRA or " f"set data parallelism to 1.") if sharding_strategy.attention_data_parallelism > 1: if not envs.NEW_MODEL_DESIGN: raise ValueError( "Must run Attention DP with NEW_MODEL_DESIGN enabled. Please set " "NEW_MODEL_DESIGN=True") if sharding_strategy.decode_context_parallelism > 1: if not envs.NEW_MODEL_DESIGN: raise ValueError( "Must run Context Parallelism with NEW_MODEL_DESIGN enabled. Please set " "NEW_MODEL_DESIGN=True") if sharding_strategy.prefill_context_parallelism > 1: if not envs.NEW_MODEL_DESIGN: raise ValueError( "Must run Prefill Context Parallelism with NEW_MODEL_DESIGN " "enabled. Please set NEW_MODEL_DESIGN=True") if sharding_strategy.prefill_context_parallelism % 2 != 0: raise ValueError( "Prefill context parallelism size must be even: the ring " "cache phase rotates KV shards between rank pairs, got " f"{sharding_strategy.prefill_context_parallelism}.") if sharding_strategy.decode_context_parallelism > 1: raise ValueError( "Only one of prefill/decode context parallelism may be " "enabled at a time.") if sharding_strategy.data_parallelism > 1: raise ValueError( "Prefill context parallelism is not compatible with data parallelism yet." ) @property def total_dp_size(self) -> int: return self.sharding_strategy.data_parallelism * self.sharding_strategy.attention_data_parallelism * self.sharding_strategy.attention_data_expert_parallelism @property def model_dp_size(self) -> int: return self.sharding_strategy.data_parallelism @property def attn_dp_size(self) -> int: return self.sharding_strategy.attention_data_parallelism @property def attn_dp_expert_size(self) -> int: return self.sharding_strategy.attention_data_expert_parallelism @property def tp_size(self) -> int: return self.sharding_strategy.tensor_parallelism @property def expert_size(self) -> int: return self.sharding_strategy.expert_parallelism @property def sequence_size(self) -> int: return self.sharding_strategy.sequence_parallelism @property def decode_cp_size(self) -> int: return self.sharding_strategy.decode_context_parallelism @property def prefill_cp_size(self) -> int: return self.sharding_strategy.prefill_context_parallelism @property def total_devices(self) -> int: return self._total_devices def apply_vision_sharding(self): ShardingAxisName.reset() if self.mm_encoder_tp_mode == "data" and self.tp_size > 1: base = ShardingAxisName.VIT_BATCH model_axis = ShardingAxisName.MODEL vit_batch = (base, model_axis) if isinstance( base, str) else tuple(base) + (model_axis, ) ShardingAxisName.override(VIT_BATCH=vit_batch, VIT_MODEL=None) def __str__(self): return (f"ShardingConfigManager(total_devices={self.total_devices}, " f"sharding_strategy={self.sharding_strategy}, " f"mm_encoder_tp_mode={self.mm_encoder_tp_mode}, " f"device_indexes={self.device_indexes})") #TODO split this into block unique sharding config, i.e. attentionShardingConfig, MoEShardingConfig @dataclass class ShardingRulesConfig: """Holds detailed sharding configurations for individual tensors, namely logical rules. Each attribute in this class corresponds to a specific weight or activation tensor within a transformer model. The value of each attribute is a tuple of logical mesh axis names (e.g., 'dp', 'sp', 'tp'), which defines how the corresponding tensor's dimensions are partitioned across the device mesh. The dimension order in the attribute name (e.g., `btd` for batch, sequence, d_model) maps directly to the sharding tuple. TODO: update the mesh axis names to be clear and reduce confusion between prefill & generate """ # Activation for attn input: (Batch * Sequence, Dim) activation_attention_td: tuple = (None, None) # Activation for attn out: (Batch * Sequence, Dim) activation_attention_out_td: tuple = (None, None) # Activation for q projection input: (Batch * Sequence, Dim) activation_q_td: tuple = (None, None) # Attention Out activation after projection: (Batch * Sequence, NumHeads, HeadDim) attn_o_tnh: tuple = (None, None, None) # Q vector: (Batch * Sequence, NumHeads, HeadDim) query_tnh: tuple = (None, None, None) # K/V vector: (Batch * Sequence, NumKVHeads, HeadDim) keyvalue_skh: tuple = (None, None, None) # Attention Q weight: (Dim, NumHeads, HeadDim) attn_q_weight_dnh: tuple = (None, None, None) # Attention K weight: (Dim, NumKVHeads, HeadDim) attn_k_weight_dkh: tuple = (None, None, None) # Attention V weight: (Dim, NumKVHeads, HeadDim) attn_v_weight_dkh: tuple = (None, None, None) # Attention Out weight: (NumHeads, HeadDim, Dim) attn_o_weight_nhd: tuple = (None, None, None) # Activation for ffw input: (Batch * Sequence, Dim) activation_ffw_td: tuple = (None, None) # Activation for ffw input: (Batch * Sequence, Expert, Dim) activation_ffw_ted: tuple = (None, None, None) # FFW hidden activation: (Batch * Sequence, FfwDim) ffw_hidden_tf: tuple = (None, None) # FFW up/gate weight: (Dim, FfwDim) ffw_weight_df: tuple = (None, None) # FFW down weight: (FfwDim, Dim) ffw_weight_fd: tuple = (None, None) # MoE gate/up weights: (NumExperts, Dim, FfwDim) moe_weights_edf: tuple = (None, None, None) # MoE down weights: (NumExperts, FfwDim, Dim) moe_weights_efd: tuple = (None, None, None) # MoE router weights: (Dim, NumExperts) moe_router_de: tuple = (None, None) # MoE router bias weights: (NumExperts,) moe_router_bias_e: tuple = (None, ) # Embedding weight: (VocabSize, Dim) emb_weight_vd: tuple = (None, None) # Activation between layers: (Batch * Sequence, Dim) activation_td: tuple = (None, None) # Final activation before logits: (Batch * Sequence, Dim) prelogit_td: tuple = (None, None) # Logit activation: (Batch * Sequence, VocabSize) logits_tv: tuple = (None, None) # RMS norm scale weight: (Dim,) norm_scale: tuple = (None) # Vocab projection weight (tied embeddings): (Dim, VocabSize) vocab_vd: tuple = (None, None) vocab_dv: tuple = (None, None) class ShardingConfig: """Container for operation-specific sharding configurations. This class holds two separate `ShardingRulesConfig` objects, one for the 'prefill' phase and one for the 'generate' (or decode) phase of model execution. This allows tailoring sharding strategies to the different computational patterns of each phase. Example Sharding Strategy and Configuration: Sharding Strategy defines the high-level parallelism dimensions. For a device mesh like `Mesh((2, 4, 4, 4), ('data', 'seq', 'expert', 'tensor'))` on 128 devices: - data: Data Parallelism (2-way) - seq: Sequence Parallelism (4-way) - expert: Expert Parallelism (4-way) - tensor: Tensor Parallelism (4-way) ShardingConfig then maps tensor dimensions to these logical mesh axes. For example, a tensor with shape (Batch, Sequence, Dimension) could be sharded differently for prefill and decode/generate operations: - Prefill (long sequences, small batch): Sharding sequence dim on the 'sp' axis is often efficient. `prefill_rules.activation_attention_btd = (None, 'seq', 'tensor')` - Generate (short sequences, large batch): Sharding batch dim on the 'dp' axis is often efficient. `generate_rules.activation_attention_btd = ('data', None, 'tensor')` """ def __init__(self, prefill_rules=None, generate_rules=None, default_rules_cls=ShardingRulesConfig): """Initializes the ShardingConfig. Args: prefill_rules: An `ShardingRulesConfig` for the prefill phase. If None, a default config is created. generate_rules: An `ShardingRulesConfig` for the generate phase. If None, a default config is created. default_rules_cls: The default sharding rules (class) to use. """ # Use a factory pattern to avoid mutable default arguments self.default_rules_cls = default_rules_cls self.prefill_rules = prefill_rules if prefill_rules is not None else default_rules_cls( ) self.generate_rules = generate_rules if generate_rules is not None else default_rules_cls( ) def build_mesh(devices, strategy: dict[str, int]) -> Mesh: """Constructs a JAX device mesh from a sharding strategy. This method creates a logical grid of devices based on the parallelism degrees defined in the strategy. The logical axis names ('dp', 'ep', 'sp', 'tp') are used to map tensor dimensions to the physical device grid. Args: strategy: A dictionary from upper level config. Returns: A JAX `Mesh` object. """ axis_order = { "data": strategy.get("data_parallelism", 1), "expert": strategy.get("expert_parallelism", 1), "seq": strategy.get("sequence_parallelism", 1), "model": strategy.get("tensor_parallelism", 1), "dcp": strategy.get("decode_context_parallelism", 1), "pcp": strategy.get("prefill_context_parallelism", 1), } # TODO: add logic to infer axis when the degree is -1 mesh_axis_names = [] mesh_shape = [] for axis, dim in axis_order.items(): mesh_axis_names.append(axis) mesh_shape.append(dim) if not mesh_shape: mesh_shape = [1] mesh_axis_names = [ 'data' ] # default to data parallelism if no other strategy is specified devices = np.asarray(devices).reshape(mesh_shape) return Mesh(devices, axis_names=tuple(mesh_axis_names)) class Sharding: """Generates and manages sharding configurations based on a high-level strategy. This class populates a `ShardingConfig` with detailed tensor sharding rules for both prefill and generation phases. It also allows for runtime overrides of these rules. Attributes: sharding_cfg: The generated `ShardingConfig` with detailed rules. """ def __init__(self, prefill_rules: dict | None = None, generate_rules: dict | None = None, default_rules_cls=ShardingRulesConfig, vllm_config: 'VllmConfig' = None): """Initializes the Sharding manager. Args: prefill_rules: A dictionary of overrides for the prefill sharding config. Keys are attribute names in `ShardingRulesConfig`, and values are the new sharding tuples. generate_rules: A dictionary of overrides for the generate sharding config. """ self.vllm_config = vllm_config self.default_rules_cls = default_rules_cls self.sharding_cfg = self.make_sharding_config( default_rules_cls=default_rules_cls, prefill_overrides=prefill_rules, generate_overrides=generate_rules) def _get_overrides(self, sharding_phase: str): """Return the overrides from the vLLM config for the given sharding phase.""" overrides = {} try: overrides = self.vllm_config.additional_config["sharding"][ "logical_rules"]["all"] except KeyError: pass try: additional_overrides = self.vllm_config.additional_config[ "sharding"]["logical_rules"][f"{sharding_phase}"] overrides.update(additional_overrides) except KeyError: pass return overrides def __str__(self): """Succinct representation of relevant Sharding settings and overrides.""" output_str = f" Using {self.default_rules_cls.__name__} logical rules.\n" output_str += f" {self.__class__.__name__:} overrides:\n" output_str += f" prefill logical_rule overrides:\n {json.dumps(self._get_overrides('prefill'), indent=4, default=str)}\n\n" output_str += f" generate logical_rule overrides:\n {json.dumps(self._get_overrides('generate'), indent=4, default=str)}\n\n" return output_str def validate_sharding_strategy(self, ): """Validates if the sharding strategy is compatible with the environment. This method is a placeholder now, and will check if the product of parallelism degrees matches the number of available devices. """ #TODO: check num_devices % parallelism == 0 #TODO: check num_devices == multiply(parallelism(with inferred)) return def get_sharding_cfg(self) -> ShardingConfig: """Returns the generated sharding configuration.""" return self.sharding_cfg def _apply_overrides(self, config_obj: ShardingRulesConfig, overrides: dict | None): """Applies runtime overrides to a sharding configuration object. Args: config_obj: The sharding configuration object (e.g., prefill_rules) to be updated. overrides: A dictionary where keys are attribute names of the config object and values are the new sharding tuples. Raises: AttributeError: If a key in the overrides dictionary is not a valid attribute of the configuration object. """ for key, value in overrides.items(): if hasattr(config_obj, key): setattr(config_obj, key, value) else: # Raise an error for invalid keys to prevent silent failures raise AttributeError( f"'{key}' is not a valid attribute of {type(config_obj).__name__}" ) def _make_default_sharding_config(self, prefill_rules, generate_rules): # Populate Prefill Config # During prefill, sequence length is long, so we shard along the sequence axis. prefill_rules.activation_attention_td = (ShardingAxisName.ATTN_DATA, ShardingAxisName.ATTN_TENSOR) prefill_rules.activation_attention_out_td = ( ShardingAxisName.ATTN_DATA, ShardingAxisName.ATTN_TENSOR) prefill_rules.activation_q_td = (ShardingAxisName.ATTN_DATA, ShardingAxisName.ATTN_TENSOR) #TODO: the default qkv and kvcache is sharded on head dim # We may change it after we finalize the KVCache design prefill_rules.attn_o_tnh = (ShardingAxisName.ATTN_DATA, ShardingAxisName.ATTN_HEAD, None) prefill_rules.query_tnh = (ShardingAxisName.ATTN_DATA, ShardingAxisName.ATTN_HEAD, None) prefill_rules.keyvalue_skh = (ShardingAxisName.ATTN_DATA, ShardingAxisName.ATTN_HEAD, None) # Populate Generate (Decode) Config # During decode, batch size is the large dimension, so we shard along the batch axis. generate_rules.activation_attention_td = (ShardingAxisName.ATTN_DATA, ShardingAxisName.ATTN_TENSOR) generate_rules.activation_attention_out_td = ( ShardingAxisName.MLP_DATA, ShardingAxisName.ATTN_TENSOR) generate_rules.activation_q_td = (ShardingAxisName.ATTN_DATA, ShardingAxisName.ATTN_TENSOR) #TODO: the default qkv and kvcache is sharded on head dim # We may change it after we finalize the KVCache design generate_rules.attn_o_tnh = (ShardingAxisName.ATTN_DATA, ShardingAxisName.ATTN_HEAD, None) generate_rules.query_tnh = (ShardingAxisName.ATTN_DATA, ShardingAxisName.ATTN_HEAD, None) generate_rules.keyvalue_skh = (ShardingAxisName.ATTN_DATA, ShardingAxisName.ATTN_HEAD, None) generate_rules.attn_q_weight_dnh = (None, ShardingAxisName.ATTN_HEAD, ShardingAxisName.ATTN_TENSOR) generate_rules.attn_k_weight_dkh = (None, ShardingAxisName.ATTN_HEAD, ShardingAxisName.ATTN_TENSOR) generate_rules.attn_v_weight_dkh = (None, ShardingAxisName.ATTN_HEAD, ShardingAxisName.ATTN_TENSOR) generate_rules.attn_o_weight_nhd = (ShardingAxisName.ATTN_HEAD, None, ShardingAxisName.ATTN_TENSOR) generate_rules.activation_ffw_td = (ShardingAxisName.MLP_DATA, None) generate_rules.activation_ffw_ted = (ShardingAxisName.MLP_DATA, ShardingAxisName.EXPERT, None) generate_rules.ffw_hidden_tf = (ShardingAxisName.MLP_DATA, ShardingAxisName.MLP_TENSOR) # FFW weights are typically sharded along the hidden dimension (F). generate_rules.ffw_weight_df = (None, ShardingAxisName.MLP_TENSOR) generate_rules.ffw_weight_fd = (ShardingAxisName.MLP_TENSOR, None) # MoE weights are sharded along the expert axis and the hidden dimension. generate_rules.moe_weights_edf = (ShardingAxisName.EXPERT, None, ShardingAxisName.MOE_TENSOR) generate_rules.moe_weights_efd = (ShardingAxisName.EXPERT, ShardingAxisName.MOE_TENSOR, None) generate_rules.moe_router_de = (None, ShardingAxisName.EXPERT) # Embedding weight: (VocabSize, Dim) generate_rules.emb_weight_vd = (ShardingAxisName.MLP_TENSOR, None) generate_rules.activation_td = (ShardingAxisName.MLP_DATA, ShardingAxisName.ATTN_TENSOR) generate_rules.prelogit_td = (ShardingAxisName.MLP_DATA, ShardingAxisName.MLP_TENSOR) generate_rules.logits_tv = (ShardingAxisName.MLP_DATA, ShardingAxisName.MLP_TENSOR) generate_rules.vocab_vd = (ShardingAxisName.VOCAB, None) generate_rules.vocab_dv = (None, ShardingAxisName.VOCAB) def make_sharding_config( self, default_rules_cls: ShardingRulesConfig, prefill_overrides: dict | None = None, generate_overrides: dict | None = None) -> ShardingConfig: """Creates the detailed `ShardingConfig` with specific partitioning rules and applies any runtime overrides. This method populates the `prefill_rules` and `generate_rules` with hardcoded sharding rules that are generally effective for transformer models, and then updates them with any provided overrides. Args: prefill_overrides: A dictionary with attribute names and their new values for the prefill sharding configuration. generate_overrides: A dictionary with attribute names and their new values for the generate sharding configuration. Returns: The populated and overridden `ShardingConfig` object. """ #TODO: organize into update_prefill() and update_decode for each axis #TODO: verify the sharding axes sharding_cfg = ShardingConfig(default_rules_cls=default_rules_cls) prefill_rules = sharding_cfg.prefill_rules generate_rules = sharding_cfg.generate_rules # Extract the overrides from the vllm_config if they are not provided programatically. if prefill_overrides is None: prefill_overrides = self._get_overrides("prefill") if generate_overrides is None: generate_overrides = self._get_overrides("generate") # Apply default sharding configs self._make_default_sharding_config(prefill_rules, generate_rules) # Apply overriding the runtime sharding rules self._apply_overrides(prefill_rules, prefill_overrides) self._apply_overrides(generate_rules, generate_overrides) return sharding_cfg #TODO: Add __repr__ class ShardingInfo: #TODO a sharding info class for visualizing & debugging the sharding performance # Will implement it for the next version pass