nemo_automodel.components.checkpoint.stateful_wrappers
nemo_automodel.components.checkpoint.stateful_wrappers
Module Contents
Classes
Functions
Data
API
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:
The PyTorch model to track.
Refresh tied-head metadata after DCP has normalized module state.
Load the state dictionary into the model.
Parameters:
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.
Whether missing or unexpected keys should fail the load.
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.
Get the model’s state dictionary.
Returns: dict[str, Any]
Dictionary containing the model state dict, optionally offloaded to CPU.
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:
The PyTorch model associated with the optimizer.
The optimizer to track.
Optional learning rate scheduler.
Return the single gradient sketch optimizer among the parts, or None.
Load the state dictionaries into the optimizer and scheduler.
Parameters:
State dictionary containing optimizer and scheduler states to load.
Get the optimizer and scheduler state dictionaries.
Returns: dict[str, Any]
Dictionary containing the optimizer and scheduler state dicts, optionally offloaded to CPU.
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.
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.
Paths of the modules that own LoRA parameters.
Name groups of trainable non-LoRA parameters that are registered under several names, such as tied input and output embeddings.
Paths of the ModuleList, ModuleDict, ParameterList and
ParameterDict modules, which HF PEFT cannot wrap in modules_to_save.
For every module path that holds parameters, whether all of them are trainable non-LoRA parameters.
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.
Prepend prefix once to every key in-place (inverse of _drop_outer_prefix).
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:
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.
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,
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:
This rank’s model or pipeline-stage parts, optionally wrapped in DDP.
Pipeline-parallel process group, or None without pipeline parallelism.
Returns: _TrainableModuleLayout
The layout of every parameter of the model.
Copy an unsharded checkpoint tensor into a parameter’s or buffer’s storage.
Parameters:
Destination parameter data or buffer, of arbitrary shape. A DTensor receives the
shard of full_tensor that its placements assign to this rank.
Tensor with the destination’s global shape.
Normalize a named_modules() path the way _dcp_parameter_name normalizes parameter names.
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.
Remove the first occurrence of prefix on every key in-place.
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 of the whole model, from _combined_trainable_module_layout.
A trainable non-LoRA parameter name from layout.trainable.
Returns: str
The module’s native name.
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 of the whole model, from _combined_trainable_module_layout.
Returns: list[str]
Sorted module names. Empty when only LoRA weights train.
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:
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.
The pipeline-parallel process group to gather over.
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
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:
One local model part.
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
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:
One local model part.
Returns: dict[str, Any]
CPU copies of the trainable parameters, keyed by the names DCP’s state dict uses
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.
Check if model has any BitsAndBytes quantized modules.
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.).
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:
One local model part.
Modules the checkpoint stores whole, from _fully_trained_modules.
Return the path of the module that owns the LoRA parameter name.
Create zero-valued Adam state for parameters that do not have state yet.
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 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.
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.
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.
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:
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.
The model parts model_state_dict was collected from.
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-emptymodel_state_dict. Saving would otherwise drop trained weights silently.
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:
One local model part.
Checkpoint tensors keyed by native name, each with the global shape of its parameter or buffer. Keys of other tensors are skipped.
Describe the trainable non-LoRA parameters of local model parts.
Parameters:
This rank’s model or pipeline-stage parts, optionally wrapped in DDP.
Returns: _TrainableModuleLayout
The layout of the parameters these parts hold.
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 or pipeline-stage parts, optionally wrapped in DDP.
Returns: set[str]
Normalized parameter names, matching the keys of get_model_state_dict. A shared
Reject trainable non-LoRA parameters that an HF PEFT adapter cannot restore.
Parameters:
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_savewould restore each alias as a separate copy, untying them), belongs to the root module (modules_to_savenames 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 amodules_to_savemodule whole, so the adapter would need those as well), or belongs to a container that HF PEFT cannot wrap, such as aParameterList, with no enclosing module that trains in full.
Allocate zero optimizer state matching a parameter.
Parameters:
Tensor of arbitrary shape representing one optimizer parameter.
Returns: torch.Tensor
Zero tensor with the same shape, dtype, device, and layout as param.
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:
This rank’s model or pipeline-stage parts, optionally wrapped in DDP.
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.
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:
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.