Auto-resume

KempnerForge resumes a training run automatically on restart — no flag to pass, no manual path to point at. Every SLURM requeue, every preemption-and-restart, every “I killed the job and started it again” just works, as long as a checkpoint directory exists.

The resolution order

resolve_resume_path:

# kempnerforge/resilience/elastic.py (abridged: logging calls elided)
def resolve_resume_path(
    checkpoint_dir: str, num_stages: int | None = None, *, require_train_state: bool = True
) -> Path | None:
    base = Path(checkpoint_dir)
    if not base.exists():
        return None

    # 1. latest symlink, if it is a complete save (the rule of is_complete_checkpoint)
    latest = base / "latest"
    committed = None
    if latest.exists():
        resolved = latest.resolve()
        reason = _incomplete_reason(resolved, num_stages, require_train_state)
        if reason is None:
            return resolved
        if _incomplete_reason(resolved, num_stages, require_train_state=False) is None:
            committed = resolved, reason  # every shard there, a train-state file lost

    # 2. newest step_N directory whose save completed
    step_dirs = sorted(
        (d for d in base.iterdir()
         if d.is_dir() and d.name.startswith("step_") and d.name.split("_")[1].isdigit()),
        key=lambda d: int(d.name.split("_")[1]),
        reverse=True,
    )
    short_of_stages = None
    for path in step_dirs:
        if _incomplete_reason(path, num_stages, require_train_state) is None:
            return path
        if num_stages is not None and num_stages > 1:
            if _incomplete_reason(path, None, require_train_state) is None:
                short_of_stages = short_of_stages or path  # every stage present is complete

    # 3. nothing complete: keep the old choices (logged as errors)
    if committed is not None:
        return committed[0]
    return short_of_stages

A checkpoint counts when is_complete_checkpoint accepts it, with the same num_stages and require_train_state; _incomplete_reason is the private function behind it that also says why not. Two fallbacks:

  1. latest symlink: the canonical pointer, updated atomically after every successful save (see Symlink updates below). Used in all healthy cases. Its target is checked like a step_N below, every stage’s .metadata, train_state.pt and metadata.json included, so one that lost files after it was committed is skipped with a warning and the scan picks the checkpoint. When nothing is complete and the target holds all its shards but lost train_state.pt or metadata.json, it is chosen anyway, after an error log, instead of the run starting over from step 0: the load then refuses a target without train_state.pt, and the optimizer state of one without metadata.json, the only record of the weight-decay scope that state was saved under.

  2. Newest complete step_N directory: a safety net. If the symlink is missing (disk corruption, manual rm, never created because no save has completed), the resolver scans the step_N directories from the highest number down and uses the first whose save completed. It skips, with a warning, a directory without DCP’s .metadata (a save cut short while writing its shards) and one whose shards hold optimizer state, or that has a train_state.pt, but that lacks train_state.pt or metadata.json (a save cut short before rank 0 wrote both, metadata.json last, or a copy that lost one). Resuming the second kind would continue its weights and optimizer moments from step 0, or, without metadata.json, stop the run on every requeue: the load restores no optimizer state without the weight-decay scope that file records. A directory whose shards hold no optimizer state and that has no train_state.pt, such as an hf-to-dcp import, needs neither file. A caller that loads the weights alone, such as scripts/eval.py, passes require_train_state=False and keeps the second kind.

    Under pipeline parallelism, DCP’s .metadata means every stage’s pp{k}/.metadata, for pp0 through pp{n-1} where n is the degree the checkpoint’s metadata.json records as pp, so a step that one stage never started saving is skipped instead of resumed with that stage loading an older step. A checkpoint of another layout counts as complete when its own shards are, so the newest one is resumed as found, never passed over for an older one, and the load applies the layout checks it applies to any checkpoint (see Resharding § PP): a stage checkpoint of another pp, or one resumed without PP, is refused, naming both layouts, and so is a checkpoint saved without PP that holds optimizer state, since a resume restores it.

    A checkpoint saved before the degree was recorded takes n from distributed.pp. When no step has every stage, the newest one that is otherwise complete (neither of the two kinds skipped above) is resumed as before, after an error log, instead of the run starting over. Such a checkpoint saved with another distributed.pp looks the same, and the load refuses it, naming the stage directories it holds.

