| 1 | # SPDX-License-Identifier: Apache-2.0 |
| 2 | # SPDX-FileCopyrightText: Copyright contributors to the vLLM project |
| 3 | from collections.abc import Iterable |
| 4 | from itertools import islice |
| 5 | |
| 6 | import torch |
| 7 | from torch import nn |
| 8 | |
| 9 | from vllm.compilation.decorators import support_torch_compile |
| 10 | from vllm.config import ( |
| 11 | CacheConfig, |
| 12 | VllmConfig, |
| 13 | get_current_vllm_config, |
| 14 | str_dtype_to_torch_dtype, |
| 15 | ) |
| 16 | from vllm.distributed import ( |
| 17 | get_ep_group, |
| 18 | get_pp_group, |
| 19 | get_tensor_model_parallel_rank, |
| 20 | get_tensor_model_parallel_world_size, |
| 21 | tensor_model_parallel_all_gather, |
| 22 | ) |
| 23 | from vllm.logger import init_logger |
| 24 | from vllm.model_executor.layers.activation import SiluAndMul |
| 25 | from vllm.model_executor.layers.attention import Attention |
| 26 | from vllm.model_executor.layers.fused_moe import ( |
| 27 | FusedMoEFactory, |
| 28 | fused_moe_make_expert_params_mapping, |
| 29 | ) |
| 30 | from vllm.model_executor.layers.fused_moe.router.gate_linear import GateLinear |
| 31 | from vllm.model_executor.layers.layernorm import RMSNorm |
| 32 | from vllm.model_executor.layers.linear import ( |
| 33 | MergedColumnParallelLinear, |
| 34 | QKVParallelLinear, |
| 35 | RowParallelLinear, |
| 36 | ) |
| 37 | from vllm.model_executor.layers.logits_processor import LogitsProcessor |
| 38 | from vllm.model_executor.layers.quantization import QuantizationConfig |
| 39 | from vllm.model_executor.layers.quantization.utils.quant_utils import ( |
| 40 | GroupShape, |
| 41 | scaled_quantize, |
| 42 | ) |
| 43 | from vllm.model_executor.layers.rotary_embedding import get_rope |
| 44 | from vllm.model_executor.layers.vocab_parallel_embedding import ( |
| 45 | ParallelLMHead, |
| 46 | VocabParallelEmbedding, |
| 47 | ) |
| 48 | from vllm.model_executor.model_loader.weight_utils import ( |
| 49 | default_weight_loader, |
| 50 | maybe_remap_kv_scale_name, |
| 51 | ) |
| 52 | from vllm.model_executor.models.utils import sequence_parallel_chunk |
| 53 | from vllm.sequence import IntermediateTensors |
| 54 | from vllm.utils.math_utils import cdiv |
| 55 | from vllm.v1.attention.backend import AttentionType |
| 56 | from vllm.v1.attention.backends.registry import AttentionBackendEnum |
| 57 | |
| 58 | from .interfaces import ( |
| 59 | EagleModelMixin, |
| 60 | MixtureOfExperts, |
| 61 | SupportsEagle3, |
| 62 | SupportsPP, |
| 63 | ) |
| 64 | from .utils import ( |
| 65 | AutoWeightsLoader, |
| 66 | PPMissingLayer, |
| 67 | extract_layer_index, |
| 68 | is_pp_missing_parameter, |
| 69 | make_empty_intermediate_tensors_factory, |
| 70 | make_layers, |
| 71 | maybe_prefix, |
| 72 | ) |
| 73 | |
| 74 | logger = init_logger(__name__) |
| 75 | |
| 76 | |
| 77 | class MiMoV2MLP(nn.Module): |
| 78 | def __init__( |
| 79 | self, |
| 80 | hidden_size: int, |
| 81 | intermediate_size: int, |
| 82 | hidden_act: str, |
| 83 | quant_config: QuantizationConfig | None = None, |
| 84 | reduce_results: bool = True, |
| 85 | prefix: str = "", |
| 86 | ) -> None: |
| 87 | super().__init__() |
| 88 | self.gate_up_proj = MergedColumnParallelLinear( |
| 89 | hidden_size, |
| 90 | [intermediate_size] * 2, |
| 91 | bias=False, |
| 92 | quant_config=quant_config, |
| 93 | prefix=f"{prefix}.gate_up_proj", |
| 94 | ) |
| 95 | self.down_proj = RowParallelLinear( |
| 96 | intermediate_size, |
| 97 | hidden_size, |
| 98 | bias=False, |
| 99 | quant_config=quant_config, |
| 100 | reduce_results=reduce_results, |
| 101 | prefix=f"{prefix}.down_proj", |
| 102 | ) |
| 103 | if hidden_act != "silu": |
| 104 | raise ValueError( |
| 105 | f"Unsupported activation: {hidden_act}. Only silu is supported for now." |
| 106 | ) |
| 107 | self.act_fn = SiluAndMul() |
| 108 | |
| 109 | def forward(self, x): |
| 110 | gate_up, _ = self.gate_up_proj(x) |
| 111 | x = self.act_fn(gate_up) |
| 112 | x, _ = self.down_proj(x) |
| 113 | return x |
| 114 | |
| 115 | |
| 116 | class MiMoV2MoE(nn.Module): |
| 117 | def __init__( |
| 118 | self, |
| 119 | vllm_config: VllmConfig, |
| 120 | prefix: str = "", |
| 121 | is_nextn: bool = False, |
| 122 | ): |
| 123 | super().__init__() |
| 124 | |
| 125 | config = vllm_config.model_config.hf_text_config |
| 126 | parallel_config = vllm_config.parallel_config |
| 127 | quant_config = vllm_config.quant_config |
| 128 | |
| 129 | self.tp_size = get_tensor_model_parallel_world_size() |
| 130 | |
| 131 | self.ep_group = get_ep_group().device_group |
| 132 | self.ep_size = self.ep_group.size() |
| 133 | self.n_routed_experts = config.n_routed_experts |
| 134 | |
| 135 | self.is_sequence_parallel = parallel_config.use_sequence_parallel_moe |
| 136 | |
| 137 | if self.tp_size > config.n_routed_experts: |
| 138 | raise ValueError( |
| 139 | f"Tensor parallel size {self.tp_size} is greater than " |
| 140 | f"the number of experts {config.n_routed_experts}." |
| 141 | ) |
| 142 | |
| 143 | if config.hidden_act != "silu": |
| 144 | raise ValueError( |
| 145 | f"Unsupported activation: {config.hidden_act}. " |
| 146 | "Only silu is supported for now." |
| 147 | ) |
| 148 | |
| 149 | vllm_config = get_current_vllm_config() |
| 150 | eplb_config = vllm_config.parallel_config.eplb_config |
| 151 | self.enable_eplb = parallel_config.enable_eplb |
| 152 | |
| 153 | self.n_logical_experts = self.n_routed_experts |
| 154 | self.n_redundant_experts = eplb_config.num_redundant_experts |
| 155 | self.n_physical_experts = self.n_logical_experts + self.n_redundant_experts |
| 156 | self.n_local_physical_experts = self.n_physical_experts // self.ep_size |
| 157 | |
| 158 | dtype = getattr(config, "moe_router_dtype", "float32") |
| 159 | self.gate_dtype = str_dtype_to_torch_dtype(dtype) |
| 160 | self.gate = GateLinear( |
| 161 | config.hidden_size, |
| 162 | config.n_routed_experts, |
| 163 | bias=False, |
| 164 | params_dtype=self.gate_dtype, |
| 165 | out_dtype=torch.float32, |
| 166 | prefix=f"{prefix}.gate", |
| 167 | ) |
| 168 | self.gate.e_score_correction_bias = nn.Parameter( |
| 169 | torch.empty(config.n_routed_experts, dtype=self.gate.out_dtype) |
| 170 | ) |
| 171 | |
| 172 | self.experts = FusedMoEFactory( |
| 173 | num_experts=self.n_routed_experts, |
| 174 | top_k=config.num_experts_per_tok, |
| 175 | hidden_size=config.hidden_size, |
| 176 | intermediate_size=config.moe_intermediate_size, |
| 177 | renormalize=config.norm_topk_prob, |
| 178 | quant_config=quant_config, |
| 179 | prefix=f"{prefix}.experts", |
| 180 | e_score_correction_bias=self.gate.e_score_correction_bias, |
| 181 | enable_eplb=self.enable_eplb, |
| 182 | num_redundant_experts=self.n_redundant_experts, |
| 183 | is_sequence_parallel=self.is_sequence_parallel, |
| 184 | use_grouped_topk=True, |
| 185 | num_expert_group=config.n_group, |
| 186 | topk_group=config.topk_group, |
| 187 | scoring_func="sigmoid", |
| 188 | router_logits_dtype=self.gate.out_dtype, |
| 189 | ) |
| 190 | |
| 191 | def forward(self, hidden_states: torch.Tensor) -> torch.Tensor: |
| 192 | assert hidden_states.dim() <= 2, "MiMoV2MoE only supports 1D or 2D inputs" |
| 193 | is_input_1d = hidden_states.dim() == 1 |
| 194 | num_tokens, hidden_dim = hidden_states.shape |
| 195 | hidden_states = hidden_states.view(-1, hidden_dim) |
| 196 | |
| 197 | if self.is_sequence_parallel: |
| 198 | hidden_states = sequence_parallel_chunk(hidden_states) |
| 199 | |
| 200 | if self.gate_dtype is not None: |
| 201 | gate_input = hidden_states.to(self.gate_dtype) |
| 202 | else: |
| 203 | gate_input = hidden_states |
| 204 | router_logits, _ = self.gate(gate_input) |
| 205 | final_hidden_states = self.experts( |
| 206 | hidden_states=hidden_states, router_logits=router_logits |
| 207 | ) |
| 208 | |
| 209 | if self.is_sequence_parallel: |
| 210 | final_hidden_states = tensor_model_parallel_all_gather( |
| 211 | final_hidden_states, 0 |
| 212 | ) |
| 213 | final_hidden_states = final_hidden_states[:num_tokens] |
| 214 | |
| 215 | return final_hidden_states.squeeze(0) if is_input_1d else final_hidden_states |
| 216 | |
| 217 | |
| 218 | class MiMoV2Attention(nn.Module): |
| 219 | def __init__( |
| 220 | self, |
| 221 | hidden_size: int, |
| 222 | num_heads: int, |
| 223 | num_kv_heads: int, |
| 224 | head_dim: int, |
| 225 | v_head_dim: int | None = None, |
| 226 | v_scale: float | None = None, |
| 227 | sliding_window_size: int = -1, |
| 228 | attention_bias: bool = False, |
| 229 | add_swa_attention_sink_bias: bool = False, |
| 230 | layer_id: int = 0, |
| 231 | rope_theta: float = 1000000, |
| 232 | max_position_embeddings: int = 32768, |
| 233 | cache_config: CacheConfig | None = None, |
| 234 | quant_config: QuantizationConfig | None = None, |
| 235 | partial_rotary_factor: float = 1.0, |
| 236 | prefix: str = "", |
| 237 | ) -> None: |
| 238 | super().__init__() |
| 239 | self.hidden_size = hidden_size |
| 240 | self.layer_id = layer_id |
| 241 | tp_size = get_tensor_model_parallel_world_size() |
| 242 | |
| 243 | self.total_num_heads = num_heads |
| 244 | self.num_heads = self.total_num_heads // tp_size |
| 245 | |
| 246 | self.total_num_kv_heads = num_kv_heads |
| 247 | self.num_kv_heads = max(1, self.total_num_kv_heads // tp_size) |
| 248 | |
| 249 | self.head_dim = head_dim |
| 250 | |
| 251 | self.v_head_dim = v_head_dim if v_head_dim is not None else head_dim |
| 252 | |
| 253 | self.q_size = self.num_heads * self.head_dim |
| 254 | self.k_size = self.num_kv_heads * self.head_dim |
| 255 | self.v_size = self.num_kv_heads * self.v_head_dim |
| 256 | |
| 257 | self.v_scale = v_scale |
| 258 | self.scaling = self.head_dim**-0.5 |
| 259 | self.rope_theta = rope_theta |
| 260 | self.max_position_embeddings = max_position_embeddings |
| 261 | |
| 262 | self.qkv_proj = QKVParallelLinear( |
| 263 | hidden_size, |
| 264 | self.head_dim, |
| 265 | self.total_num_heads, |
| 266 | self.total_num_kv_heads, |
| 267 | bias=attention_bias, |
| 268 | quant_config=quant_config, |
| 269 | prefix=f"{prefix}.qkv_proj", |
| 270 | v_head_size=self.v_head_dim, |
| 271 | ) |
| 272 | |
| 273 | self.o_proj = RowParallelLinear( |
| 274 | self.total_num_heads * self.v_head_dim, |
| 275 | hidden_size, |
| 276 | bias=False, |
| 277 | quant_config=quant_config if "mtp.layers" not in prefix else None, |
| 278 | reduce_results=True, |
| 279 | prefix=f"{prefix}.o_proj", |
| 280 | ) |
| 281 | |
| 282 | self.rotary_emb = get_rope( |
| 283 | head_size=self.head_dim, |
| 284 | max_position=max_position_embeddings, |
| 285 | rope_parameters={ |
| 286 | "rope_type": "default", |
| 287 | "rope_theta": rope_theta, |
| 288 | "partial_rotary_factor": partial_rotary_factor, |
| 289 | }, |
| 290 | ) |
| 291 | |
| 292 | self.attention_sink_bias = ( |
| 293 | torch.nn.Parameter(torch.empty(self.num_heads), requires_grad=False) |
| 294 | if add_swa_attention_sink_bias |
| 295 | else None |
| 296 | ) |
| 297 | |
| 298 | sliding_window = sliding_window_size if sliding_window_size > -1 else None |
| 299 | |
| 300 | # Use DiffKV backend when V has a different head dim than K. |
| 301 | # Auto-pick FA-DiffKV when FA3/4 is usable on this device, else fall |
| 302 | # back to TRITON_ATTN_DIFFKV. Users can force a choice via |
| 303 | # `--attention-backend <FLASH_ATTN_DIFFKV|TRITON_ATTN_DIFFKV>`. |
| 304 | if self.v_head_dim != self.head_dim: |
| 305 | requested = get_current_vllm_config().attention_config.backend |
| 306 | if requested is not None and requested.name.endswith("_DIFFKV"): |
| 307 | backend_enum = requested |
| 308 | else: |
| 309 | fa_backend = AttentionBackendEnum.FLASH_ATTN_DIFFKV.get_class() |
| 310 | assert hasattr(fa_backend, "is_supported_on_current_device") |
| 311 | if fa_backend.is_supported_on_current_device( |
| 312 | head_size=self.head_dim, |
| 313 | head_size_v=self.v_head_dim, |
| 314 | has_sinks=self.attention_sink_bias is not None, |
| 315 | ): |
| 316 | backend_enum = AttentionBackendEnum.FLASH_ATTN_DIFFKV |
| 317 | else: |
| 318 | backend_enum = AttentionBackendEnum.TRITON_ATTN_DIFFKV |
| 319 | attn_backend = backend_enum.get_class() |
| 320 | assert hasattr(attn_backend, "set_head_size_v") |
| 321 | attn_backend.set_head_size_v(self.v_head_dim) |
| 322 | logger.info_once("Using %s for attention.", attn_backend.get_name()) |
| 323 | else: |
| 324 | attn_backend = None |
| 325 | |
| 326 | self.attn = Attention( |
| 327 | self.num_heads, |
| 328 | self.head_dim, |
| 329 | self.scaling, |
| 330 | num_kv_heads=self.num_kv_heads, |
| 331 | cache_config=cache_config, |
| 332 | quant_config=quant_config, |
| 333 | per_layer_sliding_window=sliding_window, |
| 334 | attn_type=AttentionType.DECODER, |
| 335 | prefix=f"{prefix}.attn", |
| 336 | sinks=self.attention_sink_bias, |
| 337 | attn_backend=attn_backend, |
| 338 | head_size_v=self.v_head_dim, |
| 339 | ) |
| 340 | |
| 341 | def forward( |
| 342 | self, |
| 343 | positions: torch.Tensor, |
| 344 | hidden_states: torch.Tensor, |
| 345 | ) -> torch.Tensor: |
| 346 | qkv, _ = self.qkv_proj(hidden_states) |
| 347 | q, k, v = qkv.split([self.q_size, self.k_size, self.v_size], dim=-1) |
| 348 | q, k = self.rotary_emb(positions, q, k) |
| 349 | |
| 350 | # Apply v_scale before attention |
| 351 | if self.v_scale is not None: |
| 352 | v = v * self.v_scale |
| 353 | |
| 354 | attn_output = self.attn(q, k, v) |
| 355 | |
| 356 | output, _ = self.o_proj(attn_output) |
| 357 | return output |
| 358 | |
| 359 | |
| 360 | class MiMoV2FlashDecoderLayer(nn.Module): |
| 361 | def __init__(self, vllm_config: VllmConfig, prefix: str = "") -> None: |
| 362 | super().__init__() |
| 363 | config = vllm_config.model_config.hf_text_config |
| 364 | quant_config = vllm_config.quant_config |
| 365 | layer_id = extract_layer_index(prefix) |
| 366 | |
| 367 | self.hidden_size = config.hidden_size |
| 368 | self.config = config |
| 369 | self.layer_id = layer_id |
| 370 | |
| 371 | rope_theta = getattr(config, "rope_theta", 1000000) |
| 372 | max_position_embeddings = getattr(config, "max_position_embeddings", 32768) |
| 373 | |
| 374 | v_scale = getattr(config, "attention_value_scale", None) |
| 375 | |
| 376 | if self.is_compressed_softmax_layer(): |
| 377 | self.self_attn = MiMoV2Attention( |
| 378 | hidden_size=self.hidden_size, |
| 379 | num_heads=config.swa_num_attention_heads, |
| 380 | num_kv_heads=config.swa_num_key_value_heads, |
| 381 | head_dim=config.swa_head_dim, |
| 382 | v_head_dim=getattr(config, "swa_v_head_dim", None), |
| 383 | v_scale=v_scale, |
| 384 | sliding_window_size=config.sliding_window_size, |
| 385 | attention_bias=config.attention_bias, |
| 386 | add_swa_attention_sink_bias=getattr( |
| 387 | config, "add_swa_attention_sink_bias", False |
| 388 | ), |
| 389 | layer_id=layer_id, |
| 390 | rope_theta=getattr(config, "swa_rope_theta", rope_theta), |
| 391 | max_position_embeddings=max_position_embeddings, |
| 392 | quant_config=quant_config, |
| 393 | partial_rotary_factor=getattr(config, "partial_rotary_factor", 1.0), |
| 394 | prefix=f"{prefix}.self_attn", |
| 395 | ) |
| 396 | else: |
| 397 | self.self_attn = MiMoV2Attention( |
| 398 | hidden_size=self.hidden_size, |
| 399 | num_heads=config.num_attention_heads, |
| 400 | num_kv_heads=config.num_key_value_heads, |
| 401 | head_dim=config.head_dim, |
| 402 | v_head_dim=getattr(config, "v_head_dim", None), |
| 403 | v_scale=v_scale, |
| 404 | sliding_window_size=-1, # normal attention |
| 405 | attention_bias=config.attention_bias, |
| 406 | layer_id=layer_id, |
| 407 | rope_theta=rope_theta, |
| 408 | max_position_embeddings=max_position_embeddings, |
| 409 | quant_config=quant_config, |
| 410 | partial_rotary_factor=getattr(config, "partial_rotary_factor", 1.0), |
| 411 | prefix=f"{prefix}.self_attn", |
| 412 | ) |
| 413 | |
| 414 | self.is_layer_sparse = self.is_moe_layer(layer_id) |
| 415 | if self.is_layer_sparse: |
| 416 | self.mlp = MiMoV2MoE( |
| 417 | vllm_config=vllm_config, |
| 418 | prefix=f"{prefix}.mlp", |
| 419 | ) |
| 420 | else: |
| 421 | self.mlp = MiMoV2MLP( |
| 422 | hidden_size=self.hidden_size, |
| 423 | intermediate_size=config.intermediate_size, |
| 424 | hidden_act=config.hidden_act, |
| 425 | quant_config=quant_config, |
| 426 | prefix=f"{prefix}.mlp", |
| 427 | ) |
| 428 | |
| 429 | self.input_layernorm = RMSNorm(config.hidden_size, eps=config.layernorm_epsilon) |
| 430 | self.post_attention_layernorm = RMSNorm( |
| 431 | config.hidden_size, eps=config.layernorm_epsilon |
| 432 | ) |
| 433 | |
| 434 | def forward( |
| 435 | self, |
| 436 | positions: torch.Tensor, |
| 437 | hidden_states: torch.Tensor, |
| 438 | residual: torch.Tensor | None, |
| 439 | ) -> tuple[torch.Tensor, torch.Tensor]: |
| 440 | if residual is None: |
| 441 | residual = hidden_states |
| 442 | hidden_states = self.input_layernorm(hidden_states) |
| 443 | else: |
| 444 | hidden_states, residual = self.input_layernorm(hidden_states, residual) |
| 445 | |
| 446 | hidden_states = self.self_attn( |
| 447 | positions=positions, |
| 448 | hidden_states=hidden_states, |
| 449 | ) |
| 450 | |
| 451 | hidden_states, residual = self.post_attention_layernorm(hidden_states, residual) |
| 452 | hidden_states = self.mlp(hidden_states) |
| 453 | return hidden_states, residual |
| 454 | |
| 455 | def is_moe_layer(self, layer_idx: int) -> bool: |
| 456 | return ( |
| 457 | hasattr(self.config, "moe_layer_freq") |
| 458 | and layer_idx >= 0 |
| 459 | and not isinstance(self.config.moe_layer_freq, int) |
| 460 | and self.config.moe_layer_freq[layer_idx] |
| 461 | ) |
| 462 | |
| 463 | def is_compressed_softmax_layer(self) -> bool: |
| 464 | return self.config.hybrid_layer_pattern[self.layer_id] == 1 |
| 465 | |
| 466 | |
| 467 | def _requantize_fp8( |
| 468 | grouped: torch.Tensor, rows_rank: int, block: int, dtype: torch.dtype |
| 469 | ) -> tuple[torch.Tensor, torch.Tensor]: |
| 470 | """Block-quantize a rank's ``[Q | K | V]`` rows back to fp8. |
| 471 | |
| 472 | A rank's rows need not end on a block boundary (a single 1856-row slice is |
| 473 | 14.5 blocks) while ``scaled_quantize`` requires both dims to be multiples of |
| 474 | the block size, so pad the tail with zeros: zero rows cannot raise a block's |
| 475 | amax, so every scale -- and the number of scale rows -- is unchanged. The |
| 476 | padding is dropped again here. |
| 477 | """ |
| 478 | padded = cdiv(rows_rank, block) * block |
| 479 | if padded != rows_rank: |
| 480 | grouped = torch.cat( |
| 481 | [grouped, grouped.new_zeros(padded - rows_rank, grouped.shape[1])], dim=0 |
| 482 | ) |
| 483 | w_rank, s_rank = scaled_quantize( |
| 484 | grouped, GroupShape(block, block), dtype, compute_dtype=torch.float32 |
| 485 | ) |
| 486 | return w_rank[:rows_rank], s_rank |
| 487 | |
| 488 | |
| 489 | def _shard_fp8_qkv_proj( |
| 490 | w_full: torch.Tensor, |
| 491 | s_full: torch.Tensor, |
| 492 | num_heads: int, |
| 493 | num_kv_heads: int, |
| 494 | head_dim: int, |
| 495 | v_head_dim: int, |
| 496 | tp_rank: int, |
| 497 | tp_size: int, |
| 498 | ckpt_tp: int, |
| 499 | block: int = 128, |
| 500 | ) -> tuple[torch.Tensor, torch.Tensor]: |
| 501 | """Shard the fp8 qkv_proj weights for ``tp_rank``. |
| 502 | |
| 503 | The checkpoint stores the fused QKV pre-sharded for ``ckpt_tp`` ranks (the |
| 504 | model config's ``num_key_value_heads``), each chunk holding that slice's |
| 505 | Q, K and V rows: |
| 506 | |
| 507 | [Q_0 | K_0 | V_0 | Q_1 | K_1 | V_1 | ... | Q_n | K_n | V_n] (n = ckpt_tp) |
| 508 | |
| 509 | Per chunk, Q has ``(num_heads / ckpt_tp) * head_dim`` rows, K has |
| 510 | ``(num_kv_heads / ckpt_tp) * head_dim`` rows, and V has |
| 511 | ``(num_kv_heads / ckpt_tp) * v_head_dim`` rows, and the fp8 block scales |
| 512 | are tiled per chunk too (``ceil(rows_per_chunk / block)`` rows each). |
| 513 | |
| 514 | ``ckpt_tp`` is not the layer's KV-head count: a MiMo-V2.5 SWA layer has 8 |
| 515 | KV heads over 4 chunks, so each chunk carries two KV heads (3712 rows = 29 |
| 516 | blocks) while a GA layer has 4 KV heads over 4 chunks (3392 rows each). |
| 517 | |
| 518 | The forward expects each rank's slice de-interleaved: |
| 519 | |
| 520 | [Q_1 | Q_2 | ... | Q_g | K_1 | K_2 | ... | K_g | V_1 | V_2 | ... | V_g] |
| 521 | |
| 522 | When ``tp_size == ckpt_tp`` the checkpoint chunk *is* that layout, so a |
| 523 | plain chunk of both weight and scale suffices. Otherwise each rank's Q, K |
| 524 | and V rows are gathered from the chunks that hold them, dequantized with |
| 525 | the chunk's own scales, reordered, and re-quantized to fp8. |
| 526 | """ |
| 527 | assert num_heads % tp_size == 0, ( |
| 528 | f"num_heads={num_heads} must be divisible by tp_size={tp_size}." |
| 529 | ) |
| 530 | if ckpt_tp <= 0 or num_heads % ckpt_tp or num_kv_heads % ckpt_tp: |
| 531 | raise ValueError( |
| 532 | f"fused qkv_proj is pre-sharded at {ckpt_tp} chunks, which do not " |
| 533 | f"divide num_heads={num_heads} / num_kv_heads={num_kv_heads}." |
| 534 | ) |
| 535 | # When there are fewer KV heads than ranks, vLLM replicates them |
| 536 | # (`num_kv_head_replicas`) and rank r owns KV head r // replicas, which |
| 537 | # keeps every Q head grouped with the KV head it attends to. |
| 538 | if tp_size <= num_kv_heads: |
| 539 | assert num_kv_heads % tp_size == 0, ( |
| 540 | f"num_kv_heads={num_kv_heads} must be divisible by tp_size={tp_size}." |
| 541 | ) |
| 542 | kv_head_ids = list( |
| 543 | range( |
| 544 | tp_rank * (num_kv_heads // tp_size), |
| 545 | (tp_rank + 1) * (num_kv_heads // tp_size), |
| 546 | ) |
| 547 | ) |
| 548 | else: |
| 549 | assert tp_size % num_kv_heads == 0, ( |
| 550 | f"tp_size={tp_size} must be divisible by num_kv_heads={num_kv_heads}." |
| 551 | ) |
| 552 | kv_head_ids = [tp_rank // (tp_size // num_kv_heads)] |
| 553 | q_head_ids = list( |
| 554 | range(tp_rank * (num_heads // tp_size), (tp_rank + 1) * (num_heads // tp_size)) |
| 555 | ) |
| 556 | |
| 557 | rows_per_chunk = w_full.shape[0] // ckpt_tp |
| 558 | q_per_chunk = (num_heads // ckpt_tp) * head_dim |
| 559 | k_per_chunk = (num_kv_heads // ckpt_tp) * head_dim |
| 560 | v_per_chunk = (num_kv_heads // ckpt_tp) * v_head_dim |
| 561 | if q_per_chunk + k_per_chunk + v_per_chunk != rows_per_chunk: |
| 562 | raise ValueError( |
| 563 | f"fused qkv_proj has {w_full.shape[0]} rows, not {ckpt_tp} chunks of " |
| 564 | f"{q_per_chunk} Q + {k_per_chunk} K + {v_per_chunk} V rows." |
| 565 | ) |
| 566 | |
| 567 | # The scales are tiled per chunk; they collapse to one continuous grid when |
| 568 | # a chunk is a whole number of blocks (the SWA chunks are: 3712 = 29 * 128). |
| 569 | chunk_scale_rows = cdiv(rows_per_chunk, block) |
| 570 | rows = torch.arange(w_full.shape[0]) |
| 571 | per_chunk_scales = s_full.shape[0] == ckpt_tp * chunk_scale_rows |
| 572 | if per_chunk_scales: |
| 573 | scale_index = (rows // rows_per_chunk) * chunk_scale_rows + ( |
| 574 | rows % rows_per_chunk |
| 575 | ) // block |
| 576 | elif s_full.shape[0] == cdiv(w_full.shape[0], block): |
| 577 | scale_index = rows // block |
| 578 | else: |
| 579 | raise ValueError( |
| 580 | f"fused qkv_proj scale has {s_full.shape[0]} rows, expected either " |
| 581 | f"{ckpt_tp * chunk_scale_rows} ({ckpt_tp} chunks of " |
| 582 | f"{chunk_scale_rows} rows) or {cdiv(w_full.shape[0], block)} " |
| 583 | f"(one continuous grid)" |
| 584 | ) |
| 585 | |
| 586 | if tp_size == ckpt_tp and per_chunk_scales: |
| 587 | # One checkpoint chunk per rank: already [Q | K | V] for that rank, and |
| 588 | # its scale rows line up with ceil(rows_per_chunk / block). |
| 589 | return ( |
| 590 | w_full.chunk(ckpt_tp, dim=0)[tp_rank], |
| 591 | s_full.chunk(ckpt_tp, dim=0)[tp_rank], |
| 592 | ) |
| 593 | |
| 594 | # Gather this rank's Q, K and V rows from the chunks that hold them. |
| 595 | q_heads_per_chunk = num_heads // ckpt_tp |
| 596 | kv_heads_per_chunk = num_kv_heads // ckpt_tp |
| 597 | head_rows = torch.arange(head_dim) |
| 598 | v_head_rows = torch.arange(v_head_dim) |
| 599 | row_index: list[torch.Tensor] = [] |
| 600 | for head in q_head_ids: |
| 601 | chunk = head // q_heads_per_chunk |
| 602 | row_index.append( |
| 603 | chunk * rows_per_chunk + (head % q_heads_per_chunk) * head_dim + head_rows |
| 604 | ) |
| 605 | for head in kv_head_ids: |
| 606 | chunk = head // kv_heads_per_chunk |
| 607 | row_index.append( |
| 608 | chunk * rows_per_chunk |
| 609 | + q_per_chunk |
| 610 | + (head % kv_heads_per_chunk) * head_dim |
| 611 | + head_rows |
| 612 | ) |
| 613 | for head in kv_head_ids: |
| 614 | chunk = head // kv_heads_per_chunk |
| 615 | row_index.append( |
| 616 | chunk * rows_per_chunk |
| 617 | + q_per_chunk |
| 618 | + k_per_chunk |
| 619 | + (head % kv_heads_per_chunk) * v_head_dim |
| 620 | + v_head_rows |
| 621 | ) |
| 622 | index = torch.cat(row_index) |
| 623 | grouped = w_full[index].to(torch.float32) * s_full[ |
| 624 | scale_index[index] |
| 625 | ].repeat_interleave(block, dim=1) |
| 626 | return _requantize_fp8(grouped, index.numel(), block, w_full.dtype) |
| 627 | |
| 628 | |
| 629 | @support_torch_compile |
| 630 | class MiMoV2Model(nn.Module, EagleModelMixin): |
| 631 | def __init__(self, *, vllm_config: VllmConfig, prefix: str = ""): |
| 632 | super().__init__() |
| 633 | |
| 634 | config = vllm_config.model_config.hf_config.get_text_config() |
| 635 | quant_config = vllm_config.quant_config |
| 636 | eplb_config = vllm_config.parallel_config.eplb_config |
| 637 | |
| 638 | self.config = config |
| 639 | self.quant_config = quant_config |
| 640 | self.vocab_size = config.vocab_size |
| 641 | self.num_redundant_experts = eplb_config.num_redundant_experts |
| 642 | |
| 643 | if get_pp_group().is_first_rank or ( |
| 644 | config.tie_word_embeddings and get_pp_group().is_last_rank |
| 645 | ): |
| 646 | self.embed_tokens = VocabParallelEmbedding( |
| 647 | config.vocab_size, |
| 648 | config.hidden_size, |
| 649 | quant_config=quant_config, |
| 650 | prefix=f"{prefix}.embed_tokens", |
| 651 | ) |
| 652 | else: |
| 653 | self.embed_tokens = PPMissingLayer() |
| 654 | |
| 655 | self.start_layer, self.end_layer, self.layers = make_layers( |
| 656 | config.num_hidden_layers, |
| 657 | lambda prefix: MiMoV2FlashDecoderLayer( |
| 658 | vllm_config=vllm_config, |
| 659 | prefix=prefix, |
| 660 | ), |
| 661 | prefix=f"{prefix}.layers", |
| 662 | ) |
| 663 | |
| 664 | self.make_empty_intermediate_tensors = make_empty_intermediate_tensors_factory( |
| 665 | ["hidden_states", "residual"], config.hidden_size |
| 666 | ) |
| 667 | if get_pp_group().is_last_rank: |
| 668 | self.norm = RMSNorm(config.hidden_size, eps=config.layernorm_epsilon) |
| 669 | else: |
| 670 | self.norm = PPMissingLayer() |
| 671 | |
| 672 | def embed_input_ids(self, input_ids: torch.Tensor) -> torch.Tensor: |
| 673 | return self.embed_tokens(input_ids) |
| 674 | |
| 675 | def forward( |
| 676 | self, |
| 677 | input_ids: torch.Tensor | None, |
| 678 | positions: torch.Tensor, |
| 679 | intermediate_tensors: IntermediateTensors | None = None, |
| 680 | inputs_embeds: torch.Tensor | None = None, |
| 681 | ) -> torch.Tensor | IntermediateTensors: |
| 682 | if get_pp_group().is_first_rank: |
| 683 | if inputs_embeds is not None: |
| 684 | hidden_states = inputs_embeds |
| 685 | else: |
| 686 | hidden_states = self.embed_input_ids(input_ids) |
| 687 | residual = None |
| 688 | else: |
| 689 | assert intermediate_tensors is not None |
| 690 | hidden_states = intermediate_tensors["hidden_states"] |
| 691 | residual = intermediate_tensors["residual"] |
| 692 | |
| 693 | aux_hidden_states = self._maybe_add_hidden_state( |
| 694 | [], self.start_layer, hidden_states, residual |
| 695 | ) |
| 696 | for idx, layer in enumerate( |
| 697 | islice(self.layers, self.start_layer, self.end_layer) |
| 698 | ): |
| 699 | hidden_states, residual = layer(positions, hidden_states, residual) |
| 700 | self._maybe_add_hidden_state( |
| 701 | aux_hidden_states, idx + 1, hidden_states, residual |
| 702 | ) |
| 703 | |
| 704 | if not get_pp_group().is_last_rank: |
| 705 | return IntermediateTensors( |
| 706 | {"hidden_states": hidden_states, "residual": residual} |
| 707 | ) |
| 708 | |
| 709 | hidden_states, _ = self.norm(hidden_states, residual) |
| 710 | |
| 711 | if len(aux_hidden_states) > 0: |
| 712 | return hidden_states, aux_hidden_states |
| 713 | return hidden_states |
| 714 | |
| 715 | def get_expert_mapping(self) -> list[tuple[str, str, int, str]]: |
| 716 | # Params for weights, fp8 weight scales, fp8 activation scales |
| 717 | # (param_name, weight_name, expert_id, shard_id) |
| 718 | return fused_moe_make_expert_params_mapping( |
| 719 | self, |
| 720 | ckpt_gate_proj_name="gate_proj", |
| 721 | ckpt_down_proj_name="down_proj", |
| 722 | ckpt_up_proj_name="up_proj", |
| 723 | num_experts=self.config.n_routed_experts, |
| 724 | num_redundant_experts=self.num_redundant_experts, |
| 725 | ) |
| 726 | |
| 727 | def load_weights(self, weights: Iterable[tuple[str, torch.Tensor]]) -> set[str]: |
| 728 | stacked_params_mapping: list[tuple[str, str, str | int]] = [ |
| 729 | # (param_name, shard_name, shard_id) |
| 730 | ("qkv_proj", "q_proj", "q"), |
| 731 | ("qkv_proj", "k_proj", "k"), |
| 732 | ("qkv_proj", "v_proj", "v"), |
| 733 | ("gate_up_proj", "gate_proj", 0), |
| 734 | ("gate_up_proj", "up_proj", 1), |
| 735 | ] |
| 736 | |
| 737 | tp_rank = get_tensor_model_parallel_rank() |
| 738 | tp_size = get_tensor_model_parallel_world_size() |
| 739 | |
| 740 | params_dict = dict(self.named_parameters(remove_duplicate=False)) |
| 741 | loaded_params: set[str] = set() |
| 742 | expert_params_mapping = self.get_expert_mapping() |
| 743 | # Pro-format fused qkv_proj arrives as two tensors (weight and |
| 744 | # weight_scale_inv). Store them per-layer so that they can be |
| 745 | # sharded together. The state must outlive this call: AutoWeightsLoader |
| 746 | # delegates per contiguous group of names, so a pair can straddle two |
| 747 | # calls and would otherwise be dropped silently. |
| 748 | pending_fp8_qkv_proj = getattr(self, "_pending_fp8_qkv_proj", None) |
| 749 | if pending_fp8_qkv_proj is None: |
| 750 | self._pending_fp8_qkv_proj = pending_fp8_qkv_proj = {} |
| 751 | for name, loaded_weight in weights: |
| 752 | if "rotary_emb.inv_freq" in name: |
| 753 | continue |
| 754 | if "rotary_emb.cos_cached" in name or "rotary_emb.sin_cached" in name: |
| 755 | continue |
| 756 | if "mtp" in name: |
| 757 | continue |
| 758 | |
| 759 | expert_matched = False |
| 760 | for param_name, weight_name, expert_id, shard_id in expert_params_mapping: |
| 761 | if weight_name not in name: |
| 762 | continue |
| 763 | |
| 764 | name_rewritten = name.replace(weight_name, param_name) |
| 765 | |
| 766 | if is_pp_missing_parameter(name_rewritten, self): |
| 767 | continue |
| 768 | |
| 769 | if ( |
| 770 | name_rewritten.endswith(".bias") or name_rewritten.endswith("_bias") |
| 771 | ) and name_rewritten not in params_dict: |
| 772 | continue |
| 773 | |
| 774 | if name_rewritten not in params_dict: |
| 775 | continue |
| 776 | |
| 777 | param = params_dict[name_rewritten] |
| 778 | weight_loader = param.weight_loader |
| 779 | |
| 780 | weight_loader( |
| 781 | param, |
| 782 | loaded_weight, |
| 783 | name_rewritten, |
| 784 | shard_id=shard_id, |
| 785 | expert_id=expert_id, |
| 786 | ) |
| 787 | loaded_params.add(name_rewritten) |
| 788 | expert_matched = True |
| 789 | break |
| 790 | |
| 791 | if expert_matched: |
| 792 | continue |
| 793 | # Support fused qkv_proj checkpoint (Pro format) |
| 794 | if self._try_load_fp8_qkv_proj( |
| 795 | name, |
| 796 | loaded_weight, |
| 797 | pending_fp8_qkv_proj, |
| 798 | params_dict, |
| 799 | loaded_params, |
| 800 | tp_rank, |
| 801 | tp_size, |
| 802 | ): |
| 803 | continue |
| 804 | stacked_matched = False |
| 805 | for param_name, weight_name, stacked_shard_id in stacked_params_mapping: |
| 806 | if weight_name not in name: |
| 807 | continue |
| 808 | name_rewritten = name.replace(weight_name, param_name) |
| 809 | |
| 810 | if ( |
| 811 | name_rewritten.endswith(".bias") |
| 812 | and name_rewritten not in params_dict |
| 813 | ): |
| 814 | continue |
| 815 | |
| 816 | if is_pp_missing_parameter(name_rewritten, self): |
| 817 | continue |
| 818 | |
| 819 | if name_rewritten not in params_dict: |
| 820 | continue |
| 821 | |
| 822 | param = params_dict[name_rewritten] |
| 823 | weight_loader = getattr(param, "weight_loader", default_weight_loader) |
| 824 | weight_loader(param, loaded_weight, stacked_shard_id) |
| 825 | loaded_params.add(name_rewritten) |
| 826 | |
| 827 | stacked_matched = True |
| 828 | break |
| 829 | |
| 830 | if stacked_matched: |
| 831 | continue |
| 832 | |
| 833 | if name.endswith(".bias") and name not in params_dict: |
| 834 | continue |
| 835 | |
| 836 | orig_name = name |
| 837 | mapped_name = maybe_remap_kv_scale_name(name, params_dict) |
| 838 | name = mapped_name if mapped_name is not None else orig_name |
| 839 | |
| 840 | if name not in params_dict: |
| 841 | continue |
| 842 | |
| 843 | param = params_dict[name] |
| 844 | |
| 845 | if "attention_sink_bias" in name: |
| 846 | total_heads = loaded_weight.shape[0] |
| 847 | heads_per_rank = total_heads // tp_size |
| 848 | head_start = tp_rank * heads_per_rank |
| 849 | narrow_weight = loaded_weight.narrow(0, head_start, heads_per_rank) |
| 850 | |
| 851 | param.data.copy_(narrow_weight) |
| 852 | loaded_params.add(name) |
| 853 | else: |
| 854 | weight_loader = getattr(param, "weight_loader", default_weight_loader) |
| 855 | weight_loader(param, loaded_weight) |
| 856 | loaded_params.add(name) |
| 857 | |
| 858 | return loaded_params |
| 859 | |
| 860 | def _try_load_fp8_qkv_proj( |
| 861 | self, |
| 862 | name: str, |
| 863 | tensor: torch.Tensor, |
| 864 | fp8_qkv_proj_dict: dict[str, dict[str, torch.Tensor]], |
| 865 | params_dict: dict[str, torch.nn.Parameter], |
| 866 | loaded_params: set[str], |
| 867 | tp_rank: int, |
| 868 | tp_size: int, |
| 869 | ) -> bool: |
| 870 | """The fused fp8 QKV projection weights and scale are stored separately. |
| 871 | Special care must be taken while sharding these tensors across TP ranks. |
| 872 | See _shard_fp8_qkv_proj for more details. |
| 873 | |
| 874 | Returns: |
| 875 | True if ``tensor`` was an fp8 qkv_proj weight/scale and was consumed |
| 876 | (caller should skip it); False otherwise, so the caller falls |
| 877 | through to its normal loading path. |
| 878 | |
| 879 | """ |
| 880 | is_weight = ( |
| 881 | name.endswith("qkv_proj.weight") and tensor.dtype == torch.float8_e4m3fn |
| 882 | ) |
| 883 | is_scale = name.endswith("qkv_proj.weight_scale_inv") |
| 884 | if not is_weight and not is_scale: |
| 885 | # Weight is not in FP8 format. Ignore. |
| 886 | return False |
| 887 | |
| 888 | if is_pp_missing_parameter(name, self): |
| 889 | # This qkv_proj is for a layer not on this PP rank. |
| 890 | return True |
| 891 | |
| 892 | prefix, qkv_kind = name.rsplit(".", 1) |
| 893 | entry = fp8_qkv_proj_dict.setdefault(prefix, {}) |
| 894 | entry[qkv_kind] = tensor |
| 895 | if "weight" not in entry or "weight_scale_inv" not in entry: |
| 896 | # Still waiting for the other param. |
| 897 | return True |
| 898 | del fp8_qkv_proj_dict[prefix] |
| 899 | |
| 900 | # Get self_attn module, which is a parent of qkv_proj. |
| 901 | attn = self.get_submodule(prefix.rsplit(".", 1)[0]) |
| 902 | |
| 903 | # Shard the qkv_proj per-rank. |
| 904 | w_rank, s_rank = _shard_fp8_qkv_proj( |
| 905 | entry["weight"], |
| 906 | entry["weight_scale_inv"], |
| 907 | num_heads=attn.total_num_heads, |
| 908 | num_kv_heads=attn.total_num_kv_heads, |
| 909 | head_dim=attn.head_dim, |
| 910 | v_head_dim=attn.v_head_dim, |
| 911 | tp_rank=tp_rank, |
| 912 | tp_size=tp_size, |
| 913 | # The fused qkv_proj is pre-sharded for this many ranks. |
| 914 | ckpt_tp=self.config.num_key_value_heads, |
| 915 | ) |
| 916 | sharded = {"weight": w_rank, "weight_scale_inv": s_rank} |
| 917 | for kind, tensor in sharded.items(): |
| 918 | param_name = f"{prefix}.{kind}" |
| 919 | param = params_dict[param_name] |
| 920 | if tensor.shape[0] > param.shape[0]: |
| 921 | tensor = tensor[: param.shape[0]] |
| 922 | default_weight_loader(param, tensor) |
| 923 | loaded_params.add(param_name) |
| 924 | return True |
| 925 | |
| 926 | |
| 927 | class MiMoV2FlashForCausalLM(nn.Module, SupportsPP, MixtureOfExperts, SupportsEagle3): |
| 928 | packed_modules_mapping = { |
| 929 | "qkv_proj": ["q_proj", "k_proj", "v_proj"], |
| 930 | "gate_up_proj": ["gate_proj", "up_proj"], |
| 931 | } |
| 932 | |
| 933 | def __init__(self, *, vllm_config: VllmConfig, prefix: str = ""): |
| 934 | super().__init__() |
| 935 | config = vllm_config.model_config.hf_config |
| 936 | quant_config = vllm_config.quant_config |
| 937 | |
| 938 | self.config = config |
| 939 | self.quant_config = quant_config |
| 940 | self.model = MiMoV2Model( |
| 941 | vllm_config=vllm_config, |
| 942 | prefix=maybe_prefix(prefix, "model"), |
| 943 | ) |
| 944 | |
| 945 | if get_pp_group().is_last_rank: |
| 946 | self.lm_head = ParallelLMHead( |
| 947 | config.vocab_size, |
| 948 | config.hidden_size, |
| 949 | quant_config=quant_config, |
| 950 | prefix=maybe_prefix(prefix, "lm_head"), |
| 951 | ) |
| 952 | else: |
| 953 | self.lm_head = PPMissingLayer() |
| 954 | |
| 955 | self.logits_processor = LogitsProcessor(config.vocab_size) |
| 956 | |
| 957 | self.make_empty_intermediate_tensors = ( |
| 958 | self.model.make_empty_intermediate_tensors |
| 959 | ) |
| 960 | |
| 961 | def embed_input_ids(self, input_ids: torch.Tensor) -> torch.Tensor: |
| 962 | return self.model.embed_input_ids(input_ids) |
| 963 | |
| 964 | def forward( |
| 965 | self, |
| 966 | input_ids: torch.Tensor | None, |
| 967 | positions: torch.Tensor, |
| 968 | intermediate_tensors: IntermediateTensors | None = None, |
| 969 | inputs_embeds: torch.Tensor | None = None, |
| 970 | ) -> torch.Tensor | IntermediateTensors: |
| 971 | hidden_states = self.model( |
| 972 | input_ids, positions, intermediate_tensors, inputs_embeds |
| 973 | ) |
| 974 | return hidden_states |
| 975 | |
| 976 | def compute_logits( |
| 977 | self, |
| 978 | hidden_states: torch.Tensor, |
| 979 | ) -> torch.Tensor | None: |
| 980 | logits = self.logits_processor(self.lm_head, hidden_states) |
| 981 | return logits |
| 982 | |
| 983 | def get_expert_mapping(self) -> list[tuple[str, str, int, str]]: |
| 984 | return self.model.get_expert_mapping() |
| 985 | |
| 986 | def load_weights(self, weights: Iterable[tuple[str, torch.Tensor]]) -> set[str]: |
| 987 | loader = AutoWeightsLoader(self) |
| 988 | return loader.load_weights(weights) |
| 989 | |
| 990 | |
| 991 | class MiMoV2ForCausalLM(MiMoV2FlashForCausalLM): |
| 992 | packed_modules_mapping = { |
| 993 | "qkv_proj": ["qkv_proj"], |
| 994 | "gate_up_proj": ["gate_proj", "up_proj"], |
| 995 | } |