Distributed Checkpoint (DCP) supports loading and saving models from multiple ranks in parallel.
It handles load-time resharding which enables saving in one cluster topology and loading into another.
DCP is different than torch.save and torch.load in a few significant ways:
It produces multiple files per checkpoint, with at least one per rank.
It operates in place, meaning that the model should allocate its data first and DCP uses that storage instead.
The entrypoints to load and save a checkpoint are the following:
This class contains futures for staging and upload completion.
It is returned by async_save().
staging_completion is a future that indicates when local copy
of state_dict is complete.
upload_completion is a future that indicates when a checkpoint
completed saving.
This function is different from torch.save() as it handles
ShardedTensor , and DTensor by having each rank only save their local shards.
For each Stateful object (having both a state_dict and a load_state_dict),
save will call state_dict before serialization.
Parameters:
state_dict (Dict[str, Any]) – The state_dict to save.
checkpoint_id (Union[str, os.PathLike, None]) – The ID of this checkpoint instance. The meaning of the checkpoint_id
depends on the storage. It can be a path to a folder or to a file.
It can also be a key if the storage is a key-value store.
(Default: None)
storage_writer (Optional[) – Instance of StorageWriter used to perform writes. If this is not
specified, DCP will automatically infer the writer based on the
checkpoint_id. If checkpoint_id is also None, an exception will
be raised. (Default: )
Asynchronous version of save. This code first de-stages the state_dict on to the
staging storage (defaults to CPU memory), and then calls the save in a separate thread.
Parameters:
state_dict (Dict[str, Any]) – The state_dict to save.
checkpoint_id () – The ID of this checkpoint instance. The meaning of the checkpoint_id
depends on the storage. It can be a path to a folder or to a file.
It can also be a key if the storage is a key-value store.
(Default: )
Load a checkpoint into a distributed state dict in SPMD style.
Each rank must have the same keys in their state_dict provided to this
API. Mismatched keys may result in hangs or errors. If unsure, you can use
the utils._assert_same_keys API to check (but may incur communication
costs).
Each rank will try to read the least amount of data necessary
to fulfill the requested state_dict. When loading ShardedTensor
or DTensor instances, each rank only reads data for their local shards.
For each Stateful object (having both a state_dict and a load_state_dict),
load will first call state_dict before attempting deserialization, followed by
load_state_dict once the deserialization is complete.
For each non-Stateful object, load will deserialize the object, and then replace
it in the state_dict with the deserialized object.
Parameters:
state_dict (Dict[str, Any]) – The state_dict to load the checkpoint into.
checkpoint_id (Union[str, os.PathLike, None]) – The ID of this checkpoint instance. The meaning of the checkpoint_id
depends on the storage. It can be a path to a folder or to a file.
It can also be a key if the storage is a key-value store.
(Default: None)
storage_reader (Optional[) – Instance of StorageWriter used to perform reads. If this is not
specified, DCP will automatically infer the reader based on the
checkpoint_id. If checkpoint_id is also None, an exception will
be raised. (Default: )
This method is deprecated. Please switch to ‘load’.
The following module is also useful for additional customization of the staging mechanisms used for asynchronous checkpointing (torch.distributed.checkpoint.async_save):
This protocol is meant to provide customization and extensibility for dcp.async_save, allowing users
to customize how data is staged previous to executing the usual dcp.save path in parallel.
The expected order of operations (concretely defined in torch.distributed.state_dict_saver.async_save)
is the following:
AsyncStager.stage_data(state_dict):
This call gives the AsyncStager the opportunity to ‘stage’
the state_dict. The expectation and purpose of staging in this context is to create a “training-safe”
representation of the state dict, meaning that any updates to module data after staging is complete
should not be reflected in the state dict returned from this method. For example, in the default
case a copy of the entire state dict is created on CPU RAM and returned here, allowing users
to continue training without risking changes to data which is being serialized.
dcp.save is called on the state_dict returned from stage in parallel. This call is responsible
for serializing the state_dict and writing it to storage.
If AsyncStager.should_synchronize_after_execute is True, this method will be called immediately after
the serialization thread starts and before returning from dcp.async_save. If this is set to False,
the assumption is the user has defined a custom synchronization point for the purpose of further
optimizing save latency in the training loop (for example, by overlapping staging with the
forward/backward pass), and it is the respondsibility of the user to call AsyncStager.synchronize_staging
at the appropriate time.
Returns a “staged” copy of state_dict. The expectation of the staged copy is that it is
inoculated from any updates incurred after the stage call is complete.
In the case stage is async in some way, this method should be called to ensure staging
is complete and it is safe to begin modifying the original state_dict
DefaultStager provides a full-featured staging implementation that combines
multiple optimization techniques for efficient checkpoint preparation.
The staging process works as follows:
1. State dictionary is submitted for staging (sync or async)
2. Tensors are copied from GPU to optimized CPU storage
3. CUDA operations are synchronized if non-blocking copies are used
4. Staged state dictionary is returned or made available via Future
# Asynchronous staging
stager = DefaultStager(StagingOptions(use_async_staging=True))
future = stager.stage(state_dict)
# … do other work …
staged_dict = future.result()
stager.close()
Performance Considerations:
Async staging provides best performance when model computation
can overlap with staging operations
Pinned memory improves CPU-GPU transfer speeds but uses more memory
Shared memory allows efficient IPC to checkpoint process
Non-blocking copies reduce GPU idle time during memory transfers
Thread Safety:
DefaultStager is not thread-safe. Each thread should use its own
instance, or external synchronization should be provided.
close()
Clean up all resources used by the DefaultStager. Shuts down the ThreadPoolExecutor
used for async staging operations and cleans up the underlying StateDictStager’s
cached storages. Should be called when the stager is no longer needed to prevent
resource leaks, especially in long-running applications. After calling close(),
the stager should not be used for further staging operations.
Example Usage:
stager = DefaultStager(StagingOptions(use_async_staging=True))
future = stager.stage(state_dict)
result = future.result()
stager.close() # Clean up all resources
stage(state_dict, **kwargs)
This function is responsible for staging staging the state_dict.
See class docstring for more details on staging.
If use_async_staging is True, it will return a Future object that will be
fulfilled when staging is complete.
If use_async_staging is False, it will return the fully staged state_dict.
Parameters:
state_dict (STATE_DICT_TYPE) – The state_dict to be staged.
Configuration options for checkpoint staging behavior.
Variables:
use_pinned_memory (bool) – Enable pinned memory allocation for faster
CPU-GPU transfers. Requires CUDA to be available. Default: True
use_shared_memory (bool) – Enable shared memory for multi-process
scenarios. Useful when multiple processes need access to the
same staged data. Default: True
use_async_staging (bool) – Enable asynchronous staging using a
background thread pool. Allows overlapping computation with
staging operations. Requires CUDA. Default: True
use_non_blocking_copy (bool) – Use non-blocking device memory
copies with stream synchronization. Improves performance by
allowing CPU work to continue during GPU transfers. Default: True
An implementation of AsyncStager which stages the state_dict on CPU RAM and blocks until the copy is complete.
This implementation also provides an option to optimize stage latency using pinned memory.
Stateful protocol for objects that can be checkpointed and restored.
load_state_dict(state_dict)
Restore the object’s state from the provided state_dict.
Parameters:
state_dict (dict[str, Any]) – The state dict to restore from
state_dict()
Objects should return their state_dict representation as a dictionary.
The output of this function will be checkpointed, and later restored in
load_state_dict().
Returns:
The objects state dict
Return type:
Dict
This example shows how to use PyTorch Distributed Checkpoint to save a FSDP model.
The following types define the IO interface used during checkpoint:
classtorch.distributed.checkpoint.StorageReader
Interface used by load_state_dict to read from storage.
One StorageReader instance acts as both the coordinator and the follower
in a distributed checkpoint. As part of initialization, each instance
is told its role.
A subclass should expect the following sequence of calls by load_state_dict:
(all ranks) set checkpoint_id if users pass a valid checkpoint_id.
(all ranks) read_metadata()
(all ranks) set_up_storage_reader()
(all ranks) prepare_local_plan()
(coordinator) prepare_global_plan()
(all ranks) read_data()
abstractprepare_global_plan(plans)
Perform centralized planning of storage loading.
This method is only called on the coordinator instance.
While this method can produce a completely different plan, the preferred
way is to store storage specific data in LoadPlan::storage_data.
Parameters:
plans (list[LoadPlan]) – A list of LoadPlan instances, one for each rank.
Returns:
A list of transformed LoadPlan after storage global planning
While this method can produce a completely different plan, the recommended
way is to store storage specific data in LoadPlan::storage_data.
Parameters:
plan (LoadPlan) – The local plan from the LoadPlan in use.
Returns:
A transformed LoadPlan after storage local planning
Return type
abstractread_data(plan, planner)
Read all items from plan using planner to resolve the data.
A subclass should call LoadPlanner::load_bytes to deserialize a BytesIO
object into the right place.
A subclass should call LoadPlanner::resolve_tensor to get access to the
tensors that in should load data into.
It’s the StorageLayer responsibility to properly schedule any cross device copies
required.
Parameters:
abstractread_metadata(*args, **kwargs)
Read the checkpoint metadata.
Returns:
The metadata object associated with the checkpoint being loaded.
Return type:
Metadata
abstractreset(checkpoint_id=None)
Calls to indicates a brand new checkpoint read is going to happen.
A checkpoint_id may be present if users set the checkpoint_id for
this checkpoint read. The meaning of the checkpoint_id is
storage-dependent. It can be a path to a folder/file or a key for
a key-value storage.
Parameters:
checkpoint_id (Union[str, os.PathLike, None]) – The ID of this checkpoint instance. The meaning of the checkpoint_id
depends on the storage. It can be a path to a folder or to a file.
It can also be a key if the storage is more like a key-value store.
(Default: )
Interface used by save_state_dict to write to storage.
One StorageWriter instance acts as both the coordinator and the follower
in a distributed checkpoint. As part of initialization, each instance
is told its role.
A subclass should expect the following sequence of calls.
(all ranks) set checkpoint_id if users pass a valid checkpoint_id.
(all ranks) set_up_storage_writer()
(all ranks) prepare_local_plan()
(coordinator) prepare_global_plan()
(all ranks) write_data()
(coordinator) finish()
abstractfinish(metadata, results)
Write the metadata and marks the current checkpoint as successful.
The actual format/schema used for serializing metadata is an
implementation detail. The only requirement is that it’s recoverable
in to the same object graph.
Parameters:
metadata (Metadata) – metadata for the new checkpoint
results (list[list[WriteResult]]) – A list of WriteResults from all ranks.
Returns:
None
Return type:
None
abstractprepare_global_plan(plans)
Perform centralized planning of storage.
This method is only called on the coordinator instance.
While this method can produce a completely different plan, the preferred
way is to store storage specific data in SavePlan::storage_data.
Parameters:
plans (list[SavePlan]) – A list of SavePlan instances, one for each rank.
Returns:
abstractprepare_local_plan(plan)
Perform storage-specific local planning.
While this method can produce a completely different plan, the recommended
way is to store storage specific data in SavePlan::storage_data.
Parameters:
plan (SavePlan) – The local plan from the SavePlanner in use.
Returns:
A transformed SavePlan after storage local planning
Return type
abstractreset(checkpoint_id=None)
Calls to indicates a brand new checkpoint write is going to happen.
A checkpoint_id may be present if users set the checkpoint_id for
this checkpoint write. The meaning of the checkpoint_id is
storage-dependent. It can be a path to a folder/file or a key for
a key-value storage.
Parameters:
checkpoint_id (Union[str, os.PathLike, None]) – The ID of this checkpoint instance. The meaning of the checkpoint_id
depends on the storage. It can be a path to a folder or to a file.
It can also be a key if the storage is a key-value store.
(Default: )
is_coordinator (bool) – Whether this instance is responsible for coordinating
the checkpoint.
storage_meta()
Return the storage-specific metadata. This is used to store additional information
in a checkpoint that can be useful for providing request-level observability. StorageMeta
is passed to the SavePlanner during save calls. Returns None by default.
The following types define the planner interface used during checkpoint:
classtorch.distributed.checkpoint.LoadPlanner
Abstract class defining the protocol used by load_state_dict to plan the load process.
LoadPlanner are stateful objects that can be used to customize the whole load process.
LoadPlanner acts as an access proxy to the state_dict, so any transformation done to it
will be visible to the whole process.
A planner subclass can expect the following sequence of calls during load_state_dict:
set_up_planner - called on all ranks.
Signals the start of loading a checkpoint.
create_local_plan - called on all ranks.
Process the state_dict and produces a LoadPlan that will be sent for global planning.
create_global_plan - called on the coordinator rank only.
Takes the LoadPlan from all ranks and make any global decision.
load_bytes - called multiple times on each rank
This is called once per non-tensor value in state_dict.
resolve_tensor and commit_tensor - called multiple times on each rank
They are called in pair for each Tensor value in state_dict.
Users are recommended to extend DefaultLoadPlanner instead of this interface directly as
most changes can be expressed by changes in a single method.
There are two usual patterns of extension:
Rewriting state_dict. This is the simplest way to extend the load process as it
doesn’t require understanding the intricacies of how LoadPlan works. We need
to keep a reference to the original state_dict as load happens in place so
we need to be able to perform it in place
Call once the StorageReader finished loading data into tensor.
The provided tensor is the same one returned by the call to resolve_tensor.
This method is only needed if this LoadPlanner needs to post process tensor prior to
copying it back to the one in the state_dict.
The contents of tensor will follow its device synchronization model.
abstractcreate_global_plan(global_plan)
Compute the global load plan and return plans for each rank.
. N.B. This is called on the coordinator rank only
This method is expected to modify in-place the underlying state_dict.
The contents of value are defined by the SavePlanner used to produce
the checkpoint being loaded.
resolve_bytes(read_item)
Return the BytesIO to be used by the StorageReader to load read_item.
The BytesIO should alias with one on the underlying state_dict as StorageReader will replace its contents.
Return type:
BytesIO
abstractresolve_tensor(read_item)
Return the tensor described by read_item to be used by the StorageReader to load read_item.
The tensor should alias with one on the underlying state_dict as StorageReader will replace its contents.
If, for any reason, that’s not possible, the planner can use the commit_tensor method to copy the data
back to the one in state_dict.
Using the global planning step to make central decisions that can’t be made individually by each rank
>>> fromitertoolsimportzip_longest>>> fromdataclassesimportreplace>>> classDDPLoadBalancingPlanner(DefaultSavePlanner):>>> # This uses the default local plan behavior of having all non-sharded writes in rank 0>>> # This sample doesn't handle ShardedTensors>>> defcreate_global_plan(self,
Finally, some planners need to save additional metadata in the checkpoint, this is
accomplished by having each rank contribute their data items in the local plan and
the global planner aggregate them:
Transform and prepare write_item from state_dict for storage, ensuring idempotency and thread-safety.
Lookup the object associated with write_item in state_dict and apply any
transformation (such as serialization) prior to the storage layer consuming it.
Called on each rank multiple times, at least once per WriteItem in the final SavePlan.
This method should be idempotent and thread-save. StorageWriter implementations
are free to call it as frequently as they need.
Any transformation that allocates memory should be lazily done when his method
is called in order to reduce peak memory required by checkpointing.
When returning tensors, they can be on any device or format, they can be views too.
It’s the storage layer responsibility to figure out how to save them.
Basic implementation of StorageWriter using file IO.
This implementation makes the following assumptions and simplifications:
The checkpoint path is an empty or non-existing directory.
File creation is atomic
The checkpoint consist of one file per write request plus
a global .metadata file with the serialized metadata if rank coordination is enabled.
a rank local __{rank}.metadata file with the serialized metadata if rank coordination is NOT enabled.
We provide default implementations of LoadPlanner and SavePlanner that
can handle all of torch.distributed constructs such as FSDP, DDP, ShardedTensor and DistributedTensor.
DefaultLoadPlanner that adds multiple features on top of LoadPlanner.
In particular it adds the following:
flatten_state_dict: Handle state_dict with nested dicts
flatten_sharded_tensors: For FSDP in 2D parallel mode
allow_partial_load: If False, will raise a runtime error if a key is present in state_dict, but not in the checkpoint.
lookup_tensor(index)
Extension from the planner interface to make it easy to extend the default planner.
Extension from the planner interface to make it easy to extend the default planner.
Due to legacy design decisions, the state dictionaries of FSDP and DDP may have different keys or fully qualified names (e.g., layer1.weight) even when the original unparallelized model is identical. Moreover, FSDP offers various types of model state dictionaries, such as full and sharded state dictionaries. Additionally, optimizer state dictionaries employ parameter IDs instead of fully qualified names to identify parameters, potentially causing issues when parallelisms are used (e.g., pipeline parallelism).
To tackle these challenges, we offer a collection of APIs for users to easily manage state_dicts. get_model_state_dict() returns a model state dictionary with keys consistent with those returned by the unparallelized model state dictionary. Similarly, get_optimizer_state_dict() provides the optimizer state dictionary with keys uniform across all parallelisms applied. To achieve this consistency, get_optimizer_state_dict() converts parameter IDs to fully qualified names identical to those found in the unparallelized model state dictionary.
Note that results returned by these APIs can be used directly with the torch.distributed.checkpoint.save() and torch.distributed.checkpoint.load() methods without requiring any additional conversions.
set_model_state_dict() and set_optimizer_state_dict() are provided to load the model and optimizer state_dict generated by their respective getter APIs.
Note that set_optimizer_state_dict() can only be called before backward() or after step() is called on optimizers.
Note that this feature is experimental, and API signatures might change in the future.
Return the model state_dict and optimizers state_dict.
get_state_dict can process any module that is parallelized by PyTorch
FSDP/fully_shard, DDP/replicate, tensor_parallel/parallelize_module, and any
combination of these parallelisms. The main functions of get_state_dict
are: 1.) returning a model and optimizer state_dict that can be resharded
with a different number of trainers and/or different parallelisms.
2.) hiding the parallelism-specific state_dict APIs. Users don’t have to call
these APIs.
3.) sanity checking the result state_dict.
The keys of the result state dictionary are the canonical FQNs (Fully
Qualified Names). A canonical FQN refers to the FQN based on a parameter’s
position in an nn.Module hierarchy. More specifically, a canonical FQN to a
parameter is the FQN returned by module.named_parameters() or
module.named_buffers() when the module is not distributed by any
parallelisms. Since the optimizer internally uses parameter IDs to represent
a parameter, there will be a conversion from the parameter IDs to the
canonical FQNs when calling this API.
get_state_dict can also process a module that is not parallelized. In
such a case, get_state_dict only performs one function – converting the
optimizer parameter IDs to the canonical FQNs.
>>> # if we simply call ddp_model.state_dict() and fsdp_model.state_dict(),>>> # the asserts will fail.>>> assertddp_state_dict==fsdp_state_dict>>> assertddp_optim_state==fsdp_optim_state_dict
submodules (deprecated) – Optional[set[nn.Module]]: only return the model parameters
that belong to the submodules.
options (StateDictOptions) – the options to control how
model state_dict and optimizer state_dict should be returned. See
StateDictOptions for the details.
optimizers (Union[None, Optimizer, Iterable[Optimizer]]) – The optimizers that are used to optimize model.
submodules (deprecated) – Optional[set[nn.Module]]: only return the model parameters
that belong to the submodules.
options (StateDictOptions) – the options to control how
model state_dict and optimizer state_dict should be returned. See
StateDictOptions for the details.
Load the model state_dict and optimizers state_dict.
The counterpart of get_state_dict to set the state_dict to the model and
optimizers. The given model_state_dict and optim_state_dict do not
have to be returned by get_state_dict but must meet the following
requirements: 1) all FQNs are canonical FQNs as defined in get_state_dict,
2) if a tensor is sharded, it must be either a ShardedTensor or DTensor,
3) optimizer state_dict cannot contain the parameter IDs; the keys should be
the canonical FQNs.
WARN: set_state_dict can only be called before backward() or after step()
is called on the optimizers. Otherwise, the optimizer states won’t be initialized
correctly.
optimizers (Union[Optimizer, Iterable[Optimizer]]) – The optimizers that are used to optimize model.
model_state_dict (Dict[str, ) – (Union[Dict[nn.Module, Dict[str, ValueType]], Dict[str, ValueType]]):
the model state_dict to load. If the key of the
is nn.Module, the key is a submodule of and the value should
be the state_dict of the submodule. When loading the state_dict,
the prefix of the submodule will be append to the state_dict.
model_state_dict (Dict[str, ValueType]) – (Dict[str, ValueType]):
the model state_dict to load. If the key of the model_state_dict
is nn.Module, the key is a submodule of model and the value should
be the state_dict of the submodule. When loading the state_dict,
the prefix of the submodule will be append to the state_dict.
options (StateDictOptions) – the options to control how
model state_dict and optimizer state_dict should be loaded. See
StateDictOptions for the details.
Returns:
missing_keys is a list of str containing the missing keys
unexpected_keys is a list of str containing the unexpected keys
Return type:
NamedTuple with missing_keys and unexpected_keys fields
This dataclass specifies how get_state_dict/set_state_dict will work.
full_state_dict: if this is set to True, all the tensors in the
returned state_dict will be gathered. No ShardedTensor and DTensor
will be in the returned state_dict.
cpu_offload: offload all the tensors to cpu. To prevent CPU OOM, if
full_state_dict is also true, then only the rank0 will get the
state_dict and all other ranks will get empty state_dict.
ignore_frozen_params: if the value is True, the returned state_dict
won’t contain any frozen parameters – the requires_grad is False.
The default value is False.
keep_submodule_prefixes (deprecated): when submodules is not None, this option
indicates whether to keep the submodule prefixes from the state_dict keys.
or example, if the submodule is and the full FQN of
the parameter is of the param. When this option
is True, the parameter’s key in the returned state_dict will be
. If the options is False, the key will be
.
Note that if is False, there may be conflicted
FQNs, hence there should be only one submodule in .
For users which are used to using and sharing models in the torch.save format, the following methods are provided which provide offline utilities for converting between formats.
StorageReader for reading a Torch Save file. This reader will read the entire checkpoint
on the coordinator rank, and then broadcast and shard each tensor to all ranks.
. N.B. Intended to be used with DynamicMetaLoadPlanner
Reads torch save data on the coordinator rank, and broadcast afterwards
this incurrs a communication cost, but avoids having to load
the entire checkpoint on each rank, hopefully preventing OOM issues
Extension of DefaultLoadPlanner, which creates a new Metadata object based on the passed in state dict,
avoiding the need to read metadata from disk. This is useful when reading formats which don’t have a
metadata file, like Torch Save files.
. N.B. Intended to be used with BroadcastingTorchSaveReader
Setups of the planner, extnding default behavior by creating the Metadata object from the state dict
The following experimental interfaces are provided for improved observability in production environments:
StorageWriter
]
None
planner (Optional[SavePlanner]) – Instance of SavePlanner. If this is not specified, the default
planner will be used. (Default: None)
process_group (Optional[ProcessGroup]) – ProcessGroup to be used for cross-rank synchronization.
(Default: None)
no_dist (bool) – If True, this function will assume the intent is to load
a checkpoint on a single rank/process.
(Default: False)
use_collectives (bool) – If False, this function will assume the intent is to save
a checkpoint without using cross-rank synchronization.
(Default: True)
This configuration is experimental and should be used with caution.
It will change the format of the saved checkpoint and may not be backward compatible.
storage_writer (Optional[StorageWriter]) – Instance of StorageWriter used to perform ‘stage’ and ‘save’. If
this is not specified, DCP will automatically infer the writer based on the
checkpoint_id. If checkpoint_id is also None, an exception will
be raised. (Default: None)
planner (Optional[SavePlanner]) – Instance of SavePlanner. If this is not specified, the default
planner will be used. (Default: None)
process_group (Optional[ProcessGroup]) – ProcessGroup to be used for cross-rank synchronization.
(Default: None)
async_checkpointer_type (AsyncCheckpointerType) – whether to do checkpoint in separate thread or process
(Default: AsyncCheckpointerType.THREAD)
async_stager (AsyncStager) – provides staging implementation. If storage_writer implements
AsyncStager and async_stager is not provided, storage_writer
will be used for staging. User-provided stagers remain owned by the
caller and should be closed after the last checkpoint is saved.
no_dist (bool) – If True, this function will assume the intent is to save
a checkpoint on a single rank/process.
(Default: False)
use_collectives (bool) – If False, Save the checkpoint without rank coordination. (Default: True)
This configuration is experimental and should be used with caution.
It will change the format of the saved checkpoint and may not be backward compatible.
Returns:
A future holding the resultant Metadata object from save.
>>> fs_storage_writer=torch.distributed.checkpoint.FileSystemWriter(... "/checkpoint/1"... )>>> checkpoint_future=torch.distributed.checkpoint.async_save(>>> state_dict=state_dict,>>> storage_writer=fs_storage_writer,>>> )>>>>>> # ... do some work ...>>>>>> checkpoint_future.result()
StorageReader
]
None
planner (Optional[LoadPlanner]) – Instance of LoadPlanner. If this is not specified, the default
planner will be used. (Default: None)
process_group (Optional[ProcessGroup]) – ProcessGroup to be used for cross-rank synchronization.
(Default: None)
no_dist (bool) – If True, this function will assume the intent is to load
a checkpoint without using cross-rank synchronization. (Default: False)
>>> # module.load_state_dict() function might have customized steps>>> # to flush the state_dict, must call it to>>> # ensure correct behavior.>>> my_model.load_state_dict(model_state_dict)
optim_state_dict (OptimizerStateType) – OptimizerStateType:
the optimizer state_dict to load.
options (StateDictOptions) – the options to control how
model state_dict and optimizer state_dict should be loaded. See
StateDictOptions for the details.
Returns:
missing_keys is a list of str containing the missing keys of the model state_dict.
unexpected_keys is a list of str containing the unexpected keys of the model state_dict.
Return type:
NamedTuple with missing_keys and unexpected_keys fields
StateDictOptions
Returns:
None
Return type:
None
module.pretrain
pretrain.layer1.weight
pretrain.layer1.weight
layer1.weight
keep_submodule_prefixes
submodules
strict: the strict option when set_state_dict calls
model.load_state_dict().
broadcast_from_rank0: when the option is True, rank0 should receive a
full state_dict and will broadcast the tensors in the state_dict/
optim_state_dict one by one to other ranks. Other ranks will receive
the tensors and shard according to the local shards in the model and
optimizer. full_state_dict must be set to True when using this option.
This option currently only supports DTensor, not the legacy ShardedTensor.