If neither path finds anything, the function returns None and training starts from step 0, or from checkpoint.load_path when one is set. When step_N directories exist but none holds a complete save, it says so at ERROR level.

Where it’s called

training/entry.py::restore_checkpoint calls this once, right after creating the CheckpointManager; with a process group, rank 0 calls it and broadcasts the path, or the error it raised, to every rank:

num_stages = config.distributed.pp if config.distributed.pp > 1 else None
if dist.is_initialized():
    resume_path = _resume_path_on_rank_zero(config.checkpoint.dir, num_stages)
else:
    resume_path = resolve_resume_path(config.checkpoint.dir, num_stages)
step, tokens_seen = 0, 0
if resume_path and config.checkpoint.load_path:
    logger.warning(...)  # rank 0, unless load_path is resume_path: load_path is not used
if resume_path or config.checkpoint.load_path:
    warm_start_exclude = (
        (config.checkpoint.exclude_from_loading or None) if resume_path is None else None
    )
    vlm_freeze_expected = partial(freeze_meta_at_step, config=config.vlm)  # VLM, not weights-only
    with _trainable_for_the_run(model, config) as unfrozen_later:
        step, tokens_seen, ckpt_extra_loaded = ckpt_mgr.load(
            path=str(resume_path) if resume_path else None,
            scheduler=scheduler,
            warm_start=resume_path is None,
            exclude_keys=warm_start_exclude,
            vlm_freeze_expected=vlm_freeze_expected,
            fresh_if_unheld=unfrozen_later,
            exact_resume=resume_path is not None,
        )
    if resume_path:
        if ckpt_extra_loaded.get("wandb_run_id"):
            config.metrics.wandb_run_id = ckpt_extra_loaded["wandb_run_id"]
        if ckpt_extra_loaded.get("mlflow_run_id"):
            config.metrics.mlflow_run_id = ckpt_extra_loaded["mlflow_run_id"]
    elif rank_zero:
        _tag_warm_start_run(config, ckpt_extra_loaded)

So two things can trigger a resume:

  • resume_path found: auto-resume; user passed nothing. It continues the run, its MLflow and W&B runs included.

  • config.checkpoint.load_path set: a warm start from that path, used only while checkpoint.dir holds no checkpoint. Useful for loading pretrained weights, fine-tuning from a specific checkpoint, or debugging. It is a new run, so it logs to new MLflow and W&B runs, and its MLflow run is tagged with the checkpoint it started from (MLflow § Run ID and resume).

A warm start restores the saved data position where it carries over to the new run: a single pre-tokenized, eager Hugging Face or VLM dataset continues at the same sample on any data-parallel size. Where it cannot, as with a mixture or a streamed dataset on another data-parallel size, a switch of data.hf_streaming, a changed stream, or a checkpoint saved before the loader recorded its batch size on another data-parallel size, the warm start logs a warning that names the reason and every rank starts the data at its first sample. A resume from checkpoint.dir stops instead, on every rank. Every rank checks the position before any rank applies it and the ranks agree, so one rank whose view of the data differs, such as a stream’s data file at another size, cannot leave the others resuming without it. A checkpoint with per-rank state refuses a resume onto another world size or data-parallel layout with a RankStateMismatchError, before any data position is applied; on the topology that saved it, a position that does not fit, after a switch of data.hf_streaming or a changed stream, raises DataPositionError. A checkpoint saved before per-rank state was recorded applies rank 0’s position on every rank and raises DataPositionError where it cannot carry over. With checkpoint.ignore_rank_state_mismatch set, a resume onto another world size or layout, and any resume of a checkpoint saved before per-rank state was recorded, even on the topology that saved it, treats the data position as a warm start does, except that a stream on the saved data-parallel size resumes each data-parallel rank from the position it saved, and restarts the RNG streams. Per-rank state that is unreadable or incomplete even on the topology that saved it is the exception: the flag keeps no data position from it, so the data starts at its first sample. The flag does not cover a position that does not fit on the topology that saved per-rank state: it still raises DataPositionError (see Scaling a run to a different world size).

