Skip to navigation

nemo_automodel.components.checkpoint.stateful_wrappers

View as MarkdownOpen in Claude

Module Contents

Classes

NameDescription
ModelStateHelper class for tracking model state in distributed checkpointing.
OptimizerStateHelper class for tracking optimizer state in distributed checkpointing.
SketchStateOptimizerOptimizer exposing extra state that DCP’s optimizer state dict does not carry (gradient sketch).
_TrainableModuleLayoutWhere a PEFT model’s trainable non-LoRA parameters sit in its module tree.

Functions

NameDescription
_add_outer_prefixPrepend prefix once to every key in-place (inverse of _drop_outer_prefix).
_broadcast_tensors_across_groupGive every rank of group the tensors that each rank holds, one tensor at a time.
_combined_trainable_module_layoutReturn the trainable-module layout of the whole model, combining pipeline stages.
_copy_full_tensor_intoCopy an unsharded checkpoint tensor into a parameter’s or buffer’s storage.
_dcp_module_pathNormalize a named_modules() path the way _dcp_parameter_name normalizes parameter names.
_dcp_parameter_nameNormalize a named_parameters() name to the key DCP’s state dict uses for it.
_drop_outer_prefixRemove the first occurrence of prefix on every key in-place.
_full_module_ofReturn the module a PEFT checkpoint stores whole for the trainable parameter name.
_fully_trained_modulesReturn the modules a PEFT checkpoint stores whole, under their native names.
_gather_peft_state_dict_across_ppAll-gather PEFT adapter tensors across a pipeline-parallel group.
_get_lm_head_weight_and_name-
_get_peft_full_module_buffersCollect the persistent buffers of the modules a PEFT checkpoint stores whole, bypassing DCP.
_get_peft_state_dictExtract only trainable PEFT adapter weights, bypassing DCP.
_has_expert_parallelismCheck if any MoE expert module in the model has expert parallelism enabled.
_has_quantized_paramsCheck if model has any BitsAndBytes quantized modules.
_is_quantized_moduleCheck if a module is a BitsAndBytes quantized type.
_iter_peft_full_module_buffersYield the persistent buffers of the modules a PEFT checkpoint stores whole.
_lora_adapted_moduleReturn the path of the module that owns the LoRA parameter name.
_materialize_missing_adam_stateCreate zero-valued Adam state for parameters that do not have state yet.
_materialize_native_fused_adam_stateCreate the state a never-stepped TE FusedAdam would otherwise allocate in its first step().
_rename_dora_keys_from_hfReverse of _rename_dora_keys_to_hf: convert HF PEFT key format back to internal names.
_rename_dora_keys_to_hfRename DoRA magnitude keys to match HF PEFT’s saved checkpoint format in-place.
_safe_op_set_extra_state-
_safe_set_extra_state-
_select_peft_tensorsKeep the entries of a PEFT model’s DCP state dict that its checkpoint holds.
_set_peft_state_dictLoad PEFT checkpoint tensors into the model, bypassing DCP.
_trainable_module_layoutDescribe the trainable non-LoRA parameters of local model parts.
_trainable_non_lora_parameter_namesReturn the DCP state-dict names of trainable parameters that are not LoRA weights.
_validate_trainable_module_layoutReject trainable non-LoRA parameters that an HF PEFT adapter cannot restore.
_zeros_like_optimizer_paramAllocate zero optimizer state matching a parameter.
fully_trained_peft_modulesReturn the modules a PEFT adapter checkpoint stores whole, for modules_to_save.
validate_peft_trainable_modulesCheck that a PEFT model’s trainable parameters fit an HF PEFT adapter checkpoint.

Data

_OPTIMIZER_PARTS_KEY

_OPTIMIZER_PART_KEY_PREFIX

_PREFIX

_UNWRAPPABLE_MODULE_TYPES

_original_op_set_extra_state

_original_set_extra_state

API

class nemo_automodel.components.checkpoint.stateful_wrappers.ModelState(
model: torch.nn.Module | list[torch.nn.Module],
is_peft: bool = False,
is_init_step: bool = False,
skip_task_head_prefixes: list[str] | None = None,
cpu_offload: bool = False,
pp_group: torch.distributed.ProcessGroup | None = None,
has_expert_parallelism: bool = False
)

