| 1 | # SPDX-License-Identifier: Apache-2.0 |
| 2 | # SPDX-FileCopyrightText: Copyright contributors to the vLLM project |
| 3 | """Inference-only Jurassic model.""" |
| 4 | |
| 5 | import typing |
| 6 | from collections.abc import Callable, Iterable |
| 7 | from typing import Any |
| 8 | |
| 9 | import torch |
| 10 | from torch import nn |
| 11 | |
| 12 | from vllm.compilation.decorators import support_torch_compile |
| 13 | from vllm.config import CacheConfig, VllmConfig |
| 14 | from vllm.distributed import ( |
| 15 | get_dp_group, |
| 16 | get_ep_group, |
| 17 | get_pp_group, |
| 18 | get_tensor_model_parallel_rank, |
| 19 | get_tensor_model_parallel_world_size, |
| 20 | get_tp_group, |
| 21 | ) |
| 22 | from vllm.logger import init_logger |
| 23 | from vllm.model_executor.layers.activation import SiluAndMul, SwigluStepAndMul |
| 24 | from vllm.model_executor.layers.attention import Attention |
| 25 | from vllm.model_executor.layers.fused_moe import ( |
| 26 | FusedMoEFactory, |
| 27 | GateLinear, |
| 28 | MoERunner, |
| 29 | fused_moe_make_expert_params_mapping, |
| 30 | ) |
| 31 | from vllm.model_executor.layers.layernorm import GemmaRMSNorm |
| 32 | from vllm.model_executor.layers.linear import ( |
| 33 | ColumnParallelLinear, |
| 34 | MergedColumnParallelLinear, |
| 35 | QKVParallelLinear, |
| 36 | RowParallelLinear, |
| 37 | ) |
| 38 | from vllm.model_executor.layers.logits_processor import LogitsProcessor |
| 39 | from vllm.model_executor.layers.quantization.base_config import QuantizationConfig |
| 40 | from vllm.model_executor.layers.rotary_embedding import get_rope |
| 41 | from vllm.model_executor.layers.vocab_parallel_embedding import ( |
| 42 | ParallelLMHead, |
| 43 | VocabParallelEmbedding, |
| 44 | ) |
| 45 | from vllm.model_executor.model_loader.weight_utils import default_weight_loader |
| 46 | from vllm.sequence import IntermediateTensors |
| 47 | from vllm.v1.attention.backend import AttentionType |
| 48 | |
| 49 | if typing.TYPE_CHECKING: |
| 50 | from vllm.transformers_utils.configs.step3p5 import Step3p5Config |
| 51 | else: |
| 52 | from transformers import PreTrainedConfig as Step3p5Config |
| 53 | |
| 54 | from .interfaces import MixtureOfExperts, SupportsPP |
| 55 | from .utils import ( |
| 56 | AutoWeightsLoader, |
| 57 | PPMissingLayer, |
| 58 | WeightsMapper, |
| 59 | extract_layer_index, |
| 60 | get_spec_layer_idx_from_weight_name, |
| 61 | is_pp_missing_parameter, |
| 62 | make_empty_intermediate_tensors_factory, |
| 63 | make_layers, |
| 64 | maybe_prefix, |
| 65 | ) |
| 66 | |
| 67 | logger = init_logger(__name__) |
| 68 | |
| 69 | |
| 70 | class Step3p5MLP(nn.Module): |
| 71 | def __init__( |
| 72 | self, |
| 73 | config: Step3p5Config, |
| 74 | hidden_size: int, |
| 75 | intermediate_size: int, |
| 76 | hidden_act: str, |
| 77 | quant_config: QuantizationConfig | None = None, |
| 78 | reduce_results: bool = True, |
| 79 | prefix: str = "", |
| 80 | ) -> None: |
| 81 | super().__init__() |
| 82 | self.gate_up_proj = MergedColumnParallelLinear( |
| 83 | hidden_size, |
| 84 | [intermediate_size] * 2, |
| 85 | bias=False, |
| 86 | quant_config=quant_config, |
| 87 | prefix=f"{prefix}.gate_up_proj", |
| 88 | ) |
| 89 | self.down_proj = RowParallelLinear( |
| 90 | intermediate_size, |
| 91 | hidden_size, |
| 92 | bias=False, |
| 93 | quant_config=quant_config, |
| 94 | reduce_results=reduce_results, |
| 95 | prefix=f"{prefix}.down_proj", |
| 96 | ) |
| 97 | |
| 98 | if hidden_act != "silu": |
| 99 | raise ValueError( |
| 100 | f"Unsupported activation: {hidden_act}. Only silu is supported for now." |
| 101 | ) |
| 102 | self.act_fn = SiluAndMul() |
| 103 | self.prefix = prefix |
| 104 | self.hidden_size = hidden_size |
| 105 | self.limit = None |
| 106 | layer_idx = extract_layer_index(prefix) |
| 107 | if ( |
| 108 | config.swiglu_limits_shared |
| 109 | and config.swiglu_limits_shared[layer_idx] is not None |
| 110 | and config.swiglu_limits_shared[layer_idx] != 0 |
| 111 | ): |
| 112 | self.limit = config.swiglu_limits_shared[layer_idx] |
| 113 | self.act_fn = SwigluStepAndMul(limit=self.limit) |
| 114 | |
| 115 | def forward(self, hidden_states: torch.Tensor) -> torch.Tensor: |
| 116 | gate_up, _ = self.gate_up_proj(hidden_states) |
| 117 | intermediate_act = self.act_fn(gate_up) |
| 118 | output, _ = self.down_proj(intermediate_act) |
| 119 | return output |
| 120 | |
| 121 | |
| 122 | class Step3p5Attention(nn.Module): |
| 123 | def __init__( |
| 124 | self, |
| 125 | hidden_size: int, |
| 126 | num_heads: int, |
| 127 | num_kv_heads: int, |
| 128 | max_position: int = 4096 * 32, |
| 129 | head_dim: int | None = None, |
| 130 | rms_norm_eps: float = 1e-06, |
| 131 | qkv_bias: bool = False, |
| 132 | rope_theta: float | list[float] | None = 10000, |
| 133 | cache_config: CacheConfig | None = None, |
| 134 | quant_config: QuantizationConfig | None = None, |
| 135 | rope_scaling: dict[str, Any] | None = None, |
| 136 | prefix: str = "", |
| 137 | attn_type: str = AttentionType.DECODER, |
| 138 | # Step3p5 specific args |
| 139 | sliding_window: int | None = None, |
| 140 | use_head_wise_attn_gate: bool = False, |
| 141 | layer_types: list[str] | None = None, |
| 142 | use_rope_layers: list[bool] | None = None, |
| 143 | yarn_only_types: list[str] | None = None, |
| 144 | swa_num_attention_heads: int | None = None, |
| 145 | partial_rotary_factor: float = 1.0, |
| 146 | ): |
| 147 | super().__init__() |
| 148 | self.hidden_size = hidden_size |
| 149 | self.total_num_heads = num_heads |
| 150 | tp_size = get_tensor_model_parallel_world_size() |
| 151 | self.layer_idx = extract_layer_index(prefix) |
| 152 | if layer_types: |
| 153 | enable_sliding_window = layer_types[self.layer_idx] == "sliding_attention" |
| 154 | else: |
| 155 | enable_sliding_window = self.layer_idx % 2 == 0 |
| 156 | if yarn_only_types: |
| 157 | assert layer_types is not None |
| 158 | if layer_types[self.layer_idx] not in yarn_only_types: |
| 159 | rope_scaling = None |
| 160 | |
| 161 | if sliding_window is not None and enable_sliding_window: |
| 162 | if swa_num_attention_heads is not None: |
| 163 | num_heads = swa_num_attention_heads |
| 164 | self.total_num_heads = swa_num_attention_heads |
| 165 | else: |
| 166 | sliding_window = None |
| 167 | |
| 168 | if isinstance(rope_theta, list): |
| 169 | rope_theta = rope_theta[self.layer_idx] |
| 170 | |
| 171 | self.rank = get_tensor_model_parallel_rank() |
| 172 | self.partial_rotary_factor = partial_rotary_factor |
| 173 | assert self.total_num_heads % tp_size == 0 |
| 174 | self.num_heads = self.total_num_heads // tp_size |
| 175 | self.total_num_kv_heads = num_kv_heads |
| 176 | if self.total_num_kv_heads >= tp_size: |
| 177 | # Number of KV heads is greater than TP size, so we partition |
| 178 | # the KV heads across multiple tensor parallel GPUs. |
| 179 | assert self.total_num_kv_heads % tp_size == 0 |
| 180 | else: |
| 181 | # Number of KV heads is less than TP size, so we replicate |
| 182 | # the KV heads across multiple tensor parallel GPUs. |
| 183 | assert tp_size % self.total_num_kv_heads == 0 |
| 184 | self.num_kv_heads = max(1, self.total_num_kv_heads // tp_size) |
| 185 | self.head_dim = head_dim or hidden_size // self.total_num_heads |
| 186 | self.q_size = self.num_heads * self.head_dim |
| 187 | self.kv_size = self.num_kv_heads * self.head_dim |
| 188 | self.scaling = self.head_dim**-0.5 |
| 189 | self.rope_theta = rope_theta |
| 190 | self.qkv_proj = QKVParallelLinear( |
| 191 | hidden_size, |
| 192 | self.head_dim, |
| 193 | self.total_num_heads, |
| 194 | self.total_num_kv_heads, |
| 195 | bias=qkv_bias, |
| 196 | quant_config=quant_config, |
| 197 | prefix=f"{prefix}.qkv_proj", |
| 198 | ) |
| 199 | self.o_proj = RowParallelLinear( |
| 200 | self.total_num_heads * self.head_dim, |
| 201 | hidden_size, |
| 202 | bias=False, |
| 203 | quant_config=quant_config, |
| 204 | prefix=f"{prefix}.o_proj", |
| 205 | ) |
| 206 | |
| 207 | if rope_scaling is not None and not isinstance(rope_scaling, dict): |
| 208 | raise ValueError("rope_scaling must be a dict for Step3p5Attention.") |
| 209 | |
| 210 | rope_parameters: dict[str, Any] = ( |
| 211 | dict(rope_scaling) if rope_scaling is not None else {} |
| 212 | ) |
| 213 | rope_parameters.setdefault("rope_type", "default") |
| 214 | rope_parameters["rope_theta"] = self.rope_theta |
| 215 | rope_parameters["partial_rotary_factor"] = partial_rotary_factor |
| 216 | |
| 217 | self.rotary_emb = get_rope( |
| 218 | head_size=self.head_dim, |
| 219 | max_position=max_position, |
| 220 | rope_parameters=rope_parameters, |
| 221 | ) |
| 222 | |
| 223 | self.q_norm = GemmaRMSNorm(self.head_dim, rms_norm_eps) |
| 224 | self.k_norm = GemmaRMSNorm(self.head_dim, rms_norm_eps) |
| 225 | self.use_head_wise_attn_gate = use_head_wise_attn_gate |
| 226 | if use_head_wise_attn_gate: |
| 227 | self.g_proj = ColumnParallelLinear( |
| 228 | hidden_size, |
| 229 | self.total_num_heads, |
| 230 | bias=False, |
| 231 | quant_config=quant_config, |
| 232 | prefix=f"{prefix}.g_proj", |
| 233 | ) |
| 234 | |
| 235 | self.use_rope = True |
| 236 | if use_rope_layers: |
| 237 | self.use_rope = use_rope_layers[self.layer_idx] |
| 238 | |
| 239 | self.attn = Attention( |
| 240 | self.num_heads, |
| 241 | self.head_dim, |
| 242 | self.scaling, |
| 243 | num_kv_heads=self.num_kv_heads, |
| 244 | cache_config=cache_config, |
| 245 | quant_config=quant_config, |
| 246 | prefix=f"{prefix}.attn", |
| 247 | per_layer_sliding_window=sliding_window, |
| 248 | attn_type=attn_type, |
| 249 | ) |
| 250 | |
| 251 | self.max_position_embeddings = max_position |
| 252 | assert self.partial_rotary_factor == 1 or self.partial_rotary_factor == 0.5 |
| 253 | self.rotary_dim = ( |
| 254 | self.head_dim if self.partial_rotary_factor == 1 else self.head_dim // 2 |
| 255 | ) |
| 256 | |
| 257 | def forward( |
| 258 | self, |
| 259 | positions: torch.Tensor, |
| 260 | hidden_states: torch.Tensor, |
| 261 | ) -> torch.Tensor: |
| 262 | qkv, _ = self.qkv_proj(hidden_states) |
| 263 | q, k, v = qkv.split([self.q_size, self.kv_size, self.kv_size], dim=-1) |
| 264 | # Add qk-norm inline similar to Qwen3 MOE attention |
| 265 | q_by_head = q.view(*q.shape[:-1], q.shape[-1] // self.head_dim, self.head_dim) |
| 266 | q_by_head = self.q_norm(q_by_head) |
| 267 | q = q_by_head.view(q.shape) |
| 268 | |
| 269 | k_by_head = k.view(*k.shape[:-1], k.shape[-1] // self.head_dim, self.head_dim) |
| 270 | k_by_head = self.k_norm(k_by_head) |
| 271 | k = k_by_head.view(k.shape) |
| 272 | if self.use_rope: |
| 273 | q, k = self.rotary_emb(positions, q, k) |
| 274 | attn_output = self.attn(q, k, v) |
| 275 | if self.use_head_wise_attn_gate: |
| 276 | extra_dims, _ = self.g_proj(hidden_states) |
| 277 | output = ( |
| 278 | attn_output.view(*attn_output.shape[:-1], self.num_heads, self.head_dim) |
| 279 | * extra_dims.unsqueeze(-1).sigmoid() |
| 280 | ) |
| 281 | attn_output = output.view(*attn_output.shape) |
| 282 | output, _ = self.o_proj(attn_output) |
| 283 | return output |
| 284 | |
| 285 | |
| 286 | class FusedMoEBlock(nn.Module): |
| 287 | def __init__( |
| 288 | self, |
| 289 | vllm_config: VllmConfig, |
| 290 | prefix: str = "", |
| 291 | ): |
| 292 | super().__init__() |
| 293 | |
| 294 | self.tp_size = get_tensor_model_parallel_world_size() |
| 295 | self.layer_idx = extract_layer_index(prefix) |
| 296 | |
| 297 | self.ep_size = get_ep_group().device_group.size() |
| 298 | config = vllm_config.model_config.hf_config |
| 299 | assert isinstance(config, Step3p5Config) |
| 300 | quant_config = vllm_config.quant_config |
| 301 | parallel_config = vllm_config.parallel_config |
| 302 | |
| 303 | self.hidden_size = config.hidden_size |
| 304 | self.enable_eplb = parallel_config.enable_eplb |
| 305 | self.n_routed_experts = config.moe_num_experts |
| 306 | self.n_logical_experts = self.n_routed_experts |
| 307 | self.n_redundant_experts = parallel_config.eplb_config.num_redundant_experts |
| 308 | self.n_physical_experts = self.n_logical_experts + self.n_redundant_experts |
| 309 | self.n_local_physical_experts = self.n_physical_experts // self.ep_size |
| 310 | |
| 311 | if self.tp_size > config.moe_num_experts: |
| 312 | raise ValueError( |
| 313 | f"Tensor parallel size {self.tp_size} is greater than " |
| 314 | f"the number of experts {config.moe_num_experts}." |
| 315 | ) |
| 316 | |
| 317 | # Router logits are accumulated in FP32 for higher precision. |
| 318 | self.gate = GateLinear( |
| 319 | config.hidden_size, |
| 320 | config.moe_num_experts, |
| 321 | out_dtype=torch.float32, |
| 322 | params_dtype=torch.float32, |
| 323 | prefix=f"{prefix}.gate", |
| 324 | ) |
| 325 | self.use_moe_router_bias = config.use_moe_router_bias |
| 326 | assert self.use_moe_router_bias, "Only support use_moe_router_bias is true." |
| 327 | self.routed_scaling_factor = config.moe_router_scaling_factor |
| 328 | self.router_bias = nn.Parameter( |
| 329 | torch.zeros(config.moe_num_experts, dtype=torch.float32), |
| 330 | requires_grad=False, |
| 331 | ) |
| 332 | self.need_fp32_gate = config.need_fp32_gate |
| 333 | assert self.need_fp32_gate, ( |
| 334 | "Router logits must use FP32 precision for numerical stability." |
| 335 | ) |
| 336 | |
| 337 | activation = "silu" |
| 338 | swiglu_limits = config.swiglu_limits or [] |
| 339 | swiglu_limit = ( |
| 340 | swiglu_limits[self.layer_idx] |
| 341 | if self.layer_idx < len(swiglu_limits) |
| 342 | else None |
| 343 | ) |
| 344 | if swiglu_limit not in (None, 0): |
| 345 | assert swiglu_limit is not None |
| 346 | swiglu_limit = float(swiglu_limit) |
| 347 | assert swiglu_limit == 7.0, ( |
| 348 | "Swiglu limit in fused moe block only support 7.0 now." |
| 349 | ) |
| 350 | activation = "swiglustep" |
| 351 | logger.debug( |
| 352 | "step3p5 layer_idx: %s, activation: %s, limit: %s", |
| 353 | self.layer_idx, |
| 354 | activation, |
| 355 | swiglu_limit, |
| 356 | ) |
| 357 | |
| 358 | self.share_expert = Step3p5MLP( |
| 359 | config=config, |
| 360 | hidden_size=self.hidden_size, |
| 361 | intermediate_size=config.share_expert_dim, |
| 362 | hidden_act="silu", |
| 363 | reduce_results=False, |
| 364 | quant_config=quant_config, |
| 365 | prefix=f"{prefix}.share_expert", |
| 366 | ) |
| 367 | self.experts = FusedMoEFactory( |
| 368 | shared_experts=self.share_expert, |
| 369 | gate=self.gate, |
| 370 | num_experts=config.moe_num_experts, |
| 371 | top_k=config.moe_top_k, |
| 372 | hidden_size=config.hidden_size, |
| 373 | intermediate_size=config.moe_intermediate_size, |
| 374 | renormalize=config.norm_expert_weight, |
| 375 | quant_config=quant_config, |
| 376 | activation=activation, |
| 377 | prefix=f"{prefix}.experts", |
| 378 | scoring_func=getattr(config, "moe_router_activation", "sigmoid"), |
| 379 | e_score_correction_bias=self.router_bias, |
| 380 | routed_scaling_factor=config.moe_router_scaling_factor, |
| 381 | enable_eplb=self.enable_eplb, |
| 382 | num_redundant_experts=self.n_redundant_experts, |
| 383 | router_logits_dtype=torch.float32, |
| 384 | ) |
| 385 | |
| 386 | def forward(self, hidden_states: torch.Tensor) -> torch.Tensor: |
| 387 | num_tokens, hidden_dim = hidden_states.shape |
| 388 | hidden_states = hidden_states.view(-1, hidden_dim) |
| 389 | |
| 390 | final_hidden_states = self.experts( |
| 391 | hidden_states=hidden_states, router_logits=hidden_states |
| 392 | ) |
| 393 | |
| 394 | return final_hidden_states.view(num_tokens, hidden_dim) |
| 395 | |
| 396 | |
| 397 | class Step3p5DecoderLayer(nn.Module): |
| 398 | def __init__( |
| 399 | self, |
| 400 | vllm_config: VllmConfig, |
| 401 | prefix: str = "", |
| 402 | ) -> None: |
| 403 | super().__init__() |
| 404 | config = vllm_config.model_config.hf_config |
| 405 | assert isinstance(config, Step3p5Config) |
| 406 | self.hidden_size = config.hidden_size |
| 407 | layer_idx = extract_layer_index(prefix) |
| 408 | self.layer_idx = layer_idx |
| 409 | cache_config = vllm_config.cache_config |
| 410 | quant_config = vllm_config.quant_config |
| 411 | if cache_config is not None: |
| 412 | cache_config.sliding_window = None |
| 413 | if config.att_impl_type == "GQA": |
| 414 | num_attention_heads = None |
| 415 | num_attention_groups = None |
| 416 | head_dim = None |
| 417 | attention_other_setting = config.attention_other_setting |
| 418 | layer_types = config.layer_types |
| 419 | if ( |
| 420 | attention_other_setting |
| 421 | and layer_types |
| 422 | and layer_types[layer_idx] == attention_other_setting["attention_type"] |
| 423 | ): |
| 424 | num_attention_heads = attention_other_setting["num_attention_heads"] |
| 425 | num_attention_groups = attention_other_setting["num_attention_groups"] |
| 426 | head_dim = attention_other_setting["head_dim"] |
| 427 | partial_rotary_factors = getattr(config, "partial_rotary_factors", []) |
| 428 | assert config.max_position_embeddings is not None |
| 429 | self.self_attn = Step3p5Attention( |
| 430 | hidden_size=self.hidden_size, |
| 431 | num_heads=num_attention_heads |
| 432 | if num_attention_heads |
| 433 | else config.num_attention_heads, |
| 434 | max_position=config.max_position_embeddings, |
| 435 | num_kv_heads=num_attention_groups |
| 436 | if num_attention_groups |
| 437 | else config.num_attention_groups, |
| 438 | rope_theta=config.rope_theta, |
| 439 | rms_norm_eps=config.rms_norm_eps, |
| 440 | qkv_bias=getattr(config, "attention_bias", False), |
| 441 | head_dim=head_dim if head_dim else getattr(config, "head_dim", None), |
| 442 | cache_config=cache_config, |
| 443 | quant_config=quant_config, |
| 444 | rope_scaling=getattr(config, "rope_scaling", None), |
| 445 | sliding_window=getattr(config, "sliding_window", None), |
| 446 | use_head_wise_attn_gate=getattr( |
| 447 | config, "use_head_wise_attn_gate", False |
| 448 | ), |
| 449 | layer_types=getattr(config, "layer_types", []), |
| 450 | use_rope_layers=getattr(config, "use_rope_layers", []), |
| 451 | yarn_only_types=getattr(config, "yarn_only_types", []), |
| 452 | partial_rotary_factor=partial_rotary_factors[layer_idx] |
| 453 | if partial_rotary_factors |
| 454 | else 1.0, |
| 455 | prefix=f"{prefix}.self_attn", |
| 456 | ) |
| 457 | else: |
| 458 | raise ValueError( |
| 459 | f"Unsupported attention implementation: {config.att_impl_type}" |
| 460 | ) |
| 461 | self.use_moe = False |
| 462 | self.tp_group = get_tp_group() |
| 463 | self.use_fused_all_reduce = ( |
| 464 | get_tensor_model_parallel_world_size() > 1 |
| 465 | and get_dp_group().world_size == 1 |
| 466 | ) |
| 467 | if self.use_fused_all_reduce: |
| 468 | logger.warning_once("Enable custom fused all reduce...") |
| 469 | else: |
| 470 | logger.warning_once("Disable custom fused all reduce...") |
| 471 | |
| 472 | moe_layers_enum = getattr(config, "moe_layers_enum", None) |
| 473 | if moe_layers_enum is not None: |
| 474 | moe_layers_idx = [int(i) for i in moe_layers_enum.strip().split(",")] |
| 475 | else: |
| 476 | moe_layers_idx = [i for i in range(1, config.num_hidden_layers)] |
| 477 | if layer_idx in moe_layers_idx: |
| 478 | self.moe = FusedMoEBlock( |
| 479 | vllm_config, |
| 480 | prefix=f"{prefix}.moe", |
| 481 | ) |
| 482 | self.use_moe = True |
| 483 | else: |
| 484 | self.mlp = Step3p5MLP( |
| 485 | config=config, |
| 486 | hidden_size=config.hidden_size, |
| 487 | intermediate_size=config.intermediate_size, |
| 488 | hidden_act="silu", |
| 489 | quant_config=quant_config, |
| 490 | reduce_results=True, |
| 491 | prefix=f"{prefix}.mlp", |
| 492 | ) |
| 493 | self.input_layernorm = GemmaRMSNorm(config.hidden_size, config.rms_norm_eps) |
| 494 | self.post_attention_layernorm = GemmaRMSNorm( |
| 495 | config.hidden_size, config.rms_norm_eps |
| 496 | ) |
| 497 | self.prefix = prefix |
| 498 | |
| 499 | def add_and_maybe_inplace_all_reduce( |
| 500 | self, in1: torch.Tensor, in2: torch.Tensor |
| 501 | ) -> torch.Tensor: |
| 502 | if not self.use_fused_all_reduce: |
| 503 | return in1 + in2 |
| 504 | return self.tp_group.all_reduce(in1 + in2) |
| 505 | |
| 506 | def forward( |
| 507 | self, positions: torch.Tensor, hidden_states: torch.Tensor |
| 508 | ) -> torch.Tensor: |
| 509 | residual = hidden_states |
| 510 | hidden_states = self.input_layernorm(hidden_states) |
| 511 | |
| 512 | hidden_states = self.self_attn( |
| 513 | positions=positions, |
| 514 | hidden_states=hidden_states, |
| 515 | ) |
| 516 | hidden_states += residual |
| 517 | residual = hidden_states |
| 518 | hidden_states = self.post_attention_layernorm(hidden_states) |
| 519 | |
| 520 | if self.use_moe: |
| 521 | ffn_output = self.moe(hidden_states) |
| 522 | else: |
| 523 | ffn_output = self.mlp(hidden_states) |
| 524 | hidden_states = ffn_output + residual |
| 525 | return hidden_states |
| 526 | |
| 527 | |
| 528 | @support_torch_compile |
| 529 | class Step3p5Model(nn.Module): |
| 530 | def __init__(self, vllm_config: VllmConfig, prefix: str = "") -> None: |
| 531 | super().__init__() |
| 532 | |
| 533 | self.vllm_config = vllm_config |
| 534 | config = vllm_config.model_config.hf_config |
| 535 | assert isinstance(config, Step3p5Config) |
| 536 | self.vocab_size = config.vocab_size |
| 537 | self.config = config |
| 538 | |
| 539 | self.moe_num_experts = config.moe_num_experts |
| 540 | |
| 541 | if get_pp_group().is_first_rank or ( |
| 542 | config.tie_word_embeddings and get_pp_group().is_last_rank |
| 543 | ): |
| 544 | self.embed_tokens = VocabParallelEmbedding( |
| 545 | self.vocab_size, |
| 546 | config.hidden_size, |
| 547 | ) |
| 548 | else: |
| 549 | self.embed_tokens = PPMissingLayer() |
| 550 | |
| 551 | self.start_layer, self.end_layer, self.layers = make_layers( |
| 552 | config.num_hidden_layers, |
| 553 | lambda prefix: Step3p5DecoderLayer( |
| 554 | vllm_config, |
| 555 | prefix=prefix, |
| 556 | ), |
| 557 | prefix=f"{prefix}.layers", |
| 558 | ) |
| 559 | if get_pp_group().is_last_rank: |
| 560 | self.norm = GemmaRMSNorm(config.hidden_size, config.rms_norm_eps) |
| 561 | else: |
| 562 | self.norm = PPMissingLayer() |
| 563 | |
| 564 | self.make_empty_intermediate_tensors = make_empty_intermediate_tensors_factory( |
| 565 | ["hidden_states"], config.hidden_size |
| 566 | ) |
| 567 | |
| 568 | def embed_input_ids(self, input_ids: torch.Tensor) -> torch.Tensor: |
| 569 | return self.embed_tokens(input_ids) |
| 570 | |
| 571 | def forward( |
| 572 | self, |
| 573 | input_ids: torch.Tensor, |
| 574 | positions: torch.Tensor, |
| 575 | intermediate_tensors: IntermediateTensors | None = None, |
| 576 | inputs_embeds: torch.Tensor | None = None, |
| 577 | ) -> torch.Tensor: |
| 578 | if get_pp_group().is_first_rank: |
| 579 | if inputs_embeds is not None: |
| 580 | hidden_states = inputs_embeds |
| 581 | else: |
| 582 | hidden_states = self.embed_input_ids(input_ids) |
| 583 | else: |
| 584 | assert intermediate_tensors is not None |
| 585 | hidden_states = intermediate_tensors["hidden_states"] |
| 586 | for i in range(self.start_layer, self.end_layer): |
| 587 | layer = self.layers[i] |
| 588 | hidden_states = layer(positions, hidden_states) |
| 589 | |
| 590 | if not get_pp_group().is_last_rank: |
| 591 | return IntermediateTensors( |
| 592 | { |
| 593 | "hidden_states": hidden_states, |
| 594 | } |
| 595 | ) |
| 596 | |
| 597 | return hidden_states |
| 598 | |
| 599 | def load_weights(self, weights: Iterable[tuple[str, torch.Tensor]]) -> set[str]: |
| 600 | config = self.config |
| 601 | assert config.num_attention_groups > 1, "Only support GQA" |
| 602 | qkv_params_mapping: list[tuple[str, str, float, float]] = [] |
| 603 | stacked_params_mapping: list[tuple[str, str, str | int]] = [ |
| 604 | # (param_name, shard_name, shard_id) |
| 605 | ("qkv_proj", "q_proj", "q"), |
| 606 | ("qkv_proj", "k_proj", "k"), |
| 607 | ("qkv_proj", "v_proj", "v"), |
| 608 | ("gate_up_proj", "gate_proj", 0), |
| 609 | ("gate_up_proj", "up_proj", 1), |
| 610 | ] |
| 611 | |
| 612 | params_dict = dict(self.named_parameters()) |
| 613 | loaded_params: set[str] = set() |
| 614 | base_layer = ( |
| 615 | "base_layer." if any(".base_layer." in name for name in params_dict) else "" |
| 616 | ) |
| 617 | |
| 618 | # Old packed 3D format: .moe.gate_proj.weight [num_experts, out, in] |
| 619 | expert_params_mapping: list[tuple[str, str, str]] = [ |
| 620 | ( |
| 621 | f".moe.experts.routed_experts.{base_layer}w13_weight", |
| 622 | ".moe.gate_proj.weight", |
| 623 | "w1", |
| 624 | ), |
| 625 | ( |
| 626 | f".moe.experts.routed_experts.{base_layer}w13_weight", |
| 627 | ".moe.up_proj.weight", |
| 628 | "w3", |
| 629 | ), |
| 630 | ( |
| 631 | f".moe.experts.routed_experts.{base_layer}w2_weight", |
| 632 | ".moe.down_proj.weight", |
| 633 | "w2", |
| 634 | ), |
| 635 | ( |
| 636 | f".moe.experts.routed_experts.{base_layer}w13_weight_scale_2", |
| 637 | ".moe.gate_proj.weight_scale_2", |
| 638 | "w1", |
| 639 | ), |
| 640 | ( |
| 641 | f".moe.experts.routed_experts.{base_layer}w13_weight_scale_2", |
| 642 | ".moe.up_proj.weight_scale_2", |
| 643 | "w3", |
| 644 | ), |
| 645 | ( |
| 646 | f".moe.experts.routed_experts.{base_layer}w2_weight_scale_2", |
| 647 | ".moe.down_proj.weight_scale_2", |
| 648 | "w2", |
| 649 | ), |
| 650 | ( |
| 651 | f".moe.experts.routed_experts.{base_layer}w13_weight_scale", |
| 652 | ".moe.gate_proj.weight_scale", |
| 653 | "w1", |
| 654 | ), |
| 655 | ( |
| 656 | f".moe.experts.routed_experts.{base_layer}w13_weight_scale", |
| 657 | ".moe.up_proj.weight_scale", |
| 658 | "w3", |
| 659 | ), |
| 660 | ( |
| 661 | f".moe.experts.routed_experts.{base_layer}w2_weight_scale", |
| 662 | ".moe.down_proj.weight_scale", |
| 663 | "w2", |
| 664 | ), |
| 665 | # Required due to the Step3 HF model's packed expert format: |
| 666 | # input scales are stored as moe.{gate,up,down}_proj.input_scale |
| 667 | # rather than the standard per-expert format handled generically. |
| 668 | ( |
| 669 | f".moe.experts.routed_experts.{base_layer}w13_input_scale", |
| 670 | ".moe.gate_proj.input_scale", |
| 671 | "w1", |
| 672 | ), |
| 673 | ( |
| 674 | f".moe.experts.routed_experts.{base_layer}w13_input_scale", |
| 675 | ".moe.up_proj.input_scale", |
| 676 | "w3", |
| 677 | ), |
| 678 | ( |
| 679 | f".moe.experts.routed_experts.{base_layer}w2_input_scale", |
| 680 | ".moe.down_proj.input_scale", |
| 681 | "w2", |
| 682 | ), |
| 683 | ] |
| 684 | |
| 685 | # New per-expert format: .moe.experts.E.gate_proj.weight_packed [out, in] |
| 686 | per_expert_mapping = fused_moe_make_expert_params_mapping( |
| 687 | self, |
| 688 | ckpt_gate_proj_name="gate_proj", |
| 689 | ckpt_down_proj_name="down_proj", |
| 690 | ckpt_up_proj_name="up_proj", |
| 691 | num_experts=self.moe_num_experts, |
| 692 | ) |
| 693 | |
| 694 | disable_moe_stacked_params = [data[1] for data in expert_params_mapping] |
| 695 | |
| 696 | for name, loaded_weight in weights: |
| 697 | if name.startswith("model."): |
| 698 | local_name = name[len("model.") :] |
| 699 | full_name = name |
| 700 | else: |
| 701 | local_name = name |
| 702 | full_name = f"model.{name}" if name else "model" |
| 703 | |
| 704 | spec_layer = get_spec_layer_idx_from_weight_name(config, full_name) |
| 705 | if spec_layer is not None: |
| 706 | continue # skip spec decode layers for main model |
| 707 | |
| 708 | # Skip any layers beyond the main model's depth (e.g., MTP layers) |
| 709 | if full_name.startswith("model.layers."): |
| 710 | parts = full_name.split(".") |
| 711 | if len(parts) > 2 and parts[2].isdigit(): |
| 712 | layer_idx = int(parts[2]) |
| 713 | if layer_idx >= config.num_hidden_layers: |
| 714 | continue |
| 715 | |
| 716 | # Per-expert MoE weights (new format from LLM Compressor): |
| 717 | # .moe.experts.{E}.{gate,up,down}_proj.{weight_packed,scale,...} |
| 718 | # Each weight is individual per-expert, not stacked 3D. |
| 719 | if ".moe.experts." in local_name: |
| 720 | is_expert_weight = False |
| 721 | for mapping in per_expert_mapping: |
| 722 | param_name, weight_name, expert_id, shard_id = mapping |
| 723 | if weight_name not in local_name: |
| 724 | continue |
| 725 | is_expert_weight = True |
| 726 | name_mapped = local_name.replace(weight_name, param_name) |
| 727 | if is_pp_missing_parameter(name_mapped, self): |
| 728 | continue |
| 729 | if name_mapped not in params_dict: |
| 730 | continue |
| 731 | param = params_dict[name_mapped] |
| 732 | weight_loader = typing.cast( |
| 733 | Callable[..., bool], param.weight_loader |
| 734 | ) |
| 735 | success = weight_loader( |
| 736 | param, |
| 737 | loaded_weight, |
| 738 | name_mapped, |
| 739 | shard_id=shard_id, |
| 740 | expert_id=expert_id, |
| 741 | return_success=True, |
| 742 | ) |
| 743 | if success: |
| 744 | loaded_params.add(name_mapped) |
| 745 | break |
| 746 | else: |
| 747 | if ( |
| 748 | not is_expert_weight |
| 749 | and not is_pp_missing_parameter(local_name, self) |
| 750 | and local_name in params_dict |
| 751 | ): |
| 752 | # Not an expert proj — use default loader |
| 753 | # (e.g. share_expert weights if they matched) |
| 754 | param = params_dict[local_name] |
| 755 | fallback_loader = getattr( |
| 756 | param, |
| 757 | "weight_loader", |
| 758 | default_weight_loader, |
| 759 | ) |
| 760 | fallback_loader(param, loaded_weight) |
| 761 | loaded_params.add(local_name) |
| 762 | continue |
| 763 | |
| 764 | for param_name, weight_name, stacked_shard_id in stacked_params_mapping: |
| 765 | if weight_name not in local_name: |
| 766 | continue |
| 767 | if any( |
| 768 | disable_moe_stacked_param in local_name |
| 769 | for disable_moe_stacked_param in disable_moe_stacked_params |
| 770 | ): |
| 771 | continue |
| 772 | replaced_name = local_name.replace(weight_name, param_name) |
| 773 | if is_pp_missing_parameter(replaced_name, self): |
| 774 | continue |
| 775 | if replaced_name not in params_dict: |
| 776 | continue |
| 777 | param = params_dict[replaced_name] |
| 778 | weight_loader = param.weight_loader |
| 779 | weight_loader(param, loaded_weight, stacked_shard_id) |
| 780 | loaded_params.add(replaced_name) |
| 781 | break |
| 782 | else: |
| 783 | for param_name, weight_name, expert_shard_id in expert_params_mapping: |
| 784 | if weight_name not in local_name: |
| 785 | continue |
| 786 | replaced_name = local_name.replace(weight_name, param_name) |
| 787 | if is_pp_missing_parameter(replaced_name, self): |
| 788 | continue |
| 789 | if ( |
| 790 | replaced_name.endswith(".bias") |
| 791 | or replaced_name.endswith("_bias") |
| 792 | ) and replaced_name not in params_dict: |
| 793 | continue |
| 794 | if replaced_name not in params_dict: |
| 795 | continue |
| 796 | param = params_dict[replaced_name] |
| 797 | weight_loader = param.weight_loader |
| 798 | moe_expert_num = self.moe_num_experts |
| 799 | # Per-tensor global scales (e.g. weight_global_scale) |
| 800 | # have shape [1] in compressed-tensors NVFP4 checkpoints. |
| 801 | # Expand to per-expert before the iteration loop. |
| 802 | if loaded_weight.ndim == 0: |
| 803 | loaded_weight = loaded_weight.unsqueeze(0).expand( |
| 804 | moe_expert_num |
| 805 | ) |
| 806 | elif ( |
| 807 | loaded_weight.shape[0] == 1 |
| 808 | and loaded_weight.shape[0] != moe_expert_num |
| 809 | ): |
| 810 | loaded_weight = loaded_weight.expand( |
| 811 | moe_expert_num, *loaded_weight.shape[1:] |
| 812 | ) |
| 813 | assert loaded_weight.shape[0] == moe_expert_num |
| 814 | for expert_id in range(moe_expert_num): |
| 815 | loaded_weight_expert = loaded_weight[expert_id] |
| 816 | weight_loader( |
| 817 | param, |
| 818 | loaded_weight_expert, |
| 819 | replaced_name, |
| 820 | shard_id=expert_shard_id, |
| 821 | expert_id=expert_id, |
| 822 | ) |
| 823 | loaded_params.add(replaced_name) |
| 824 | break |
| 825 | else: |
| 826 | for ( |
| 827 | param_name, |
| 828 | weight_name, |
| 829 | start_idx, |
| 830 | end_idx, |
| 831 | ) in qkv_params_mapping: |
| 832 | if weight_name not in local_name: |
| 833 | continue |
| 834 | replaced_name = local_name.replace(weight_name, param_name) |
| 835 | if is_pp_missing_parameter(replaced_name, self): |
| 836 | continue |
| 837 | if replaced_name not in params_dict: |
| 838 | continue |
| 839 | param = params_dict[replaced_name] |
| 840 | dim = param.shape[param.output_dim] |
| 841 | begin_idx = int(start_idx * dim) |
| 842 | end_idx = int(end_idx * dim) |
| 843 | param_slice = param.narrow( |
| 844 | param.output_dim, begin_idx, end_idx - begin_idx |
| 845 | ) |
| 846 | param_slice.copy_(loaded_weight) |
| 847 | loaded_params.add(replaced_name) |
| 848 | break |
| 849 | else: |
| 850 | if is_pp_missing_parameter(local_name, self): |
| 851 | continue |
| 852 | if "expert_bias" in local_name: |
| 853 | logger.warning_once("ignore expert_bias") |
| 854 | continue |
| 855 | if local_name not in params_dict: |
| 856 | continue |
| 857 | param = params_dict[local_name] |
| 858 | fallback_loader = getattr( |
| 859 | param, "weight_loader", default_weight_loader |
| 860 | ) |
| 861 | fallback_loader(param, loaded_weight) |
| 862 | loaded_params.add(local_name) |
| 863 | return loaded_params |
| 864 | |
| 865 | |
| 866 | class Step3p5ForCausalLM(nn.Module, SupportsPP, MixtureOfExperts): |
| 867 | # Required so quantization exclude lists match fused module prefixes. |
| 868 | packed_modules_mapping = { |
| 869 | "qkv_proj": ["q_proj", "k_proj", "v_proj"], |
| 870 | "gate_up_proj": ["gate_proj", "up_proj"], |
| 871 | } |
| 872 | |
| 873 | hf_to_vllm_mapper = WeightsMapper( |
| 874 | orig_to_new_substr={".share_expert.": ".moe.share_expert."} |
| 875 | ) |
| 876 | |
| 877 | def __init__( |
| 878 | self, |
| 879 | *, |
| 880 | vllm_config: VllmConfig, |
| 881 | prefix: str = "", |
| 882 | ): |
| 883 | super().__init__() |
| 884 | config = vllm_config.model_config.hf_config |
| 885 | self.model = Step3p5Model( |
| 886 | vllm_config=vllm_config, prefix=maybe_prefix(prefix, "model") |
| 887 | ) |
| 888 | if get_pp_group().is_last_rank: |
| 889 | self.lm_head = ParallelLMHead( |
| 890 | config.vocab_size, |
| 891 | config.hidden_size, |
| 892 | quant_config=vllm_config.quant_config, |
| 893 | prefix=maybe_prefix(prefix, "lm_head"), |
| 894 | ) |
| 895 | self.logits_processor = LogitsProcessor(config.vocab_size) |
| 896 | else: |
| 897 | self.lm_head = PPMissingLayer() |
| 898 | |
| 899 | self.make_empty_intermediate_tensors = ( |
| 900 | self.model.make_empty_intermediate_tensors |
| 901 | ) |
| 902 | |
| 903 | # Set MoE hyperparameters |
| 904 | self.moe_layers: list[MoERunner] = [] |
| 905 | example_layer: FusedMoEBlock | None = None |
| 906 | for layer in self.model.layers: |
| 907 | if isinstance(layer, PPMissingLayer): |
| 908 | continue |
| 909 | assert isinstance(layer, Step3p5DecoderLayer) |
| 910 | if hasattr(layer, "moe") and isinstance(layer.moe, FusedMoEBlock): |
| 911 | example_layer = layer.moe |
| 912 | self.moe_layers.append(layer.moe.experts) |
| 913 | |
| 914 | assert len(self.moe_layers) > 0, "No MoE layers found in the model." |
| 915 | assert example_layer is not None |
| 916 | self.num_moe_layers = len(self.moe_layers) |
| 917 | self.num_expert_groups = 1 |
| 918 | self.num_shared_experts = 0 |
| 919 | self.num_logical_experts = example_layer.n_logical_experts |
| 920 | self.num_physical_experts = example_layer.n_physical_experts |
| 921 | self.num_local_physical_experts = example_layer.n_local_physical_experts |
| 922 | self.num_routed_experts = example_layer.n_routed_experts |
| 923 | self.num_redundant_experts = example_layer.n_redundant_experts |
| 924 | |
| 925 | def forward( |
| 926 | self, |
| 927 | input_ids: torch.Tensor, |
| 928 | positions: torch.Tensor, |
| 929 | intermediate_tensors: IntermediateTensors | None = None, |
| 930 | inputs_embeds: torch.Tensor | None = None, |
| 931 | ): |
| 932 | hidden_states = self.model( |
| 933 | input_ids, positions, intermediate_tensors, inputs_embeds |
| 934 | ) |
| 935 | return hidden_states |
| 936 | |
| 937 | def compute_logits(self, hidden_states: torch.Tensor) -> torch.Tensor: |
| 938 | hidden_states = self.model.norm(hidden_states) |
| 939 | logits = self.logits_processor(self.lm_head, hidden_states) |
| 940 | return logits |
| 941 | |
| 942 | def embed_input_ids(self, input_ids: torch.Tensor) -> torch.Tensor: |
| 943 | return self.model.embed_tokens(input_ids) |
| 944 | |
| 945 | def update_physical_experts_metadata( |
| 946 | self, |
| 947 | num_physical_experts: int, |
| 948 | num_local_physical_experts: int, |
| 949 | ) -> None: |
| 950 | assert self.num_local_physical_experts == num_local_physical_experts |
| 951 | self.num_physical_experts = num_physical_experts |
| 952 | self.num_local_physical_experts = num_local_physical_experts |
| 953 | self.num_redundant_experts = num_physical_experts - self.num_logical_experts |
| 954 | for layer in self.moe_layers: |
| 955 | assert isinstance(layer, FusedMoEBlock) |
| 956 | layer.n_local_physical_experts = num_local_physical_experts |
| 957 | layer.n_physical_experts = num_physical_experts |
| 958 | layer.n_redundant_experts = self.num_redundant_experts |
| 959 | layer.experts.update_expert_map() |
| 960 | |
| 961 | def load_weights(self, weights: Iterable[tuple[str, torch.Tensor]]) -> set[str]: |
| 962 | loader = AutoWeightsLoader(self) |
| 963 | return loader.load_weights(weights, mapper=self.hf_to_vllm_mapper) |