nemo_automodel.components.models.nemotron_omni.model
nemo_automodel.components.models.nemotron_omni.model
NemotronOmni (NemotronH_Nano_Omni_Reasoning_V3) custom model for Nemo Automodel.
This model is a VLM (vision-language model) with:
- Vision encoder: RADIO v2.5-H (ViT-Huge, patch_size=16) — loaded from HF
- Audio encoder: Parakeet (FastConformer-based) — loaded from HF
- LLM: NemotronH (hybrid Mamba+Attention MoE) — reuses nemotron_v3 custom implementation
- Projectors: MLP projectors for vision->LLM and audio->LLM
Architecture name: “NemotronH_Nano_Omni_Reasoning_V3” (from config.json)
Module Contents
Classes
Functions
Data
API
Bases: PretrainedConfig
Configuration for the NemotronOmni (NemotronH_Nano_Omni_Reasoning_V3) model.
This wraps the HF config and provides easy access to sub-configs.
Bases: HFCheckpointingMixin, Module, MoEFSDPSyncMixin
NemotronOmni VLM model for conditional generation (training).
Wraps:
- Vision encoder (RADIO v2.5-H) — HF implementation via trust_remote_code
- Audio encoder (Parakeet) — HF implementation via trust_remote_code
- Vision projector (MLP: RMSNorm -> Linear -> SquaredReLU -> Linear)
- Sound projector (MLP: RMSNorm -> Linear -> SquaredReLU -> Linear)
- Language model (NemotronH hybrid Mamba+Attention MoE) — nemotron_v3 custom impl
The LLM part reuses the nemotron_v3 implementation (NemotronHForCausalLM) which has custom DTensor parallelism for the Mamba+Attention hybrid MoE architecture.
Whether the wrapped NemotronV3 LM computes MTP outputs during model.eval().
Return the nested language-model output head without re-registering it.
The LM’s MTP head (so the MoE parallelizer / FSDP block iteration find its MoE sublayers).
MTP head configuration of the wrapped NemotronV3 LM (drives supports.mtp_enabled).
Embed local future tokens and restore their encoded media features.
Parameters:
Globally shifted, boundary-masked token IDs, each shaped [local_tokens] for THD or [batch, local_sequence].
Int64 Tensor of shape [local_tokens], mapping the flattened local layout to the original global token stream. Required only when media_features is nonempty.
Maps each media placeholder token ID to a pair of encoded features [global_media_tokens, hidden] and Int64 feature ordinals [global_tokens]. Both follow the original global token order and are computed once per forward; features retain the encoder’s autograd graph.
Optional Boolean tensors with the same shapes as per_depth_input_ids; false entries cannot consume media.
Returns: torch.Tensor
Per-depth tensors shaped […, hidden], matching each ID tensor’s
Encode a dense image batch, applying the final norm before pixel shuffle.
Parameters:
Images shaped [batch, channels, height, width].
Returns: torch.Tensor
Projected features shaped [batch, image_tokens, llm_hidden_size].
Encode a dense image batch before projector-owned normalization.
Parameters:
Images shaped [tiles, channels, height, width].
Returns: torch.Tensor
BF16 features [tiles, patches, vision_hidden] and their (height, width)
Convert persistent buffers that are NOT saved in HF checkpoints to non-persistent buffers.
The RADIO vision encoder registers some buffers (e.g. summary_idxs)
as persistent, but the HF checkpoint does not contain them. When the DCP
loader builds its load plan it expects every persistent buffer to appear
in the checkpoint and raises RuntimeError: Missing key otherwise.
This method re-registers such buffers as non-persistent so they are kept at their init-time values and not expected on disk.
Recover a packed partition when the sharder did not supply it.
Parameters:
Tensor of shape [documents + 1] or [1, documents + 1], containing global physical boundaries and optional -1000 padding.
Number of physical tokens in the global stream.
Number of CP ranks.
Rank within the CP group.
Returns: torch.Tensor
Int64 Tensor of shape [local_tokens] in TE head-tail order.
Per-image pixel-shuffle for dynamic-resolution outputs.
Ported from vLLM’s NanoNemotronVLMultimodal.pixel_shuffle_dynamic_res.
Splits x along the sequence dim by per-image patch counts, reshapes
each split to (N, H_patches, W_patches, C_feat), applies pixel_shuffle
with downsample_ratio, and flattens back to a concatenated (N, L’, C).
Pick this CP rank’s slice of full-sequence media features (packed THD CP).
The framework TE THD sharder hands forward an input_ids shard (TE’s
per-document partition) while the media encoders ran on every image /
clip, so features is ordered by GLOBAL placeholder position. Map each
local token to its global position, then to its feature row.
Parameters:
Tensor of shape [num_global_media_tokens, hidden], ordered by media-placeholder position in the global packed sequence.
Boolean Tensor of shape [global_tokens], flattened from the global packed sequence, with true entries at media placeholders.
Boolean Tensor of shape [local_tokens], with true entries at media placeholders in this rank’s TE THD partition.
Int32 Tensor of shape [num_documents + 1] containing cumulative physical document boundaries for the global packed sequence.
Number of context-parallel ranks.
This rank’s zero-based index in the context-parallel group.
Optional Tensor of shape [local_tokens] with the partition already computed by the native THD sharder.
Optional Int64 Tensor of shape [global_tokens] containing cached global media-feature ordinals.
Returns: torch.Tensor
Tensor of shape [num_local_media_tokens, hidden] containing this rank’s
Extract vision features from pixel values through RADIO + projector.
Parameters:
Image tensors [num_tiles, C, H, W], or a list of
per-image tensors ([C, H, W] or [num_tiles, C, H, W]) when the
batch mixes resolutions and cannot be stacked. The collate fn
(nemotron_omni_collate_fn) emits the list form whenever the
dataset is variable-resolution and local_batch_size > 1.
Returns: torch.Tensor | list[torch.Tensor]
Vision embeddings [num_tiles, num_tokens, llm_hidden_size], or, for
Dynamic-resolution feature extraction (no tile splitting).
Matches vLLM’s dynamic-resolution vision path for Nano v3 VL /
Nemotron-Omni (see 3rdparty/vllm/vllm/model_executor/models/
nano_nemotron_vl.py). Required when the rollout uses
DynamicResolutionImageTiler — tile-based extract_feature would
produce different embeddings and break rollout/train logprob
agreement.
Unlike vLLM’s RADIO port (which supports packed imgs_sizes= inputs),
the HF RADIO from nvidia/C-RADIOv2-H only accepts a dense
(B, C, H, W) tensor. We crop each padded image back to its real
size and run the vision model per-image, then concatenate features.
Parameters:
[num_images, C, H_padded, W_padded] batch of dynamically-resized images padded to the batch max (h, w).
[num_images, 2] actual (h, w) per image (torch tensor of ints) or an equivalent list of tuples.
Returns: torch.Tensor
Vision embeddings [sum_num_embeddings_after_pixel_shuffle,
Extract and project sound features from audio input.
Parameters:
Mel spectrogram features [batch, seq_len, feature_dim]
Optional attention mask [batch, seq_len]
Returns: torch.Tensor
Sound embeddings projected to LLM hidden size
Encode consecutive frame groups with the checkpoint’s temporal projector.
Parameters:
Tensor of shape [frames, channels, height, width]. Frames belong to one video and share a spatial grid. The final frame is repeated to complete a temporal group when necessary.
Returns: torch.Tensor
Tensor of shape [groups, image_tokens, llm_hidden], where groups is
Forward pass for training.
This follows the same pattern as the HF NemotronH_Nano_Omni_Reasoning_V3.forward():
- Get text embeddings from LLM embed_tokens
- Extract vision features from pixel_values
- Replace image token embeddings with vision embeddings
- Run LLM forward pass
- Compute loss if labels provided
Parameters:
Image pixel values [num_tiles, C, H, W]
Token IDs of shape [batch, sequence] before BSHD CP sharding, or [local_tokens] after packed THD sharding.
Attention mask [batch, seq_len]
Position IDs (ignored by the RoPE-free backbone; forwarded to the MTP head)
Flags indicating real images vs padding [num_tiles, 1]
Token IDs for loss computation [batch, seq_len]
Optional precomputed embeddings of shape [batch, local_sequence, hidden] or [local_tokens, hidden]. With CP MTP, this entry point supports text only: media futures require the original IDs and media inputs to preserve global features.
Whether to use caching (not used in training)
Whether the returned output should carry the
final decoder hidden states (required for fused linear
cross-entropy / cut-CE). Defaults to the text sub-config’s
output_hidden_states when None.
If 0 (default), compute logits for all positions;
if > 0, only compute logits for the last logits_to_keep
positions (used by fused linear cross-entropy to avoid the full
logit matrix). Forwarded to the language-model lm_head gating.
Additional arguments
Returns: Union[dict, Tuple, CausalLMOutputWithPast]
CausalLMOutputWithPast with loss and logits
Create model from config.
Parameters:
NemotronH_Nano_Omni_Reasoning_V3 config (HF config with trust_remote_code)
Backend configuration
Additional arguments
Returns:
NemotronOmniForConditionalGeneration instance
Load pretrained model.
Parameters:
Path or name of pretrained model
Additional positional arguments
Additional keyword arguments
Returns:
NemotronOmniForConditionalGeneration instance
Return the input embeddings from the language model.
Return the output embeddings (lm_head) from the language model.
Initialize model weights.
Parameters:
Device to use for buffer initialization
Target dtype for model weights
Pixel shuffle for downsampling spatial resolution while increasing channels.
Parameters:
Input tensor [N, W, H, C]
Downsampling ratio (default 0.5 = halve spatial dims)
Returns: torch.Tensor
Shuffled tensor [N, Wscale, Hscale, C/(scale^2)]
Return a sharder-only CP backend; embed + splice + shard happen in forward.
Embedding and the image/video/audio multimodal scatter now run inside
forward per microbatch (the existing inputs_embeds is None block),
which then round-robin shards the result with
shard_sequence_for_cp_round_robin. The returned
ContextParallelSharder round-robin-shards only the no-grad aux
streams (labels/position_ids/loss_mask/padding_mask) and leaves
input_ids and the media inputs full-length for the forward. NemotronOmni
uses plain 1-D positions, so no position_ids are computed here.
Parameters:
The full-sequence batch (with input_ids [batch, sequence]); left intact.
Accepted for hook-signature parity; unused (round-robin CP).
Globally ordered MTP future-token inputs/targets, prepared before CP sharding.
Delegates to the NemotronV3 LM (the batch is still the full text-token stream; media placeholders are ordinary tokens at this stage).
Set the input embeddings of the language model.
Set the output embeddings (lm_head) of the language model.
Bases: Module
Root Mean Square Layer Normalization.
Bases: Module
MLP projector from sound encoder to LLM hidden space.
HF checkpoint structure: sound_projection.norm.weight -> RMSNorm weight (sound_hidden_size,) sound_projection.linear1.weight -> Linear1 weight (projection_hidden_size, sound_hidden_size) sound_projection.linear2.weight -> Linear2 weight (llm_hidden_size, projection_hidden_size)
Bases: Module
Squared ReLU activation: ReLU(x)^2.
Bases: Module
MLP projector from vision encoder to LLM hidden space.
HF checkpoint structure (mlp1): mlp1.0.weight -> RMSNorm weight (vit_hidden_size * pixel_shuffle_factor^2,) mlp1.1.weight -> Linear1 weight (projector_hidden_size, vit_hidden_size * pixel_shuffle_factor^2) mlp1.3.weight -> Linear2 weight (llm_hidden_size, projector_hidden_size)
Between linear1 and linear2 there is a SquaredReLU activation (index 2 in Sequential, but it has no weight). Super 3.5 also stores a vision_final_layernorm here; forward applies it before pixel shuffle.
Normalize raw patch features, shuffle each image, then project.
Parameters:
Raw features [batch, sum_patches, vit_hidden_size] when patch_grid_shapes is provided; otherwise already shuffled features [batch, image_tokens, pixel_shuffle_channels].
Per-image (height, width) in patches.
Checkpoint pixel-shuffle layout version.
Returns: torch.Tensor
Projected features [batch, image_tokens, llm_hidden_size].
Thin proxy so the MoE parallelizer can navigate model.model.moe_config and model.model -> get_text_module -> .layers without changing the weight hierarchy.
The parallelizer (parallelizer.py) expects: model.model.moe_config (for expert-count validation) model.model -> get_text_module() (finds language_model attr) -> .layers
By setting self.model = _ModelProxy(self.language_model) on the VLM: model.model.moe_config -> language_model.model.moe_config OK get_text_module(model.model) -> model.model.language_model == language_model.model (NemotronV3Model) -> .layers OK
Rearrange spatial patches into channels with the checkpoint layout.
Parameters:
Features shaped [batch, grid_height, grid_width, hidden_size].
Spatial downsampling ratio.
Pixel-shuffle layout version.
Returns: torch.Tensor
Features with downsampled spatial axes and expanded channels.