Skip to content

vllm.model_executor.models.nemotron_h

Inference-only NemotronH model.

ALL_DECODER_LAYER_TYPES module-attribute

NemotronHAttention

Bases: Module

Source code in vllm/model_executor/models/nemotron_h.py
class NemotronHAttention(nn.Module):
    def __init__(
        self,
        config: NemotronHConfig,
        layer_idx: int,
        model_config: ModelConfig | None = None,
        cache_config: CacheConfig | None = None,
        quant_config: QuantizationConfig | None = None,
        prefix: str = "",
    ) -> None:
        super().__init__()
        self.hidden_size = config.hidden_size
        tp_size = get_tensor_model_parallel_world_size()
        self.total_num_heads = config.num_attention_heads
        assert self.total_num_heads % tp_size == 0
        self.num_heads = self.total_num_heads // tp_size
        self.total_num_kv_heads = config.num_key_value_heads
        if self.total_num_kv_heads >= tp_size:
            # Number of KV heads is greater than TP size, so we partition
            # the KV heads across multiple tensor parallel GPUs.
            assert self.total_num_kv_heads % tp_size == 0
        else:
            # Number of KV heads is less than TP size, so we replicate
            # the KV heads across multiple tensor parallel GPUs.
            assert tp_size % self.total_num_kv_heads == 0
        self.num_kv_heads = max(1, self.total_num_kv_heads // tp_size)
        if hasattr(config, "head_dim") and config.head_dim is not None:
            self.head_dim = config.head_dim
        else:
            self.head_dim = config.hidden_size // self.total_num_heads
        self.q_size = self.num_heads * self.head_dim
        self.kv_size = self.num_kv_heads * self.head_dim
        self.scaling = self.head_dim**-0.5

        self.qkv_proj = QKVParallelLinear(
            config.hidden_size,
            self.head_dim,
            self.total_num_heads,
            self.total_num_kv_heads,
            bias=False,
            quant_config=quant_config,
            prefix=f"{prefix}.qkv_proj",
        )
        self.o_proj = RowParallelLinear(
            self.total_num_heads * self.head_dim,
            config.hidden_size,
            bias=False,
            quant_config=quant_config,
            prefix=f"{prefix}.o_proj",
        )

        self.attn = Attention(
            self.num_heads,
            self.head_dim,
            self.scaling,
            num_kv_heads=self.num_kv_heads,
            cache_config=cache_config,
            prefix=f"{prefix}.attn",
        )

    def forward(
        self,
        hidden_states: torch.Tensor,
        **kwargs,
    ) -> torch.Tensor:
        qkv, _ = self.qkv_proj(hidden_states)
        q, k, v = qkv.split([self.q_size, self.kv_size, self.kv_size], dim=-1)
        attn_output = self.attn(q, k, v)
        output, _ = self.o_proj(attn_output)
        return output

attn instance-attribute

attn = Attention(
    num_heads,
    head_dim,
    scaling,
    num_kv_heads=num_kv_heads,
    cache_config=cache_config,
    prefix=f"{prefix}.attn",
)

head_dim instance-attribute

head_dim = head_dim

hidden_size instance-attribute

hidden_size = hidden_size

kv_size instance-attribute

kv_size = num_kv_heads * head_dim

num_heads instance-attribute

num_heads = total_num_heads // tp_size

num_kv_heads instance-attribute

num_kv_heads = max(1, total_num_kv_heads // tp_size)

o_proj instance-attribute

o_proj = RowParallelLinear(
    total_num_heads * head_dim,
    hidden_size,
    bias=False,
    quant_config=quant_config,
    prefix=f"{prefix}.o_proj",
)

q_size instance-attribute

q_size = num_heads * head_dim

qkv_proj instance-attribute

qkv_proj = QKVParallelLinear(
    hidden_size,
    head_dim,
    total_num_heads,
    total_num_kv_heads,
    bias=False,
    quant_config=quant_config,
    prefix=f"{prefix}.qkv_proj",
)

scaling instance-attribute

scaling = head_dim ** -0.5

total_num_heads instance-attribute

total_num_heads = num_attention_heads

total_num_kv_heads instance-attribute

total_num_kv_heads = num_key_value_heads

__init__

__init__(
    config: NemotronHConfig,
    layer_idx: int,
    model_config: ModelConfig | None = None,
    cache_config: CacheConfig | None = None,
    quant_config: QuantizationConfig | None = None,
    prefix: str = "",
) -> None
Source code in vllm/model_executor/models/nemotron_h.py
def __init__(
    self,
    config: NemotronHConfig,
    layer_idx: int,
    model_config: ModelConfig | None = None,
    cache_config: CacheConfig | None = None,
    quant_config: QuantizationConfig | None = None,
    prefix: str = "",
) -> None:
    super().__init__()
    self.hidden_size = config.hidden_size
    tp_size = get_tensor_model_parallel_world_size()
    self.total_num_heads = config.num_attention_heads
    assert self.total_num_heads % tp_size == 0
    self.num_heads = self.total_num_heads // tp_size
    self.total_num_kv_heads = config.num_key_value_heads
    if self.total_num_kv_heads >= tp_size:
        # Number of KV heads is greater than TP size, so we partition
        # the KV heads across multiple tensor parallel GPUs.
        assert self.total_num_kv_heads % tp_size == 0
    else:
        # Number of KV heads is less than TP size, so we replicate
        # the KV heads across multiple tensor parallel GPUs.
        assert tp_size % self.total_num_kv_heads == 0
    self.num_kv_heads = max(1, self.total_num_kv_heads // tp_size)
    if hasattr(config, "head_dim") and config.head_dim is not None:
        self.head_dim = config.head_dim
    else:
        self.head_dim = config.hidden_size // self.total_num_heads
    self.q_size = self.num_heads * self.head_dim
    self.kv_size = self.num_kv_heads * self.head_dim
    self.scaling = self.head_dim**-0.5

    self.qkv_proj = QKVParallelLinear(
        config.hidden_size,
        self.head_dim,
        self.total_num_heads,
        self.total_num_kv_heads,
        bias=False,
        quant_config=quant_config,
        prefix=f"{prefix}.qkv_proj",
    )
    self.o_proj = RowParallelLinear(
        self.total_num_heads * self.head_dim,
        config.hidden_size,
        bias=False,
        quant_config=quant_config,
        prefix=f"{prefix}.o_proj",
    )

    self.attn = Attention(
        self.num_heads,
        self.head_dim,
        self.scaling,
        num_kv_heads=self.num_kv_heads,
        cache_config=cache_config,
        prefix=f"{prefix}.attn",
    )

forward

forward(hidden_states: Tensor, **kwargs) -> Tensor
Source code in vllm/model_executor/models/nemotron_h.py
def forward(
    self,
    hidden_states: torch.Tensor,
    **kwargs,
) -> torch.Tensor:
    qkv, _ = self.qkv_proj(hidden_states)
    q, k, v = qkv.split([self.q_size, self.kv_size, self.kv_size], dim=-1)
    attn_output = self.attn(q, k, v)
    output, _ = self.o_proj(attn_output)
    return output

NemotronHAttentionDecoderLayer

Bases: Module

Source code in vllm/model_executor/models/nemotron_h.py
class NemotronHAttentionDecoderLayer(nn.Module):
    def __init__(
        self,
        config: NemotronHConfig,
        layer_idx: int,
        model_config: ModelConfig | None = None,
        cache_config: CacheConfig | None = None,
        quant_config: QuantizationConfig | None = None,
        parallel_config: ParallelConfig | None = None,
        prefix: str = "",
    ) -> None:
        super().__init__()

        self.mixer = NemotronHAttention(
            config,
            layer_idx,
            model_config,
            cache_config,
            quant_config,
            prefix=f"{prefix}.mixer",
        )

        self.norm = RMSNorm(config.hidden_size, eps=config.layer_norm_epsilon)

    def forward(
        self,
        positions: torch.Tensor,
        hidden_states: torch.Tensor,
        residual: torch.Tensor | None,
        **kwargs,
    ):
        if residual is None:
            residual = hidden_states
            hidden_states = self.norm(hidden_states)
        else:
            hidden_states, residual = self.norm(hidden_states, residual)

        hidden_states = self.mixer(hidden_states=hidden_states)
        return hidden_states, residual

mixer instance-attribute

mixer = NemotronHAttention(
    config,
    layer_idx,
    model_config,
    cache_config,
    quant_config,
    prefix=f"{prefix}.mixer",
)

norm instance-attribute

norm = RMSNorm(hidden_size, eps=layer_norm_epsilon)

__init__

__init__(
    config: NemotronHConfig,
    layer_idx: int,
    model_config: ModelConfig | None = None,
    cache_config: CacheConfig | None = None,
    quant_config: QuantizationConfig | None = None,
    parallel_config: ParallelConfig | None = None,
    prefix: str = "",
) -> None
Source code in vllm/model_executor/models/nemotron_h.py
def __init__(
    self,
    config: NemotronHConfig,
    layer_idx: int,
    model_config: ModelConfig | None = None,
    cache_config: CacheConfig | None = None,
    quant_config: QuantizationConfig | None = None,
    parallel_config: ParallelConfig | None = None,
    prefix: str = "",
) -> None:
    super().__init__()

    self.mixer = NemotronHAttention(
        config,
        layer_idx,
        model_config,
        cache_config,
        quant_config,
        prefix=f"{prefix}.mixer",
    )

    self.norm = RMSNorm(config.hidden_size, eps=config.layer_norm_epsilon)

forward

forward(
    positions: Tensor,
    hidden_states: Tensor,
    residual: Tensor | None,
    **kwargs,
)
Source code in vllm/model_executor/models/nemotron_h.py
def forward(
    self,
    positions: torch.Tensor,
    hidden_states: torch.Tensor,
    residual: torch.Tensor | None,
    **kwargs,
):
    if residual is None:
        residual = hidden_states
        hidden_states = self.norm(hidden_states)
    else:
        hidden_states, residual = self.norm(hidden_states, residual)

    hidden_states = self.mixer(hidden_states=hidden_states)
    return hidden_states, residual

NemotronHForCausalLM

Bases: Module, HasInnerState, SupportsLoRA, SupportsPP, IsHybrid, SupportsQuant, MixtureOfExperts

Source code in vllm/model_executor/models/nemotron_h.py
class NemotronHForCausalLM(
    nn.Module,
    HasInnerState,
    SupportsLoRA,
    SupportsPP,
    IsHybrid,
    SupportsQuant,
    MixtureOfExperts,
):
    hf_to_vllm_mapper = WeightsMapper(
        orig_to_new_prefix={"backbone": "model"},
        orig_to_new_substr={"A_log": "A", "embeddings": "embed_tokens"},
    )

    packed_modules_mapping = {
        "qkv_proj": [
            "q_proj",
            "k_proj",
            "v_proj",
        ],
    }

    # LoRA specific attributes
    embedding_modules = {
        "embed_tokens": "input_embeddings",
        "lm_head": "output_embeddings",
    }
    embedding_padding_modules = ["lm_head"]

    @classmethod
    def get_mamba_state_dtype_from_config(
        cls,
        vllm_config: "VllmConfig",
    ) -> tuple[torch.dtype, torch.dtype]:
        return MambaStateDtypeCalculator.mamba2_state_dtype(
            vllm_config.model_config.dtype,
            vllm_config.cache_config.mamba_cache_dtype,
            vllm_config.cache_config.mamba_ssm_cache_dtype,
        )

    @classmethod
    def get_mamba_state_shape_from_config(
        cls,
        vllm_config: "VllmConfig",
    ) -> tuple[tuple[int, int], tuple[int, int, int]]:
        """Calculate shapes for Mamba's convolutional and state caches.

        Args:
            vllm_config: vLLM config

        Returns:
            Tuple containing:
            - conv_state_shape: Shape for convolutional state cache
            - temporal_state_shape: Shape for state space model cache
        """
        parallel_config = vllm_config.parallel_config
        hf_config = vllm_config.model_config.hf_config
        intermediate_size = hf_config.mamba_num_heads * hf_config.mamba_head_dim

        return MambaStateShapeCalculator.mamba2_state_shape(
            intermediate_size=intermediate_size,
            tp_world_size=parallel_config.tensor_parallel_size,
            n_groups=hf_config.n_groups,
            num_heads=hf_config.mamba_num_heads,
            head_dim=hf_config.mamba_head_dim,
            state_size=hf_config.ssm_state_size,
            conv_kernel=hf_config.conv_kernel,
        )

    def __init__(self, *, vllm_config: VllmConfig, prefix: str = ""):
        config = vllm_config.model_config.hf_config
        self.vllm_config = vllm_config
        self.model_config = vllm_config.model_config
        lora_config = vllm_config.lora_config
        scheduler_config = vllm_config.scheduler_config

        self.quant_config = vllm_config.quant_config

        super().__init__()
        self.config = config
        self.scheduler_config = scheduler_config
        self.model = NemotronHModel(
            vllm_config=vllm_config, prefix=maybe_prefix(prefix, "model")
        )
        self.unpadded_vocab_size = config.vocab_size
        if lora_config:
            self.unpadded_vocab_size += lora_config.lora_extra_vocab_size
        self.lm_head = ParallelLMHead(
            self.unpadded_vocab_size,
            config.hidden_size,
            org_num_embeddings=config.vocab_size,
            padding_size=DEFAULT_VOCAB_PADDING_SIZE
            # We need bigger padding if using lora for kernel
            # compatibility
            if not lora_config
            else lora_config.lora_vocab_padding_size,
            prefix=maybe_prefix(prefix, "lm_head"),
        )

        self.logits_processor = LogitsProcessor(
            self.unpadded_vocab_size, config.vocab_size
        )

        self.make_empty_intmd_tensors = self.model.make_empty_intmd_tensors

        # Set MoE hyperparameters
        if self.model.has_moe:
            self.expert_weights = []
            self.num_expert_groups = config.n_group

            self.moe_layers: list[SharedFusedMoE] = []
            example_moe = None
            for layer in self.model.layers:
                if isinstance(layer, NemotronHMoEDecoderLayer):
                    # Pick last one layer since the first ones
                    # may be dense layers.
                    example_moe = layer.mixer
                    self.moe_layers.append(layer.mixer.experts)

            self.num_moe_layers = len(self.moe_layers)
            self.num_logical_experts = example_moe.n_logical_experts
            self.num_physical_experts = example_moe.n_physical_experts
            self.num_local_physical_experts = example_moe.n_local_physical_experts  # noqa: E501
            self.num_routed_experts = example_moe.n_routed_experts
            self.num_shared_experts = example_moe.n_shared_experts
            self.num_redundant_experts = example_moe.n_redundant_experts

    def set_eplb_state(
        self,
        expert_load_view: torch.Tensor,
        logical_to_physical_map: torch.Tensor,
        logical_replica_count: torch.Tensor,
    ) -> None:
        for layer_idx, layer in enumerate(self.moe_layers):
            # Register the expert weights.
            self.expert_weights.append(layer.get_expert_weights())
            layer.set_eplb_state(
                moe_layer_idx=layer_idx,
                expert_load_view=expert_load_view,
                logical_to_physical_map=logical_to_physical_map,
                logical_replica_count=logical_replica_count,
            )

    def update_physical_experts_metadata(
        self,
        num_physical_experts: int,
        num_local_physical_experts: int,
    ) -> None:
        assert self.num_local_physical_experts == num_local_physical_experts
        self.num_physical_experts = num_physical_experts
        self.num_local_physical_experts = num_local_physical_experts
        self.num_redundant_experts = num_physical_experts - self.num_logical_experts
        for layer in self.model.layers:
            if isinstance(layer, NemotronHMoEDecoderLayer):
                moe = layer.mixer
                moe.n_local_physical_experts = num_local_physical_experts
                moe.n_physical_experts = num_physical_experts
                moe.n_redundant_experts = self.num_redundant_experts
                moe.experts.update_expert_map()

    def get_input_embeddings(self, input_ids: torch.Tensor) -> torch.Tensor:
        return self.model.get_input_embeddings(input_ids)

    def forward(
        self,
        input_ids: torch.Tensor,
        positions: torch.Tensor,
        intermediate_tensors: IntermediateTensors | None = None,
        inputs_embeds: torch.Tensor | None = None,
        **kwargs,
    ):
        hidden_states = self.model(
            input_ids, positions, intermediate_tensors, inputs_embeds
        )

        return hidden_states

    def compute_logits(
        self,
        hidden_states: torch.Tensor,
    ) -> torch.Tensor | None:
        logits = self.logits_processor(self.lm_head, hidden_states)
        return logits

    def load_weights(self, weights: Iterable[tuple[str, torch.Tensor]]) -> set[str]:
        loader = AutoWeightsLoader(self)
        return loader.load_weights(weights, mapper=self.hf_to_vllm_mapper)

config instance-attribute

config = config

embedding_modules class-attribute instance-attribute

embedding_modules = {
    "embed_tokens": "input_embeddings",
    "lm_head": "output_embeddings",
}

embedding_padding_modules class-attribute instance-attribute

embedding_padding_modules = ['lm_head']

expert_weights instance-attribute

expert_weights = []

hf_to_vllm_mapper class-attribute instance-attribute

hf_to_vllm_mapper = WeightsMapper(
    orig_to_new_prefix={"backbone": "model"},
    orig_to_new_substr={
        "A_log": "A",
        "embeddings": "embed_tokens",
    },
)

lm_head instance-attribute

lm_head = ParallelLMHead(
    unpadded_vocab_size,
    hidden_size,
    org_num_embeddings=vocab_size,
    padding_size=DEFAULT_VOCAB_PADDING_SIZE
    if not lora_config
    else lora_vocab_padding_size,
    prefix=maybe_prefix(prefix, "lm_head"),
)

logits_processor instance-attribute

logits_processor = LogitsProcessor(
    unpadded_vocab_size, vocab_size
)

make_empty_intmd_tensors instance-attribute

make_empty_intmd_tensors = make_empty_intmd_tensors

model instance-attribute

model = NemotronHModel(
    vllm_config=vllm_config,
    prefix=maybe_prefix(prefix, "model"),
)

model_config instance-attribute

model_config = model_config

moe_layers instance-attribute

moe_layers: list[SharedFusedMoE] = []

num_expert_groups instance-attribute

num_expert_groups = n_group

num_local_physical_experts instance-attribute

num_local_physical_experts = n_local_physical_experts

num_logical_experts instance-attribute

num_logical_experts = n_logical_experts

num_moe_layers instance-attribute

num_moe_layers = len(moe_layers)

num_physical_experts instance-attribute

num_physical_experts = n_physical_experts

num_redundant_experts instance-attribute

num_redundant_experts = n_redundant_experts

num_routed_experts instance-attribute

num_routed_experts = n_routed_experts

num_shared_experts instance-attribute

num_shared_experts = n_shared_experts

packed_modules_mapping class-attribute instance-attribute

packed_modules_mapping = {
    "qkv_proj": ["q_proj", "k_proj", "v_proj"]
}

quant_config instance-attribute

quant_config = quant_config

scheduler_config instance-attribute

scheduler_config = scheduler_config

unpadded_vocab_size instance-attribute

unpadded_vocab_size = vocab_size

vllm_config instance-attribute

vllm_config = vllm_config

__init__

__init__(*, vllm_config: VllmConfig, prefix: str = '')
Source code in vllm/model_executor/models/nemotron_h.py
def __init__(self, *, vllm_config: VllmConfig, prefix: str = ""):
    config = vllm_config.model_config.hf_config
    self.vllm_config = vllm_config
    self.model_config = vllm_config.model_config
    lora_config = vllm_config.lora_config
    scheduler_config = vllm_config.scheduler_config

    self.quant_config = vllm_config.quant_config

    super().__init__()
    self.config = config
    self.scheduler_config = scheduler_config
    self.model = NemotronHModel(
        vllm_config=vllm_config, prefix=maybe_prefix(prefix, "model")
    )
    self.unpadded_vocab_size = config.vocab_size
    if lora_config:
        self.unpadded_vocab_size += lora_config.lora_extra_vocab_size
    self.lm_head = ParallelLMHead(
        self.unpadded_vocab_size,
        config.hidden_size,
        org_num_embeddings=config.vocab_size,
        padding_size=DEFAULT_VOCAB_PADDING_SIZE
        # We need bigger padding if using lora for kernel
        # compatibility
        if not lora_config
        else lora_config.lora_vocab_padding_size,
        prefix=maybe_prefix(prefix, "lm_head"),
    )

    self.logits_processor = LogitsProcessor(
        self.unpadded_vocab_size, config.vocab_size
    )

    self.make_empty_intmd_tensors = self.model.make_empty_intmd_tensors

    # Set MoE hyperparameters
    if self.model.has_moe:
        self.expert_weights = []
        self.num_expert_groups = config.n_group

        self.moe_layers: list[SharedFusedMoE] = []
        example_moe = None
        for layer in self.model.layers:
            if isinstance(layer, NemotronHMoEDecoderLayer):
                # Pick last one layer since the first ones
                # may be dense layers.
                example_moe = layer.mixer
                self.moe_layers.append(layer.mixer.experts)

        self.num_moe_layers = len(self.moe_layers)
        self.num_logical_experts = example_moe.n_logical_experts
        self.num_physical_experts = example_moe.n_physical_experts
        self.num_local_physical_experts = example_moe.n_local_physical_experts  # noqa: E501
        self.num_routed_experts = example_moe.n_routed_experts
        self.num_shared_experts = example_moe.n_shared_experts
        self.num_redundant_experts = example_moe.n_redundant_experts

compute_logits

compute_logits(hidden_states: Tensor) -> Tensor | None
Source code in vllm/model_executor/models/nemotron_h.py
def compute_logits(
    self,
    hidden_states: torch.Tensor,
) -> torch.Tensor | None:
    logits = self.logits_processor(self.lm_head, hidden_states)
    return logits

forward

forward(
    input_ids: Tensor,
    positions: Tensor,
    intermediate_tensors: IntermediateTensors | None = None,
    inputs_embeds: Tensor | None = None,
    **kwargs,
)
Source code in vllm/model_executor/models/nemotron_h.py
def forward(
    self,
    input_ids: torch.Tensor,
    positions: torch.Tensor,
    intermediate_tensors: IntermediateTensors | None = None,
    inputs_embeds: torch.Tensor | None = None,
    **kwargs,
):
    hidden_states = self.model(
        input_ids, positions, intermediate_tensors, inputs_embeds
    )

    return hidden_states

get_input_embeddings

get_input_embeddings(input_ids: Tensor) -> Tensor
Source code in vllm/model_executor/models/nemotron_h.py
def get_input_embeddings(self, input_ids: torch.Tensor) -> torch.Tensor:
    return self.model.get_input_embeddings(input_ids)

get_mamba_state_dtype_from_config classmethod

get_mamba_state_dtype_from_config(
    vllm_config: VllmConfig,
) -> tuple[dtype, dtype]
Source code in vllm/model_executor/models/nemotron_h.py
@classmethod
def get_mamba_state_dtype_from_config(
    cls,
    vllm_config: "VllmConfig",
) -> tuple[torch.dtype, torch.dtype]:
    return MambaStateDtypeCalculator.mamba2_state_dtype(
        vllm_config.model_config.dtype,
        vllm_config.cache_config.mamba_cache_dtype,
        vllm_config.cache_config.mamba_ssm_cache_dtype,
    )

get_mamba_state_shape_from_config classmethod

get_mamba_state_shape_from_config(
    vllm_config: VllmConfig,
) -> tuple[tuple[int, int], tuple[int, int, int]]

Calculate shapes for Mamba's convolutional and state caches.

Parameters:

Name Type Description Default
vllm_config VllmConfig

vLLM config

required

Returns:

Type Description
tuple[int, int]

Tuple containing:

tuple[int, int, int]
  • conv_state_shape: Shape for convolutional state cache
tuple[tuple[int, int], tuple[int, int, int]]
  • temporal_state_shape: Shape for state space model cache
Source code in vllm/model_executor/models/nemotron_h.py
@classmethod
def get_mamba_state_shape_from_config(
    cls,
    vllm_config: "VllmConfig",
) -> tuple[tuple[int, int], tuple[int, int, int]]:
    """Calculate shapes for Mamba's convolutional and state caches.

    Args:
        vllm_config: vLLM config

    Returns:
        Tuple containing:
        - conv_state_shape: Shape for convolutional state cache
        - temporal_state_shape: Shape for state space model cache
    """
    parallel_config = vllm_config.parallel_config
    hf_config = vllm_config.model_config.hf_config
    intermediate_size = hf_config.mamba_num_heads * hf_config.mamba_head_dim

    return MambaStateShapeCalculator.mamba2_state_shape(
        intermediate_size=intermediate_size,
        tp_world_size=parallel_config.tensor_parallel_size,
        n_groups=hf_config.n_groups,
        num_heads=hf_config.mamba_num_heads,
        head_dim=hf_config.mamba_head_dim,
        state_size=hf_config.ssm_state_size,
        conv_kernel=hf_config.conv_kernel,
    )

load_weights

load_weights(
    weights: Iterable[tuple[str, Tensor]],
) -> set[str]
Source code in vllm/model_executor/models/nemotron_h.py
def load_weights(self, weights: Iterable[tuple[str, torch.Tensor]]) -> set[str]:
    loader = AutoWeightsLoader(self)
    return loader.load_weights(weights, mapper=self.hf_to_vllm_mapper)

set_eplb_state

set_eplb_state(
    expert_load_view: Tensor,
    logical_to_physical_map: Tensor,
    logical_replica_count: Tensor,
) -> None
Source code in vllm/model_executor/models/nemotron_h.py
def set_eplb_state(
    self,
    expert_load_view: torch.Tensor,
    logical_to_physical_map: torch.Tensor,
    logical_replica_count: torch.Tensor,
) -> None:
    for layer_idx, layer in enumerate(self.moe_layers):
        # Register the expert weights.
        self.expert_weights.append(layer.get_expert_weights())
        layer.set_eplb_state(
            moe_layer_idx=layer_idx,
            expert_load_view=expert_load_view,
            logical_to_physical_map=logical_to_physical_map,
            logical_replica_count=logical_replica_count,
        )

update_physical_experts_metadata

update_physical_experts_metadata(
    num_physical_experts: int,
    num_local_physical_experts: int,
) -> None
Source code in vllm/model_executor/models/nemotron_h.py
def update_physical_experts_metadata(
    self,
    num_physical_experts: int,
    num_local_physical_experts: int,
) -> None:
    assert self.num_local_physical_experts == num_local_physical_experts
    self.num_physical_experts = num_physical_experts
    self.num_local_physical_experts = num_local_physical_experts
    self.num_redundant_experts = num_physical_experts - self.num_logical_experts
    for layer in self.model.layers:
        if isinstance(layer, NemotronHMoEDecoderLayer):
            moe = layer.mixer
            moe.n_local_physical_experts = num_local_physical_experts
            moe.n_physical_experts = num_physical_experts
            moe.n_redundant_experts = self.num_redundant_experts
            moe.experts.update_expert_map()

NemotronHMLP

Bases: Module

Source code in vllm/model_executor/models/nemotron_h.py
class NemotronHMLP(nn.Module):
    def __init__(
        self,
        config: NemotronHConfig,
        intermediate_size: int,
        quant_config: QuantizationConfig | None = None,
        bias: bool = False,
        reduce_results: bool = True,
        is_sequence_parallel: bool = False,
        prefix: str = "",
    ) -> None:
        super().__init__()

        self.up_proj = ColumnParallelLinear(
            input_size=config.hidden_size,
            output_size=intermediate_size,
            bias=bias,
            quant_config=quant_config,
            disable_tp=is_sequence_parallel,
            prefix=f"{prefix}.up_proj",
        )
        self.down_proj = RowParallelLinear(
            input_size=intermediate_size,
            output_size=config.hidden_size,
            bias=bias,
            quant_config=quant_config,
            reduce_results=reduce_results,
            disable_tp=is_sequence_parallel,
            prefix=f"{prefix}.down_proj",
        )
        self.act_fn = ReLUSquaredActivation()

    def forward(self, x: torch.Tensor):
        x, _ = self.up_proj(x)
        x = self.act_fn(x)
        x, _ = self.down_proj(x)
        return x

act_fn instance-attribute

down_proj instance-attribute

down_proj = RowParallelLinear(
    input_size=intermediate_size,
    output_size=hidden_size,
    bias=bias,
    quant_config=quant_config,
    reduce_results=reduce_results,
    disable_tp=is_sequence_parallel,
    prefix=f"{prefix}.down_proj",
)

up_proj instance-attribute

up_proj = ColumnParallelLinear(
    input_size=hidden_size,
    output_size=intermediate_size,
    bias=bias,
    quant_config=quant_config,
    disable_tp=is_sequence_parallel,
    prefix=f"{prefix}.up_proj",
)

__init__

__init__(
    config: NemotronHConfig,
    intermediate_size: int,
    quant_config: QuantizationConfig | None = None,
    bias: bool = False,
    reduce_results: bool = True,
    is_sequence_parallel: bool = False,
    prefix: str = "",
) -> None
Source code in vllm/model_executor/models/nemotron_h.py
def __init__(
    self,
    config: NemotronHConfig,
    intermediate_size: int,
    quant_config: QuantizationConfig | None = None,
    bias: bool = False,
    reduce_results: bool = True,
    is_sequence_parallel: bool = False,
    prefix: str = "",
) -> None:
    super().__init__()

    self.up_proj = ColumnParallelLinear(
        input_size=config.hidden_size,
        output_size=intermediate_size,
        bias=bias,
        quant_config=quant_config,
        disable_tp=is_sequence_parallel,
        prefix=f"{prefix}.up_proj",
    )
    self.down_proj = RowParallelLinear(
        input_size=intermediate_size,
        output_size=config.hidden_size,
        bias=bias,
        quant_config=quant_config,
        reduce_results=reduce_results,
        disable_tp=is_sequence_parallel,
        prefix=f"{prefix}.down_proj",
    )
    self.act_fn = ReLUSquaredActivation()

forward

forward(x: Tensor)
Source code in vllm/model_executor/models/nemotron_h.py
def forward(self, x: torch.Tensor):
    x, _ = self.up_proj(x)
    x = self.act_fn(x)
    x, _ = self.down_proj(x)
    return x

NemotronHMLPDecoderLayer

Bases: Module

Source code in vllm/model_executor/models/nemotron_h.py
class NemotronHMLPDecoderLayer(nn.Module):
    def __init__(
        self,
        config: NemotronHConfig,
        layer_idx: int,
        model_config: ModelConfig | None = None,
        cache_config: CacheConfig | None = None,
        quant_config: QuantizationConfig | None = None,
        parallel_config: ParallelConfig | None = None,
        prefix: str = "",
    ) -> None:
        super().__init__()
        self.config = config

        hybrid_override_pattern = config.hybrid_override_pattern
        mlp_index = hybrid_override_pattern[: layer_idx + 1].count("-") - 1
        if isinstance(config.intermediate_size, list):
            if len(config.intermediate_size) == 1:
                intermediate_size = config.intermediate_size[0]
            else:
                intermediate_size = config.intermediate_size[mlp_index]
        else:
            intermediate_size = config.intermediate_size

        self.mixer = NemotronHMLP(
            config,
            intermediate_size=intermediate_size,
            quant_config=quant_config,
            bias=config.mlp_bias,
            prefix=f"{prefix}.mixer",
        )

        self.norm = RMSNorm(config.hidden_size, eps=config.layer_norm_epsilon)

    def forward(
        self,
        hidden_states: torch.Tensor,
        residual: torch.Tensor | None,
        **kwargs,
    ):
        if residual is None:
            residual = hidden_states
            hidden_states = self.norm(hidden_states)
        else:
            hidden_states, residual = self.norm(hidden_states, residual)

        hidden_states = self.mixer(hidden_states)
        return hidden_states, residual

config instance-attribute

config = config

mixer instance-attribute

mixer = NemotronHMLP(
    config,
    intermediate_size=intermediate_size,
    quant_config=quant_config,
    bias=mlp_bias,
    prefix=f"{prefix}.mixer",
)

norm instance-attribute

norm = RMSNorm(hidden_size, eps=layer_norm_epsilon)

__init__

__init__(
    config: NemotronHConfig,
    layer_idx: int,
    model_config: ModelConfig | None = None,
    cache_config: CacheConfig | None = None,
    quant_config: QuantizationConfig | None = None,
    parallel_config: ParallelConfig | None = None,
    prefix: str = "",
) -> None
Source code in vllm/model_executor/models/nemotron_h.py
def __init__(
    self,
    config: NemotronHConfig,
    layer_idx: int,
    model_config: ModelConfig | None = None,
    cache_config: CacheConfig | None = None,
    quant_config: QuantizationConfig | None = None,
    parallel_config: ParallelConfig | None = None,
    prefix: str = "",
) -> None:
    super().__init__()
    self.config = config

    hybrid_override_pattern = config.hybrid_override_pattern
    mlp_index = hybrid_override_pattern[: layer_idx + 1].count("-") - 1
    if isinstance(config.intermediate_size, list):
        if len(config.intermediate_size) == 1:
            intermediate_size = config.intermediate_size[0]
        else:
            intermediate_size = config.intermediate_size[mlp_index]
    else:
        intermediate_size = config.intermediate_size

    self.mixer = NemotronHMLP(
        config,
        intermediate_size=intermediate_size,
        quant_config=quant_config,
        bias=config.mlp_bias,
        prefix=f"{prefix}.mixer",
    )

    self.norm = RMSNorm(config.hidden_size, eps=config.layer_norm_epsilon)

forward

forward(
    hidden_states: Tensor, residual: Tensor | None, **kwargs
)
Source code in vllm/model_executor/models/nemotron_h.py
def forward(
    self,
    hidden_states: torch.Tensor,
    residual: torch.Tensor | None,
    **kwargs,
):
    if residual is None:
        residual = hidden_states
        hidden_states = self.norm(hidden_states)
    else:
        hidden_states, residual = self.norm(hidden_states, residual)

    hidden_states = self.mixer(hidden_states)
    return hidden_states, residual

NemotronHMambaDecoderLayer

Bases: Module

Source code in vllm/model_executor/models/nemotron_h.py
class NemotronHMambaDecoderLayer(nn.Module):
    def __init__(
        self,
        config: NemotronHConfig,
        layer_idx: int,
        model_config: ModelConfig | None = None,
        cache_config: CacheConfig | None = None,
        quant_config: QuantizationConfig | None = None,
        parallel_config: ParallelConfig | None = None,
        prefix: str = "",
    ) -> None:
        super().__init__()
        self.config = config
        self.mixer = MambaMixer2(
            hidden_size=config.hidden_size,
            ssm_state_size=config.ssm_state_size,
            conv_kernel_size=config.conv_kernel,
            intermediate_size=config.mamba_num_heads * config.mamba_head_dim,
            use_conv_bias=config.use_conv_bias,
            use_bias=config.use_bias,
            n_groups=config.n_groups,
            num_heads=config.mamba_num_heads,
            head_dim=config.mamba_head_dim,
            rms_norm_eps=config.layer_norm_epsilon,
            activation=config.mamba_hidden_act,
            model_config=model_config,
            cache_config=cache_config,
            quant_config=quant_config,
            prefix=f"{prefix}.mixer",
        )

        self.norm = RMSNorm(config.hidden_size, eps=config.layer_norm_epsilon)

    def forward(
        self,
        hidden_states: torch.Tensor,
        residual: torch.Tensor | None,
        **kwargs,
    ):
        if residual is None:
            residual = hidden_states
            hidden_states = self.norm(hidden_states)
        else:
            hidden_states, residual = self.norm(hidden_states, residual)

        output = torch.empty_like(hidden_states)
        self.mixer(hidden_states, output)
        return output, residual

config instance-attribute

config = config

mixer instance-attribute

mixer = MambaMixer2(
    hidden_size=hidden_size,
    ssm_state_size=ssm_state_size,
    conv_kernel_size=conv_kernel,
    intermediate_size=mamba_num_heads * mamba_head_dim,
    use_conv_bias=use_conv_bias,
    use_bias=use_bias,
    n_groups=n_groups,
    num_heads=mamba_num_heads,
    head_dim=mamba_head_dim,
    rms_norm_eps=layer_norm_epsilon,
    activation=mamba_hidden_act,
    model_config=model_config,
    cache_config=cache_config,
    quant_config=quant_config,
    prefix=f"{prefix}.mixer",
)

norm instance-attribute

norm = RMSNorm(hidden_size, eps=layer_norm_epsilon)

__init__

__init__(
    config: NemotronHConfig,
    layer_idx: int,
    model_config: ModelConfig | None = None,
    cache_config: CacheConfig | None = None,
    quant_config: QuantizationConfig | None = None,
    parallel_config: ParallelConfig | None = None,
    prefix: str = "",
) -> None
Source code in vllm/model_executor/models/nemotron_h.py
def __init__(
    self,
    config: NemotronHConfig,
    layer_idx: int,
    model_config: ModelConfig | None = None,
    cache_config: CacheConfig | None = None,
    quant_config: QuantizationConfig | None = None,
    parallel_config: ParallelConfig | None = None,
    prefix: str = "",
) -> None:
    super().__init__()
    self.config = config
    self.mixer = MambaMixer2(
        hidden_size=config.hidden_size,
        ssm_state_size=config.ssm_state_size,
        conv_kernel_size=config.conv_kernel,
        intermediate_size=config.mamba_num_heads * config.mamba_head_dim,
        use_conv_bias=config.use_conv_bias,
        use_bias=config.use_bias,
        n_groups=config.n_groups,
        num_heads=config.mamba_num_heads,
        head_dim=config.mamba_head_dim,
        rms_norm_eps=config.layer_norm_epsilon,
        activation=config.mamba_hidden_act,
        model_config=model_config,
        cache_config=cache_config,
        quant_config=quant_config,
        prefix=f"{prefix}.mixer",
    )

    self.norm = RMSNorm(config.hidden_size, eps=config.layer_norm_epsilon)

forward

forward(
    hidden_states: Tensor, residual: Tensor | None, **kwargs
)
Source code in vllm/model_executor/models/nemotron_h.py
def forward(
    self,
    hidden_states: torch.Tensor,
    residual: torch.Tensor | None,
    **kwargs,
):
    if residual is None:
        residual = hidden_states
        hidden_states = self.norm(hidden_states)
    else:
        hidden_states, residual = self.norm(hidden_states, residual)

    output = torch.empty_like(hidden_states)
    self.mixer(hidden_states, output)
    return output, residual

NemotronHMoE

Bases: Module

Source code in vllm/model_executor/models/nemotron_h.py
class NemotronHMoE(nn.Module):
    def __init__(
        self,
        config: NemotronHConfig,
        quant_config: QuantizationConfig | None = None,
        parallel_config: ParallelConfig | None = None,
        prefix: str = "",
    ):
        super().__init__()
        self.tp_size = get_tensor_model_parallel_world_size()
        self.routed_scaling_factor = config.routed_scaling_factor

        self.ep_group = get_ep_group().device_group
        self.ep_rank = self.ep_group.rank()
        self.ep_size = self.ep_group.size()
        self.n_routed_experts: int = config.n_routed_experts
        self.n_shared_experts: int = config.n_shared_experts

        self.is_sequence_parallel = parallel_config.use_sequence_parallel_moe

        self.gate = ReplicatedLinear(
            config.hidden_size,
            config.n_routed_experts,
            bias=False,
            params_dtype=torch.float32,
            quant_config=None,
            prefix=f"{prefix}.gate",
        )

        self.gate.e_score_correction_bias = nn.Parameter(
            torch.empty(config.n_routed_experts, dtype=torch.float32)
        )
        # Load balancing settings.
        self.enable_eplb = parallel_config.enable_eplb

        self.n_redundant_experts = parallel_config.eplb_config.num_redundant_experts  # noqa: E501
        self.n_logical_experts = self.n_routed_experts
        self.n_physical_experts = self.n_logical_experts + self.n_redundant_experts
        self.n_local_physical_experts = self.n_physical_experts // self.ep_size

        self.physical_expert_start = self.ep_rank * self.n_local_physical_experts
        self.physical_expert_end = (
            self.physical_expert_start + self.n_local_physical_experts
        )

        if config.n_shared_experts is None or config.n_shared_experts == 0:
            self.shared_experts = None
        else:
            intermediate_size = (
                config.moe_shared_expert_intermediate_size * config.n_shared_experts
            )

            self.shared_experts = NemotronHMLP(
                config=config,
                intermediate_size=intermediate_size,
                quant_config=quant_config,
                reduce_results=False,
                is_sequence_parallel=self.is_sequence_parallel,
                prefix=f"{prefix}.shared_experts",
            )

        self.experts = SharedFusedMoE(
            shared_experts=self.shared_experts,
            num_experts=config.n_routed_experts,
            top_k=config.num_experts_per_tok,
            hidden_size=config.hidden_size,
            intermediate_size=config.moe_intermediate_size,
            reduce_results=False,
            renormalize=config.norm_topk_prob,
            quant_config=quant_config,
            use_grouped_topk=True,
            num_expert_group=config.n_group,
            topk_group=config.topk_group,
            prefix=f"{prefix}.experts",
            scoring_func="sigmoid",
            e_score_correction_bias=self.gate.e_score_correction_bias,
            activation=activation_without_mul(config.mlp_hidden_act),
            is_act_and_mul=False,  # non-gated MoE
            enable_eplb=self.enable_eplb,
            num_redundant_experts=self.n_redundant_experts,
            is_sequence_parallel=self.is_sequence_parallel,
        )

    def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
        num_tokens, hidden_dim = hidden_states.shape
        hidden_states = hidden_states.view(-1, hidden_dim)

        if self.is_sequence_parallel:
            hidden_states = sequence_parallel_chunk(hidden_states)

        # router_logits: (num_tokens, n_experts)
        router_logits, _ = self.gate(hidden_states.to(dtype=torch.float32))

        fused_moe_out = self.experts(
            hidden_states=hidden_states, router_logits=router_logits
        )

        shared_output, final_hidden_states = fused_moe_out

        # Fix FP16 overflow
        # See DeepseekV2DecoderLayer for more details.
        if hidden_states.dtype != torch.float16:
            final_hidden_states *= self.routed_scaling_factor
        elif self.shared_experts is not None:
            assert shared_output is not None
            shared_output *= 1.0 / self.routed_scaling_factor

        if self.shared_experts is not None:
            assert shared_output is not None
            final_hidden_states += shared_output

        if self.is_sequence_parallel:
            final_hidden_states = tensor_model_parallel_all_gather(
                final_hidden_states, 0
            )
            final_hidden_states = final_hidden_states[:num_tokens]
        elif self.tp_size > 1:
            final_hidden_states = self.experts.maybe_all_reduce_tensor_model_parallel(
                final_hidden_states
            )

        return final_hidden_states.view(num_tokens, hidden_dim)

enable_eplb instance-attribute

enable_eplb = enable_eplb

ep_group instance-attribute

ep_group = device_group

ep_rank instance-attribute

ep_rank = rank()

ep_size instance-attribute

ep_size = size()

experts instance-attribute

experts = SharedFusedMoE(
    shared_experts=shared_experts,
    num_experts=n_routed_experts,
    top_k=num_experts_per_tok,
    hidden_size=hidden_size,
    intermediate_size=moe_intermediate_size,
    reduce_results=False,
    renormalize=norm_topk_prob,
    quant_config=quant_config,
    use_grouped_topk=True,
    num_expert_group=n_group,
    topk_group=topk_group,
    prefix=f"{prefix}.experts",
    scoring_func="sigmoid",
    e_score_correction_bias=e_score_correction_bias,
    activation=activation_without_mul(mlp_hidden_act),
    is_act_and_mul=False,
    enable_eplb=enable_eplb,
    num_redundant_experts=n_redundant_experts,
    is_sequence_parallel=is_sequence_parallel,
)

gate instance-attribute

gate = ReplicatedLinear(
    hidden_size,
    n_routed_experts,
    bias=False,
    params_dtype=float32,
    quant_config=None,
    prefix=f"{prefix}.gate",
)

is_sequence_parallel instance-attribute

is_sequence_parallel = use_sequence_parallel_moe

n_local_physical_experts instance-attribute

n_local_physical_experts = n_physical_experts // ep_size

n_logical_experts instance-attribute

n_logical_experts = n_routed_experts

n_physical_experts instance-attribute

n_physical_experts = n_logical_experts + n_redundant_experts

n_redundant_experts instance-attribute

n_redundant_experts = num_redundant_experts

n_routed_experts instance-attribute

n_routed_experts: int = n_routed_experts

n_shared_experts instance-attribute

n_shared_experts: int = n_shared_experts

physical_expert_end instance-attribute

physical_expert_end = (
    physical_expert_start + n_local_physical_experts
)

physical_expert_start instance-attribute

physical_expert_start = ep_rank * n_local_physical_experts

routed_scaling_factor instance-attribute

routed_scaling_factor = routed_scaling_factor

shared_experts instance-attribute

shared_experts = None

tp_size instance-attribute

__init__

__init__(
    config: NemotronHConfig,
    quant_config: QuantizationConfig | None = None,
    parallel_config: ParallelConfig | None = None,
    prefix: str = "",
)
Source code in vllm/model_executor/models/nemotron_h.py
def __init__(
    self,
    config: NemotronHConfig,
    quant_config: QuantizationConfig | None = None,
    parallel_config: ParallelConfig | None = None,
    prefix: str = "",
):
    super().__init__()
    self.tp_size = get_tensor_model_parallel_world_size()
    self.routed_scaling_factor = config.routed_scaling_factor

    self.ep_group = get_ep_group().device_group
    self.ep_rank = self.ep_group.rank()
    self.ep_size = self.ep_group.size()
    self.n_routed_experts: int = config.n_routed_experts
    self.n_shared_experts: int = config.n_shared_experts

    self.is_sequence_parallel = parallel_config.use_sequence_parallel_moe

    self.gate = ReplicatedLinear(
        config.hidden_size,
        config.n_routed_experts,
        bias=False,
        params_dtype=torch.float32,
        quant_config=None,
        prefix=f"{prefix}.gate",
    )

    self.gate.e_score_correction_bias = nn.Parameter(
        torch.empty(config.n_routed_experts, dtype=torch.float32)
    )
    # Load balancing settings.
    self.enable_eplb = parallel_config.enable_eplb

    self.n_redundant_experts = parallel_config.eplb_config.num_redundant_experts  # noqa: E501
    self.n_logical_experts = self.n_routed_experts
    self.n_physical_experts = self.n_logical_experts + self.n_redundant_experts
    self.n_local_physical_experts = self.n_physical_experts // self.ep_size

    self.physical_expert_start = self.ep_rank * self.n_local_physical_experts
    self.physical_expert_end = (
        self.physical_expert_start + self.n_local_physical_experts
    )

    if config.n_shared_experts is None or config.n_shared_experts == 0:
        self.shared_experts = None
    else:
        intermediate_size = (
            config.moe_shared_expert_intermediate_size * config.n_shared_experts
        )

        self.shared_experts = NemotronHMLP(
            config=config,
            intermediate_size=intermediate_size,
            quant_config=quant_config,
            reduce_results=False,
            is_sequence_parallel=self.is_sequence_parallel,
            prefix=f"{prefix}.shared_experts",
        )

    self.experts = SharedFusedMoE(
        shared_experts=self.shared_experts,
        num_experts=config.n_routed_experts,
        top_k=config.num_experts_per_tok,
        hidden_size=config.hidden_size,
        intermediate_size=config.moe_intermediate_size,
        reduce_results=False,
        renormalize=config.norm_topk_prob,
        quant_config=quant_config,
        use_grouped_topk=True,
        num_expert_group=config.n_group,
        topk_group=config.topk_group,
        prefix=f"{prefix}.experts",
        scoring_func="sigmoid",
        e_score_correction_bias=self.gate.e_score_correction_bias,
        activation=activation_without_mul(config.mlp_hidden_act),
        is_act_and_mul=False,  # non-gated MoE
        enable_eplb=self.enable_eplb,
        num_redundant_experts=self.n_redundant_experts,
        is_sequence_parallel=self.is_sequence_parallel,
    )

forward

forward(hidden_states: Tensor) -> Tensor
Source code in vllm/model_executor/models/nemotron_h.py
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
    num_tokens, hidden_dim = hidden_states.shape
    hidden_states = hidden_states.view(-1, hidden_dim)

    if self.is_sequence_parallel:
        hidden_states = sequence_parallel_chunk(hidden_states)

    # router_logits: (num_tokens, n_experts)
    router_logits, _ = self.gate(hidden_states.to(dtype=torch.float32))

    fused_moe_out = self.experts(
        hidden_states=hidden_states, router_logits=router_logits
    )

    shared_output, final_hidden_states = fused_moe_out

    # Fix FP16 overflow
    # See DeepseekV2DecoderLayer for more details.
    if hidden_states.dtype != torch.float16:
        final_hidden_states *= self.routed_scaling_factor
    elif self.shared_experts is not None:
        assert shared_output is not None
        shared_output *= 1.0 / self.routed_scaling_factor

    if self.shared_experts is not None:
        assert shared_output is not None
        final_hidden_states += shared_output

    if self.is_sequence_parallel:
        final_hidden_states = tensor_model_parallel_all_gather(
            final_hidden_states, 0
        )
        final_hidden_states = final_hidden_states[:num_tokens]
    elif self.tp_size > 1:
        final_hidden_states = self.experts.maybe_all_reduce_tensor_model_parallel(
            final_hidden_states
        )

    return final_hidden_states.view(num_tokens, hidden_dim)

NemotronHMoEDecoderLayer

Bases: Module

Source code in vllm/model_executor/models/nemotron_h.py
class NemotronHMoEDecoderLayer(nn.Module):
    def __init__(
        self,
        config: NemotronHConfig,
        layer_idx: int,
        model_config: ModelConfig | None = None,
        cache_config: CacheConfig | None = None,
        quant_config: QuantizationConfig | None = None,
        parallel_config: ParallelConfig | None = None,
        prefix: str = "",
    ) -> None:
        super().__init__()
        self.config = config

        self.mixer = NemotronHMoE(
            config,
            quant_config=quant_config,
            parallel_config=parallel_config,
            prefix=f"{prefix}.mixer",
        )

        self.norm = RMSNorm(config.hidden_size, eps=config.layer_norm_epsilon)

    def forward(
        self,
        hidden_states: torch.Tensor,
        residual: torch.Tensor | None,
        **kwargs,
    ):
        if residual is None:
            residual = hidden_states
            hidden_states = self.norm(hidden_states)
        else:
            hidden_states, residual = self.norm(hidden_states, residual)

        hidden_states = self.mixer(hidden_states)
        return hidden_states, residual

config instance-attribute

config = config

mixer instance-attribute

mixer = NemotronHMoE(
    config,
    quant_config=quant_config,
    parallel_config=parallel_config,
    prefix=f"{prefix}.mixer",
)

norm instance-attribute

norm = RMSNorm(hidden_size, eps=layer_norm_epsilon)

__init__

__init__(
    config: NemotronHConfig,
    layer_idx: int,
    model_config: ModelConfig | None = None,
    cache_config: CacheConfig | None = None,
    quant_config: QuantizationConfig | None = None,
    parallel_config: ParallelConfig | None = None,
    prefix: str = "",
) -> None
Source code in vllm/model_executor/models/nemotron_h.py
def __init__(
    self,
    config: NemotronHConfig,
    layer_idx: int,
    model_config: ModelConfig | None = None,
    cache_config: CacheConfig | None = None,
    quant_config: QuantizationConfig | None = None,
    parallel_config: ParallelConfig | None = None,
    prefix: str = "",
) -> None:
    super().__init__()
    self.config = config

    self.mixer = NemotronHMoE(
        config,
        quant_config=quant_config,
        parallel_config=parallel_config,
        prefix=f"{prefix}.mixer",
    )

    self.norm = RMSNorm(config.hidden_size, eps=config.layer_norm_epsilon)

forward

forward(
    hidden_states: Tensor, residual: Tensor | None, **kwargs
)
Source code in vllm/model_executor/models/nemotron_h.py
def forward(
    self,
    hidden_states: torch.Tensor,
    residual: torch.Tensor | None,
    **kwargs,
):
    if residual is None:
        residual = hidden_states
        hidden_states = self.norm(hidden_states)
    else:
        hidden_states, residual = self.norm(hidden_states, residual)

    hidden_states = self.mixer(hidden_states)
    return hidden_states, residual

NemotronHModel

Bases: Module

Source code in vllm/model_executor/models/nemotron_h.py
@support_torch_compile
class NemotronHModel(nn.Module):
    def __init__(self, *, vllm_config: VllmConfig, prefix: str = ""):
        super().__init__()

        config: NemotronHConfig = vllm_config.model_config.hf_config
        model_config = vllm_config.model_config
        cache_config = vllm_config.cache_config
        quant_config = vllm_config.quant_config
        parallel_config = vllm_config.parallel_config
        lora_config = vllm_config.lora_config

        self.config = config
        lora_vocab = (
            (lora_config.lora_extra_vocab_size * (lora_config.max_loras or 1))
            if lora_config
            else 0
        )
        self.vocab_size = config.vocab_size + lora_vocab
        self.org_vocab_size = config.vocab_size

        self.embed_tokens = VocabParallelEmbedding(
            self.vocab_size,
            config.hidden_size,
            org_num_embeddings=config.vocab_size,
        )

        self.has_moe = "E" in config.hybrid_override_pattern

        def get_layer(prefix: str):
            layer_idx = int(prefix.rsplit(".", 1)[1])
            layer_class = ALL_DECODER_LAYER_TYPES[
                config.hybrid_override_pattern[layer_idx]
            ]
            return layer_class(
                config=config,
                layer_idx=layer_idx,
                model_config=model_config,
                cache_config=cache_config,
                quant_config=quant_config,
                parallel_config=parallel_config,
                prefix=prefix,
            )

        self.start_layer, self.end_layer, self.layers = make_layers(
            len(config.hybrid_override_pattern), get_layer, prefix=f"{prefix}.layers"
        )
        self.make_empty_intmd_tensors = make_empty_intermediate_tensors_factory(
            ["hidden_states", "residual"], config.hidden_size
        )

        self.norm_f = RMSNorm(config.hidden_size, eps=config.layer_norm_epsilon)

    def get_input_embeddings(self, input_ids: torch.Tensor) -> torch.Tensor:
        return self.embed_tokens(input_ids)

    def forward(
        self,
        input_ids: torch.Tensor,
        positions: torch.Tensor,
        intermediate_tensors: IntermediateTensors | None = None,
        inputs_embeds: torch.Tensor | None = None,
    ) -> torch.Tensor:
        if get_pp_group().is_first_rank:
            if inputs_embeds is not None:
                hidden_states = inputs_embeds
            else:
                hidden_states = self.get_input_embeddings(input_ids)
            residual = None
        else:
            assert intermediate_tensors is not None
            hidden_states = intermediate_tensors["hidden_states"]
            residual = intermediate_tensors["residual"]

        residual = None
        for i, layer in enumerate(self.layers):
            hidden_states, residual = layer(
                positions=positions,
                hidden_states=hidden_states,
                residual=residual,
            )

        if not get_pp_group().is_last_rank:
            return IntermediateTensors(
                {"hidden_states": hidden_states, "residual": residual}
            )
        hidden_states, _ = self.norm_f(hidden_states, residual)
        return hidden_states

    def load_weights(self, weights: Iterable[tuple[str, torch.Tensor]]) -> set[str]:
        stacked_params_mapping = [
            # (param_name, shard_name, shard_id)
            ("qkv_proj", "q_proj", "q"),
            ("qkv_proj", "k_proj", "k"),
            ("qkv_proj", "v_proj", "v"),
        ]

        if self.has_moe:
            # (param_name, weight_name, expert_id, shard_id)
            expert_params_mapping = FusedMoE.make_expert_params_mapping(
                # - FusedMoe.w1 (aka gate_proj) should be up_proj since that's
                #   what the activation is applied to
                # - FusedMoe.w3 (aka up_proj) should be ignored since we're
                #   using non-gated MoE
                ckpt_gate_proj_name="up_proj",
                ckpt_down_proj_name="down_proj",
                ckpt_up_proj_name="",
                num_experts=self.config.n_routed_experts,
                num_redundant_experts=getattr(self, "num_redundant_experts", 0),
            )
        else:
            expert_params_mapping = []

        params_dict = dict(self.named_parameters())
        loaded_params: set[str] = set()
        for name, loaded_weight in weights:
            if "scale" in name:
                # Remapping the name of FP8 kv-scale.
                name = maybe_remap_kv_scale_name(name, params_dict)
                if name is None:
                    continue

            # load stacked params
            for param_name, weight_name, shard_id in stacked_params_mapping:
                if weight_name not in name:
                    continue
                name = name.replace(weight_name, param_name)
                # Skip loading extra bias for GPTQ models.
                if name.endswith(".bias") and name not in params_dict:
                    continue

                param = params_dict[name]
                weight_loader = param.weight_loader
                weight_loader(param, loaded_weight, shard_id)
                break

            # load other params
            else:
                is_expert_weight = False
                for mapping in expert_params_mapping:
                    param_name, weight_name, expert_id, shard_id = mapping
                    if weight_name not in name:
                        continue

                    # Anyway, this is an expert weight and should not be
                    # attempted to load as other weights later
                    is_expert_weight = True

                    # Do not modify `name` since the loop may continue here
                    # Instead, create a new variable
                    name_mapped = name.replace(weight_name, param_name)

                    if is_pp_missing_parameter(name_mapped, self):
                        continue
                    param = params_dict[name_mapped]
                    # We should ask the weight loader to return success or not
                    # here since otherwise we may skip experts with other
                    # available replicas.
                    weight_loader = typing.cast(
                        Callable[..., bool], param.weight_loader
                    )
                    success = weight_loader(
                        param,
                        loaded_weight,
                        name_mapped,
                        shard_id=shard_id,
                        expert_id=expert_id,
                        return_success=True,
                    )
                    if success:
                        name = name_mapped
                        break
                else:
                    if is_expert_weight:
                        continue

                    param = params_dict[name]
                    weight_loader = getattr(
                        param, "weight_loader", default_weight_loader
                    )
                    weight_loader(param, loaded_weight)

            loaded_params.add(name)
        return loaded_params

config instance-attribute

config = config

embed_tokens instance-attribute

embed_tokens = VocabParallelEmbedding(
    vocab_size, hidden_size, org_num_embeddings=vocab_size
)

has_moe instance-attribute

has_moe = 'E' in hybrid_override_pattern

make_empty_intmd_tensors instance-attribute

make_empty_intmd_tensors = (
    make_empty_intermediate_tensors_factory(
        ["hidden_states", "residual"], hidden_size
    )
)

norm_f instance-attribute

norm_f = RMSNorm(hidden_size, eps=layer_norm_epsilon)

org_vocab_size instance-attribute

org_vocab_size = vocab_size

vocab_size instance-attribute

vocab_size = vocab_size + lora_vocab

__init__

__init__(*, vllm_config: VllmConfig, prefix: str = '')
Source code in vllm/model_executor/models/nemotron_h.py
def __init__(self, *, vllm_config: VllmConfig, prefix: str = ""):
    super().__init__()

    config: NemotronHConfig = vllm_config.model_config.hf_config
    model_config = vllm_config.model_config
    cache_config = vllm_config.cache_config
    quant_config = vllm_config.quant_config
    parallel_config = vllm_config.parallel_config
    lora_config = vllm_config.lora_config

    self.config = config
    lora_vocab = (
        (lora_config.lora_extra_vocab_size * (lora_config.max_loras or 1))
        if lora_config
        else 0
    )
    self.vocab_size = config.vocab_size + lora_vocab
    self.org_vocab_size = config.vocab_size

    self.embed_tokens = VocabParallelEmbedding(
        self.vocab_size,
        config.hidden_size,
        org_num_embeddings=config.vocab_size,
    )

    self.has_moe = "E" in config.hybrid_override_pattern

    def get_layer(prefix: str):
        layer_idx = int(prefix.rsplit(".", 1)[1])
        layer_class = ALL_DECODER_LAYER_TYPES[
            config.hybrid_override_pattern[layer_idx]
        ]
        return layer_class(
            config=config,
            layer_idx=layer_idx,
            model_config=model_config,
            cache_config=cache_config,
            quant_config=quant_config,
            parallel_config=parallel_config,
            prefix=prefix,
        )

    self.start_layer, self.end_layer, self.layers = make_layers(
        len(config.hybrid_override_pattern), get_layer, prefix=f"{prefix}.layers"
    )
    self.make_empty_intmd_tensors = make_empty_intermediate_tensors_factory(
        ["hidden_states", "residual"], config.hidden_size
    )

    self.norm_f = RMSNorm(config.hidden_size, eps=config.layer_norm_epsilon)

forward

forward(
    input_ids: Tensor,
    positions: Tensor,
    intermediate_tensors: IntermediateTensors | None = None,
    inputs_embeds: Tensor | None = None,
) -> Tensor
Source code in vllm/model_executor/models/nemotron_h.py
def forward(
    self,
    input_ids: torch.Tensor,
    positions: torch.Tensor,
    intermediate_tensors: IntermediateTensors | None = None,
    inputs_embeds: torch.Tensor | None = None,
) -> torch.Tensor:
    if get_pp_group().is_first_rank:
        if inputs_embeds is not None:
            hidden_states = inputs_embeds
        else:
            hidden_states = self.get_input_embeddings(input_ids)
        residual = None
    else:
        assert intermediate_tensors is not None
        hidden_states = intermediate_tensors["hidden_states"]
        residual = intermediate_tensors["residual"]

    residual = None
    for i, layer in enumerate(self.layers):
        hidden_states, residual = layer(
            positions=positions,
            hidden_states=hidden_states,
            residual=residual,
        )

    if not get_pp_group().is_last_rank:
        return IntermediateTensors(
            {"hidden_states": hidden_states, "residual": residual}
        )
    hidden_states, _ = self.norm_f(hidden_states, residual)
    return hidden_states

get_input_embeddings

get_input_embeddings(input_ids: Tensor) -> Tensor
Source code in vllm/model_executor/models/nemotron_h.py
def get_input_embeddings(self, input_ids: torch.Tensor) -> torch.Tensor:
    return self.embed_tokens(input_ids)

load_weights

load_weights(
    weights: Iterable[tuple[str, Tensor]],
) -> set[str]
Source code in vllm/model_executor/models/nemotron_h.py
def load_weights(self, weights: Iterable[tuple[str, torch.Tensor]]) -> set[str]:
    stacked_params_mapping = [
        # (param_name, shard_name, shard_id)
        ("qkv_proj", "q_proj", "q"),
        ("qkv_proj", "k_proj", "k"),
        ("qkv_proj", "v_proj", "v"),
    ]

    if self.has_moe:
        # (param_name, weight_name, expert_id, shard_id)
        expert_params_mapping = FusedMoE.make_expert_params_mapping(
            # - FusedMoe.w1 (aka gate_proj) should be up_proj since that's
            #   what the activation is applied to
            # - FusedMoe.w3 (aka up_proj) should be ignored since we're
            #   using non-gated MoE
            ckpt_gate_proj_name="up_proj",
            ckpt_down_proj_name="down_proj",
            ckpt_up_proj_name="",
            num_experts=self.config.n_routed_experts,
            num_redundant_experts=getattr(self, "num_redundant_experts", 0),
        )
    else:
        expert_params_mapping = []

    params_dict = dict(self.named_parameters())
    loaded_params: set[str] = set()
    for name, loaded_weight in weights:
        if "scale" in name:
            # Remapping the name of FP8 kv-scale.
            name = maybe_remap_kv_scale_name(name, params_dict)
            if name is None:
                continue

        # load stacked params
        for param_name, weight_name, shard_id in stacked_params_mapping:
            if weight_name not in name:
                continue
            name = name.replace(weight_name, param_name)
            # Skip loading extra bias for GPTQ models.
            if name.endswith(".bias") and name not in params_dict:
                continue

            param = params_dict[name]
            weight_loader = param.weight_loader
            weight_loader(param, loaded_weight, shard_id)
            break

        # load other params
        else:
            is_expert_weight = False
            for mapping in expert_params_mapping:
                param_name, weight_name, expert_id, shard_id = mapping
                if weight_name not in name:
                    continue

                # Anyway, this is an expert weight and should not be
                # attempted to load as other weights later
                is_expert_weight = True

                # Do not modify `name` since the loop may continue here
                # Instead, create a new variable
                name_mapped = name.replace(weight_name, param_name)

                if is_pp_missing_parameter(name_mapped, self):
                    continue
                param = params_dict[name_mapped]
                # We should ask the weight loader to return success or not
                # here since otherwise we may skip experts with other
                # available replicas.
                weight_loader = typing.cast(
                    Callable[..., bool], param.weight_loader
                )
                success = weight_loader(
                    param,
                    loaded_weight,
                    name_mapped,
                    shard_id=shard_id,
                    expert_id=expert_id,
                    return_success=True,
                )
                if success:
                    name = name_mapped
                    break
            else:
                if is_expert_weight:
                    continue

                param = params_dict[name]
                weight_loader = getattr(
                    param, "weight_loader", default_weight_loader
                )
                weight_loader(param, loaded_weight)

        loaded_params.add(name)
    return loaded_params