Helper class for tracking model state in distributed checkpointing.

This class is compliant with the Stateful protocol, allowing DCP to automatically call state_dict/load_state_dict as needed in the dcp.save/load APIs.

Parameters:

model
torch.nn.Module | list[torch.nn.Module]

The PyTorch model to track.

has_local_tied_lm_head
= has_local_tied_lm_head(self.model[0])
model
skip_task_head_prefixes
= skip_task_head_prefixes or []
uses_tied_lm_head
= is_tied_word_embeddings(self.model[0])
nemo_automodel.components.checkpoint.stateful_wrappers.ModelState._get_base_model_state_dict() -> dict[str, typing.Any]
nemo_automodel.components.checkpoint.stateful_wrappers.ModelState._refresh_local_tied_lm_head() -> None

Refresh tied-head metadata after DCP has normalized module state.

nemo_automodel.components.checkpoint.stateful_wrappers.ModelState._set_base_model_state_dict(
state_dict: dict[str, typing.Any]
) -> None
nemo_automodel.components.checkpoint.stateful_wrappers.ModelState.load_state_dict(
state_dict: dict[str, typing.Any],
strict: bool = True,
broadcast_from_rank0: bool = True
) -> None

Load the state dictionary into the model.

Parameters:

state_dict
dict[str, Any]

Model state mapping whose tensor values may have arbitrary rank and axis order and retain each parameter or buffer’s exact shape and DTensor placement.

strict
boolDefaults to True

Whether missing or unexpected keys should fail the load.

broadcast_from_rank0
boolDefaults to True

Whether rank 0 owns the full PEFT state dict. Set to False when every rank in a model-local process group loaded the adapter independently.

nemo_automodel.components.checkpoint.stateful_wrappers.ModelState.state_dict() -> dict[str, typing.Any]

Get the model’s state dictionary.

Returns: dict[str, Any]

Dictionary containing the model state dict, optionally offloaded to CPU.

class nemo_automodel.components.checkpoint.stateful_wrappers.OptimizerState(
model: torch.nn.Module | list[torch.nn.Module],
optimizer: torch.optim.Optimizer | list[torch.optim.Optimizer],
scheduler: typing.Any | None = None,
is_peft: bool = False,
cpu_offload: bool = False,
has_expert_parallelism: bool = False,
optimizer_part_ids: list[int] | None = None
)

Helper class for tracking optimizer state in distributed checkpointing.

This class is compliant with the Stateful protocol, allowing DCP to automatically call state_dict/load_state_dict as needed in the dcp.save/load APIs.

Parameters:

model
torch.nn.Module | list[torch.nn.Module]

The PyTorch model associated with the optimizer.

optimizer
torch.optim.Optimizer | list[torch.optim.Optimizer]

The optimizer to track.

scheduler
Any | NoneDefaults to None

Optional learning rate scheduler.

_use_native_optimizer_state
model
optimizer
scheduler
nemo_automodel.components.checkpoint.stateful_wrappers.OptimizerState._sketch_optimizer() -> nemo_automodel.components.checkpoint.stateful_wrappers.SketchStateOptimizer | None

Return the single gradient sketch optimizer among the parts, or None.

nemo_automodel.components.checkpoint.stateful_wrappers.OptimizerState.load_state_dict(
state_dict: dict[str, typing.Any]
) -> None

Load the state dictionaries into the optimizer and scheduler.

Parameters:

state_dict
dict

State dictionary containing optimizer and scheduler states to load.

nemo_automodel.components.checkpoint.stateful_wrappers.OptimizerState.state_dict() -> dict[str, typing.Any]

Get the optimizer and scheduler state dictionaries.

Returns: dict[str, Any]

Dictionary containing the optimizer and scheduler state dicts, optionally offloaded to CPU.

class nemo_automodel.components.checkpoint.stateful_wrappers.SketchStateOptimizer()
Protocol

Optimizer exposing extra state that DCP’s optimizer state dict does not carry (gradient sketch).

Matched structurally so checkpointing does not import the optim component; plain torch.optim.Optimizer instances have neither method.

