kempnerforge.checkpoint.manager¶
Checkpoint manager for distributed checkpointing.
Uses PyTorch Distributed Checkpoint (DCP) for model and optimizer state,
which supports automatic resharding: a checkpoint saved on N GPUs loads on M,
under another dp_shard, dp_replicate (HSDP), tp or ep layout,
with the model and optimizer state as saved. A stage checkpoint loads only at
the pipeline degree it was saved with (see SavedLayout), and a checkpoint
of an MoE model only into the expert layout, packed or not, that saved it (see
check_saved_experts).
Non-distributed state (scheduler, dataloader, training meta, RNG) is saved
separately as a torch file written by rank 0 and broadcast from rank 0 on
load. Scheduler and training meta restore from that single copy on every
rank. Dataloader and RNG state are per-rank: every rank’s payload is gathered
into a versioned envelope at save time, and on an exact resume
(load(exact_resume=True)) each rank restores its own entry from the
broadcast (see kempnerforge.checkpoint.state). Any other load (a
load_path warm start, evaluation) restores rank 0’s single copy on every
rank. A weights-only warm start (exclude_keys=["optimizer", "train_state"])
reads no train_state.pt, so it restores neither and checks no topology.
Resharding model and optimizer state is therefore free, but an exact resume
is not: a rank’s RNG streams, and a loader cursor kept per rank, are valid
only on the world size and data-parallel layout that saved them, so an exact
resume under a changed topology raises on every rank. Setting
checkpoint.ignore_rank_state_mismatch resumes it anyway: step, model,
optimizer and scheduler resume onto the new topology and the random streams
restart fresh, while the saved data position carries over where every rank’s
loader can place it on the new layout, and every rank restarts at the first
sample where one cannot. That position is the one the saved rank 0 reached,
which a StatefulDataLoader counts across all data-parallel ranks, or for a
stream on the saved data-parallel size the one each data-parallel rank saved
for its own part. An envelope the flag lets through for another reason
(unreadable or incomplete) restores neither loader nor RNG state. A checkpoint
saved before per-rank state was recorded cannot show whether the topology
changed, so under the flag it resumes as if it had.
Functions
|
Have the owner of each derived buffer at |
|
Map the state-dict key of each buffer a module lists in |
|
Take out of a load template the derived buffers its checkpoint predates. |
Classes
Manages save/load/cleanup of distributed checkpoints. |
|
Records checkpoints with the logging backends, which this module never imports. |
- class kempnerforge.checkpoint.manager.CheckpointRegistrar[source]¶
Bases:
ProtocolRecords checkpoints with the logging backends, which this module never imports.
- checkpoint_fields(step)[source]¶
Fields each backend adds to its record of the checkpoint saved at
step, by backend.Called on rank 0 inside
save(), so it must answer from what it holds, never a server.
- register_checkpoint(step, directory, record)[source]¶
Register the checkpoint at
directoryoncelatestpoints at it.Called on rank 0 when the checkpoint is committed, so it must not block.
recordadds fields to a backend’s record in that checkpoint’smetadata.json, from any thread, later.
- __init__(*args, **kwargs)¶
- kempnerforge.checkpoint.manager.derived_buffer_owners(model)[source]¶
Map the state-dict key of each buffer a module lists in
derived_buffersto its owner.A module lists there the buffers it gained after its checkpoints were first written and derives from its other state when a load lacks them, as the sigmoid router does for its FP32 masters. Each key maps to the module and the buffer’s name; a buffer another module holds under the same name is not one of them. The keys are named as
get_model_state_dictnames them (seestate_dict_name).- Parameters:
model (torch.nn.Module)
- Return type:
dict[str, tuple[torch.nn.Module, str]]
- kempnerforge.checkpoint.manager.drop_derived_model_keys(model_state, model, saved_keys)[source]¶
Take out of a load template the derived buffers its checkpoint predates.
Only the buffers
derived_buffer_ownersmaps are taken out, and only those the checkpoint, whose keys prefix the model’s withmodel., lacks; any other key a checkpoint lacks still fails the load. Returns the entries taken out. Put back after the read, they let the strictset_model_state_dictfind every key, undertorch.compiletoo, andderive_buffersthen recomputes them from the loaded state.
- kempnerforge.checkpoint.manager.derive_buffers(model, keys)[source]¶
Have the owner of each derived buffer at
keysrecompute it from its loaded state.Only those buffers are derived; every other entry keeps the value loaded. Deriving may gather a parameter that FSDP2 shards, so every rank calls this with the same keys.
- Raises:
TypeError – A module lists
derived_buffersbut has noderive_buffers.- Parameters:
model (torch.nn.Module)
- Return type:
None
- class kempnerforge.checkpoint.manager.CheckpointManager[source]¶
Bases:
objectManages save/load/cleanup of distributed checkpoints.
Each checkpoint is stored in a subdirectory:
{dir}/step_{N}/containing DCP shards and a non-distributed training state file.A
latestsymlink always points to the most recent checkpoint.- Parameters:
config – Checkpoint configuration.
model – The model (FSDP-wrapped or plain).
optimizer – The optimizer.
pp_rank – This rank’s pipeline stage, None without pipeline parallelism. Each stage saves its DCP shards in
pp{pp_rank}/of the checkpoint (seekempnerforge.checkpoint.layout), throughprocess_group.pp_size – The run’s pipeline degree, which needs
pp_rank. Every save then records it inmetadata.jsonaspp. A load refuses, with aValueErroron every rank before anything is loaded, a stage checkpoint of another degree: one that records its degree, or, saved before the record existed, holds another number of stage directories. Without it, the degree is neither recorded nor compared. A pipeline-parallel run loads its stage’s model weights from a checkpoint saved without pipeline parallelism, but refuses its optimizer state, and a run without pipeline parallelism refuses a stage checkpoint (seeload).dp_info – This rank’s
(dp_rank, dp_size), the data partition its loader reads. Recorded with the per-rank loader/RNG state and checked on load, so a resume under a different data-parallel layout is refused even at the same world size. None records no layout and checks only the world size.weight_decay_scope – The run’s
optimizer.weight_decay_scope. When set, every save records it inmetadata.json, and a load that restores optimizer state on any rank raisesValueErroron every rank, before anything is loaded, when the checkpoint was saved under a different scope. A checkpoint that holds no optimizer state, such as a converted one or one saved before the first step, loads under any scope with a fresh optimizer. A checkpoint whosemetadata.jsonrecords no scope counts as"exclude_norms_and_biases", and one without the file is refused, since it records nothing.lr_multipliers – The run’s
optimizer.lr_multipliers. When set, every save records a non-empty one inmetadata.json, with the patterns of its modules and, without pipeline parallelism, the module each optimizer param group names. A load of a checkpoint saved with other multipliers or patterns raisesValueErroron every rank when it restores the checkpoint’s optimizer state on any rank, before anything is loaded, or the scheduler state in itstrain_state.pt, before anything from that file is restored. A load that restores neither, such as a weights-only warm start (exclude_keys=["optimizer", "train_state"]), goes ahead without checking the record. A checkpoint that records none counts as saved without multipliers. One whosemetadata.jsoncannot be read, or holds an invalid record, is refused the same way when multipliers are set; without them it loads as one saved without multipliers, with a warning, and only a record of some is refused. With multipliers set, a load that restores optimizer state into param groups laid out otherwise than at the save, a group of another module at a position included, raises on every rank before anything is loaded. A restored scheduler state carries the saved schedule on in every group, a group of a module the checkpoint holds no group of at the saved peak times its multiplier (seerestore_train_state).module_patterns – Module name to fnmatch patterns, such as
VLMConfig.module_patterns. Required for every modulelr_multiplierslists.group_timeout_sec – Collective timeout of the gloo group the manager creates to order its saves across ranks,
distributed.nccl_timeout_secin training. None leaves PyTorch’s default.
- __init__(config, model, optimizer, process_group=None, pp_rank=None, dp_info=None, weight_decay_scope=None, lr_multipliers=None, module_patterns=None, group_timeout_sec=None, pp_size=None)[source]¶
- Parameters:
config (CheckpointConfig)
model (torch.nn.Module)
optimizer (torch.optim.Optimizer)
pp_rank (int | None)
weight_decay_scope (str | None)
group_timeout_sec (float | None)
pp_size (int | None)
- Return type:
None
- claim_dir()[source]¶
Make this run the owner of the checkpoint directory before it resumes or saves.
Rank 0 records the run in
<dir>/.owner(seeclaim_checkpoint_dir), and every rank raises when that fails, so two live runs never share the directory. Every rank must call this.- Return type:
None
- release_dir()[source]¶
Mark released the
<dir>/.ownerrecord that this rank’sclaim_dirwrote.- Return type:
None
- agree(error, what='Checkpoint save')[source]¶
Agree on the manager’s dedicated gloo group that every rank’s
whatsucceeded.See
agree_across_ranks. The group is not the default process group that DCP’s async-save background thread issues collectives on.- Parameters:
error (BaseException | None)
what (str)
- Return type:
None
- set_tracking_source(source)[source]¶
Record the logging runs
sourcereports in every latermetadata.json.sourcereturns one JSON-ready record per live run, and is called on rank 0 only, insidesave(), so it must return promptly. Thetrackingkey is omitted when it reports none, raises, or returns what JSON cannot write.Nonedetaches it.
- set_checkpoint_registrar(registrar)[source]¶
Record every later checkpoint with the logging backends through
registrar.Both of its methods run on rank 0 only.
checkpoint_fieldsis asked insidesave()when a backend has a live run, and its fields join that save’strackingrecords.register_checkpointgets each checkpoint once it is committed, with arecord(backend, fields)that later adds fields to that backend’s record, atomically and from any thread. A registrar that raises, or answers what a record cannot hold, costs only those fields or that registration, never the save or the commit.Nonedetaches it.- Parameters:
registrar (CheckpointRegistrar | None)
- Return type:
None
- save(step, tokens_seen=0, scheduler=None, dataloader=None, extra=None)[source]¶
Save a checkpoint at the given step.
An optimizer that evaluates at another point than it trains at, as schedule-free AdamW does, has the model saved at its evaluation point, the averaged weights
x, so every reader of the model entry alone gets them; the parameters are back at the training point when this returns, andloadrebuilds that point. The swap back runs as soon asAsyncCheckpointer.savereturns, which is safe only because the state is staged by then: both async modes stage synchronously, so every tensor is copied to CPU memory beforedcp.async_savereturns. Theasyncmode passes no stager and gets torch’s default,DefaultStager(StagingOptions(False, False, False, False));async_with_pinned_mempasses its pinnedDefaultStager, built withuse_async_staging=False, whosestagewaits for its copies to finish. An asynchronous stager would let the write read the parameters after the swap back, so adding one means moving the swap back after staging completes.Under expert parallelism each EP rank holds a copy of every weight outside the routed experts. The training step keeps the copies equal, but a model stepped without
average_non_expert_grads_can hold copies that differ in the last bits. DCP writes each chunk that several ranks hold from one of them, by default the one with the least to write so far, which could join chunks of different copies into one tensor. An EP save writes each such chunk from its lowest rank instead, so the checkpoint holds one EP rank’s copy whole.
- property has_pending_save: bool¶
Whether
wait()has an async save to drain or alatestcommit to make.Always False with synchronous saves, which commit inside
save().
- property flushing: bool¶
Whether this rank’s background write of the pending async save is still running.
Never blocks. False with synchronous saves, and once the write has ended, whether it succeeded or failed. The training loop reduces it over every rank at each step and, once no rank’s write is still running, calls
wait(), which moveslatestto the save then rather than at the next save.
- wait()[source]¶
Block until any pending async checkpoint save completes.
Once the flush is durable, commit its deferred latest symlink + cleanup. The training loop calls this at the first step boundary at which no rank’s write is still running (see
flushing), and after the loop exits, so the final checkpoint’s latest is committed before process teardown. A flush that failed on any rank raises on every rank, and nothing is committed.- Return type:
None
- flush_pending_save()[source]¶
Drain any in-flight async save before mutating model state.
Called from the FreezeStage transition hook in the training loop: when a transition fires at step S, any save started at step S-1 must have written
metadata.jsonwith the pre-transition spec before the transition flipsrequires_grad. Otherwisemetadata.jsonlands with the post-transition spec attached to the pre-transition shards.Also commits the deferred latest symlink for that save, so a transition (or any caller draining the queue) leaves latest pointed at the now-durable checkpoint. A flush that failed on any rank raises on every rank, and nothing is committed.
- Return type:
None
- peek_saved_step(path=None)[source]¶
Read
stepfrom a candidate checkpoint’smetadata.json, on this rank alone.Returns
Noneif no checkpoint resolves, or itsmetadata.jsonis absent, cannot be read, does not hold a JSON object, or records no step that is a non-negative integer.loaddoes not use it: a load takes the step its checks need from rank 0’s read of the checkpoint it settles on (seevlm_freeze_expected).
- load(path=None, scheduler=None, dataloader=None, exclude_keys=None, vlm_freeze_expected=None, fresh_if_unheld=(), warm_start=False, exact_resume=False, plugins_expected=None)[source]¶
Load a checkpoint and restore all state.
A load that restores optimizer state then calls the optimizer’s
train_params, if it has one, so a schedule-free run resumes at the training point it was saved at.- Parameters:
path (str | None) – Checkpoint path. If None, loads from
config.load_pathor thelatestsymlink.scheduler (Any | None) – LR scheduler to restore.
dataloader (Any | None) – Stateful dataloader to restore.
exclude_keys (list[str] | None) – State to skip: the DCP keys
"model"and"optimizer"(e.g.["optimizer"]for fine-tuning), or["optimizer", "train_state"]for a weights-only warm start that loads the model alone and ignorestrain_state.pt(step, token count, scheduler, dataloader position, RNG) and the saved freeze metadata, so the new run starts at step 0 with its own schedule, data order and freeze."train_state"in any other combination raisesValueError.vlm_freeze_expected (list[dict[str, Any]] | Callable[[int], list[dict[str, Any]]] | None) – Canonical freeze metadata (output of
canonical_freeze_meta) for the current run’s VLMConfig, or a function that gives it for a step, such asfreeze_meta_at_stepwith that config, which is called with the step the checkpoint’smetadata.jsonrecords. It is compared with the freeze that file records, both from rank 0’s read of the checkpoint the load settles on (see_check_vlm_freeze), so every rank raises or goes on together; every rank must pass it or none. A mismatch raisesValueErrorunless the checkpoint config hasignore_freeze_mismatch=True, in which case the load proceeds with a warning.fresh_if_unheld (Iterable[str]) – Names of parameters the saved optimizer may not hold, the ones a freeze stage unfreezes after the build froze them. One with neither saved state nor a never-stepped record resumes with empty optimizer state, in the saved group of its group’s other parameters or, when the saved optimizer has as many groups, in the empty saved group in its group’s place. A group that holds only such parameters and that the saved optimizer did not keep, as Muon’s inner AdamW keeps no empty group, resumes with the settings the optimizer being loaded gives it and empty state.
warm_start (bool) – True when this load starts a new run from another run’s checkpoint (
checkpoint.load_path) rather than resuming this one. A data position that cannot carry over to this run’s loader, passed here asdataloaderor later toapply_dataloader_state, then starts the data at its first sample with a warning, instead of raisingDataPositionError.exact_resume (bool) – True only when the run resumes from its own checkpoint (auto-resume). Each rank then restores its own dataloader/RNG state from the per-rank envelope, which must match this run’s world size and data-parallel layout unless
checkpoint.ignore_rank_state_mismatchis set: a changed topology, or a checkpoint with no per-rank state, then keeps the saved data position where the loader can place it and restarts the random streams. Every rank must pass the same value. False (aload_pathwarm start, evaluation, any other load) restores the single-copyrng/dataloaderkeys (rank 0’s) on every rank with no topology check. The weights-onlyexclude_keyspair reads no train state: no rank restores loader/RNG state or enters the train-state broadcasts or the layout gather, and withexact_resumeit raises. Every load takes the checkpoint rank 0 resolves (see_agreed_load_dir); an exact resume that reads DCP shards falls back, when that checkpoint is not a complete save (seeis_complete_checkpoint), to the neweststep_Nbeside it that is. Any other load takes its checkpoint as is. Whichever it takes, a load that reads DCP shards reads them as the layout rank 0 found there: a pipeline stage loads its model weights from a checkpoint saved without pipeline parallelism too (see_shard_dir).plugins_expected (list[str] | None) – The run’s
pluginslist, compared with the one the checkpoint’smetadata.jsonrecords before any state is read (see_check_plugins). Every rank must pass the same value. A weights-only warm start, which reads no train state, is not compared.
- Returns:
Tuple of (step, tokens_seen, extra) where extra contains any additional keys saved via
build_train_state(extra=...).- Raises:
FileNotFoundError – No checkpoint resolves although one was named, or the checkpoint holds optimizer state that this load restores but has no
train_state.pt. Raised before any state is loaded.ValueError –
exclude_keysis not a list of distinct DCP keys, names"train_state"outside["optimizer", "train_state"], or is that pair withexact_resume, raised before the path is resolved; the checkpoint was saved under another weight-decay scope, LR multipliers or patterns of their modules (see__init__), or with anotherpluginslist (seeplugins_expected); or, on an exact resume, its per-rank state does not fit this run’s topology andcheckpoint.ignore_rank_state_mismatchis off (seeexact_resume). Also, for a load that reads DCP shards, before any is read: the checkpoint was saved under pipeline parallelism and this run has none, or another pipeline degree (seepp_sizein__init__); or it was saved without pipeline parallelism, this run is pipeline-parallel, and the load would restore the optimizer state it holds. Each message names both layouts and the way to carry the weights over. And, for a load that reads the model, before any tensor is read: the checkpoint holds model tensors this run’s model does not have, unlesscheckpoint.ignore_extra_model_tensorsis set, or one of another size, or lacks one this run loads (see_check_model_fits). It also records another VLM freeze (seevlm_freeze_expected).RuntimeError – The saved optimizer state does not fit this run’s optimizers, as when a name in
fresh_if_unheldwith neither saved state nor a never-stepped record is listed in the saved param groups, or no saved param group fits it, or the checkpoint holds fewer param groups than the optimizer and the missing ones are not groups of such names. Also, on every rank, when rank 0 could not read a DCP index to compare it with the model.
- Return type:
A load that restores optimizer state refuses it on every rank together, before any state is loaded: each rank checks its own part of the checkpoint, and one all-reduce on the manager’s gloo group, which every rank enters, has the other ranks raise a
RuntimeErrornaming the ranks that refused. A second such all-reduce follows DCP’s load, once each rank has restored the state of the parameters its checkpoint left out or never stepped, and before any state is set; every rank enters it too, also a pipeline stage whose checkpoint holds no optimizer state.
- property restored_extra: dict[str, Any]¶
The extra keys the last
load()restored fromtrain_state.pt.Empty before a load, and after one that restored no train state.
- property restored_optimizer: bool¶
Whether the last
load()restored this rank’s optimizer state, its rates included.False before a load, and after one that left the optimizer out or found no optimizer state in the checkpoint, as one saved before the first update holds none.
- apply_dataloader_state(dataloader)[source]¶
Apply any dataloader state stashed during load().
Training loops call load() before constructing the dataloader (since the dataloader depends on phase/annealing state that load() restores). This method applies the stashed state once the loader exists.
No-op if no state is pending, or if the loader does not support
load_state_dict(e.g., a plain torch DataLoader). AStatefulDataLoaderorStreamingDataLoaderchecks the position on every rank first (check_state), and the ranks share their verdicts before any rank applies it, since a rank’s view of the data, such as a data file’s size, can differ from another’s: every rank applies the position, or none does. A position that some rank’s loader cannot place raisesDataPositionErroron every rank on a resume; after awarm_startload, or an exact resume thatcheckpoint.ignore_rank_state_mismatchlet onto a changed topology or past a checkpoint with no per-rank state, every rank starts the data at its first sample instead, with a warning that names the ranks that cannot place it and why. Whether the ranks share verdicts follows from the broadcast train state and the loader’s type alone, so every rank reaches that collective or none does. On such a flag resume only these two loaders take the saved position, since they check that it fits the new layout; another loader’s state may be rank 0’s own, so it is dropped with a warning and the data starts at its first sample. A restored checkpoint that holds no data position, such as a streaming checkpoint saved before streaming positions were recorded, leaves a stateful loader at its first sample, with a warning.- Parameters:
dataloader (Any)
- Return type:
None