Checkpointing¶
Distributed checkpoints via torch.distributed.checkpoint (DCP):
what’s saved, how resharding works, auto-resume rules, and
HuggingFace interchange.
At a glance¶
Every checkpoint lands in {config.checkpoint.dir}/step_{N}/ and
contains two kinds of state:
File(s) |
Contents |
Format |
|---|---|---|
DCP shards ( |
Model + optimizer state, one shard per rank |
|
|
step, tokens_seen, scheduler, per-rank dataloader/RNG state, extras (e.g. |
|
|
Human-readable |
Plain JSON, see below |
|
Points at the most recent |
|
|
The run that owns the directory: its claim id, host, pid, pid namespace and SLURM job |
A complete save¶
A step_N directory holds a complete save once every DCP index of its layout is there: the
.metadata at its top, or under pipeline parallelism one in each of pp0/ to pp{n-1}/.
A save whose shards hold optimizer state, or that wrote train_state.pt, also needs
train_state.pt and metadata.json. Rank 0 writes them, metadata.json after
train_state.pt, after the shards in a synchronous save and while they flush in an
asynchronous one. A checkpoint without optimizer state or train_state.pt, such as an
hf-to-dcp import, needs neither file.
kempnerforge.checkpoint.is_complete_checkpoint applies that rule, the one auto-resume and
the fallback of an exact resume apply, so code that reads a run’s checkpoints while the run
saves them counts the same steps as saved:
from kempnerforge.checkpoint import is_complete_checkpoint
num_stages = config.distributed.pp if config.distributed.pp > 1 else None
for step_dir in sorted(run_dir.glob("step_*"), key=lambda d: int(d.name.split("_")[1])):
if is_complete_checkpoint(step_dir, num_stages):
evaluate(step_dir)
To poll a live run, keep the default require_train_state=True and pass the run’s
distributed.pp as num_stages, as above. A step then counts 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 indexes are there, before 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 count a step the first time the check accepts it.
require_train_state=False leaves the train-state files out, for a reader of
the weights alone, as scripts/eval.py reads a finished run.
num_stages matters for a stage checkpoint that records no degree: one saved before the
degree was recorded, and a live save until its metadata.json lands, which can come after its
first stage’s index. A stage of it that has not created its directory is noticed only
against that degree. With require_train_state (the default), the DCP index of a checkpoint
without train_state.pt is read to tell whether it holds optimizer state, and reading it
unpickles it (see Loading runs pickle). With
require_train_state=False the check reads only metadata.json, which is plain JSON.
metadata.json¶
Written by rank 0 beside train_state.pt, and readable with a plain json.load (no torch).
It holds step and tokens_seen, plus the run’s optimizer.weight_decay_scope as
weight_decay_scope when the checkpoint manager was built with it, as the training entry does
(VLM runs add vlm_freeze, and lr_multipliers with the lr_module_patterns of its
modules and the module of each optimizer param group, lr_group_modules, when
optimizer.lr_multipliers lists any), the run’s plugins list as plugins (see
Train state), and under pipeline parallelism the degree as pp (see
Resharding § PP). A load reads it on rank 0,
once, for the checks of those records and the checkpoint’s layout. A checkpoint without the
file records none of them: the plugins and VLM freeze comparisons are skipped with a
warning, and the training entry refuses to restore its optimizer state, since the
weight-decay scope it was saved under is unknown (see
Optimizers). When a logging backend
has a live run at save time it also holds a tracking list, one entry per backend:
{
"step": 1000,
"tokens_seen": 4096000,
"tracking": [
{"backend": "wandb", "run_id": "<run id>", "experiment": "<project>",
"entity": "<entity>", "url": "<run url>"},
{"backend": "tensorboard", "log_dir": "tb_logs"},
{"backend": "mlflow", "run_id": "<run id>", "experiment": "<experiment>",
"tracking_uri": "<tracking uri>"}
]
}
Each backend describes its own run, as it knows it: the resolved tracking URI and the experiment name for MLflow, the project for wandb, the writer’s directory for TensorBoard.
entityandurlappear when the wandb run has them (an offline run has no URL). The MLflow entry always has all four fields shown. With checkpoint registration on it also hasmodel_name, and getsmodel_idonce the committed checkpoint is registered. Every write ofmetadata.jsonreplaces the file atomically, so a reader never sees a partial one.A backend contributes only while its run is live, and runs start on the first log. A checkpoint saved before that (step 0, or soon after a resume when
checkpoint.intervalis shorter thanmetrics.log_interval) lacks the entry, and the key is omitted when no backend is live.The training entry hands
CheckpointManager.set_tracking_sourcethe tracker’stracking_entries, whichsave()reads on rank 0, andset_checkpoint_registrarthe tracker itself (Registering checkpoints). A source that raises, or returns what JSON cannot hold, costs thetrackingkey with a warning, never the save; a registrar that fails costs only its fields or its registration.Values are recorded as resolved. Credentials embedded in the tracking URI (
scheme://user:token@host) are stripped at write time; authentication comes from the environment, a profile or OAuth, never from this file. The URI, experiment path and run ids remain, so drop thetrackingkey before sharing a checkpoint outside your team.The key is additive. Older checkpoints lack it, nothing on the resume path reads it, and run ids still resume from
train_state.pt. Offline tools read it:kempnerforge.metrics.mlflow.publishappends eval metrics to the MLflow run itsmlflowentry names.
Loading runs pickle¶
A load passes checkpoint files to an unrestricted unpickler in three places, so a crafted checkpoint can run code in the process that loads it:
Every rank reads the DCP index, the
.metadatafile in the shard directory, through PyTorch’sFileSystemReader.read_metadata, which unpickles it with no check.Values in the DCP shards (the
.distcpfiles) that are not tensors, such as the optimizer’s param group settings, go through PyTorch’sDefaultLoadPlanner.load_bytes, which loads them withtorch.load(weights_only=False), also with no check.Rank 0 reads
train_state.ptwithtorch.load(weights_only=False), since the file holds scheduler, dataloader and RNG state and the run’s extras. Before that it refuses a file another user owns, and warns about, but still loads, one that is group- or world-writable. It checks only the file’s owner and mode: a checkpoint you downloaded, copied or extracted from an archive is yours, and can load silently.
So load only checkpoints you trust, in practice ones you or your team saved. Take weights
from elsewhere with hf-to-dcp (HF conversion), from a local directory or
a Hub model ID: it reads safetensors files, and .bin files with torch.load(weights_only=True),
and runs none of the model repository’s code. metadata.json is plain JSON: a tool that needs only
the step, the token count or the logging runs can read it without loading the checkpoint.
Key modules¶
kempnerforge/checkpoint/manager.py—CheckpointManager.save()/load()/wait(),latestsymlink maintenance, retention cleanup.kempnerforge/checkpoint/async_save.py—AsyncCheckpointer: the sync and async save modes (async_with_pinned_memstages the snapshot in pinned CPU memory where a CUDA device is available).kempnerforge/checkpoint/state.py—build_train_state/restore_train_state, RNG capture.kempnerforge/resilience/elastic.py—resolve_resume_path()(checks thelatestsymlink and falls back to the neweststep_Nwhose save completed).scripts/convert_checkpoint.py—dcp-to-hfandhf-to-dcpCLI.
Read next¶
New reader: DCP model + optimizer → Train state.
Resuming a job: Auto-resume first, then Resharding if you’re changing GPU count.
Exporting for inference or HF checkpoints: HF conversion.
Config knobs: Configuration § CheckpointConfig (search for
interval,dyn_ckpt_window,async_mode,keep_last_n,load_path).