kempnerforge.checkpoint

Distributed checkpointing for KempnerForge.

Public API:
  • CheckpointManager: Save/load/cleanup distributed checkpoints

  • AsyncCheckpointer: Non-blocking checkpoint saves

  • build_train_state / restore_train_state: State assembly

  • is_complete_checkpoint: Whether a step directory holds a complete save

class kempnerforge.checkpoint.AsyncCheckpointer[source]

Bases: object

Non-blocking checkpoint saver.

Wraps dcp.async_save() and manages the background save future. Each new save waits for the previous async save to complete first. Not thread-safe: call it from one thread, as the training loop does.

Parameters:

mode – Checkpoint mode (disabled/async/async_with_pinned_mem). The pinned mode stages through pinned memory only where a CUDA device is available, and saves as async elsewhere, with one warning.

__init__(mode=AsyncCheckpointMode.disabled)[source]
Parameters:

mode (AsyncCheckpointMode)

Return type:

None

save(state_dict, checkpoint_id, process_group=None, planner=None)[source]

Save distributed state, potentially asynchronously.

Parameters:
  • state_dict (dict) – DCP-compatible state dict (model + optimizer).

  • checkpoint_id (str) – Checkpoint directory path.

  • process_group – Process group for DCP. Required for PP where each stage has a different state dict — pass a group scoped to ranks within the same PP stage. None uses the default global group.

  • planner (SavePlanner | None) – DCP save planner. None calls DCP as before, with its default planner.

Return type:

None

close()[source]

Wait for any pending save, then release the pinned copies the stager holds.

The stager is released and the pending save dropped even when that save failed, whose error still propagates. A later save in the pinned mode builds a new stager.

Return type:

None

wait()[source]

Block until any pending async save completes.

Return type:

None

property is_pending: bool

Whether an async save was started and wait() has not drained it yet.

property is_flushing: bool

Whether the pending save’s background write is still running; never blocks.

False with nothing pending, and once the write has ended, whether it succeeded or failed: wait() then returns, or raises the write’s error, at once.

class kempnerforge.checkpoint.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

kempnerforge.checkpoint.build_train_state(step, tokens_seen, scheduler=None, dataloader=None, extra=None, per_rank=None)[source]

Build the non-distributed portion of the training state.

Model and optimizer state are handled by DCP directly. This function captures everything else needed for exact resumption.

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

  • tokens_seen (int) – Total tokens processed so far.

  • scheduler (Any | None) – LR scheduler (must have state_dict()). When a param group of its optimizer names a module, as build_optimizer names those of optimizer.lr_multipliers, the module of every group is recorded under scheduler_group_modules.

  • dataloader (Any | None) – Stateful dataloader (must have state_dict()); writes the legacy single-copy dataloader key (the caller’s own loader, rank 0 in distributed runs).

  • extra (dict | None) – Additional metadata to include.

  • per_rank (dict[str, Any] | None) – Versioned per-rank envelope (build_per_rank_envelope) holding every rank’s own loader/RNG payload.

Returns:

Dict with training state, scheduler state, dataloader state, and RNG states.

Return type:

dict[str, Any]

kempnerforge.checkpoint.get_rng_state()[source]

Capture all RNG states for reproducibility on resume.

Return type:

dict[str, Any]

kempnerforge.checkpoint.is_complete_checkpoint(ckpt_dir, num_stages=None, *, require_train_state=True)[source]

Whether ckpt_dir holds a complete save, by the rule auto-resume applies.

resolve_resume_path picks a checkpoint this accepts whenever there is one, and so does the fallback of an exact resume in CheckpointManager.load. Code that reads a run’s checkpoints while the run saves them, such as a process that evaluates each saved step, calls it to count the same steps as saved.

A save is complete when every DCP index of its layout is there (see saved_layout): .metadata at the top of a checkpoint saved without pipeline parallelism, and in each of pp0/ to pp{n-1}/ of one that records its pipeline degree n. A stage checkpoint saved before the degree was recorded needs an index in every pp{k}/ it holds and, with num_stages, in pp0/ to pp{num_stages - 1}/, since a stage that stopped before its save began leaves no directory.

