nemo_automodel.components.utils.model_utils
nemo_automodel.components.utils.model_utils
Module Contents
Classes
Functions
Data
API
Typed schema for the freeze_config recipe section.
Trainability semantics, in application order:
- Full fine-tuning preserves the model’s existing trainability state; PEFT establishes a LoRA-trainable, base-frozen baseline.
freeze_modulesrecursively freezes the selected modules.unfreeze_modulesrecursively unfreezes the selected modules and wins on overlap.- Framework-required freezes (dead K/V projections, indexer parameters) are applied by the infrastructure afterwards and remain protected.
- The final trainable parameter set is validated before the optimizer is constructed.
The legacy modality booleans remain supported. freeze_vision_tower
defaults to True only for legacy-only configurations; a configuration
that declares freeze_modules or unfreeze_modules uses
explicit-selector semantics and does not implicitly freeze vision modules.
Validate selectors and legacy compatibility options.
Return whether either generic selector field was explicitly declared.
Select modules by exact canonical path or case-sensitive shell-style glob.
Exactly one of path or glob must be set. Both match against the full
canonical module path (activation-checkpoint and torch.compile wrapper
components stripped): path is an exact match, while glob uses
:func:fnmatch.fnmatchcase semantics where * also crosses .
separators. Matching is recursive: a selected module’s entire subtree is
frozen or unfrozen.
Validate that exactly one matching mode is configured.
Return the selector in its key: value configuration form.
Return whether this selector matches a canonical module path.
Parameters:
Canonical fully qualified module path.
Returns: bool
Whether the selector matches module_path.
Set requires_grad on every module matched by selectors, recursively.
Module paths are canonicalized (activation-checkpoint and _orig_mod
wrapper components stripped) so selectors keep matching after model surgery
that wraps or renames parameter-holding modules.
Parameters:
The model (or pipeline-parallel model part) to modify.
Typed selectors to resolve against the module hierarchy.
Trainability to apply to matched modules.
When True, raise if a selector matches no parameters. Rebinding after parallelization uses False because sharding may relocate or regroup the selected modules (e.g. pipeline stages hold only a part of the model).
Owning FreezeConfig field name, used in error messages.
Raises:
ValueError: Ifstrictand a selector matches no parameters.
Freeze a legacy model attribute and modules matching name substrings.
Best-effort retrieval cached by the underlying forward callable.
Retrieve model.forward once per callable, preserving live patches.
Return the logical number of elements for a parameter, accounting for quantized (packed) storage.
For bitsandbytes 4-bit params (Params4bit), the physical tensor packs multiple values per byte. We recover the logical count from the original shape stored in param.quant_state.
Get the number of trainable parameters and the L2 norm of the model.
Parameters:
Model to analyze
Returns: int
int
Parse one freeze_modules/unfreeze_modules entry into a ModuleSelector.
Parameters:
Mapping with exactly one of path or glob, or an existing
ModuleSelector.
Owning list field name, used in error messages.
Returns: ModuleSelector
The validated ModuleSelector.
Raises:
ValueError: If the entry is not a{path: ...}/{glob: ...}mapping or contains unknown keys.
Check if the model supports logits_to_keep.
Parameters:
The model to check.
Returns: bool
True if the model supports logits_to_keep, False otherwise.
Check if the model’s forward() accepts seq_lens.
Returns True if:
- forward() has an explicit
seq_lensparameter, OR - forward() has **kwargs (so it won’t crash if seq_lens is passed)
Returns False otherwise (passing seq_lens would cause “unexpected kwarg” error).
Apply parameter freezing based on a typed FreezeConfig.
Application order: legacy modality booleans and freeze_modules freeze,
then unfreeze_modules unfreezes and wins on overlap. Framework-required
freezes (dead K/V projections, indexer parameters) are applied separately
by the infrastructure after this function, before and after sharding.
Parameters:
The model to apply freezing to.
Typed freeze configuration or a raw mapping retained for compatibility with direct callers. Raw mappings are validated and converted to FreezeConfig before use.
When True, raise if a freeze_modules/unfreeze_modules
selector matches no parameters. Set False when rebinding the policy
onto a post-parallelization model part.
Cast fp32 parameters and buffers to bf16 for FSDP2 compatibility.
Count total and trainable parameters. Safe to call on meta-device models.
Parameters:
Model to analyze
Returns: int
int
Route RADIO ViT attention through F.scaled_dot_product_attention.
RADIO’s timm Attention blocks default to fused_attn=False, which
materializes the full (B, H, seq, seq) attention tensor (~5 GiB per
block at RADIO-v2-H + dynamic-resolution patch counts). Flipping
fused_attn=True matches the Megatron-Bridge path which sets
vision_config.use_flash_attn=True via
attn_implementation="flash_attention_2".
No-op when the model has no RADIO vision tower.
Parameters:
The model to patch in place.
Drop kwargs that model.forward does not accept.
If the model exposes **kwargs or its signature cannot be inspected, the
input kwargs are returned unchanged. The original dict is never mutated.
Freeze DeepSeek V4 indexer params that only feed discrete top-k masks.
Freeze MiniMax M3 lightning-indexer params that only feed discrete top-k masks.
Freeze dead K/V parameters in KV-shared layers.
Models like Gemma4 E2B/E4B use KV-sharing where the last N layers reuse
key/value states from earlier layers. The k_proj, v_proj,
k_norm, and v_norm modules still exist in those shared layers but
are never used during forward. Their parameters therefore receive no
gradients, yet the optimizer still tracks them. On checkpoint resume the
distributed checkpoint framework expects optimizer state for every
parameter the optimizer was created with, but zero-gradient params may
have been excluded from the saved state — causing a RuntimeError.
Calling this function before optimizer creation sets
requires_grad=False on the dead parameters so the optimizer never
tracks them, keeping save and load consistent.
Parameters:
The model (or pipeline-parallel model part).
Return the model’s LM head module, if one can be found.
Return the model’s LM-head weight, materializing DTensor weights when needed.
A context manager under which models are initialized with all parameters on the specified device.
Example:
Parameters:
Device to initialize all parameters on.
Validate raw freeze_config YAML data and return a typed FreezeConfig.
Parameters:
A FreezeConfig (returned unchanged), a raw mapping from the recipe config, or None.
Returns: FreezeConfig | None
The validated FreezeConfig, or None when no freeze configuration was
Raises:
TypeError: Ifconfigis neither a mapping nor a FreezeConfig.ValueError: Ifconfigcontains unknown options, malformed selectors, or non-boolean legacy options.
Print the number of trainable parameters in the model.
Parameters:
Model to analyze
Label for the summary header (e.g. "Draft" to distinguish the
draft model from the target in speculative-decoding training).
Returns: int
int
Whitelist NVIDIA models to allow remote code execution.
Parameters:
The name or path of the pretrained model.
Returns:
True if the model should be loaded with trust_remote_code, False otherwise.
Context manager to skip random weight initialization when loading pretrained models.
Squeeze batch dimension and prepare inputs for THD (total, hidden, depth) format.
This function removes the batch dimension from input tensors and processes attention kwargs for use with Transformer Engine’s THD format. It’s typically used when the batch has already been converted to THD format (with batch_size=1 as a placeholder dimension) and that dimension needs to be removed.
The function performs three key operations:
- Removes the batch dimension (dim 0) from input tensors
- Filters out padding values from cumulative sequence length tensors
- Converts max_seqlen from tensor to scalar if needed
Parameters:
Input token IDs with shape [1, total_tokens]
or [1, total_tokens, hidden_dim]. The first dimension will be squeezed.
None is permitted when the caller is feeding the model via
inputs_embeds instead — embeddings are squeezed inside the model
forward (the squeezed_for_thd branch in NemotronHModel.forward
and analogous code paths), so this helper has nothing to squeeze and
simply returns None for the input_ids slot.
Position IDs with shape [1, total_tokens]. The first dimension will be squeezed.
Padding mask with shape [1, total_tokens]. The first dimension will be squeezed.
Dictionary of attention-related tensors. May contain:
- cu_seqlens: Cumulative sequence lengths [1, num_seqs+1]
- cu_seqlens_padded: Cumulative padded sequence lengths [1, num_seqs+1]
- max_seqlen: Maximum sequence length (tensor or int)
- Other attention parameters (will be squeezed if tensors)
Sentinel value used to indicate padding in cu_seqlens and cu_seqlens_padded tensors. These values will be filtered out. Default: -1000.
Returns:
A tuple containing:
- input_ids (torch.Tensor): Input IDs with batch dimension removed [total_tokens] or [total_tokens, hidden_dim]
- position_ids (torch.Tensor): Position IDs with batch dimension removed [total_tokens]
- padding_mask (torch.Tensor): Padding mask with batch dimension removed [total_tokens]
- attn_kwargs (dict): Updated attention kwargs with:
- Batch dimensions removed from all tensor values
- Padding values filtered from cu_seqlens and cu_seqlens_padded
- max_seqlen converted to scalar if it was a tensor