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

derive_buffers(model, keys)

Have the owner of each derived buffer at keys recompute it from its loaded state.

derived_buffer_owners(model)

Map the state-dict key of each buffer a module lists in derived_buffers to its owner.

drop_derived_model_keys(model_state, model, ...)

Take out of a load template the derived buffers its checkpoint predates.

Classes

CheckpointManager

Manages save/load/cleanup of distributed checkpoints.

CheckpointRegistrar

Records checkpoints with the logging backends, which this module never imports.

class kempnerforge.checkpoint.manager.CheckpointRegistrar[source]

Bases: Protocol

Records 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.

Parameters:

step (int)

Return type:

dict[str, dict[str, str]]

register_checkpoint(step, directory, record)[source]

Register the checkpoint at directory once latest points at it.

Called on rank 0 when the checkpoint is committed, so it must not block. record adds fields to a backend’s record in that checkpoint’s metadata.json, from any thread, later.

Parameters:
Return type:

None

__init__(*args, **kwargs)
kempnerforge.checkpoint.manager.derived_buffer_owners(model)[source]

Map the state-dict key of each buffer a module lists in derived_buffers to 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_dict names them (see state_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_owners maps are taken out, and only those the checkpoint, whose keys prefix the model’s with model., lacks; any other key a checkpoint lacks still fails the load. Returns the entries taken out. Put back after the read, they let the strict set_model_state_dict find every key, under torch.compile too, and derive_buffers then recomputes them from the loaded state.

Parameters:
Return type:

dict[str, Any]

kempnerforge.checkpoint.manager.derive_buffers(model, keys)[source]

Have the owner of each derived buffer at keys recompute 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_buffers but has no derive_buffers.

Parameters:
Return type:

None

class kempnerforge.checkpoint.manager.CheckpointManager[source]

Bases: object

Manages 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 latest symlink 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 (see kempnerforge.checkpoint.layout), through process_group.

  • pp_size – The run’s pipeline degree, which needs pp_rank. Every save then records it in metadata.json as pp. A load refuses, with a ValueError on 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 (see load).

  • 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 in metadata.json, and a load that restores optimizer state on any rank raises ValueError on 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 whose metadata.json records 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 in metadata.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 raises ValueError on every rank when it restores the checkpoint’s optimizer state on any rank, before anything is loaded, or the scheduler state in its train_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 whose metadata.json cannot 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 (see restore_train_state).

  • module_patterns – Module name to fnmatch patterns, such as VLMConfig.module_patterns. Required for every module lr_multipliers lists.

  • group_timeout_sec – Collective timeout of the gloo group the manager creates to order its saves across ranks, distributed.nccl_timeout_sec in 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:
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 (see claim_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>/.owner record that this rank’s claim_dir wrote.

Return type:

None

agree(error, what='Checkpoint save')[source]

Agree on the manager’s dedicated gloo group that every rank’s what succeeded.

See agree_across_ranks. The group is not the default process group that DCP’s async-save background thread issues collectives on.

Parameters:
Return type:

None

set_tracking_source(source)[source]

Record the logging runs source reports in every later metadata.json.

source returns one JSON-ready record per live run, and is called on rank 0 only, inside save(), so it must return promptly. The tracking key is omitted when it reports none, raises, or returns what JSON cannot write. None detaches it.

Parameters:

source (Callable[[], list[dict[str, str]]] | None)

Return type:

None

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_fields is asked inside save() when a backend has a live run, and its fields join that save’s tracking records. register_checkpoint gets each checkpoint once it is committed, with a record(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. None detaches 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, and load rebuilds that point. The swap back runs as soon as AsyncCheckpointer.save returns, which is safe only because the state is staged by then: both async modes stage synchronously, so every tensor is copied to CPU memory before dcp.async_save returns. The async mode passes no stager and gets torch’s default, DefaultStager(StagingOptions(False, False, False, False)); async_with_pinned_mem passes its pinned DefaultStager, built with use_async_staging=False, whose stage waits 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.

Parameters:
  • step (int) – Current training step.

  • tokens_seen (int) – Total tokens processed.

  • scheduler (Any | None) – LR scheduler to save.

  • dataloader (Any | None) – Stateful dataloader to save.

  • extra (dict | None) – Additional metadata.

Return type:

None

property has_pending_save: bool

Whether wait() has an async save to drain or a latest commit 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 moves latest to 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.json with the pre-transition spec before the transition flips requires_grad. Otherwise metadata.json lands 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 step from a candidate checkpoint’s metadata.json, on this rank alone.

Returns None if no checkpoint resolves, or its metadata.json is absent, cannot be read, does not hold a JSON object, or records no step that is a non-negative integer. load does not use it: a load takes the step its checks need from rank 0’s read of the checkpoint it settles on (see vlm_freeze_expected).

Parameters:

path (str | None)

Return type:

int | None

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_path or the latest symlink.

  • 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 ignores train_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 raises ValueError.

  • 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 as freeze_meta_at_step with that config, which is called with the step the checkpoint’s metadata.json records. 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 raises ValueError unless the checkpoint config has ignore_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 as dataloader or later to apply_dataloader_state, then starts the data at its first sample with a warning, instead of raising DataPositionError.

  • 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_mismatch is 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 (a load_path warm start, evaluation, any other load) restores the single-copy rng/dataloader keys (rank 0’s) on every rank with no topology check. The weights-only exclude_keys pair reads no train state: no rank restores loader/RNG state or enters the train-state broadcasts or the layout gather, and with exact_resume it 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 (see is_complete_checkpoint), to the newest step_N beside 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 plugins list, compared with the one the checkpoint’s metadata.json records 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_keys is not a list of distinct DCP keys, names "train_state" outside ["optimizer", "train_state"], or is that pair with exact_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 another plugins list (see plugins_expected); or, on an exact resume, its per-rank state does not fit this run’s topology and checkpoint.ignore_rank_state_mismatch is off (see exact_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 (see pp_size in __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, unless checkpoint.ignore_extra_model_tensors is set, or one of another size, or lacks one this run loads (see _check_model_fits). It also records another VLM freeze (see vlm_freeze_expected).

  • RuntimeError – The saved optimizer state does not fit this run’s optimizers, as when a name in fresh_if_unheld with 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:

tuple[int, int, dict[str, Any]]

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 RuntimeError naming 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 from train_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). A StatefulDataLoader or StreamingDataLoader checks 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 raises DataPositionError on every rank on a resume; after a warm_start load, or an exact resume that checkpoint.ignore_rank_state_mismatch let 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