Model

ankit/NVIDIA-Nemotron-3.5-Super-VL-120B-A12B-NVFP4

22 KBBlameHistoryRawDownload
Viewing revisionView main files
#                🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
#           This file was automatically generated from src/transformers/models/nemotron_h_omni/modular_nemotron_h_omni.py.
#               Do NOT edit this file manually as any edits will be overwritten by the generation of
#             the file from the modular. If any change should be done, please apply the change to the
#                          modular_nemotron_h_omni.py file directly. One of our CI enforces this.
#                🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
# Copyright (c) 2026, NVIDIA CORPORATION.  All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import warnings

import torch
from torch import nn
from torch.nn import CrossEntropyLoss
from transformers.activations import ACT2FN
from transformers.generation import GenerationMixin
from transformers.integrations import use_kernel_forward_from_hub
from transformers.modeling_outputs import CausalLMOutputWithPast
from transformers.modeling_utils import PreTrainedModel
from transformers.conversion_mapping import register_checkpoint_conversion_mapping
from transformers.core_model_loading import WeightRenaming
from transformers.models.auto import CONFIG_MAPPING, FEATURE_EXTRACTOR_MAPPING, AutoModel, AutoModelForCausalLM

from .configuration_nemotron_h_omni import NemotronH_Omni_Reasoning_V3_Config

# Transformers 5.8 only copies direct sibling imports into its dynamic-module cache.
from .configuration_radio import RadioConfig as _RadioConfig  # noqa: F401
from .modeling_radio import RadioModel


def register_nemotron_h_omni_conversion_mapping():
    """
    Register the conversion mapping for the Omni composition level (projector and sound prefixes).

    See `register_radio_conversion_mapping` in `modeling_radio.py` for why this lives in the
    remote code rather than in the global `conversion_mapping.py`. The vision mapping is registered
    there and the `nemotron_h` mapping ships with Transformers itself (upstream since v5.3.0); this
    entry covers the keys owned by the top-level model.
    """

    register_checkpoint_conversion_mapping(
        "nemotron_h_omni",
        [
            WeightRenaming(r"^mlp1\.0\.", r"vision_projector\.mlp1\.norm\."),
            WeightRenaming(r"^mlp1\.1\.", r"vision_projector\.mlp1\.linear1\."),
            WeightRenaming(r"^mlp1\.3\.", r"vision_projector\.mlp1\.linear2\."),
            WeightRenaming(r"^sound_encoder\.", r"sound_projector\.sound_encoder\."),
            WeightRenaming(r"^sound_projection\.", r"sound_projector\.sound_projection\."),
        ],
        overwrite=True,
    )


@use_kernel_forward_from_hub("RMSNorm")
class NemotronH_Omni_RMSNorm(nn.Module):
    def __init__(self, hidden_size, eps: float = 1e-6) -> None:
        """
        NemotronHOmniRMSNorm is equivalent to T5LayerNorm
        """
        super().__init__()
        self.weight = nn.Parameter(torch.ones(hidden_size))
        self.variance_epsilon = eps

    def forward(self, hidden_states) -> torch.Tensor:
        input_dtype = hidden_states.dtype
        hidden_states = hidden_states.to(torch.float32)
        variance = hidden_states.pow(2).mean(-1, keepdim=True)
        hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
        return (self.weight.to(torch.float32) * hidden_states).to(input_dtype)

    def extra_repr(self):
        return f"{tuple(self.weight.shape)}, eps={self.variance_epsilon}"


class NemotronH_Omni_Reasoning_V3SoundEncoder(nn.Module):
    """Thin wrapper exposing the Parakeet encoder's `last_hidden_state` for audio embedding."""

    def __init__(self, config):
        super().__init__()
        self.config = config
        self.encoder = AutoModel.from_config(config)

    def forward(self, input_features: torch.Tensor, attention_mask: torch.Tensor | None = None) -> torch.Tensor:
        return self.encoder(input_features=input_features, attention_mask=attention_mask).last_hidden_state

    @property
    def hidden_size(self) -> int:
        return self.config.hidden_size