With require_train_state, a checkpoint whose shards hold optimizer state, or that has a train_state.pt, also needs train_state.pt and metadata.json. A save’s rank 0 writes the two, metadata.json after train_state.pt: after every stage’s shards when the save is synchronous, and while they flush when it is asynchronous, so either may land first. A checkpoint with neither optimizer state nor train_state.pt, such as an hf-to-dcp import, needs neither file. To tell which it is, the DCP index is read only when train_state.pt is absent; reading it unpickles it, as a load does. An index that cannot be read is logged and counted as holding no optimizer state, which leaves the load to report it.

With require_train_state and num_stages, a process that polls a live run gets a step only once its save has written every file, except a save made before the optimizer’s first step: its shards hold no optimizer state, so, like an import, it counts once its DCP indexes are there, before rank 0 writes train_state.pt and metadata.json. It then drops out while train_state.pt is there without metadata.json, and counts again once metadata.json lands, so a poller counts a step the first time this accepts it. Without num_stages, a pipeline-parallel save can count early too: it records its degree only in metadata.json, which can land after the first stage’s index, so it counts once the stage directories that exist hold their indexes, before a later stage has created its own.

Parameters:
  • ckpt_dir (str | PathLike[str]) – A step_N directory, or a link to one such as latest.

  • num_stages (int | None) – The pipeline degree of the run that reads the checkpoint, or None. It counts only for a stage checkpoint that records no degree, as a live save does until its metadata.json lands: one that records it is complete at its own degree, and a load refuses a degree the run cannot load.

  • require_train_state (bool) – True for a resume, which restores the step, LR schedule and data position from train_state.pt; False for a reader of the weights alone, such as scripts/eval.py, which needs only the DCP shards.

Returns:

Whether the save is complete; False for a path that is no directory, or one that holds no DCP index.

Return type:

bool

kempnerforge.checkpoint.restore_train_state(state, scheduler=None, dataloader=None, lr_multipliers=None)[source]

Restore the non-distributed portion of the training state.

Parameters:
  • state (dict[str, Any]) – Training state dict (from build_train_state).

  • scheduler (Any | None) – LR scheduler to restore. The saved schedule carries on in every param group, peak included, whatever the rates the optimizer was built with, and each group’s initial_lr is set to the base rate it now runs from. Its state is laid out by module for groups other than those it was saved with (see build_train_state): each group of a module the checkpoint holds resumes at that module’s rates, and any other at the saved peak times its multiplier. Nothing is restored when that fails. When a group names a module, the peak rate of each module’s groups is logged, with a warning when one differs from the rate the optimizer was built with, as when optimizer.lr changed since the save.

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

  • lr_multipliers (Mapping[str, float] | None) – The optimizer.lr_multipliers the scheduler’s groups were built with, which must be those of the save. Needed only for a group of a module the checkpoint holds no group of.

Return type:

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

Restores whatever rng/dataloader keys state carries. On an exact resume the manager hands each rank its own view of the broadcast train state (its per-rank envelope entry overlaid on these keys) before calling this; any other load passes the broadcast state as is, so rank 0’s single copy restores on every rank.

Returns:

Tuple of (step, tokens_seen, extra) where extra contains any additional keys saved via build_train_state(extra=…).

Raises:

ValueError – The scheduler state cannot be laid out for the scheduler’s param groups.

Parameters:
Return type:

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

kempnerforge.checkpoint.set_rng_state(state)[source]

Restore all RNG states from a checkpoint.

Parameters:

state (dict[str, Any])

Return type:

None

Modules

async_save

Async checkpointing for non-blocking saves.

expert_layout

Expert-parallel experts under their global identity in a DCP state dict.

layout

Where a checkpoint keeps its DCP shards, and whether a step directory holds a whole save.

manager

Checkpoint manager for distributed checkpointing.

ownership

One training run per checkpoint directory.

state

Training state assembly for checkpointing.