nemo_automodel.components.checkpoint.stateful_wrappers.SketchStateOptimizer.load_sketch_state_dict(
sketch_state: dict[str, torch.Tensor]
) -> None
nemo_automodel.components.checkpoint.stateful_wrappers.SketchStateOptimizer.sketch_state_dict() -> dict[str, torch.Tensor]
class nemo_automodel.components.checkpoint.stateful_wrappers._TrainableModuleLayout(
trainable: frozenset[str],
aliased: tuple[tuple[str, ...], ...],
adapted: frozenset[str],
fully_trainable: dict[str, bool],
containers: frozenset[str]
)
Dataclass

Where a PEFT model’s trainable non-LoRA parameters sit in its module tree.

freeze_config can make parameters trainable next to the LoRA adapters (for example unfreeze_modules). Those train in full, so the adapter checkpoint stores them whole and names their modules in modules_to_save, which tells Hugging Face PEFT to restore them. All names use the DCP state-dict normalization.

adapted
frozenset[str]

Paths of the modules that own LoRA parameters.

aliased
tuple[tuple[str, ...], ...]

Name groups of trainable non-LoRA parameters that are registered under several names, such as tied input and output embeddings.

containers
frozenset[str]

Paths of the ModuleList, ModuleDict, ParameterList and ParameterDict modules, which HF PEFT cannot wrap in modules_to_save.

fully_trainable
dict[str, bool]

For every module path that holds parameters, whether all of them are trainable non-LoRA parameters.

trainable
frozenset[str]

Names of trainable parameters that are not LoRA weights, one name per parameter.

Combine the layouts of two pipeline stages that hold different parameters.

A module path present on both stages is fully trainable only if it is on each.

nemo_automodel.components.checkpoint.stateful_wrappers._add_outer_prefix(
sd: dict[str, typing.Any],
prefix: str = _PREFIX,
skip_keys: list[str] | None = None
) -> None

Prepend prefix once to every key in-place (inverse of _drop_outer_prefix).

nemo_automodel.components.checkpoint.stateful_wrappers._broadcast_tensors_across_group(
local_tensors: dict[str, torch.Tensor],
group: torch.distributed.ProcessGroup
) -> dict[str, torch.Tensor]

Give every rank of group the tensors that each rank holds, one tensor at a time.

all_gather_object pickles each rank’s whole payload and stages the payloads of all ranks on every rank’s device at once, so a large tensor, such as a trained embedding, costs several times its size in device memory there. Here only names, shapes and dtypes go through the object gather. Each tensor’s bytes are then broadcast from the rank that holds it, so a rank stages at most one tensor on its device at a time. Every rank of group must call this together.

Parameters:

local_tensors
dict[str, torch.Tensor]

This rank’s CPU tensors keyed by name, of arbitrary rank (including 0-dim), shape and dtype. Each moves whole, so it holds the full tensor rather than a shard. The mapping is not mutated.

group
torch.distributed.ProcessGroup

Process group whose ranks exchange their tensors.

Returns: dict[str, torch.Tensor]

CPU tensors from every rank of group, keyed by name. When several ranks hold a name,