class NemotronH_Omni_Reasoning_V3SoundProjector(nn.Module):
    """Single-forward audio pipeline: feature-extract raw clip(s), encode with Parakeet and project,
    returning flattened LLM-space embeddings ready to scatter onto `<audio>` positions.
    """

    def __init__(self, config, llm_hidden_size: int):
        super().__init__()
        feature_extractor_class = FEATURE_EXTRACTOR_MAPPING[CONFIG_MAPPING["parakeet_encoder"]]
        self.feature_extractor = feature_extractor_class(
            sampling_rate=getattr(config, "sampling_rate", 16000),
            feature_size=config.num_mel_bins,
        )
        self.sound_encoder = NemotronH_Omni_Reasoning_V3SoundEncoder(config)
        self.sound_projection = NemotronH_Omni_Reasoning_V3MLP(
            config.hidden_size,
            config.projection_hidden_size,
            llm_hidden_size,
            bias=config.projection_bias,
        )

    def forward(self, sound_clips) -> torch.Tensor:
        weight = self.sound_encoder.encoder.subsampling.linear.weight
        device, dtype = weight.device, weight.dtype

        if isinstance(sound_clips, torch.Tensor) and sound_clips.dim() >= 3:
            input_features = sound_clips.to(device=device, dtype=dtype)
            attention_mask = None
        else:
            # `.tolist()` keeps a raw waveform tensor within the feature extractor's accepted input
            # types (`list[float]` / `list[list[float]]`) without pulling in numpy here.
            raw_speech = sound_clips.tolist() if isinstance(sound_clips, torch.Tensor) else sound_clips
            audio_inputs = self.feature_extractor(
                raw_speech, sampling_rate=self.feature_extractor.sampling_rate, return_tensors="pt"
            )
            input_features = audio_inputs.input_features.to(device=device, dtype=dtype)
            attention_mask = audio_inputs.get("attention_mask", None)
            if attention_mask is not None:
                attention_mask = attention_mask.to(device=device)

        sound_embeds = self.sound_projection(self.sound_encoder(input_features, attention_mask).to(torch.bfloat16))

        # Multiple clips are batch-padded; keep only each clip's real (subsampled) length before flattening.
        if sound_embeds.dim() == 3 and sound_embeds.shape[0] > 1 and attention_mask is not None:
            lengths = self.sound_encoder.encoder._get_subsampling_output_length(attention_mask.sum(-1) + 1)
            return torch.cat([sound_embeds[i, : int(n)] for i, n in enumerate(lengths.tolist())], dim=0)
        return sound_embeds.reshape(-1, sound_embeds.shape[-1])


class NemotronH_Omni_Reasoning_V3MLP(nn.Module):
    """Projector MLP: RMSNorm -> linear1 -> ReLUΒ² -> linear2 (NemotronHMLP-style).

    Used both for the vision-to-LLM projector (`mlp1`) and the sound-to-LLM projection. The
    `linear1`/`linear2` submodule names match the Megatron sound-projection checkpoint structure
    (`sound_projection.{norm,linear1,linear2}.weight`); pass `bias=True` for the sound projection.
    """

    def __init__(
        self, in_features: int, hidden_features: int, out_features: int, bias: bool = False, eps: float = 1e-5
    ):
        super().__init__()
        self.norm = NemotronH_Omni_RMSNorm(in_features, eps=eps)
        self.linear1 = nn.Linear(in_features, hidden_features, bias=bias)
        self.linear2 = nn.Linear(hidden_features, out_features, bias=bias)
        self.act_fn = ACT2FN["relu2"]

    def forward(self, x):
        return self.linear2(self.act_fn(self.linear1(self.norm(x))))