If both are set, resume_path wins (auto-resume takes precedence over the static config). This is deliberate: SLURM requeues should always pick up where they left off, not re-load the initial load_path every time. Rank 0 logs a warning that names both paths, so a load_path meant as a rollback does not go unnoticed (unless load_path names the very checkpoint being resumed and excludes nothing, since the resume then does what it asks): see Loading a specific step. exclude_from_loading follows the same rule: it applies only to the load_path warm start, so when a resume wins it is dropped with load_path and a weights-only warm start becomes a full resume, which the same warning states. Use an empty dir to guarantee the warm start. Per-rank dataloader/RNG state follows it too: only the auto-resume is an exact resume, where each rank restores its own state and a changed world size or data-parallel layout is refused; a load_path warm start restores rank 0’s single copy on every rank on any topology, and a weights-only one (below) restores neither (see Train state). To auto-resume onto a different topology anyway, set checkpoint.ignore_rank_state_mismatch: the data position then carries over where the loader can place it on the new layout, and the RNG streams restart. See Scaling a run to a different world size.

A training checkpoint also holds train_state.pt, and load_path restores it: the step, token count, LR schedule, dataloader position and RNG state continue from the saved run, and the freeze the checkpoint records is compared with the new run’s at the step it records. To start a new stage from a previous stage’s weights alone, add "train_state":

[checkpoint]
load_path = "/runs/stage1/step_50000"
exclude_from_loading = ["optimizer", "train_state"]

The new run then begins at step 0 with its own warmup, data order and freeze specs, and only the model weights come from the checkpoint. "train_state" is accepted only in that pair: with the optimizer kept, a restarted warmup would apply the saved moments and step counters, and a changed freeze would fail inside the optimizer load instead of at the freeze check; with the model excluded too, nothing would load. A MoT run with mot_warm_start_from_text keeps the loaded weights: the text warm start runs only when no checkpoint supplied the model, that is on a run with nothing to resume from or a warm start that excludes "model" and starts at step 0, and never on a resume. A weights-only warm start also skips the freeze check, since the new run’s own freeze applies, and the plugins comparison. The freeze check takes the step and the freeze from rank 0’s read of the metadata.json of the checkpoint load settles on, the one it falls back to included, so every rank compares the same record. Any other warm start, like a resume, compares the run’s plugins list with the one metadata.json records before reading any state, and refuses another list unless checkpoint.ignore_plugins_mismatch is set.

One run per checkpoint directory

Two live runs pointed at one checkpoint.dir, such as one config launched twice from the same working directory, would overwrite each other’s checkpoints, prune each other’s step_* directories and resume from each other’s latest. So before a training run resumes or saves, rank 0 records it in <checkpoint.dir>/.owner, and every rank stops when that fails. The record holds a claim id of its own, a random id of the process, by which a process knows its own records, the host, pid, pid namespace and start time, and under SLURM the job (SLURM_JOB_ID, or <SLURM_ARRAY_JOB_ID>_<SLURM_ARRAY_TASK_ID> for a job array element), its cluster (SLURM_CLUSTER_NAME) and its requeue count (SLURM_RESTART_COUNT). A run finds one of these:

  • No record: the run claims the directory. The record is written to a temporary file and linked into place, so it appears whole and only one of two runs claiming at once creates it.

  • A record this process wrote: replaced, as when a run that raised is followed by another in the same process, unless the process released it; a released record goes through the token below.

  • A record of a run that is still alive: the run stops with an error that names the owner.

  • A released record: replaced, as below but without a warning.

  • A record of a run that has ended: replaced, with a warning. Of two runs that find it at once, only the one that creates .owner.<that record's claim id>.takeover replaces it, and the other then finds the new owner alive. The run renames a link of its own temporary file, under a name only its claim uses, so a rename that NFS replays finds nothing to move, and it reads the record back before it counts the claim.

  • A record of a run this process cannot check: the run stops, and the error names the file to remove if that run has ended.