nemo_automodel.components.checkpoint.stateful_wrappers._combined_trainable_module_layout(
model_parts: collections.abc.Sequence[torch.nn.Module],
pp_group: torch.distributed.ProcessGroup | None = None

Return the trainable-module layout of the whole model, combining pipeline stages.

Under pipeline parallelism each rank holds some stages, so the layouts of all stages are gathered and merged, and every rank returns the same layout. Every rank of pp_group must call this together.

Parameters:

model_parts
Sequence[torch.nn.Module]

This rank’s model or pipeline-stage parts, optionally wrapped in DDP.

pp_group
torch.distributed.ProcessGroup | NoneDefaults to None

Pipeline-parallel process group, or None without pipeline parallelism.

Returns: _TrainableModuleLayout

The layout of every parameter of the model.

nemo_automodel.components.checkpoint.stateful_wrappers._copy_full_tensor_into(
target: torch.Tensor,
full_tensor: torch.Tensor
) -> None

Copy an unsharded checkpoint tensor into a parameter’s or buffer’s storage.

Parameters:

target
torch.Tensor

Destination parameter data or buffer, of arbitrary shape. A DTensor receives the shard of full_tensor that its placements assign to this rank.

full_tensor
torch.Tensor

Tensor with the destination’s global shape.

nemo_automodel.components.checkpoint.stateful_wrappers._dcp_module_path(
path: str
) -> str

Normalize a named_modules() path the way _dcp_parameter_name normalizes parameter names.

nemo_automodel.components.checkpoint.stateful_wrappers._dcp_parameter_name(
name: str
) -> str

Normalize a named_parameters() name to the key DCP’s state dict uses for it.

DCP drops activation-checkpoint and torch.compile wrapper components; DDP’s module. prefix is handled by unwrapping the model before naming parameters.

nemo_automodel.components.checkpoint.stateful_wrappers._drop_outer_prefix(
sd: dict[str, typing.Any],
prefix: str = _PREFIX
) -> None

Remove the first occurrence of prefix on every key in-place.

nemo_automodel.components.checkpoint.stateful_wrappers._full_module_of(
name: str
) -> str

Return the module a PEFT checkpoint stores whole for the trainable parameter name.

This is the largest module on the parameter’s path that HF PEFT can wrap and whose parameters all train in full; an empty string when there is none. HF PEFT wraps every module listed in modules_to_save and loads all of its state-dict entries from the adapter file. Listing a submodule of a fully trained module breaks loading when PEFT also wraps the parent; for sequence classification it always wraps classifier/score. Containers such as a ModuleList of decoder layers cannot be wrapped, so the search continues past them: a trained model.layers is stored as model.layers.0, model.layers.1, and so on, unless an enclosing module such as model trains in full as well.

Parameters:

layout
_TrainableModuleLayout

Layout of the whole model, from _combined_trainable_module_layout.

name
str

A trainable non-LoRA parameter name from layout.trainable.

Returns: str

The module’s native name.

nemo_automodel.components.checkpoint.stateful_wrappers._fully_trained_modules(
) -> list[str]

Return the modules a PEFT checkpoint stores whole, under their native names.

Each entry is the largest module that HF PEFT can wrap and whose parameters are all trainable and none of them LoRA weights; see _full_module_of.

This only names the modules. fully_trained_peft_modules, which writers of adapter_config.json use, rejects layouts HF PEFT cannot restore first.

Parameters:

layout
_TrainableModuleLayout

Layout of the whole model, from _combined_trainable_module_layout.

Returns: list[str]

Sorted module names. Empty when only LoRA weights train.

nemo_automodel.components.checkpoint.stateful_wrappers._gather_peft_state_dict_across_pp(
local_state_dict: dict[str, typing.Any],
pp_group: torch.distributed.ProcessGroup,
full_modules: collections.abc.Collection[str] = ()
) -> dict[str, typing.Any]

All-gather PEFT adapter tensors across a pipeline-parallel group.

Pipeline parallelism partitions the model’s layers across PP ranks: each rank’s local module only contains its own stage’s layers. The local collection in ModelState.state_dict gathers PEFT tensors solely from the local model parts, so under pp_size > 1 the per-rank state dict is missing every layer owned by another stage. Saving that directly yields a truncated adapter (only ~1/pp of the layers), which silently degrades a merged model.

This gathers the per-rank PEFT dicts over pp_group and merges them by FQN so every rank returns the complete adapter. Keys are globally unique across PP stages (layer indices never overlap between stages), so the union is exact and order-independent; on the rare chance the same key appears on two ranks (e.g. a replicated tied parameter) the lowest-rank value wins deterministically.

The tensors of the modules the checkpoint stores whole, such as a trained embedding or LM head, can be large, so they skip the pickled object gather and move one tensor at a time (_broadcast_tensors_across_group).

Parameters:

local_state_dict
dict[str, Any]

This rank’s PEFT tensors keyed by native name: CPU tensors of arbitrary rank, shape and dtype, each holding its full logical tensor rather than a per-rank shard. They include the scalar and other persistent buffers of the modules the checkpoint stores whole. The mapping is not mutated.

pp_group
torch.distributed.ProcessGroup

The pipeline-parallel process group to gather over.

full_modules
Collection[str]Defaults to ()

Modules the checkpoint stores whole, from _fully_trained_modules. Every rank of pp_group passes the same modules.

Returns: dict[str, Any]

The union of every PP stage’s entries: native names mapped to CPU tensors with

nemo_automodel.components.checkpoint.stateful_wrappers._get_lm_head_weight_and_name(
model: torch.nn.Module
) -> tuple[torch.Tensor, str] | None
nemo_automodel.components.checkpoint.stateful_wrappers._get_peft_full_module_buffers(
model: torch.nn.Module,
full_modules: collections.abc.Collection[str]
) -> dict[str, typing.Any]

Collect the persistent buffers of the modules a PEFT checkpoint stores whole, bypassing DCP.

The local counterpart of the buffer selection in _select_peft_tensors; see _iter_peft_full_module_buffers.

Parameters:

model
torch.nn.Module

One local model part.

full_modules
Collection[str]

Modules the checkpoint stores whole, from _fully_trained_modules.

Returns: dict[str, Any]

CPU copies of the persistent buffers under full_modules, keyed by name. Each buffer keeps

nemo_automodel.components.checkpoint.stateful_wrappers._get_peft_state_dict(
model: torch.nn.Module
) -> dict[str, typing.Any]

Extract only trainable PEFT adapter weights, bypassing DCP.

This function directly iterates over model parameters to collect trainable weights, avoiding PyTorch DCP’s state_dict traversal which fails on (1) BitsAndBytes quantized modules (Params4bit, Int8Params, etc.) and (2) MoE models with expert parallelism where expert weights are sharded across EP ranks.

Parameters:

model
torch.nn.Module

One local model part.

Returns: dict[str, Any]

CPU copies of the trainable parameters, keyed by the names DCP’s state dict uses

nemo_automodel.components.checkpoint.stateful_wrappers._has_expert_parallelism(
model: torch.nn.Module
) -> bool

Check if any MoE expert module in the model has expert parallelism enabled.

After EP initialization, expert modules (GroupedExpertsDeepEP, GroupedExpertsTE) store ep_size on themselves. A value > 1 signals that expert weights are sharded across EP ranks and DCP’s state_dict APIs cannot handle them.

nemo_automodel.components.checkpoint.stateful_wrappers._has_quantized_params(
model: torch.nn.Module
) -> bool

Check if model has any BitsAndBytes quantized modules.

nemo_automodel.components.checkpoint.stateful_wrappers._is_quantized_module(
module: torch.nn.Module
) -> bool

Check if a module is a BitsAndBytes quantized type.

Detects quantization by checking for quant_state attribute which is common across BitsAndBytes quantized module types (Params4bit, Int8Params, etc.).

nemo_automodel.components.checkpoint.stateful_wrappers._iter_peft_full_module_buffers(
model: torch.nn.Module,
full_modules: collections.abc.Collection[str]
) -> collections.abc.Iterator[tuple[str, torch.Tensor]]

Yield the persistent buffers of the modules a PEFT checkpoint stores whole.

Saving and the DCP-free load select these buffers the same way. Names follow _get_peft_state_dict, which names the parameters on the same paths.

Parameters:

model
torch.nn.Module

One local model part.

full_modules
Collection[str]

Modules the checkpoint stores whole, from _fully_trained_modules.

nemo_automodel.components.checkpoint.stateful_wrappers._lora_adapted_module(
name: str
) -> str

Return the path of the module that owns the LoRA parameter name.

nemo_automodel.components.checkpoint.stateful_wrappers._materialize_missing_adam_state(
optimizer: torch.optim.Optimizer
) -> None

Create zero-valued Adam state for parameters that do not have state yet.

nemo_automodel.components.checkpoint.stateful_wrappers._materialize_native_fused_adam_state(
optimizer: torch.optim.Optimizer
) -> None

Create the state a never-stepped TE FusedAdam would otherwise allocate in its first step().

TE FusedAdam keeps the step counter in each parameter group and allocates the moments and master weights lazily inside step(). A fresh optimizer therefore returns an empty state_dict(), and DCP only loads keys present in that skeleton, so a resume on the native optimizer checkpoint path would restore nothing. This mirrors the initialization in FusedAdam.step: a zero step counter for every group (an int32 tensor of shape [1] when capturable) and TE’s own initialize_state for every parameter without state, which allocates zero moments plus the fp32 master copy, or the zero int16 remainder of a bf16 parameter. The first real update after materialization is unchanged.

Parameters:

optimizer
torch.optim.Optimizer

Optimizer to populate; every other optimizer type is left untouched. Each parameter keeps its shape, dtype, device and DTensor placements, and TE allocates matching per-parameter buffers.

nemo_automodel.components.checkpoint.stateful_wrappers._rename_dora_keys_from_hf(
sd: dict[str, typing.Any]
) -> None

Reverse of _rename_dora_keys_to_hf: convert HF PEFT key format back to internal names.

Handles both the current on-disk format (<module>.lora_magnitude_vector) and the legacy format that included .default.weight for robustness.

nemo_automodel.components.checkpoint.stateful_wrappers._rename_dora_keys_to_hf(
sd: dict[str, typing.Any]
) -> None

Rename DoRA magnitude keys to match HF PEFT’s saved checkpoint format in-place.

HF PEFT’s get_peft_model_state_dict strips the adapter name and the .weight suffix from lora_magnitude_vector.<adapter>.<weight> so the round-trip format on disk is simply <module>.lora_magnitude_vector. When loading, set_peft_model_state_dict re-inserts the adapter name and the .weight suffix automatically, so we must NOT include them here.

nemo_automodel.components.checkpoint.stateful_wrappers._safe_op_set_extra_state(
self,
state
)
nemo_automodel.components.checkpoint.stateful_wrappers._safe_set_extra_state(
self,
state
)
nemo_automodel.components.checkpoint.stateful_wrappers._select_peft_tensors(
model_state_dict: dict[str, typing.Any],
model_parts: list[torch.nn.Module],
full_modules: collections.abc.Collection[str]
) -> dict[str, typing.Any]

Keep the entries of a PEFT model’s DCP state dict that its checkpoint holds.

get_model_state_dict(..., ignore_frozen_params=True) returns the trainable parameters together with every persistent buffer. A PEFT checkpoint holds the LoRA weights, every other trainable parameter, and the persistent buffers of the modules it stores whole, because HF PEFT restores a modules_to_save module from all of its state-dict entries. Other buffers are dropped.

Parameters:

model_state_dict
dict[str, Any]

DCP model state dict mapping names to tensors of arbitrary shape. DCP materializes it on rank 0 only, so other ranks pass an empty dict.

model_parts
list[torch.nn.Module]

The model parts model_state_dict was collected from.

full_modules
Collection[str]

Modules the checkpoint stores whole, from _fully_trained_modules.

Returns: dict[str, Any]

A new dict holding the same tensor objects (not copies) for the selected entries.

Raises:

  • RuntimeError: If a trainable non-LoRA parameter is missing from a non-empty model_state_dict. Saving would otherwise drop trained weights silently.
nemo_automodel.components.checkpoint.stateful_wrappers._set_peft_state_dict(
model: torch.nn.Module,
state_dict: dict[str, typing.Any]
) -> None

Load PEFT checkpoint tensors into the model, bypassing DCP.

Mirrors the local collection in ModelState.state_dict: assigns saved tensors by name to the trainable parameters (_get_peft_state_dict) and to the persistent buffers of the modules the checkpoint stores whole (_get_peft_full_module_buffers), handling DTensor re-sharding for EP-parallel weights. This avoids DCP’s set_model_state_dict() which raises KeyError on expert-parallel FQNs.

Parameters:

model
torch.nn.Module

One local model part.

state_dict
dict[str, Any]

Checkpoint tensors keyed by native name, each with the global shape of its parameter or buffer. Keys of other tensors are skipped.

nemo_automodel.components.checkpoint.stateful_wrappers._trainable_module_layout(
model_parts: collections.abc.Sequence[torch.nn.Module]

Describe the trainable non-LoRA parameters of local model parts.

Parameters:

model_parts
Sequence[torch.nn.Module]

This rank’s model or pipeline-stage parts, optionally wrapped in DDP.

Returns: _TrainableModuleLayout

The layout of the parameters these parts hold.

nemo_automodel.components.checkpoint.stateful_wrappers._trainable_non_lora_parameter_names(
model_parts: list[torch.nn.Module]
) -> set[str]

Return the DCP state-dict names of trainable parameters that are not LoRA weights.

Under PEFT these are parameters freeze_config made trainable next to the adapters (unfreeze_modules/unfreeze_parameters), which train in full and must be saved with the adapter.

Parameters:

model_parts
list[torch.nn.Module]

Model or pipeline-stage parts, optionally wrapped in DDP.

Returns: set[str]

Normalized parameter names, matching the keys of get_model_state_dict. A shared

nemo_automodel.components.checkpoint.stateful_wrappers._validate_trainable_module_layout(
) -> None

Reject trainable non-LoRA parameters that an HF PEFT adapter cannot restore.

Parameters:

layout
_TrainableModuleLayout

Layout of the whole model, or of the pipeline stages this rank holds.

Raises:

  • ValueError: If a trainable non-LoRA parameter has several names (modules_to_save would restore each alias as a separate copy, untying them), belongs to the root module (modules_to_save names submodules), shares a module path with a LoRA adapter (the adapter and a full copy of the same module conflict on load), belongs to a module that also has frozen parameters (HF PEFT restores a modules_to_save module whole, so the adapter would need those as well), or belongs to a container that HF PEFT cannot wrap, such as a ParameterList, with no enclosing module that trains in full.
nemo_automodel.components.checkpoint.stateful_wrappers._zeros_like_optimizer_param(
param: torch.Tensor
) -> torch.Tensor

Allocate zero optimizer state matching a parameter.

Parameters:

param
torch.Tensor

Tensor of arbitrary shape representing one optimizer parameter.

Returns: torch.Tensor

Zero tensor with the same shape, dtype, device, and layout as param.

nemo_automodel.components.checkpoint.stateful_wrappers.fully_trained_peft_modules(
model_parts: collections.abc.Sequence[torch.nn.Module],
pp_group: torch.distributed.ProcessGroup | None = None
) -> list[str]

Return the modules a PEFT adapter checkpoint stores whole, for modules_to_save.

These are the modules freeze_config trains in full next to the LoRA adapters, named the way ModelState.state_dict names their tensors. Under pipeline parallelism the stages’ layouts are combined first, so every rank of pp_group must call this together and gets the same result.

Parameters:

model_parts
Sequence[torch.nn.Module]

This rank’s model or pipeline-stage parts, optionally wrapped in DDP.

pp_group
torch.distributed.ProcessGroup | NoneDefaults to None

Pipeline-parallel process group, or None without pipeline parallelism.

Returns: list[str]

Sorted native module names; see _full_module_of. Empty when only LoRA weights train.

Raises:

  • ValueError: If a trainable non-LoRA parameter cannot be restored by Hugging Face PEFT; see _validate_trainable_module_layout.
nemo_automodel.components.checkpoint.stateful_wrappers.validate_peft_trainable_modules(
model: torch.nn.Module
) -> None

Check that a PEFT model’s trainable parameters fit an HF PEFT adapter checkpoint.

Run this after the trainability policy is final and before training starts, so an unsupported freeze_config fails at startup instead of at the first checkpoint save.

Parameters:

model
torch.nn.Module

A PEFT model or pipeline stage, optionally wrapped in DDP.

Raises:

  • ValueError: If a trainable non-LoRA parameter cannot be restored by Hugging Face PEFT; see _validate_trainable_module_layout.
nemo_automodel.components.checkpoint.stateful_wrappers._OPTIMIZER_PARTS_KEY = 'optimizer_parts'
nemo_automodel.components.checkpoint.stateful_wrappers._OPTIMIZER_PART_KEY_PREFIX = 'stage_'
nemo_automodel.components.checkpoint.stateful_wrappers._PREFIX = 'model.'
nemo_automodel.components.checkpoint.stateful_wrappers._UNWRAPPABLE_MODULE_TYPES = (torch.nn.ModuleList, torch.nn.ModuleDict, torch.nn.ParameterList, torch.nn.Para...
nemo_automodel.components.checkpoint.stateful_wrappers._original_op_set_extra_state = te_ops.BasicOperation.set_extra_state
nemo_automodel.components.checkpoint.stateful_wrappers._original_set_extra_state = te_base.TransformerEngineBaseModule.set_extra_state