class NemotronH_Omni_Reasoning_V3VisionProjector(nn.Module):
    """Single-forward vision pipeline: run the vision tower (image, or temporally-packed video) through
    pixel-shuffle downsampling and the projection MLP (`mlp1`) into LLM-space embeddings. The
    weight-bearing `vision_model` is passed in so its checkpoint keys stay at the top level.
    """

    def __init__(self, config):
        super().__init__()
        self.downsample_ratio = config.downsample_ratio
        self.video_temporal_patch_dim = config.video_temporal_patch_size
        self.ps_version = config.ps_version
        self.mlp1 = NemotronH_Omni_Reasoning_V3MLP(
            config.vit_hidden_size * int(1 / config.downsample_ratio) ** 2,
            config.projector_hidden_size,
            config.llm_config.hidden_size,
        )
        # Mirror Megatron training behavior: when the language model has MTP,
        # Megatron-Core's TransformerBlock places a final LayerNorm with the last
        # layer of every block built from the (shared) config -- including the
        # vision tower, whose config inherits `mtp_num_layers` from the language
        # model. The vision tower output is therefore layer-normalized before the
        # projector. LayerNorm is applied per token, so normalizing the RADIO
        # features here is exactly equivalent to Megatron's block-internal
        # placement before class-token stripping.
        if (getattr(config.llm_config, "num_nextn_predict_layers", 0) or 0) > 0:
            self.vision_final_layernorm = nn.LayerNorm(
                config.vit_hidden_size, eps=config.vision_config.layer_norm_eps
            )
        else:
            self.vision_final_layernorm = None

    def pixel_shuffle(self, x, scale_factor=0.5):
        n, w, h, c = x.size()
        x = x.view(n, w, int(h * scale_factor), int(c / scale_factor))
        x = x.permute(0, 2, 1, 3).contiguous()
        x = x.view(
            n,
            int(h * scale_factor),
            int(w * scale_factor),
            int(c / (scale_factor * scale_factor)),
        )
        if self.ps_version == "v1":
            warnings.warn(
                "In ps_version 'v1', the height and width have not been swapped back, "
                "which results in a transposed image."
            )
        else:
            x = x.permute(0, 2, 1, 3).contiguous()
        return x

    def _project(self, vit_embeds, h, w):
        if self.vision_final_layernorm is not None:
            vit_embeds = self.vision_final_layernorm(vit_embeds)
        vit_embeds = vit_embeds.reshape(vit_embeds.shape[0], h, w, -1)
        vit_embeds = self.pixel_shuffle(vit_embeds, scale_factor=self.downsample_ratio)
        vit_embeds = vit_embeds.reshape(vit_embeds.shape[0], -1, vit_embeds.shape[-1])
        return self.mlp1(vit_embeds)

    def forward(self, pixel_values, vision_model):
        if isinstance(pixel_values, (list, tuple)):
            return torch.cat([self.forward(pv, vision_model) for pv in pixel_values], dim=0)
        pixel_values = pixel_values.to(dtype=vision_model.config.torch_dtype)
        vit_embeds = vision_model(pixel_values).features
        _, _, H, W = pixel_values.shape
        patch_size = vision_model.patch_size
        return self._project(vit_embeds, H // patch_size, W // patch_size)

    def forward_video(self, pixel_values_videos, vision_model):
        pixel_values_videos = pixel_values_videos.to(dtype=vision_model.config.torch_dtype)
        T = self.video_temporal_patch_dim
        N, C, H, W = pixel_values_videos.shape

        if N % T != 0:
            pad = pixel_values_videos[-1:].expand(T - (N % T), -1, -1, -1)
            pixel_values_videos = torch.cat([pixel_values_videos, pad], dim=0)
            N = pixel_values_videos.shape[0]
        num_groups = N // T

        x = pixel_values_videos.reshape(num_groups, T * C, H, W)
        vit_embeds = vision_model(x, use_video_patch_projection=True).features
        patch_size = vision_model.patch_size
        return self._project(vit_embeds, H // patch_size, W // patch_size)


def compute_retention_mask(
    *,
    video_embeds: torch.FloatTensor,
    thw: torch.LongTensor,
    spatial_merge_size: int,
    q: float,
):
    """
    Computes the retention mask for video embeddings based on the grid dimensions.

    Args:
        video_embeds (`torch.FloatTensor` of shape `(T * H * W, hidden_size)`):
            The video embeddings to compute the retention mask for.
        thw (`torch.LongTensor` of shape `(3)`):
            The temporal, height and width of feature shape of each video in LLM.
        spatial_merge_size (`int`): The spatial merge size of the video embeddings.
            If embeddings will be downsampled *later*, this should be the downsampling factor.
        q: (`float`): Pruning rate factor, indicating number of tokens to prune (remove)

    Returns:
        `torch.Tensor`: The retention mask for the video embeddings (T * H * W).
            1 for tokens to keep, 0 for tokens to prune.
    """
    T, H, W = thw

    # Use reshape instead of einops to avoid graph breaks
    video_embeds = video_embeds.reshape(T, H // spatial_merge_size, W // spatial_merge_size, video_embeds.size(-1))

    # Core EVS
    similarity = torch.nn.functional.cosine_similarity(video_embeds[1:, ...], video_embeds[:-1, ...], dim=-1)
    dissimilarity = 1 - similarity

    # Always ensure we include all tokens from the first frame
    dissimilarity = torch.cat([255 * torch.ones_like(video_embeds[:1, :, :, 0]), dissimilarity], dim=0)
    dissimilarity_flat = dissimilarity.view(-1)

    min_num_tokens = (H // spatial_merge_size) * (W // spatial_merge_size)  # a single frame
    evs_num_tokens = int(T * min_num_tokens * (1 - q))
    num_tokens_to_keep = max(min_num_tokens, evs_num_tokens)

    order = torch.argsort(dissimilarity_flat, dim=-1, descending=True, stable=True)
    topk_indices = order[:num_tokens_to_keep]

    retention_mask = torch.zeros_like(dissimilarity_flat, dtype=torch.bool)
    retention_mask[topk_indices] = True
    retention_mask = retention_mask.reshape(dissimilarity.size())

    mask = retention_mask.view(-1)  # "T H W -> (T H W)"
    return mask


class NemotronH_Omni_Reasoning_V3(PreTrainedModel, GenerationMixin):
    config_class = NemotronH_Omni_Reasoning_V3_Config
    main_input_name = "input_ids"
    _supports_flash_attn_2 = True
    _supports_flash_attn = True
    _no_split_modules = ["NemotronHBlock"]
    # Released checkpoints carry multi-token-prediction weights (no module here builds them) and
    # input-conditioner statistics (the vision preprocessor is external in this composition).
    _keys_to_ignore_on_load_unexpected = [r"mtp\.", r"input_conditioner\."]

    def __init__(self, config: NemotronH_Omni_Reasoning_V3_Config):
        super().__init__(config)
        register_nemotron_h_omni_conversion_mapping()

        image_size = config.force_image_size
        patch_size = config.patch_size
        self.patch_size = patch_size
        self.template = config.template
        self.num_image_token = int((image_size // patch_size) ** 2 * (config.downsample_ratio**2))
        self.downsample_ratio = config.downsample_ratio
        self.image_tag_type = config.image_tag_type
        self.img_context_token_id = config.img_context_token_id
        self.video_context_token_id = config.video_context_token_id

        self.language_model = AutoModelForCausalLM.from_config(config.llm_config)
        self.vision_model = RadioModel(config.vision_config)
        self.vision_model.make_preprocessor_external()

        self.drop_vision_class_token = True

        llm_hidden_size = config.llm_config.hidden_size

        self.video_pruning_rate = config.video_pruning_rate

        self.vision_projector = NemotronH_Omni_Reasoning_V3VisionProjector(config)

        self.sound_context_token_id = config.sound_context_token_id
        if config.sound_config is not None:
            self.sound_projector = NemotronH_Omni_Reasoning_V3SoundProjector(config.sound_config, llm_hidden_size)
        else:
            self.sound_projector = None

        self.all_tied_weights_keys = {}

        self.post_init()

    def get_input_embeddings(self):
        return self.language_model.get_input_embeddings()

    def set_input_embeddings(self, value):
        self.language_model.set_input_embeddings(value)

    def forward(
        self,
        input_ids: torch.LongTensor = None,
        pixel_values: torch.FloatTensor | None = None,
        pixel_values_videos: torch.FloatTensor | None = None,
        sound_clips: torch.FloatTensor | None = None,
        attention_mask: torch.Tensor | None = None,
        position_ids: torch.LongTensor | None = None,
        image_flags: torch.LongTensor | None = None,
        past_key_values: list[torch.FloatTensor] | None = None,
        labels: torch.LongTensor | None = None,
        inputs_embeds=None,
        use_cache: bool | None = None,
        output_attentions: bool | None = None,
        output_hidden_states: bool | None = None,
        return_dict: bool | None = None,
        **kwargs,
    ) -> CausalLMOutputWithPast:
        if inputs_embeds is None:
            inputs_embeds = self.get_input_embeddings()(input_ids)

        # Multimodal merges need `input_ids` to locate the placeholder tokens; skip them on the
        # cached decode steps and the inputs-embeds-only path where `input_ids` is absent.
        if pixel_values is not None and input_ids is not None:
            image_embeds = self.vision_projector(pixel_values, self.vision_model)
            if image_flags is not None:
                image_embeds = image_embeds[image_flags.squeeze(-1) == 1]
            image_embeds = image_embeds.to(inputs_embeds.device, inputs_embeds.dtype)
            image_mask = (input_ids == self.img_context_token_id).unsqueeze(-1).expand_as(inputs_embeds)
            inputs_embeds = inputs_embeds.masked_scatter(image_mask.to(inputs_embeds.device), image_embeds)

        if pixel_values_videos is not None and input_ids is not None:
            video_embeds = self.vision_projector.forward_video(pixel_values_videos, self.vision_model)
            video_embeds = video_embeds.to(inputs_embeds.device, inputs_embeds.dtype)
            video_mask = (input_ids == self.img_context_token_id).unsqueeze(-1).expand_as(inputs_embeds)
            inputs_embeds = inputs_embeds.masked_scatter(video_mask.to(inputs_embeds.device), video_embeds)

            if self.video_pruning_rate > 0:
                h = w = int(video_embeds.shape[1] ** 0.5)
                evs_mask = compute_retention_mask(
                    video_embeds=video_embeds,
                    thw=(video_embeds.shape[0], h, w),
                    spatial_merge_size=1,
                    q=self.video_pruning_rate,
                )
                retention_mask = torch.ones_like(input_ids, dtype=torch.bool)
                retention_mask[input_ids == self.img_context_token_id] = evs_mask.view(-1)
                inputs_embeds = inputs_embeds[retention_mask].unsqueeze(0)
                if attention_mask is not None:
                    attention_mask = attention_mask[retention_mask].unsqueeze(0)
                input_ids = input_ids[retention_mask].unsqueeze(0)

        if sound_clips is not None and self.sound_projector is not None and input_ids is not None:
            sound_embeds = self.sound_projector(sound_clips)
            sound_embeds = sound_embeds.to(inputs_embeds.device, inputs_embeds.dtype)
            sound_mask = (input_ids == self.sound_context_token_id).unsqueeze(-1).expand_as(inputs_embeds)
            inputs_embeds = inputs_embeds.masked_scatter(sound_mask.to(inputs_embeds.device), sound_embeds)

        outputs = self.language_model(
            inputs_embeds=inputs_embeds,
            attention_mask=attention_mask,
            position_ids=position_ids,
            past_key_values=past_key_values,
            use_cache=use_cache,
            output_attentions=output_attentions,
            output_hidden_states=output_hidden_states,
            return_dict=True,
        )
        logits = outputs.logits

        loss = None
        if labels is not None:
            shift_logits = logits[..., :-1, :].contiguous()
            shift_labels = labels[..., 1:].contiguous()
            loss_fct = CrossEntropyLoss()
            shift_logits = shift_logits.view(-1, self.language_model.config.vocab_size)
            shift_labels = shift_labels.view(-1)
            shift_labels = shift_labels.to(shift_logits.device)
            loss = loss_fct(shift_logits, shift_labels)

        return CausalLMOutputWithPast(
            loss=loss,
            logits=logits,
            past_key_values=outputs.past_key_values,
            hidden_states=outputs.hidden_states,
            attentions=outputs.attentions,
        )

    def prepare_inputs_for_generation(
        self,
        input_ids,
        past_key_values=None,
        attention_mask=None,
        inputs_embeds=None,
        pixel_values=None,
        pixel_values_videos=None,
        sound_clips=None,
        image_flags=None,
        use_cache=True,
        is_first_iteration=False,
        **kwargs,
    ):
        model_inputs = super().prepare_inputs_for_generation(
            input_ids,
            past_key_values=past_key_values,
            attention_mask=attention_mask,
            inputs_embeds=inputs_embeds,
            pixel_values=pixel_values,
            pixel_values_videos=pixel_values_videos,
            sound_clips=sound_clips,
            image_flags=image_flags,
            use_cache=use_cache,
            is_first_iteration=is_first_iteration,
            **kwargs,
        )

        # The multimodal inputs are only merged on the prefill step; drop them once the cache is warm.
        if not is_first_iteration and use_cache:
            model_inputs["pixel_values"] = None
            model_inputs["pixel_values_videos"] = None
            model_inputs["sound_clips"] = None
            model_inputs["image_flags"] = None

        return model_inputs


__all__ = ["NemotronH_Omni_Reasoning_V3"]