Whether the owner is alive depends on where it ran:

  • An earlier attempt of this SLURM job, the same job with another requeue count, has ended: a requeued job goes back to pending before it runs again.

  • Another run in this SLURM job, such as a second training in one allocation, is alive while its pid runs. Only a process on its host and in its pid namespace can check, since containers that share the host name but not the pid namespace reuse pids, and a host where /proc does not show the namespace cannot check at all.

  • Another SLURM job is alive until squeue lists it in a final state, such as COMPLETED, CANCELLED, FAILED or TIMEOUT, or no longer lists it. squeue runs without the SQUEUE_* and SLURM_CLUSTERS settings that narrow what it lists, and a run outside SLURM asks the owner’s cluster by name. A job of another cluster than the run’s own, or one squeue cannot answer for, cannot be checked.

  • A run outside SLURM is alive while its pid runs. Only a process on its host and in its pid namespace can check.

A run that ends cleanly marks its record released, replacing it the same way with a released record; nothing removes .owner, so a removal NFS replays cannot remove a later run’s record. An error marking it is logged, not raised. A run that crashes leaves its record, and the next run takes it over once the first has ended. A run that dies while it holds a .takeover file leaves that file, and the next run takes the file over the same way once that run has ended; while its run is alive, or cannot be checked, the next run stops with an error that names the file. Claims and releases in one process run one at a time. Scripts that only read checkpoints, such as scripts/eval.py, do not claim the directory.

The protocol assumes that the filesystem applies each request once, and that a request from a process that has died is not applied after another process has taken the directory over. Local filesystems, NFSv4.1 sessions and NFSv3 servers with a duplicate request cache give both; on a server that loses its reply cache, rare orderings could still admit two owners.

Retention cleanup

After updating the symlink, CheckpointManager._cleanup() keeps the config.checkpoint.keep_last_n highest-numbered step_* directories and removes the older ones, except three kinds it never removes:

  • the checkpoint latest points at;

  • the directory the last save() writes into, so an async save keeps it while its flush runs, even when newer step_* directories are present, as after the manual rewind below;

  • every dyn_ckpt_window milestone, so the dense early checkpoints survive a finite keep_last_n.

Default keep_last_n = 3. Set keep_last_n = 0, or any value <= 0, to keep every checkpoint: cleanup then removes nothing.

On NFS, a file deleted a moment after it was written can stay behind as a .nfs* placeholder until the client lets go of it, so removing its directory fails for a short while. Cleanup retries such a removal after 0.05, 0.1, 0.2 and 0.4 s. All the removals of one cleanup share these waits, so a cleanup requests at most 0.75 s of retry sleep.

A checkpoint it still cannot remove is logged as a warning and left for the next cleanup to retry, so on a server that keeps the placeholder longer, old checkpoints can remain, also after the last cleanup of a run. Any other error while removing a checkpoint is logged the same way: cleanup runs after latest has moved, so the checkpoint is already committed and the save still succeeds on every rank.

