Model
ankit/NVIDIA-Nemotron-3.5-Super-VL-120B-A12B-NVFP4
- Task:Image Text To Text
- Libraries:transformerspytorch
- Formats:safetensors
- Languages:GermanEnglishSpanishFrenchItalianJapanese
- License:other
Dedicated endpoint
Sign in to deployInference Providers
This hub serves this model on demand.
Try itSpaces
Create a Space with this modelUse this model
Choose individual files there, or download a full snapshot with the Python example below.
Download with the whiteduck client
pip install https://provyd.xyz/clients/whiteduck-0.1.0-py3-none-any.whl
wd login --host 'https://api.provyd.xyz'
wd download 'ankit/NVIDIA-Nemotron-3.5-Super-VL-120B-A12B-NVFP4'Using the Hugging Face client instead
Install huggingface_hub with pip install huggingface_hub, then download this pinned snapshot. Set HF_TOKEN (the variable the Hugging Face client reads) to a whiteduck Read token for private repositories. Running the downloaded model requires software that supports its architecture.
Keep your whiteduck token away from calls that ignore HF_ENDPOINT, such as list_inference_endpoints: they send it to Hugging Face. See Docs.
from huggingface_hub import snapshot_download
import os
path = snapshot_download(
repo_id='ankit/NVIDIA-Nemotron-3.5-Super-VL-120B-A12B-NVFP4',
revision='f145a010eb6cafac2e532b8b81c2dc76df47ff25',
endpoint='https://api.provyd.xyz',
token=os.environ.get("HF_TOKEN") or False,
)Load with transformers
import os
os.environ["HF_ENDPOINT"] = 'https://api.provyd.xyz'
from transformers import AutoModel, AutoTokenizer
tokenizer = AutoTokenizer.from_pretrained('ankit/NVIDIA-Nemotron-3.5-Super-VL-120B-A12B-NVFP4')
model = AutoModel.from_pretrained('ankit/NVIDIA-Nemotron-3.5-Super-VL-120B-A12B-NVFP4')Use with local apps
This hub is self-hosted, so each command points the tool at it. Add a whiteduck access token as HF_TOKEN (the variable the Hugging Face client reads) for private repositories.
vLLM
# vLLM downloads through huggingface_hub, which honours HF_ENDPOINT; set HF_TOKEN for a private repository.
HF_ENDPOINT='https://api.provyd.xyz' vllm serve 'ankit/NVIDIA-Nemotron-3.5-Super-VL-120B-A12B-NVFP4'Clone with git
git clone 'https://api.provyd.xyz/ankit/NVIDIA-Nemotron-3.5-Super-VL-120B-A12B-NVFP4'Clone with git over SSH
git clone 'ssh://git@wd.provyd.xyz:2222/ankit/NVIDIA-Nemotron-3.5-Super-VL-120B-A12B-NVFP4'Needs an SSH key on your account. Add an SSH key
Use the API
Read repository metadata at this commit. Set HF_TOKEN (the variable the Hugging Face client reads) to a whiteduck Read token. Tokens grant account-level access, not access to just this model.
curl 'https://api.provyd.xyz/api/models/ankit/NVIDIA-Nemotron-3.5-Super-VL-120B-A12B-NVFP4/revision/f145a010eb6cafac2e532b8b81c2dc76df47ff25' \
-H "Authorization: Bearer $HF_TOKEN"Inference is separate from file storage. The owner must configure and start a supported model using the inference controls. To call it you need a model API key (made on the model page), or a token of any scope (Read or stronger) from the model owner. Visitors can use the try box only when the owner allows it. A token cannot enable unavailable GPU hardware.
Blame for modeling_nemotron_h_omni.py at cb6f83b
| Line | Commit | Author | Date | Code |
|---|---|---|---|---|
| 1 | Add files using upload-large-folder toolcb6f83b | ankit | # π¨π¨π¨π¨π¨π¨π¨π¨π¨π¨π¨π¨π¨π¨π¨π¨π¨π¨π¨π¨π¨π¨π¨π¨π¨π¨π¨π¨π¨π¨π¨π¨π¨π¨π¨π¨π¨π¨π¨π¨π¨π¨π¨π¨π¨π¨π¨π¨ | |
| 2 | # This file was automatically generated from src/transformers/models/nemotron_h_omni/modular_nemotron_h_omni.py. | |||
| 3 | # Do NOT edit this file manually as any edits will be overwritten by the generation of | |||
| 4 | # the file from the modular. If any change should be done, please apply the change to the | |||
| 5 | # modular_nemotron_h_omni.py file directly. One of our CI enforces this. | |||
| 6 | # π¨π¨π¨π¨π¨π¨π¨π¨π¨π¨π¨π¨π¨π¨π¨π¨π¨π¨π¨π¨π¨π¨π¨π¨π¨π¨π¨π¨π¨π¨π¨π¨π¨π¨π¨π¨π¨π¨π¨π¨π¨π¨π¨π¨π¨π¨π¨π¨ | |||
| 7 | # Copyright (c) 2026, NVIDIA CORPORATION. All rights reserved. | |||
| 8 | # | |||
| 9 | # Licensed under the Apache License, Version 2.0 (the "License"); | |||
| 10 | # you may not use this file except in compliance with the License. | |||
| 11 | # You may obtain a copy of the License at | |||
| 12 | # | |||
| 13 | # http://www.apache.org/licenses/LICENSE-2.0 | |||
| 14 | # | |||
| 15 | # Unless required by applicable law or agreed to in writing, software | |||
| 16 | # distributed under the License is distributed on an "AS IS" BASIS, | |||
| 17 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | |||
| 18 | # See the License for the specific language governing permissions and | |||
| 19 | # limitations under the License. | |||
| 20 | ||||
| 21 | import warnings | |||
| 22 | ||||
| 23 | import torch | |||
| 24 | from torch import nn | |||
| 25 | from torch.nn import CrossEntropyLoss | |||
| 26 | from transformers.activations import ACT2FN | |||
| 27 | from transformers.generation import GenerationMixin | |||
| 28 | from transformers.integrations import use_kernel_forward_from_hub | |||
| 29 | from transformers.modeling_outputs import CausalLMOutputWithPast | |||
| 30 | from transformers.modeling_utils import PreTrainedModel | |||
| 31 | from transformers.conversion_mapping import register_checkpoint_conversion_mapping | |||
| 32 | from transformers.core_model_loading import WeightRenaming | |||
| 33 | from transformers.models.auto import CONFIG_MAPPING, FEATURE_EXTRACTOR_MAPPING, AutoModel, AutoModelForCausalLM | |||
| 34 | ||||
| 35 | from .configuration_nemotron_h_omni import NemotronH_Omni_Reasoning_V3_Config | |||
| 36 | ||||
| 37 | # Transformers 5.8 only copies direct sibling imports into its dynamic-module cache. | |||
| 38 | from .configuration_radio import RadioConfig as _RadioConfig # noqa: F401 | |||
| 39 | from .modeling_radio import RadioModel | |||
| 40 | ||||
| 41 | ||||
| 42 | def register_nemotron_h_omni_conversion_mapping(): | |||
| 43 | """ | |||
| 44 | Register the conversion mapping for the Omni composition level (projector and sound prefixes). | |||
| 45 | ||||
| 46 | See `register_radio_conversion_mapping` in `modeling_radio.py` for why this lives in the | |||
| 47 | remote code rather than in the global `conversion_mapping.py`. The vision mapping is registered | |||
| 48 | there and the `nemotron_h` mapping ships with Transformers itself (upstream since v5.3.0); this | |||
| 49 | entry covers the keys owned by the top-level model. | |||
| 50 | """ | |||
| 51 | ||||
| 52 | register_checkpoint_conversion_mapping( | |||
| 53 | "nemotron_h_omni", | |||
| 54 | [ | |||
| 55 | WeightRenaming(r"^mlp1\.0\.", r"vision_projector\.mlp1\.norm\."), | |||
| 56 | WeightRenaming(r"^mlp1\.1\.", r"vision_projector\.mlp1\.linear1\."), | |||
| 57 | WeightRenaming(r"^mlp1\.3\.", r"vision_projector\.mlp1\.linear2\."), | |||
| 58 | WeightRenaming(r"^sound_encoder\.", r"sound_projector\.sound_encoder\."), | |||
| 59 | WeightRenaming(r"^sound_projection\.", r"sound_projector\.sound_projection\."), | |||
| 60 | ], | |||
| 61 | overwrite=True, | |||
| 62 | ) | |||
| 63 | ||||
| 64 | ||||
| 65 | @use_kernel_forward_from_hub("RMSNorm") | |||
| 66 | class NemotronH_Omni_RMSNorm(nn.Module): | |||
| 67 | def __init__(self, hidden_size, eps: float = 1e-6) -> None: | |||
| 68 | """ | |||
| 69 | NemotronHOmniRMSNorm is equivalent to T5LayerNorm | |||
| 70 | """ | |||
| 71 | super().__init__() | |||
| 72 | self.weight = nn.Parameter(torch.ones(hidden_size)) | |||
| 73 | self.variance_epsilon = eps | |||
| 74 | ||||
| 75 | def forward(self, hidden_states) -> torch.Tensor: | |||
| 76 | input_dtype = hidden_states.dtype | |||
| 77 | hidden_states = hidden_states.to(torch.float32) | |||
| 78 | variance = hidden_states.pow(2).mean(-1, keepdim=True) | |||
| 79 | hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon) | |||
| 80 | return (self.weight.to(torch.float32) * hidden_states).to(input_dtype) | |||
| 81 | ||||
| 82 | def extra_repr(self): | |||
| 83 | return f"{tuple(self.weight.shape)}, eps={self.variance_epsilon}" | |||
| 84 | ||||
| 85 | ||||
| 86 | class NemotronH_Omni_Reasoning_V3SoundEncoder(nn.Module): | |||
| 87 | """Thin wrapper exposing the Parakeet encoder's `last_hidden_state` for audio embedding.""" | |||
| 88 | ||||
| 89 | def __init__(self, config): | |||
| 90 | super().__init__() | |||
| 91 | self.config = config | |||
| 92 | self.encoder = AutoModel.from_config(config) | |||
| 93 | ||||
| 94 | def forward(self, input_features: torch.Tensor, attention_mask: torch.Tensor | None = None) -> torch.Tensor: | |||
| 95 | return self.encoder(input_features=input_features, attention_mask=attention_mask).last_hidden_state | |||
| 96 | ||||
| 97 | @property | |||
| 98 | def hidden_size(self) -> int: | |||
| 99 | return self.config.hidden_size | |||
| 100 | ||||
| 101 | ||||
| 102 | class NemotronH_Omni_Reasoning_V3SoundProjector(nn.Module): | |||
| 103 | """Single-forward audio pipeline: feature-extract raw clip(s), encode with Parakeet and project, | |||
| 104 | returning flattened LLM-space embeddings ready to scatter onto `<audio>` positions. | |||
| 105 | """ | |||
| 106 | ||||
| 107 | def __init__(self, config, llm_hidden_size: int): | |||
| 108 | super().__init__() | |||
| 109 | feature_extractor_class = FEATURE_EXTRACTOR_MAPPING[CONFIG_MAPPING["parakeet_encoder"]] | |||
| 110 | self.feature_extractor = feature_extractor_class( | |||
| 111 | sampling_rate=getattr(config, "sampling_rate", 16000), | |||
| 112 | feature_size=config.num_mel_bins, | |||
| 113 | ) | |||
| 114 | self.sound_encoder = NemotronH_Omni_Reasoning_V3SoundEncoder(config) | |||
| 115 | self.sound_projection = NemotronH_Omni_Reasoning_V3MLP( | |||
| 116 | config.hidden_size, | |||
| 117 | config.projection_hidden_size, | |||
| 118 | llm_hidden_size, | |||
| 119 | bias=config.projection_bias, | |||
| 120 | ) | |||
| 121 | ||||
| 122 | def forward(self, sound_clips) -> torch.Tensor: | |||
| 123 | weight = self.sound_encoder.encoder.subsampling.linear.weight | |||
| 124 | device, dtype = weight.device, weight.dtype | |||
| 125 | ||||
| 126 | if isinstance(sound_clips, torch.Tensor) and sound_clips.dim() >= 3: | |||
| 127 | input_features = sound_clips.to(device=device, dtype=dtype) | |||
| 128 | attention_mask = None | |||
| 129 | else: | |||
| 130 | # `.tolist()` keeps a raw waveform tensor within the feature extractor's accepted input | |||
| 131 | # types (`list[float]` / `list[list[float]]`) without pulling in numpy here. | |||
| 132 | raw_speech = sound_clips.tolist() if isinstance(sound_clips, torch.Tensor) else sound_clips | |||
| 133 | audio_inputs = self.feature_extractor( | |||
| 134 | raw_speech, sampling_rate=self.feature_extractor.sampling_rate, return_tensors="pt" | |||
| 135 | ) | |||
| 136 | input_features = audio_inputs.input_features.to(device=device, dtype=dtype) | |||
| 137 | attention_mask = audio_inputs.get("attention_mask", None) | |||
| 138 | if attention_mask is not None: | |||
| 139 | attention_mask = attention_mask.to(device=device) | |||
| 140 | ||||
| 141 | sound_embeds = self.sound_projection(self.sound_encoder(input_features, attention_mask).to(torch.bfloat16)) | |||
| 142 | ||||
| 143 | # Multiple clips are batch-padded; keep only each clip's real (subsampled) length before flattening. | |||
| 144 | if sound_embeds.dim() == 3 and sound_embeds.shape[0] > 1 and attention_mask is not None: | |||
| 145 | lengths = self.sound_encoder.encoder._get_subsampling_output_length(attention_mask.sum(-1) + 1) | |||
| 146 | return torch.cat([sound_embeds[i, : int(n)] for i, n in enumerate(lengths.tolist())], dim=0) | |||
| 147 | return sound_embeds.reshape(-1, sound_embeds.shape[-1]) | |||
| 148 | ||||
| 149 | ||||
| 150 | class NemotronH_Omni_Reasoning_V3MLP(nn.Module): | |||
| 151 | """Projector MLP: RMSNorm -> linear1 -> ReLUΒ² -> linear2 (NemotronHMLP-style). | |||
| 152 | ||||
| 153 | Used both for the vision-to-LLM projector (`mlp1`) and the sound-to-LLM projection. The | |||
| 154 | `linear1`/`linear2` submodule names match the Megatron sound-projection checkpoint structure | |||
| 155 | (`sound_projection.{norm,linear1,linear2}.weight`); pass `bias=True` for the sound projection. | |||
| 156 | """ | |||
| 157 | ||||
| 158 | def __init__( | |||
| 159 | self, in_features: int, hidden_features: int, out_features: int, bias: bool = False, eps: float = 1e-5 | |||
| 160 | ): | |||
| 161 | super().__init__() | |||
| 162 | self.norm = NemotronH_Omni_RMSNorm(in_features, eps=eps) | |||
| 163 | self.linear1 = nn.Linear(in_features, hidden_features, bias=bias) | |||
| 164 | self.linear2 = nn.Linear(hidden_features, out_features, bias=bias) | |||
| 165 | self.act_fn = ACT2FN["relu2"] | |||
| 166 | ||||
| 167 | def forward(self, x): | |||
| 168 | return self.linear2(self.act_fn(self.linear1(self.norm(x)))) | |||
| 169 | ||||
| 170 | ||||
| 171 | class NemotronH_Omni_Reasoning_V3VisionProjector(nn.Module): | |||
| 172 | """Single-forward vision pipeline: run the vision tower (image, or temporally-packed video) through | |||
| 173 | pixel-shuffle downsampling and the projection MLP (`mlp1`) into LLM-space embeddings. The | |||
| 174 | weight-bearing `vision_model` is passed in so its checkpoint keys stay at the top level. | |||
| 175 | """ | |||
| 176 | ||||
| 177 | def __init__(self, config): | |||
| 178 | super().__init__() | |||
| 179 | self.downsample_ratio = config.downsample_ratio | |||
| 180 | self.video_temporal_patch_dim = config.video_temporal_patch_size | |||
| 181 | self.ps_version = config.ps_version | |||
| 182 | self.mlp1 = NemotronH_Omni_Reasoning_V3MLP( | |||
| 183 | config.vit_hidden_size * int(1 / config.downsample_ratio) ** 2, | |||
| 184 | config.projector_hidden_size, | |||
| 185 | config.llm_config.hidden_size, | |||
| 186 | ) | |||
| 187 | # Mirror Megatron training behavior: when the language model has MTP, | |||
| 188 | # Megatron-Core's TransformerBlock places a final LayerNorm with the last | |||
| 189 | # layer of every block built from the (shared) config -- including the | |||
| 190 | # vision tower, whose config inherits `mtp_num_layers` from the language | |||
| 191 | # model. The vision tower output is therefore layer-normalized before the | |||
| 192 | # projector. LayerNorm is applied per token, so normalizing the RADIO | |||
| 193 | # features here is exactly equivalent to Megatron's block-internal | |||
| 194 | # placement before class-token stripping. | |||
| 195 | if (getattr(config.llm_config, "num_nextn_predict_layers", 0) or 0) > 0: | |||
| 196 | self.vision_final_layernorm = nn.LayerNorm( | |||
| 197 | config.vit_hidden_size, eps=config.vision_config.layer_norm_eps | |||
| 198 | ) | |||
| 199 | else: | |||
| 200 | self.vision_final_layernorm = None | |||
| 201 | ||||
| 202 | def pixel_shuffle(self, x, scale_factor=0.5): | |||
| 203 | n, w, h, c = x.size() | |||
| 204 | x = x.view(n, w, int(h * scale_factor), int(c / scale_factor)) | |||
| 205 | x = x.permute(0, 2, 1, 3).contiguous() | |||
| 206 | x = x.view( | |||
| 207 | n, | |||
| 208 | int(h * scale_factor), | |||
| 209 | int(w * scale_factor), | |||
| 210 | int(c / (scale_factor * scale_factor)), | |||
| 211 | ) | |||
| 212 | if self.ps_version == "v1": | |||
| 213 | warnings.warn( | |||
| 214 | "In ps_version 'v1', the height and width have not been swapped back, " | |||
| 215 | "which results in a transposed image." | |||
| 216 | ) | |||
| 217 | else: | |||
| 218 | x = x.permute(0, 2, 1, 3).contiguous() | |||
| 219 | return x | |||
| 220 | ||||
| 221 | def _project(self, vit_embeds, h, w): | |||
| 222 | if self.vision_final_layernorm is not None: | |||
| 223 | vit_embeds = self.vision_final_layernorm(vit_embeds) | |||
| 224 | vit_embeds = vit_embeds.reshape(vit_embeds.shape[0], h, w, -1) | |||
| 225 | vit_embeds = self.pixel_shuffle(vit_embeds, scale_factor=self.downsample_ratio) | |||
| 226 | vit_embeds = vit_embeds.reshape(vit_embeds.shape[0], -1, vit_embeds.shape[-1]) | |||
| 227 | return self.mlp1(vit_embeds) | |||
| 228 | ||||
| 229 | def forward(self, pixel_values, vision_model): | |||
| 230 | if isinstance(pixel_values, (list, tuple)): | |||
| 231 | return torch.cat([self.forward(pv, vision_model) for pv in pixel_values], dim=0) | |||
| 232 | pixel_values = pixel_values.to(dtype=vision_model.config.torch_dtype) | |||
| 233 | vit_embeds = vision_model(pixel_values).features | |||
| 234 | _, _, H, W = pixel_values.shape | |||
| 235 | patch_size = vision_model.patch_size | |||
| 236 | return self._project(vit_embeds, H // patch_size, W // patch_size) | |||
| 237 | ||||
| 238 | def forward_video(self, pixel_values_videos, vision_model): | |||
| 239 | pixel_values_videos = pixel_values_videos.to(dtype=vision_model.config.torch_dtype) | |||
| 240 | T = self.video_temporal_patch_dim | |||
| 241 | N, C, H, W = pixel_values_videos.shape | |||
| 242 | ||||
| 243 | if N % T != 0: | |||
| 244 | pad = pixel_values_videos[-1:].expand(T - (N % T), -1, -1, -1) | |||
| 245 | pixel_values_videos = torch.cat([pixel_values_videos, pad], dim=0) | |||
| 246 | N = pixel_values_videos.shape[0] | |||
| 247 | num_groups = N // T | |||
| 248 | ||||
| 249 | x = pixel_values_videos.reshape(num_groups, T * C, H, W) | |||
| 250 | vit_embeds = vision_model(x, use_video_patch_projection=True).features | |||
| 251 | patch_size = vision_model.patch_size | |||
| 252 | return self._project(vit_embeds, H // patch_size, W // patch_size) | |||
| 253 | ||||
| 254 | ||||
| 255 | def compute_retention_mask( | |||
| 256 | *, | |||
| 257 | video_embeds: torch.FloatTensor, | |||
| 258 | thw: torch.LongTensor, | |||
| 259 | spatial_merge_size: int, | |||
| 260 | q: float, | |||
| 261 | ): | |||
| 262 | """ | |||
| 263 | Computes the retention mask for video embeddings based on the grid dimensions. | |||
| 264 | ||||
| 265 | Args: | |||
| 266 | video_embeds (`torch.FloatTensor` of shape `(T * H * W, hidden_size)`): | |||
| 267 | The video embeddings to compute the retention mask for. | |||
| 268 | thw (`torch.LongTensor` of shape `(3)`): | |||
| 269 | The temporal, height and width of feature shape of each video in LLM. | |||
| 270 | spatial_merge_size (`int`): The spatial merge size of the video embeddings. | |||
| 271 | If embeddings will be downsampled *later*, this should be the downsampling factor. | |||
| 272 | q: (`float`): Pruning rate factor, indicating number of tokens to prune (remove) | |||
| 273 | ||||
| 274 | Returns: | |||
| 275 | `torch.Tensor`: The retention mask for the video embeddings (T * H * W). | |||
| 276 | 1 for tokens to keep, 0 for tokens to prune. | |||
| 277 | """ | |||
| 278 | T, H, W = thw | |||
| 279 | ||||
| 280 | # Use reshape instead of einops to avoid graph breaks | |||
| 281 | video_embeds = video_embeds.reshape(T, H // spatial_merge_size, W // spatial_merge_size, video_embeds.size(-1)) | |||
| 282 | ||||
| 283 | # Core EVS | |||
| 284 | similarity = torch.nn.functional.cosine_similarity(video_embeds[1:, ...], video_embeds[:-1, ...], dim=-1) | |||
| 285 | dissimilarity = 1 - similarity | |||
| 286 | ||||
| 287 | # Always ensure we include all tokens from the first frame | |||
| 288 | dissimilarity = torch.cat([255 * torch.ones_like(video_embeds[:1, :, :, 0]), dissimilarity], dim=0) | |||
| 289 | dissimilarity_flat = dissimilarity.view(-1) | |||
| 290 | ||||
| 291 | min_num_tokens = (H // spatial_merge_size) * (W // spatial_merge_size) # a single frame | |||
| 292 | evs_num_tokens = int(T * min_num_tokens * (1 - q)) | |||
| 293 | num_tokens_to_keep = max(min_num_tokens, evs_num_tokens) | |||
| 294 | ||||
| 295 | order = torch.argsort(dissimilarity_flat, dim=-1, descending=True, stable=True) | |||
| 296 | topk_indices = order[:num_tokens_to_keep] | |||
| 297 | ||||
| 298 | retention_mask = torch.zeros_like(dissimilarity_flat, dtype=torch.bool) | |||
| 299 | retention_mask[topk_indices] = True | |||
| 300 | retention_mask = retention_mask.reshape(dissimilarity.size()) | |||
| 301 | ||||
| 302 | mask = retention_mask.view(-1) # "T H W -> (T H W)" | |||
| 303 | return mask | |||
| 304 | ||||
| 305 | ||||
| 306 | class NemotronH_Omni_Reasoning_V3(PreTrainedModel, GenerationMixin): | |||
| 307 | config_class = NemotronH_Omni_Reasoning_V3_Config | |||
| 308 | main_input_name = "input_ids" | |||
| 309 | _supports_flash_attn_2 = True | |||
| 310 | _supports_flash_attn = True | |||
| 311 | _no_split_modules = ["NemotronHBlock"] | |||
| 312 | # Released checkpoints carry multi-token-prediction weights (no module here builds them) and | |||
| 313 | # input-conditioner statistics (the vision preprocessor is external in this composition). | |||
| 314 | _keys_to_ignore_on_load_unexpected = [r"mtp\.", r"input_conditioner\."] | |||
| 315 | ||||
| 316 | def __init__(self, config: NemotronH_Omni_Reasoning_V3_Config): | |||
| 317 | super().__init__(config) | |||
| 318 | register_nemotron_h_omni_conversion_mapping() | |||
| 319 | ||||
| 320 | image_size = config.force_image_size | |||
| 321 | patch_size = config.patch_size | |||
| 322 | self.patch_size = patch_size | |||
| 323 | self.template = config.template | |||
| 324 | self.num_image_token = int((image_size // patch_size) ** 2 * (config.downsample_ratio**2)) | |||
| 325 | self.downsample_ratio = config.downsample_ratio | |||
| 326 | self.image_tag_type = config.image_tag_type | |||
| 327 | self.img_context_token_id = config.img_context_token_id | |||
| 328 | self.video_context_token_id = config.video_context_token_id | |||
| 329 | ||||
| 330 | self.language_model = AutoModelForCausalLM.from_config(config.llm_config) | |||
| 331 | self.vision_model = RadioModel(config.vision_config) | |||
| 332 | self.vision_model.make_preprocessor_external() | |||
| 333 | ||||
| 334 | self.drop_vision_class_token = True | |||
| 335 | ||||
| 336 | llm_hidden_size = config.llm_config.hidden_size | |||
| 337 | ||||
| 338 | self.video_pruning_rate = config.video_pruning_rate | |||
| 339 | ||||
| 340 | self.vision_projector = NemotronH_Omni_Reasoning_V3VisionProjector(config) | |||
| 341 | ||||
| 342 | self.sound_context_token_id = config.sound_context_token_id | |||
| 343 | if config.sound_config is not None: | |||
| 344 | self.sound_projector = NemotronH_Omni_Reasoning_V3SoundProjector(config.sound_config, llm_hidden_size) | |||
| 345 | else: | |||
| 346 | self.sound_projector = None | |||
| 347 | ||||
| 348 | self.all_tied_weights_keys = {} | |||
| 349 | ||||
| 350 | self.post_init() | |||
| 351 | ||||
| 352 | def get_input_embeddings(self): | |||
| 353 | return self.language_model.get_input_embeddings() | |||
| 354 | ||||
| 355 | def set_input_embeddings(self, value): | |||
| 356 | self.language_model.set_input_embeddings(value) | |||
| 357 | ||||
| 358 | def forward( | |||
| 359 | self, | |||
| 360 | input_ids: torch.LongTensor = None, | |||
| 361 | pixel_values: torch.FloatTensor | None = None, | |||
| 362 | pixel_values_videos: torch.FloatTensor | None = None, | |||
| 363 | sound_clips: torch.FloatTensor | None = None, | |||
| 364 | attention_mask: torch.Tensor | None = None, | |||
| 365 | position_ids: torch.LongTensor | None = None, | |||
| 366 | image_flags: torch.LongTensor | None = None, | |||
| 367 | past_key_values: list[torch.FloatTensor] | None = None, | |||
| 368 | labels: torch.LongTensor | None = None, | |||
| 369 | inputs_embeds=None, | |||
| 370 | use_cache: bool | None = None, | |||
| 371 | output_attentions: bool | None = None, | |||
| 372 | output_hidden_states: bool | None = None, | |||
| 373 | return_dict: bool | None = None, | |||
| 374 | **kwargs, | |||
| 375 | ) -> CausalLMOutputWithPast: | |||
| 376 | if inputs_embeds is None: | |||
| 377 | inputs_embeds = self.get_input_embeddings()(input_ids) | |||
| 378 | ||||
| 379 | # Multimodal merges need `input_ids` to locate the placeholder tokens; skip them on the | |||
| 380 | # cached decode steps and the inputs-embeds-only path where `input_ids` is absent. | |||
| 381 | if pixel_values is not None and input_ids is not None: | |||
| 382 | image_embeds = self.vision_projector(pixel_values, self.vision_model) | |||
| 383 | if image_flags is not None: | |||
| 384 | image_embeds = image_embeds[image_flags.squeeze(-1) == 1] | |||
| 385 | image_embeds = image_embeds.to(inputs_embeds.device, inputs_embeds.dtype) | |||
| 386 | image_mask = (input_ids == self.img_context_token_id).unsqueeze(-1).expand_as(inputs_embeds) | |||
| 387 | inputs_embeds = inputs_embeds.masked_scatter(image_mask.to(inputs_embeds.device), image_embeds) | |||
| 388 | ||||
| 389 | if pixel_values_videos is not None and input_ids is not None: | |||
| 390 | video_embeds = self.vision_projector.forward_video(pixel_values_videos, self.vision_model) | |||
| 391 | video_embeds = video_embeds.to(inputs_embeds.device, inputs_embeds.dtype) | |||
| 392 | video_mask = (input_ids == self.img_context_token_id).unsqueeze(-1).expand_as(inputs_embeds) | |||
| 393 | inputs_embeds = inputs_embeds.masked_scatter(video_mask.to(inputs_embeds.device), video_embeds) | |||
| 394 | ||||
| 395 | if self.video_pruning_rate > 0: | |||
| 396 | h = w = int(video_embeds.shape[1] ** 0.5) | |||
| 397 | evs_mask = compute_retention_mask( | |||
| 398 | video_embeds=video_embeds, | |||
| 399 | thw=(video_embeds.shape[0], h, w), | |||
| 400 | spatial_merge_size=1, | |||
| 401 | q=self.video_pruning_rate, | |||
| 402 | ) | |||
| 403 | retention_mask = torch.ones_like(input_ids, dtype=torch.bool) | |||
| 404 | retention_mask[input_ids == self.img_context_token_id] = evs_mask.view(-1) | |||
| 405 | inputs_embeds = inputs_embeds[retention_mask].unsqueeze(0) | |||
| 406 | if attention_mask is not None: | |||
| 407 | attention_mask = attention_mask[retention_mask].unsqueeze(0) | |||
| 408 | input_ids = input_ids[retention_mask].unsqueeze(0) | |||
| 409 | ||||
| 410 | if sound_clips is not None and self.sound_projector is not None and input_ids is not None: | |||
| 411 | sound_embeds = self.sound_projector(sound_clips) | |||
| 412 | sound_embeds = sound_embeds.to(inputs_embeds.device, inputs_embeds.dtype) | |||
| 413 | sound_mask = (input_ids == self.sound_context_token_id).unsqueeze(-1).expand_as(inputs_embeds) | |||
| 414 | inputs_embeds = inputs_embeds.masked_scatter(sound_mask.to(inputs_embeds.device), sound_embeds) | |||
| 415 | ||||
| 416 | outputs = self.language_model( | |||
| 417 | inputs_embeds=inputs_embeds, | |||
| 418 | attention_mask=attention_mask, | |||
| 419 | position_ids=position_ids, | |||
| 420 | past_key_values=past_key_values, | |||
| 421 | use_cache=use_cache, | |||
| 422 | output_attentions=output_attentions, | |||
| 423 | output_hidden_states=output_hidden_states, | |||
| 424 | return_dict=True, | |||
| 425 | ) | |||
| 426 | logits = outputs.logits | |||
| 427 | ||||
| 428 | loss = None | |||
| 429 | if labels is not None: | |||
| 430 | shift_logits = logits[..., :-1, :].contiguous() | |||
| 431 | shift_labels = labels[..., 1:].contiguous() | |||
| 432 | loss_fct = CrossEntropyLoss() | |||
| 433 | shift_logits = shift_logits.view(-1, self.language_model.config.vocab_size) | |||
| 434 | shift_labels = shift_labels.view(-1) | |||
| 435 | shift_labels = shift_labels.to(shift_logits.device) | |||
| 436 | loss = loss_fct(shift_logits, shift_labels) | |||
| 437 | ||||
| 438 | return CausalLMOutputWithPast( | |||
| 439 | loss=loss, | |||
| 440 | logits=logits, | |||
| 441 | past_key_values=outputs.past_key_values, | |||
| 442 | hidden_states=outputs.hidden_states, | |||
| 443 | attentions=outputs.attentions, | |||
| 444 | ) | |||
| 445 | ||||
| 446 | def prepare_inputs_for_generation( | |||
| 447 | self, | |||
| 448 | input_ids, | |||
| 449 | past_key_values=None, | |||
| 450 | attention_mask=None, | |||
| 451 | inputs_embeds=None, | |||
| 452 | pixel_values=None, | |||
| 453 | pixel_values_videos=None, | |||
| 454 | sound_clips=None, | |||
| 455 | image_flags=None, | |||
| 456 | use_cache=True, | |||
| 457 | is_first_iteration=False, | |||
| 458 | **kwargs, | |||
| 459 | ): | |||
| 460 | model_inputs = super().prepare_inputs_for_generation( | |||
| 461 | input_ids, | |||
| 462 | past_key_values=past_key_values, | |||
| 463 | attention_mask=attention_mask, | |||
| 464 | inputs_embeds=inputs_embeds, | |||
| 465 | pixel_values=pixel_values, | |||
| 466 | pixel_values_videos=pixel_values_videos, | |||
| 467 | sound_clips=sound_clips, | |||
| 468 | image_flags=image_flags, | |||
| 469 | use_cache=use_cache, | |||
| 470 | is_first_iteration=is_first_iteration, | |||
| 471 | **kwargs, | |||
| 472 | ) | |||
| 473 | ||||
| 474 | # The multimodal inputs are only merged on the prefill step; drop them once the cache is warm. | |||
| 475 | if not is_first_iteration and use_cache: | |||
| 476 | model_inputs["pixel_values"] = None | |||
| 477 | model_inputs["pixel_values_videos"] = None | |||
| 478 | model_inputs["sound_clips"] = None | |||
| 479 | model_inputs["image_flags"] = None | |||
| 480 | ||||
| 481 | return model_inputs | |||
| 482 | ||||
| 483 | ||||
| 484 | __all__ = ["NemotronH_Omni_Reasoning_V3"] |