| 1 | # SPDX-License-Identifier: Apache-2.0 |
| 2 | # SPDX-FileCopyrightText: Copyright contributors to the vLLM project |
| 3 | |
| 4 | # Adapted from https://github.com/vllm-project/vllm/blob/94d8ec8d2bcb4ec55e33022b313c7e978edf05e1/vllm/model_executor/models/bamba.py |
| 5 | # Copyright 2024 HuggingFace Inc. team. All rights reserved. |
| 6 | # Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. |
| 7 | # |
| 8 | # Licensed under the Apache License, Version 2.0 (the "License"); |
| 9 | # you may not use this file except in compliance with the License. |
| 10 | # You may obtain a copy of the License at |
| 11 | # |
| 12 | # http://www.apache.org/licenses/LICENSE-2.0 |
| 13 | # |
| 14 | # Unless required by applicable law or agreed to in writing, software |
| 15 | # distributed under the License is distributed on an "AS IS" BASIS, |
| 16 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 17 | # See the License for the specific language governing permissions and |
| 18 | # limitations under the License. |
| 19 | """Inference-only NemotronH model.""" |
| 20 | |
| 21 | from collections.abc import Iterable, Mapping |
| 22 | from itertools import islice |
| 23 | |
| 24 | import torch |
| 25 | from torch import nn |
| 26 | |
| 27 | from vllm.compilation.decorators import support_torch_compile |
| 28 | from vllm.config import ( |
| 29 | CacheConfig, |
| 30 | ModelConfig, |
| 31 | VllmConfig, |
| 32 | ) |
| 33 | from vllm.config.parallel import ParallelConfig |
| 34 | from vllm.distributed import get_ep_group, get_tensor_model_parallel_world_size |
| 35 | from vllm.distributed.communication_op import tensor_model_parallel_all_gather |
| 36 | from vllm.distributed.parallel_state import get_pp_group |
| 37 | from vllm.model_executor.layers.activation import get_act_fn |
| 38 | from vllm.model_executor.layers.attention import Attention |
| 39 | from vllm.model_executor.layers.fused_moe import ( |
| 40 | FusedMoEFactory, |
| 41 | GateLinear, |
| 42 | activation_without_mul, |
| 43 | fused_moe_make_expert_params_mapping, |
| 44 | ) |
| 45 | from vllm.model_executor.layers.fusion.fused_act_quant import maybe_fused_act_quant |
| 46 | from vllm.model_executor.layers.layernorm import RMSNorm |
| 47 | from vllm.model_executor.layers.linear import ( |
| 48 | ColumnParallelLinear, |
| 49 | QKVParallelLinear, |
| 50 | ReplicatedLinear, |
| 51 | RowParallelLinear, |
| 52 | UnquantizedLinearMethod, |
| 53 | ) |
| 54 | from vllm.model_executor.layers.logits_processor import LogitsProcessor |
| 55 | from vllm.model_executor.layers.mamba.mamba_mixer2 import MambaMixer2 |
| 56 | from vllm.model_executor.layers.mamba.mamba_utils import ( |
| 57 | MambaStateCopyFunc, |
| 58 | MambaStateCopyFuncCalculator, |
| 59 | MambaStateDtypeCalculator, |
| 60 | MambaStateShapeCalculator, |
| 61 | ) |
| 62 | from vllm.model_executor.layers.quantization import QuantizationConfig |
| 63 | from vllm.model_executor.layers.vocab_parallel_embedding import ( |
| 64 | ParallelLMHead, |
| 65 | VocabParallelEmbedding, |
| 66 | ) |
| 67 | from vllm.model_executor.models.interfaces import ( |
| 68 | EagleModelMixin, |
| 69 | HasInnerState, |
| 70 | IsHybrid, |
| 71 | MambaStateShapes, |
| 72 | MixtureOfExperts, |
| 73 | SupportsEagle, |
| 74 | SupportsEagle3, |
| 75 | SupportsLoRA, |
| 76 | SupportsMambaPrefixCaching, |
| 77 | SupportsPP, |
| 78 | SupportsQuant, |
| 79 | SupportsReplaySSM, |
| 80 | ) |
| 81 | from vllm.model_executor.models.utils import ( |
| 82 | AutoWeightsLoader, |
| 83 | WeightsMapper, |
| 84 | make_empty_intermediate_tensors_factory, |
| 85 | make_layers, |
| 86 | maybe_prefix, |
| 87 | sequence_parallel_chunk, |
| 88 | ) |
| 89 | from vllm.sequence import IntermediateTensors |
| 90 | from vllm.transformers_utils.configs.nemotron_h import NemotronHConfig |
| 91 | |
| 92 | |
| 93 | class NemotronHMLP(nn.Module): |
| 94 | def __init__( |
| 95 | self, |
| 96 | config: NemotronHConfig | None, |
| 97 | hidden_size: int, |
| 98 | intermediate_size: int, |
| 99 | quant_config: QuantizationConfig | None = None, |
| 100 | bias: bool = False, |
| 101 | reduce_results: bool = True, |
| 102 | is_sequence_parallel: bool = False, |
| 103 | prefix: str = "", |
| 104 | *, |
| 105 | hidden_act: str = "relu2", |
| 106 | output_size: int | None = None, |
| 107 | ) -> None: |
| 108 | super().__init__() |
| 109 | |
| 110 | self.up_proj = ColumnParallelLinear( |
| 111 | input_size=hidden_size, |
| 112 | output_size=intermediate_size, |
| 113 | bias=bias, |
| 114 | quant_config=quant_config, |
| 115 | disable_tp=is_sequence_parallel, |
| 116 | prefix=f"{prefix}.up_proj", |
| 117 | ) |
| 118 | self.down_proj = RowParallelLinear( |
| 119 | input_size=intermediate_size, |
| 120 | output_size=hidden_size if output_size is None else output_size, |
| 121 | bias=bias, |
| 122 | quant_config=quant_config, |
| 123 | reduce_results=reduce_results, |
| 124 | disable_tp=is_sequence_parallel, |
| 125 | prefix=f"{prefix}.down_proj", |
| 126 | ) |
| 127 | self.act_fn = get_act_fn(hidden_act) |
| 128 | |
| 129 | def forward(self, x: torch.Tensor): |
| 130 | x, _ = self.up_proj(x) |
| 131 | x = maybe_fused_act_quant(self.act_fn, x, self.down_proj) |
| 132 | x, _ = self.down_proj(x) |
| 133 | return x |
| 134 | |
| 135 | |
| 136 | class NemotronHMoE(nn.Module): |
| 137 | def __init__( |
| 138 | self, |
| 139 | config: NemotronHConfig, |
| 140 | quant_config: QuantizationConfig | None = None, |
| 141 | parallel_config: ParallelConfig | None = None, |
| 142 | prefix: str = "", |
| 143 | ): |
| 144 | super().__init__() |
| 145 | assert parallel_config is not None |
| 146 | self.tp_size = get_tensor_model_parallel_world_size() |
| 147 | self.routed_scaling_factor = config.routed_scaling_factor |
| 148 | |
| 149 | self.ep_group = get_ep_group().device_group |
| 150 | self.ep_size = self.ep_group.size() |
| 151 | self.n_routed_experts: int = config.n_routed_experts |
| 152 | self.n_shared_experts: int = config.n_shared_experts |
| 153 | self.use_latent_moe: bool = getattr(config, "moe_latent_size", None) is not None |
| 154 | self.moe_hidden_size: int = ( |
| 155 | config.moe_latent_size if self.use_latent_moe else config.hidden_size |
| 156 | ) |
| 157 | |
| 158 | self.is_sequence_parallel = parallel_config.use_sequence_parallel_moe |
| 159 | |
| 160 | self.gate = GateLinear( |
| 161 | config.hidden_size, |
| 162 | config.n_routed_experts, |
| 163 | out_dtype=torch.float32, |
| 164 | force_fp32_compute=True, |
| 165 | prefix=f"{prefix}.gate", |
| 166 | ) |
| 167 | |
| 168 | self.gate.e_score_correction_bias = nn.Parameter( |
| 169 | torch.empty(config.n_routed_experts, dtype=torch.float32) |
| 170 | ) |
| 171 | # Load balancing settings. |
| 172 | self.enable_eplb = parallel_config.enable_eplb |
| 173 | |
| 174 | self.n_redundant_experts = parallel_config.eplb_config.num_redundant_experts # noqa: E501 |
| 175 | self.n_logical_experts = self.n_routed_experts |
| 176 | self.n_physical_experts = self.n_logical_experts + self.n_redundant_experts |
| 177 | self.n_local_physical_experts = self.n_physical_experts // self.ep_size |
| 178 | |
| 179 | if config.n_shared_experts is None or config.n_shared_experts == 0: |
| 180 | self.shared_experts = None |
| 181 | else: |
| 182 | intermediate_size = ( |
| 183 | config.moe_shared_expert_intermediate_size * config.n_shared_experts |
| 184 | ) |
| 185 | |
| 186 | self.shared_experts = NemotronHMLP( |
| 187 | config=config, |
| 188 | hidden_size=config.hidden_size, |
| 189 | intermediate_size=intermediate_size, |
| 190 | quant_config=quant_config, |
| 191 | reduce_results=False, |
| 192 | is_sequence_parallel=self.is_sequence_parallel, |
| 193 | prefix=f"{prefix}.shared_experts", |
| 194 | ) |
| 195 | |
| 196 | self.fc1_latent_proj: ReplicatedLinear | None |
| 197 | self.fc2_latent_proj: ReplicatedLinear | None |
| 198 | if self.use_latent_moe: |
| 199 | self.fc1_latent_proj = ReplicatedLinear( |
| 200 | input_size=config.hidden_size, |
| 201 | output_size=self.moe_hidden_size, |
| 202 | bias=config.mlp_bias, |
| 203 | quant_config=quant_config, |
| 204 | disable_tp=self.is_sequence_parallel, |
| 205 | prefix=f"{prefix}.fc1_latent_proj", |
| 206 | ) |
| 207 | self.fc2_latent_proj = ReplicatedLinear( |
| 208 | input_size=self.moe_hidden_size, |
| 209 | output_size=config.hidden_size, |
| 210 | bias=config.mlp_bias, |
| 211 | quant_config=quant_config, |
| 212 | disable_tp=self.is_sequence_parallel, |
| 213 | prefix=f"{prefix}.fc2_latent_proj", |
| 214 | ) |
| 215 | # A bias-free, unquantized linear commutes with the TP sum |
| 216 | # (sum_r W x_r == W sum_r x_r), so one reduce after the transform |
| 217 | # suffices. Test the layer, not the model-wide `quant_config`: ModelOpt |
| 218 | # excludes the latent projections, so quantized checkpoints still get |
| 219 | # an UnquantizedLinearMethod here. |
| 220 | self.fc2_latent_proj.reduce_commutative = ( |
| 221 | not config.mlp_bias |
| 222 | and isinstance( |
| 223 | self.fc2_latent_proj.quant_method, UnquantizedLinearMethod |
| 224 | ) |
| 225 | ) |
| 226 | else: |
| 227 | self.fc1_latent_proj = None |
| 228 | self.fc2_latent_proj = None |
| 229 | |
| 230 | self.experts = FusedMoEFactory( |
| 231 | shared_experts=self.shared_experts, |
| 232 | num_experts=config.n_routed_experts, |
| 233 | top_k=config.num_experts_per_tok, |
| 234 | hidden_size=self.moe_hidden_size, |
| 235 | intermediate_size=config.moe_intermediate_size, |
| 236 | renormalize=config.norm_topk_prob, |
| 237 | quant_config=quant_config, |
| 238 | ckpt_names=("up_proj", "down_proj", ""), |
| 239 | use_grouped_topk=True, |
| 240 | num_expert_group=config.n_group, |
| 241 | topk_group=config.topk_group, |
| 242 | prefix=f"{prefix}.experts", |
| 243 | scoring_func="sigmoid", |
| 244 | e_score_correction_bias=self.gate.e_score_correction_bias, |
| 245 | activation=activation_without_mul(config.mlp_hidden_act), |
| 246 | enable_eplb=self.enable_eplb, |
| 247 | num_redundant_experts=self.n_redundant_experts, |
| 248 | is_sequence_parallel=self.is_sequence_parallel, |
| 249 | routed_input_transform=self.fc1_latent_proj, |
| 250 | routed_output_transform=self.fc2_latent_proj, |
| 251 | routed_scaling_factor=self.routed_scaling_factor, |
| 252 | apply_routed_scale_to_output=True, |
| 253 | router_logits_dtype=self.gate.out_dtype, |
| 254 | ) |
| 255 | |
| 256 | def forward(self, hidden_states: torch.Tensor) -> torch.Tensor: |
| 257 | num_tokens, hidden_dim = hidden_states.shape |
| 258 | hidden_states = hidden_states.view(-1, hidden_dim) |
| 259 | |
| 260 | if self.is_sequence_parallel: |
| 261 | hidden_states = sequence_parallel_chunk(hidden_states) |
| 262 | |
| 263 | # router_logits: (num_tokens, n_experts) |
| 264 | router_logits, _ = self.gate(hidden_states) |
| 265 | |
| 266 | final_hidden_states = self.experts( |
| 267 | hidden_states=hidden_states, router_logits=router_logits |
| 268 | ) |
| 269 | |
| 270 | if self.is_sequence_parallel: |
| 271 | final_hidden_states = tensor_model_parallel_all_gather( |
| 272 | final_hidden_states, 0 |
| 273 | ) |
| 274 | final_hidden_states = final_hidden_states[:num_tokens] |
| 275 | |
| 276 | return final_hidden_states.view(num_tokens, hidden_dim) |
| 277 | |
| 278 | |
| 279 | class NemotronHMLPDecoderLayer(nn.Module): |
| 280 | def __init__( |
| 281 | self, |
| 282 | config: NemotronHConfig, |
| 283 | layer_idx: int, |
| 284 | model_config: ModelConfig | None = None, |
| 285 | cache_config: CacheConfig | None = None, |
| 286 | quant_config: QuantizationConfig | None = None, |
| 287 | parallel_config: ParallelConfig | None = None, |
| 288 | prefix: str = "", |
| 289 | ) -> None: |
| 290 | super().__init__() |
| 291 | self.config = config |
| 292 | |
| 293 | hybrid_override_pattern = config.hybrid_override_pattern |
| 294 | mlp_index = hybrid_override_pattern[: layer_idx + 1].count("-") - 1 |
| 295 | # Get per-layer config for heterogeneous models if exist |
| 296 | get_layer_config = getattr(config, "get_nemotron_h_config_for_layer", None) |
| 297 | layer_config = get_layer_config(layer_idx) if get_layer_config else config |
| 298 | config = layer_config |
| 299 | |
| 300 | if isinstance(config.intermediate_size, list): |
| 301 | if len(config.intermediate_size) == 1: |
| 302 | intermediate_size = config.intermediate_size[0] |
| 303 | else: |
| 304 | intermediate_size = config.intermediate_size[mlp_index] |
| 305 | else: |
| 306 | intermediate_size = config.intermediate_size |
| 307 | |
| 308 | self.mixer = NemotronHMLP( |
| 309 | config, |
| 310 | hidden_size=config.hidden_size, |
| 311 | intermediate_size=intermediate_size, |
| 312 | quant_config=quant_config, |
| 313 | bias=config.mlp_bias, |
| 314 | prefix=f"{prefix}.mixer", |
| 315 | ) |
| 316 | |
| 317 | self.norm = RMSNorm(config.hidden_size, eps=config.layer_norm_epsilon) |
| 318 | |
| 319 | def forward( |
| 320 | self, |
| 321 | hidden_states: torch.Tensor, |
| 322 | residual: torch.Tensor | None, |
| 323 | **kwargs, |
| 324 | ): |
| 325 | if residual is None: |
| 326 | residual = hidden_states |
| 327 | hidden_states = self.norm(hidden_states) |
| 328 | else: |
| 329 | hidden_states, residual = self.norm(hidden_states, residual) |
| 330 | |
| 331 | hidden_states = self.mixer(hidden_states) |
| 332 | return hidden_states, residual |
| 333 | |
| 334 | |
| 335 | class NemotronHMoEDecoderLayer(nn.Module): |
| 336 | def __init__( |
| 337 | self, |
| 338 | config: NemotronHConfig, |
| 339 | layer_idx: int, |
| 340 | model_config: ModelConfig | None = None, |
| 341 | cache_config: CacheConfig | None = None, |
| 342 | quant_config: QuantizationConfig | None = None, |
| 343 | parallel_config: ParallelConfig | None = None, |
| 344 | prefix: str = "", |
| 345 | ) -> None: |
| 346 | super().__init__() |
| 347 | self.config = config |
| 348 | |
| 349 | # Get per-layer config for heterogeneous models if exists |
| 350 | get_layer_config = getattr(config, "get_nemotron_h_config_for_layer", None) |
| 351 | layer_config = get_layer_config(layer_idx) if get_layer_config else config |
| 352 | |
| 353 | self.mixer = NemotronHMoE( |
| 354 | layer_config, |
| 355 | quant_config=quant_config, |
| 356 | parallel_config=parallel_config, |
| 357 | prefix=f"{prefix}.mixer", |
| 358 | ) |
| 359 | |
| 360 | self.norm = RMSNorm(config.hidden_size, eps=config.layer_norm_epsilon) |
| 361 | |
| 362 | def forward( |
| 363 | self, |
| 364 | hidden_states: torch.Tensor, |
| 365 | residual: torch.Tensor | None, |
| 366 | **kwargs, |
| 367 | ): |
| 368 | if residual is None: |
| 369 | residual = hidden_states |
| 370 | hidden_states = self.norm(hidden_states) |
| 371 | else: |
| 372 | hidden_states, residual = self.norm(hidden_states, residual) |
| 373 | |
| 374 | hidden_states = self.mixer(hidden_states) |
| 375 | return hidden_states, residual |
| 376 | |
| 377 | |
| 378 | class NemotronHMambaDecoderLayer(nn.Module): |
| 379 | def __init__( |
| 380 | self, |
| 381 | config: NemotronHConfig, |
| 382 | layer_idx: int, |
| 383 | model_config: ModelConfig | None = None, |
| 384 | cache_config: CacheConfig | None = None, |
| 385 | quant_config: QuantizationConfig | None = None, |
| 386 | parallel_config: ParallelConfig | None = None, |
| 387 | prefix: str = "", |
| 388 | ) -> None: |
| 389 | super().__init__() |
| 390 | self.config = config |
| 391 | self.mixer = MambaMixer2( |
| 392 | hidden_size=config.hidden_size, |
| 393 | ssm_state_size=config.ssm_state_size, |
| 394 | conv_kernel_size=config.conv_kernel, |
| 395 | intermediate_size=config.mamba_num_heads * config.mamba_head_dim, |
| 396 | use_conv_bias=config.use_conv_bias, |
| 397 | use_bias=config.use_bias, |
| 398 | n_groups=config.n_groups, |
| 399 | num_heads=config.mamba_num_heads, |
| 400 | head_dim=config.mamba_head_dim, |
| 401 | rms_norm_eps=config.layer_norm_epsilon, |
| 402 | activation=config.mamba_hidden_act, |
| 403 | model_config=model_config, |
| 404 | cache_config=cache_config, |
| 405 | quant_config=quant_config, |
| 406 | prefix=f"{prefix}.mixer", |
| 407 | ) |
| 408 | |
| 409 | self.norm = RMSNorm(config.hidden_size, eps=config.layer_norm_epsilon) |
| 410 | |
| 411 | def forward( |
| 412 | self, |
| 413 | hidden_states: torch.Tensor, |
| 414 | residual: torch.Tensor | None, |
| 415 | **kwargs, |
| 416 | ): |
| 417 | if residual is None: |
| 418 | residual = hidden_states |
| 419 | hidden_states = self.norm(hidden_states) |
| 420 | else: |
| 421 | hidden_states, residual = self.norm(hidden_states, residual) |
| 422 | |
| 423 | output = self.mixer(hidden_states) |
| 424 | return output, residual |
| 425 | |
| 426 | |
| 427 | class NemotronHAttention(nn.Module): |
| 428 | def __init__( |
| 429 | self, |
| 430 | config: NemotronHConfig, |
| 431 | layer_idx: int, |
| 432 | model_config: ModelConfig | None = None, |
| 433 | cache_config: CacheConfig | None = None, |
| 434 | quant_config: QuantizationConfig | None = None, |
| 435 | prefix: str = "", |
| 436 | ) -> None: |
| 437 | super().__init__() |
| 438 | self.hidden_size = config.hidden_size |
| 439 | tp_size = get_tensor_model_parallel_world_size() |
| 440 | self.total_num_heads = config.num_attention_heads |
| 441 | assert self.total_num_heads % tp_size == 0 |
| 442 | self.num_heads = self.total_num_heads // tp_size |
| 443 | self.total_num_kv_heads = config.num_key_value_heads |
| 444 | if self.total_num_kv_heads >= tp_size: |
| 445 | # Number of KV heads is greater than TP size, so we partition |
| 446 | # the KV heads across multiple tensor parallel GPUs. |
| 447 | assert self.total_num_kv_heads % tp_size == 0 |
| 448 | else: |
| 449 | # Number of KV heads is less than TP size, so we replicate |
| 450 | # the KV heads across multiple tensor parallel GPUs. |
| 451 | assert tp_size % self.total_num_kv_heads == 0 |
| 452 | self.num_kv_heads = max(1, self.total_num_kv_heads // tp_size) |
| 453 | if hasattr(config, "head_dim") and config.head_dim is not None: |
| 454 | self.head_dim = config.head_dim |
| 455 | else: |
| 456 | self.head_dim = config.hidden_size // self.total_num_heads |
| 457 | self.q_size = self.num_heads * self.head_dim |
| 458 | self.kv_size = self.num_kv_heads * self.head_dim |
| 459 | self.scaling = self.head_dim**-0.5 |
| 460 | |
| 461 | self.qkv_proj = QKVParallelLinear( |
| 462 | config.hidden_size, |
| 463 | self.head_dim, |
| 464 | self.total_num_heads, |
| 465 | self.total_num_kv_heads, |
| 466 | bias=False, |
| 467 | quant_config=quant_config, |
| 468 | prefix=f"{prefix}.qkv_proj", |
| 469 | ) |
| 470 | self.o_proj = RowParallelLinear( |
| 471 | self.total_num_heads * self.head_dim, |
| 472 | config.hidden_size, |
| 473 | bias=False, |
| 474 | quant_config=quant_config, |
| 475 | prefix=f"{prefix}.o_proj", |
| 476 | ) |
| 477 | |
| 478 | # Get per-layer sliding window from config (for heterogeneous models) |
| 479 | sliding_window = getattr(config, "sliding_window", None) |
| 480 | |
| 481 | self.attn = Attention( |
| 482 | self.num_heads, |
| 483 | self.head_dim, |
| 484 | self.scaling, |
| 485 | num_kv_heads=self.num_kv_heads, |
| 486 | cache_config=cache_config, |
| 487 | quant_config=quant_config, |
| 488 | prefix=f"{prefix}.attn", |
| 489 | per_layer_sliding_window=sliding_window, |
| 490 | ) |
| 491 | |
| 492 | def forward( |
| 493 | self, |
| 494 | hidden_states: torch.Tensor, |
| 495 | **kwargs, |
| 496 | ) -> torch.Tensor: |
| 497 | qkv, _ = self.qkv_proj(hidden_states) |
| 498 | q, k, v = qkv.split([self.q_size, self.kv_size, self.kv_size], dim=-1) |
| 499 | attn_output = self.attn(q, k, v) |
| 500 | output, _ = self.o_proj(attn_output) |
| 501 | return output |
| 502 | |
| 503 | |
| 504 | class NemotronHAttentionDecoderLayer(nn.Module): |
| 505 | def __init__( |
| 506 | self, |
| 507 | config: NemotronHConfig, |
| 508 | layer_idx: int, |
| 509 | model_config: ModelConfig | None = None, |
| 510 | cache_config: CacheConfig | None = None, |
| 511 | quant_config: QuantizationConfig | None = None, |
| 512 | parallel_config: ParallelConfig | None = None, |
| 513 | prefix: str = "", |
| 514 | ) -> None: |
| 515 | super().__init__() |
| 516 | |
| 517 | # Get per-layer config for heterogeneous models if exists |
| 518 | get_layer_config = getattr(config, "get_nemotron_h_config_for_layer", None) |
| 519 | layer_config = get_layer_config(layer_idx) if get_layer_config else config |
| 520 | |
| 521 | self.mixer = NemotronHAttention( |
| 522 | layer_config, |
| 523 | layer_idx, |
| 524 | model_config, |
| 525 | cache_config, |
| 526 | quant_config, |
| 527 | prefix=f"{prefix}.mixer", |
| 528 | ) |
| 529 | |
| 530 | self.norm = RMSNorm(config.hidden_size, eps=config.layer_norm_epsilon) |
| 531 | |
| 532 | def forward( |
| 533 | self, |
| 534 | positions: torch.Tensor, |
| 535 | hidden_states: torch.Tensor, |
| 536 | residual: torch.Tensor | None, |
| 537 | **kwargs, |
| 538 | ): |
| 539 | if residual is None: |
| 540 | residual = hidden_states |
| 541 | hidden_states = self.norm(hidden_states) |
| 542 | else: |
| 543 | hidden_states, residual = self.norm(hidden_states, residual) |
| 544 | |
| 545 | hidden_states = self.mixer(hidden_states=hidden_states) |
| 546 | return hidden_states, residual |
| 547 | |
| 548 | |
| 549 | ALL_DECODER_LAYER_TYPES = { |
| 550 | "M": NemotronHMambaDecoderLayer, |
| 551 | "-": NemotronHMLPDecoderLayer, |
| 552 | "*": NemotronHAttentionDecoderLayer, |
| 553 | "E": NemotronHMoEDecoderLayer, |
| 554 | } |
| 555 | |
| 556 | |
| 557 | @support_torch_compile( |
| 558 | dynamic_arg_dims={ |
| 559 | "input_ids": 0, |
| 560 | "positions": -1, |
| 561 | "intermediate_tensors": 0, |
| 562 | "inputs_embeds": 0, |
| 563 | } |
| 564 | ) |
| 565 | class NemotronHModel(nn.Module, EagleModelMixin): |
| 566 | def __init__( |
| 567 | self, |
| 568 | *, |
| 569 | vllm_config: VllmConfig, |
| 570 | prefix: str = "", |
| 571 | decoder_layer_types: Mapping[str, type[nn.Module]] | None = None, |
| 572 | ): |
| 573 | super().__init__() |
| 574 | |
| 575 | config: NemotronHConfig = vllm_config.model_config.hf_config |
| 576 | model_config = vllm_config.model_config |
| 577 | cache_config = vllm_config.cache_config |
| 578 | quant_config = vllm_config.quant_config |
| 579 | parallel_config = vllm_config.parallel_config |
| 580 | |
| 581 | self.config = config |
| 582 | |
| 583 | self.vocab_size = config.vocab_size |
| 584 | |
| 585 | self.embed_tokens = VocabParallelEmbedding( |
| 586 | self.vocab_size, |
| 587 | config.hidden_size, |
| 588 | ) |
| 589 | |
| 590 | self.has_moe = "E" in config.hybrid_override_pattern |
| 591 | |
| 592 | layer_types = decoder_layer_types or ALL_DECODER_LAYER_TYPES |
| 593 | |
| 594 | def get_layer(prefix: str): |
| 595 | layer_idx = int(prefix.rsplit(".", 1)[1]) |
| 596 | layer_type = config.hybrid_override_pattern[layer_idx] |
| 597 | if layer_type not in layer_types: |
| 598 | raise ValueError( |
| 599 | f"Unsupported layer type {layer_type!r} at layer {layer_idx}" |
| 600 | ) |
| 601 | layer_class = layer_types[layer_type] |
| 602 | return layer_class( |
| 603 | config=config, |
| 604 | layer_idx=layer_idx, |
| 605 | model_config=model_config, |
| 606 | cache_config=cache_config, |
| 607 | quant_config=quant_config, |
| 608 | parallel_config=parallel_config, |
| 609 | prefix=prefix, |
| 610 | ) |
| 611 | |
| 612 | self.start_layer, self.end_layer, self.layers = make_layers( |
| 613 | len(config.hybrid_override_pattern), get_layer, prefix=f"{prefix}.layers" |
| 614 | ) |
| 615 | self.make_empty_intermediate_tensors = make_empty_intermediate_tensors_factory( |
| 616 | ["hidden_states", "residual"], config.hidden_size |
| 617 | ) |
| 618 | |
| 619 | self.norm_f = RMSNorm(config.hidden_size, eps=config.layer_norm_epsilon) |
| 620 | |
| 621 | def embed_input_ids(self, input_ids: torch.Tensor) -> torch.Tensor: |
| 622 | return self.embed_tokens(input_ids) |
| 623 | |
| 624 | def forward( |
| 625 | self, |
| 626 | input_ids: torch.Tensor | None, |
| 627 | positions: torch.Tensor, |
| 628 | intermediate_tensors: IntermediateTensors | None = None, |
| 629 | inputs_embeds: torch.Tensor | None = None, |
| 630 | ) -> torch.Tensor | IntermediateTensors: |
| 631 | if get_pp_group().is_first_rank: |
| 632 | if inputs_embeds is not None: |
| 633 | hidden_states = inputs_embeds |
| 634 | else: |
| 635 | hidden_states = self.embed_input_ids(input_ids) |
| 636 | residual = None |
| 637 | else: |
| 638 | assert intermediate_tensors is not None |
| 639 | hidden_states = intermediate_tensors["hidden_states"] |
| 640 | residual = intermediate_tensors["residual"] |
| 641 | |
| 642 | aux_hidden_states = self._maybe_add_hidden_state([], 0, hidden_states, residual) |
| 643 | for idx, layer in enumerate( |
| 644 | islice(self.layers, self.start_layer, self.end_layer) |
| 645 | ): |
| 646 | hidden_states, residual = layer( |
| 647 | positions=positions, |
| 648 | hidden_states=hidden_states, |
| 649 | residual=residual, |
| 650 | ) |
| 651 | self._maybe_add_hidden_state( |
| 652 | aux_hidden_states, idx + 1, hidden_states, residual |
| 653 | ) |
| 654 | |
| 655 | if not get_pp_group().is_last_rank: |
| 656 | return IntermediateTensors( |
| 657 | {"hidden_states": hidden_states, "residual": residual} |
| 658 | ) |
| 659 | hidden_states, _ = self.norm_f(hidden_states, residual) |
| 660 | |
| 661 | if len(aux_hidden_states) > 0: |
| 662 | return hidden_states, aux_hidden_states |
| 663 | return hidden_states |
| 664 | |
| 665 | def is_spec_layer(self, config: NemotronHConfig, weight_name: str) -> bool: |
| 666 | return weight_name.startswith("mtp.") |
| 667 | |
| 668 | def _get_max_n_routed_experts(self) -> int: |
| 669 | """Get max n_routed_experts from config or block_configs for puzzle models. |
| 670 | |
| 671 | For heterogeneous models with varying expert counts per layer, |
| 672 | returns the MAX to ensure all expert weights can be loaded. |
| 673 | """ |
| 674 | # First try top-level attribute |
| 675 | n_routed_experts = getattr(self.config, "n_routed_experts", None) |
| 676 | if n_routed_experts is not None: |
| 677 | return n_routed_experts |
| 678 | |
| 679 | # For puzzle models, get MAX from all MoE blocks in block_configs |
| 680 | # (different layers may have different expert counts) |
| 681 | max_experts = 0 |
| 682 | block_configs = getattr(self.config, "block_configs", None) |
| 683 | if block_configs: |
| 684 | for block in block_configs: |
| 685 | if isinstance(block, dict): |
| 686 | if block.get("block_type") == "moe": |
| 687 | max_experts = max(max_experts, block.get("n_routed_experts", 0)) |
| 688 | else: |
| 689 | # HF converts dicts to objects with attributes |
| 690 | if getattr(block, "block_type", "") == "moe": |
| 691 | max_experts = max( |
| 692 | max_experts, getattr(block, "n_routed_experts", 0) |
| 693 | ) |
| 694 | return max_experts |
| 695 | |
| 696 | def get_expert_mapping(self) -> list[tuple[str, str, int, str]]: |
| 697 | # Consumed by `get_moe_expert_mapping` (bitsandbytes / LoRA); the main |
| 698 | # weight load is self-served by each `RoutedExperts` layer. Sized to the |
| 699 | # MAX expert count so heterogeneous puzzle models load every expert. |
| 700 | if self.has_moe: |
| 701 | # (param_name, weight_name, expert_id, shard_id) |
| 702 | return fused_moe_make_expert_params_mapping( |
| 703 | # - FusedMoe.w1 (aka gate_proj) should be up_proj since that's |
| 704 | # what the activation is applied to |
| 705 | # - FusedMoe.w3 (aka up_proj) should be ignored since we're |
| 706 | # using non-gated MoE |
| 707 | self, |
| 708 | ckpt_gate_proj_name="up_proj", |
| 709 | ckpt_down_proj_name="down_proj", |
| 710 | ckpt_up_proj_name="", |
| 711 | num_experts=self._get_max_n_routed_experts(), |
| 712 | num_redundant_experts=getattr(self, "num_redundant_experts", 0), |
| 713 | ) |
| 714 | |
| 715 | return [] |
| 716 | |
| 717 | |
| 718 | class NemotronHForCausalLM( |
| 719 | nn.Module, |
| 720 | HasInnerState, |
| 721 | SupportsLoRA, |
| 722 | SupportsPP, |
| 723 | SupportsEagle, |
| 724 | SupportsEagle3, |
| 725 | IsHybrid, |
| 726 | SupportsQuant, |
| 727 | MixtureOfExperts, |
| 728 | SupportsMambaPrefixCaching, |
| 729 | SupportsReplaySSM, |
| 730 | ): |
| 731 | # Relevant only if self.has_moe is True |
| 732 | is_non_gated_moe = True |
| 733 | |
| 734 | hf_to_vllm_mapper = WeightsMapper( |
| 735 | orig_to_new_prefix={"backbone": "model", "mtp": None}, |
| 736 | orig_to_new_substr={"A_log": "A", "embeddings": "embed_tokens"}, |
| 737 | orig_to_new_stacked={ |
| 738 | ".q_proj": (".qkv_proj", "q"), |
| 739 | ".k_proj": (".qkv_proj", "k"), |
| 740 | ".v_proj": (".qkv_proj", "v"), |
| 741 | }, |
| 742 | ) |
| 743 | |
| 744 | packed_modules_mapping = { |
| 745 | "qkv_proj": [ |
| 746 | "q_proj", |
| 747 | "k_proj", |
| 748 | "v_proj", |
| 749 | ], |
| 750 | } |
| 751 | |
| 752 | # LoRA specific attributes |
| 753 | embedding_modules = { |
| 754 | "embed_tokens": "input_embeddings", |
| 755 | "lm_head": "output_embeddings", |
| 756 | } |
| 757 | |
| 758 | # Skip MTP (Multi-Token Prediction) layers during LoRA loading |
| 759 | lora_skip_prefixes = ["mtp."] |
| 760 | |
| 761 | @classmethod |
| 762 | def get_mamba_state_dtype_from_config( |
| 763 | cls, |
| 764 | vllm_config: "VllmConfig", |
| 765 | ) -> tuple[torch.dtype, ...]: |
| 766 | cache_config = vllm_config.cache_config |
| 767 | base_dtype = MambaStateDtypeCalculator.mamba2_state_dtype( |
| 768 | vllm_config.model_config.dtype, |
| 769 | cache_config.mamba_cache_dtype, |
| 770 | cache_config.mamba_ssm_cache_dtype, |
| 771 | ) |
| 772 | if cache_config.use_replayssm: |
| 773 | return MambaStateDtypeCalculator.append_replayssm_ring( |
| 774 | base_dtype, |
| 775 | vllm_config.model_config.dtype, |
| 776 | ) |
| 777 | return base_dtype |
| 778 | |
| 779 | @classmethod |
| 780 | def get_mamba_state_shape_from_config( |
| 781 | cls, |
| 782 | vllm_config: "VllmConfig", |
| 783 | ) -> MambaStateShapes: |
| 784 | """Calculate shapes for Mamba's convolutional and state caches. |
| 785 | |
| 786 | Args: |
| 787 | vllm_config: vLLM config |
| 788 | |
| 789 | Returns: |
| 790 | Tuple containing: |
| 791 | - conv_state_shape: Shape for convolutional state cache |
| 792 | - temporal_state_shape: Shape for state space model cache |
| 793 | - x_cache/dt_cache/B_cache ring-buffer shapes (use_replayssm only) |
| 794 | |
| 795 | """ |
| 796 | parallel_config = vllm_config.parallel_config |
| 797 | cache_config = vllm_config.cache_config |
| 798 | hf_config = vllm_config.model_config.hf_config |
| 799 | intermediate_size = hf_config.mamba_num_heads * hf_config.mamba_head_dim |
| 800 | |
| 801 | base_shape = MambaStateShapeCalculator.mamba2_state_shape( |
| 802 | intermediate_size=intermediate_size, |
| 803 | tp_world_size=parallel_config.tensor_parallel_size, |
| 804 | n_groups=hf_config.n_groups, |
| 805 | num_heads=hf_config.mamba_num_heads, |
| 806 | head_dim=hf_config.mamba_head_dim, |
| 807 | state_size=hf_config.ssm_state_size, |
| 808 | conv_kernel=hf_config.conv_kernel, |
| 809 | num_spec=vllm_config.num_speculative_tokens, |
| 810 | ) |
| 811 | if cache_config.use_replayssm: |
| 812 | return MambaStateShapeCalculator.append_replayssm_ring( |
| 813 | base_shapes=base_shape, |
| 814 | n_groups=hf_config.n_groups, |
| 815 | tp_world_size=parallel_config.tensor_parallel_size, |
| 816 | logical_window=cache_config.replayssm_buffer_len, |
| 817 | backend=vllm_config.mamba_config.backend, |
| 818 | num_speculative_tokens=vllm_config.num_speculative_tokens, |
| 819 | ) |
| 820 | return base_shape |
| 821 | |
| 822 | @classmethod |
| 823 | def get_mamba_state_copy_func(cls) -> tuple[MambaStateCopyFunc, MambaStateCopyFunc]: |
| 824 | return MambaStateCopyFuncCalculator.mamba2_state_copy_func() |
| 825 | |
| 826 | def __init__(self, *, vllm_config: VllmConfig, prefix: str = ""): |
| 827 | config = vllm_config.model_config.hf_config |
| 828 | self.vllm_config = vllm_config |
| 829 | self.model_config = vllm_config.model_config |
| 830 | |
| 831 | scheduler_config = vllm_config.scheduler_config |
| 832 | |
| 833 | self.quant_config = vllm_config.quant_config |
| 834 | |
| 835 | super().__init__() |
| 836 | self.config = config |
| 837 | self.scheduler_config = scheduler_config |
| 838 | self.model = NemotronHModel( |
| 839 | vllm_config=vllm_config, prefix=maybe_prefix(prefix, "model") |
| 840 | ) |
| 841 | |
| 842 | self.lm_head = ParallelLMHead( |
| 843 | config.vocab_size, |
| 844 | config.hidden_size, |
| 845 | quant_config=self.quant_config, |
| 846 | prefix=maybe_prefix(prefix, "lm_head"), |
| 847 | ) |
| 848 | |
| 849 | self.logits_processor = LogitsProcessor(config.vocab_size) |
| 850 | |
| 851 | self.make_empty_intermediate_tensors = ( |
| 852 | self.model.make_empty_intermediate_tensors |
| 853 | ) |
| 854 | |
| 855 | # Set MoE hyperparameters |
| 856 | if self.model.has_moe: |
| 857 | self.num_expert_groups = config.n_group |
| 858 | |
| 859 | self.moe_layers = [] |
| 860 | example_moe = None |
| 861 | for layer in self.model.layers: |
| 862 | if isinstance(layer, NemotronHMoEDecoderLayer): |
| 863 | # Pick last one layer since the first ones |
| 864 | # may be dense layers. |
| 865 | example_moe = layer.mixer |
| 866 | self.moe_layers.append(layer.mixer.experts) |
| 867 | |
| 868 | self.num_moe_layers = len(self.moe_layers) |
| 869 | assert example_moe is not None |
| 870 | self.num_logical_experts = example_moe.n_logical_experts |
| 871 | self.num_physical_experts = example_moe.n_physical_experts |
| 872 | self.num_local_physical_experts = example_moe.n_local_physical_experts # noqa: E501 |
| 873 | self.num_routed_experts = example_moe.n_routed_experts |
| 874 | self.num_shared_experts = example_moe.n_shared_experts |
| 875 | self.num_redundant_experts = example_moe.n_redundant_experts |
| 876 | |
| 877 | def update_physical_experts_metadata( |
| 878 | self, |
| 879 | num_physical_experts: int, |
| 880 | num_local_physical_experts: int, |
| 881 | ) -> None: |
| 882 | assert self.num_local_physical_experts == num_local_physical_experts |
| 883 | self.num_physical_experts = num_physical_experts |
| 884 | self.num_local_physical_experts = num_local_physical_experts |
| 885 | self.num_redundant_experts = num_physical_experts - self.num_logical_experts |
| 886 | for layer in self.model.layers: |
| 887 | if isinstance(layer, NemotronHMoEDecoderLayer): |
| 888 | moe = layer.mixer |
| 889 | moe.n_local_physical_experts = num_local_physical_experts |
| 890 | moe.n_physical_experts = num_physical_experts |
| 891 | moe.n_redundant_experts = self.num_redundant_experts |
| 892 | moe.experts.update_expert_map() |
| 893 | |
| 894 | def embed_input_ids(self, input_ids: torch.Tensor) -> torch.Tensor: |
| 895 | return self.model.embed_input_ids(input_ids) |
| 896 | |
| 897 | def forward( |
| 898 | self, |
| 899 | input_ids: torch.Tensor | None, |
| 900 | positions: torch.Tensor, |
| 901 | intermediate_tensors: IntermediateTensors | None = None, |
| 902 | inputs_embeds: torch.Tensor | None = None, |
| 903 | **kwargs, |
| 904 | ): |
| 905 | hidden_states = self.model( |
| 906 | input_ids, positions, intermediate_tensors, inputs_embeds |
| 907 | ) |
| 908 | |
| 909 | return hidden_states |
| 910 | |
| 911 | def compute_logits( |
| 912 | self, |
| 913 | hidden_states: torch.Tensor, |
| 914 | ) -> torch.Tensor | None: |
| 915 | logits = self.logits_processor(self.lm_head, hidden_states) |
| 916 | return logits |
| 917 | |
| 918 | def load_weights(self, weights: Iterable[tuple[str, torch.Tensor]]) -> set[str]: |
| 919 | loader = AutoWeightsLoader(self) |
| 920 | return loader.load_weights(weights, mapper=self.hf_to_vllm_mapper) |