Edge cases

  • A rank wedged in the train-state broadcast: PyTorch’s broadcast_object_list takes no async_op, so this call carries no per-operation timeout and inherits the process group’s 1800 s default. A wedged rank still surfaces, just later than the other fast-fail paths in resume.

  • Empty checkpoint directory — resolve_resume_path returns None, training starts from step 0. No error.

  • latest points at a removed or damaged checkpoint: if the link’s target is gone, the resolver goes straight to the step_N scan; if the target is there but is not a complete save, it warns, naming what is missing, and falls through to the scan. This catches the case where someone rm-rf’d a checkpoint, or part of one, but left the symlink.

  • The checkpoint being resumed loses files after it was resolved: on an auto-resume, rank 0 checks again in ckpt_mgr.load that it is a complete save, by the same rule (is_complete_checkpoint, with the train state an exact resume restores). If not, it picks the newest complete step_N beside it and logs a warning; with none, it keeps the checkpoint as resolved, and the load fails on the stage that lacks its shards, or refuses its optimizer state, which needs train_state.pt for the step it was saved at and metadata.json for the weight-decay scope it was saved under. A stage that never created its directory is noticed here too, by the degree the checkpoint records or, for one saved before that record, by the run’s distributed.pp. Every rank loads the checkpoint rank 0 picked, as the layout rank 0 read in it, whatever its own view of the filesystem, so no stage resumes a different step or layout than another. A checkpoint named by load_path is loaded as named.

  • A rank that cannot see the checkpoint: every load, a load_path warm start or an evaluation as well as a resume, takes the directory rank 0 resolves (the path passed to it, load_path, or latest, links followed), broadcast to the other ranks with any error rank 0 hit. A rank whose view of a shared filesystem lags neither fails alone at that point nor starts from scratch while the others load. The agreement covers which directory to load, not reading it: a rank that cannot read the files still fails when it reads them.

  • Corrupted step_N directory: resolve_resume_path checks only that a save completed (DCP’s .metadata, and train_state.pt and metadata.json when the shards hold optimizer state), not the contents. If DCP can’t load from the resolved path, ckpt_mgr.load raises and training aborts.

  • Checkpoint without train_state.pt: when load_path names a checkpoint whose shards hold optimizer state but that has no train_state.pt, or latest does and no checkpoint in dir is complete, ckpt_mgr.load raises FileNotFoundError before it loads anything, instead of resuming its weights and optimizer moments at step 0. To start from its weights alone, use a new dir with load_path pointing at it and exclude_from_loading = ["optimizer"]. See Train state.

  • load_path set and dir already has a checkpoint: the checkpoint in dir is resumed, load_path is not used, and rank 0 warns, naming both paths, unless load_path names that checkpoint and excludes nothing.

  • Fresh checkpoint dir, load_path set — load_path is used (the else branch). Training starts from the step in that checkpoint.

  • Multi-node NFS vs local disk — the latest symlink lives on disk along with the shards. For a shared filesystem (Lustre, NFS) this just works. For local scratch, every node needs its own copy of the checkpoint directory, which KempnerForge does not manage automatically — use a shared filesystem.

Loading a specific step

To rewind to an earlier checkpoint manually:

# Delete the symlink and let resolve_resume_path pick up step_5000
cd checkpoints
rm latest
ln -s step_5000 latest

Move the abandoned step_* directories newer than step 5000 out of checkpoints/ as well. Retention counts them among the newest, so they take the keep_last_n places of the rerun’s own checkpoints.

Or start a new checkpoint directory from it, which leaves the original run untouched:

[checkpoint]
dir = "checkpoints_from_5000"
load_path = "checkpoints/step_5000"

load_path is used only while dir holds no checkpoint. With exclude_from_loading empty it restores the full state of step 5000, and requeues of the new run resume from its own checkpoints in the new dir. The new run logs to new MLflow and W&B runs, the MLflow one tagged with the checkpoint it started from (MLflow § Run ID and resume), while rewinding latest as above continues the original runs, where MLflow drops the rerun’s steps up to the last train/loss step the run already holds. Setting load_path to step_5000 while dir stays checkpoints does not roll back: the run resumes from the newest checkpoint there, and rank 0 warns that load_path is not used.

Resilience interaction

Auto-resume pairs with the SLURM preemption handler in kempnerforge/resilience/:

  1. SLURM sends SIGTERM on preemption.

  2. ShutdownHandler flags shutdown; the training loop finishes the current step and saves an emergency checkpoint.

  3. ckpt_mgr.wait() flushes any async save before destroy_distributed().

  4. SLURM requeues the job.

  5. New job starts, resolve_resume_path finds latest, training resumes from the emergency checkpoint.

See Resilience § Signal handling.

See also