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¶
# 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:
latestsymlink: the canonical pointer, updated atomically after every successful save (see Symlink updates below). Used in all healthy cases. Its target is checked like astep_Nbelow, every stage’s.metadata,train_state.ptandmetadata.jsonincluded, 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 losttrain_state.ptormetadata.json, it is chosen anyway, after an error log, instead of the run starting over from step 0: the load then refuses a target withouttrain_state.pt, and the optimizer state of one withoutmetadata.json, the only record of the weight-decay scope that state was saved under.Newest complete
step_Ndirectory: a safety net. If the symlink is missing (disk corruption, manualrm, never created because no save has completed), the resolver scans thestep_Ndirectories 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 atrain_state.pt, but that lackstrain_state.ptormetadata.json(a save cut short before rank 0 wrote both,metadata.jsonlast, or a copy that lost one). Resuming the second kind would continue its weights and optimizer moments from step 0, or, withoutmetadata.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 notrain_state.pt, such as anhf-to-dcpimport, needs neither file. A caller that loads the weights alone, such asscripts/eval.py, passesrequire_train_state=Falseand keeps the second kind.Under pipeline parallelism, DCP’s
.metadatameans every stage’spp{k}/.metadata, forpp0throughpp{n-1}wherenis the degree the checkpoint’smetadata.jsonrecords aspp, 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 anotherpp, 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
nfromdistributed.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 anotherdistributed.pplooks 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_pathfound: auto-resume; user passed nothing. It continues the run, its MLflow and W&B runs included.config.checkpoint.load_pathset: a warm start from that path, used only whilecheckpoint.dirholds 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.
Symlink updates¶
Inside CheckpointManager.save (rank 0 only):
# manager.py
latest = self._latest_link() # <dir>/latest
tag = f"{socket.gethostname()}-{os.getpid()}-{uuid.uuid4().hex}"
tmp_link = latest.with_name(f"{latest.name}.{tag}.tmp")
tmp_link.symlink_to(ckpt_dir.name) # relative link: "step_1000"
try:
tmp_link.rename(latest) # atomic rename
except BaseException:
tmp_link.unlink(missing_ok=True)
raise
Three details that matter:
Relative target: the symlink points at
step_1000, not/abs/path/checkpoints/step_1000. Checkpoint directories stay portable when moved or bind-mounted.Atomic rename:
tmp_link.rename(latest)is a single atomic syscall (rename(2)on POSIX). Either the old symlink is still there or the new one is, never a half-written state. Safe against crashes mid-save.A temporary name of its own: the new link is made under a name of this host, process and call, so no other writer removes or replaces it before the rename, and a rename that fails removes it.
The symlink is updated after the DCP save completes, so latest
only ever points at a fully-flushed checkpoint. A synchronous save
moves it before save() returns. An async save moves it once its
background write has ended on every rank: at the end of every step the
training loop’s shutdown vote also all-reduces each rank’s
CheckpointManager.flushing, which reads the write’s future without
blocking, and at the first step at which no rank is still writing,
every rank calls wait(), which no longer blocks on the write and
moves latest. The check adds no collective to the step, since it
rides on the vote. The next save(), a freeze stage’s flush and the
loop’s final wait() move latest too, if they come first. A crash
after that step resumes from the async save rather than from the
checkpoint before it. Under pipeline parallelism each stage saves
through its own process group, so every rank first waits at a barrier
until every stage’s save has completed; only then does rank 0 move
latest and prune.
A save that fails on any rank (a DCP write or async flush, a rank’s
capture of its own dataloader and RNG state, or rank 0’s
train_state.pt, metadata.json or move of latest) fails on every
rank, and latest never points at it. An async write that fails raises
at the first step at which no rank is still writing, through the same
wait(). The barriers that end save(),
wait() and flush_pending_save() carry each rank’s outcome: a rank
whose own part failed raises that error, and every other rank raises a
RuntimeError naming the ranks that failed, so no rank is left waiting
for one that has already raised. Pruning runs only once latest has
moved, so an error while pruning fails no rank (see
Retention cleanup).
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>.takeoverreplaces 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
/procdoes not show the namespace cannot check at all.Another SLURM job is alive until
squeuelists it in a final state, such asCOMPLETED,CANCELLED,FAILEDorTIMEOUT, or no longer lists it.squeueruns without theSQUEUE_*andSLURM_CLUSTERSsettings 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 onesqueuecannot 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
latestpoints at;the directory the last
save()writes into, so an async save keeps it while its flush runs, even when newerstep_*directories are present, as after the manual rewind below;every
dyn_ckpt_windowmilestone, so the dense early checkpoints survive a finitekeep_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_listtakes noasync_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_pathreturnsNone, training starts from step 0. No error.latestpoints at a removed or damaged checkpoint: if the link’s target is gone, the resolver goes straight to thestep_Nscan; 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.loadthat 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 completestep_Nbeside 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 needstrain_state.ptfor the step it was saved at andmetadata.jsonfor 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’sdistributed.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 byload_pathis loaded as named.A rank that cannot see the checkpoint: every load, a
load_pathwarm start or an evaluation as well as a resume, takes the directory rank 0 resolves (the path passed to it,load_path, orlatest, 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_Ndirectory:resolve_resume_pathchecks only that a save completed (DCP’s.metadata, andtrain_state.ptandmetadata.jsonwhen the shards hold optimizer state), not the contents. If DCP can’t load from the resolved path,ckpt_mgr.loadraises and training aborts.Checkpoint without
train_state.pt: whenload_pathnames a checkpoint whose shards hold optimizer state but that has notrain_state.pt, orlatestdoes and no checkpoint indiris complete,ckpt_mgr.loadraisesFileNotFoundErrorbefore it loads anything, instead of resuming its weights and optimizer moments at step 0. To start from its weights alone, use a newdirwithload_pathpointing at it andexclude_from_loading = ["optimizer"]. See Train state.load_pathset anddiralready has a checkpoint: the checkpoint indiris resumed,load_pathis not used, and rank 0 warns, naming both paths, unlessload_pathnames that checkpoint and excludes nothing.Fresh checkpoint dir,
load_pathset —load_pathis used (the else branch). Training starts from the step in that checkpoint.Multi-node NFS vs local disk — the
latestsymlink 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/:
SLURM sends
SIGTERMon preemption.ShutdownHandlerflags shutdown; the training loop finishes the current step and saves an emergency checkpoint.ckpt_mgr.wait()flushes any async save beforedestroy_distributed().SLURM requeues the job.
New job starts,
resolve_resume_pathfindslatest, training resumes from the emergency checkpoint.
See also¶
DCP model + optimizer — the checkpoint format that
ckpt_mgr.loadconsumes.Train state — what gets restored alongside the model weights.
Resharding — what auto-resume does when the GPU count changes between save and load.
Configuration § CheckpointConfig —
load_path,keep_last_n,dir.Resilience — the preemption handler that drives the emergency save.