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 (.distcp + .metadata)

Model + optimizer state, one shard per rank

DCP § Model + optimizer

train_state.pt

step, tokens_seen, scheduler, per-rank dataloader/RNG state, extras (e.g. phase_idx, wandb_run_id, mlflow_run_id)

Train state

metadata.json

Human-readable {"step": N, "tokens_seen": M}, plus the logging runs live at save time

Plain JSON, see below

latest symlink

Points at the most recent step_N (updated atomically)

Auto-resume

.owner

The run that owns the directory: its claim id, host, pid, pid namespace and SLURM job

JSON, see Auto-resume § One run per checkpoint directory

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. entity and url appear 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 has model_name, and gets model_id once the committed checkpoint is registered. Every write of metadata.json replaces 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.interval is shorter than metrics.log_interval) lacks the entry, and the key is omitted when no backend is live.

  • The training entry hands CheckpointManager.set_tracking_source the tracker’s tracking_entries, which save() reads on rank 0, and set_checkpoint_registrar the tracker itself (Registering checkpoints). A source that raises, or returns what JSON cannot hold, costs the tracking key 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 the tracking key 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.publish appends eval metrics to the MLflow run its mlflow entry 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 .metadata file in the shard directory, through PyTorch’s FileSystemReader.read_metadata, which unpickles it with no check.

  • Values in the DCP shards (the .distcp files) that are not tensors, such as the optimizer’s param group settings, go through PyTorch’s DefaultLoadPlanner.load_bytes, which loads them with torch.load(weights_only=False), also with no check.

  • Rank 0 reads train_state.pt with torch.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