Skip to content

[checkpoint] Don't purge directories at or past the saving step - #6373

Merged
tianyu-l merged 2 commits into
pytorch:mainfrom
zhixiangli:torch-checkpointing-purge-drain
Nov 29, 2026
Merged

tianyu-l merged 2 commits into
pytorch:mainfrom
zhixiangli:torch-checkpointing-purge-drain

Conversation

@zhixiangli

@zhixiangli zhixiangli commented Nov 25, 2026 •

Copy link
Copy Markdown
Contributor

Summary (human-written)

Fixes #6409

  • Before: Cleaning up old checkpoints also touched leftover checkpoints from future steps, which could accidentally delete a newly saved checkpoint or evict older valid ones.
  • After: Cleanup only looks at checkpoints before the current step and leaves current and future ones alone.

Why

_purge_stale_checkpoints queues deletes onto a background purge_thread and skips only saving_step itself. A run resumed from an earlier step, or one with a changed interval / keep_latest_k, can have directories from later steps, such as a tmp_step-N left by a crash mid-save. On main, those directories are:

  • Queued for deletion. When remote deletes lag behind training (GCS), the delete can still be running when training reaches that step and writes it again, so it removes what the new save wrote.
  • Counted toward keep_latest_k if they are valid, which evicts older checkpoints below saving_step.

Example (reproduced on local disk with a slowed delete, and on real GCS HNS and Rapid buckets):

old run (interval=3): step-3, crashed while saving 6 -> tmp_step-6 left behind
new run (interval=2), resumes from step-3:
  save(4): queues tmp_step-6 for deletion
  save(6): the delete lands after save 6 wrote its files
main:    save(6) returns OK, but step-6 does not exist
this PR: tmp_step-6 is not queued; step-6 is committed

What changed

  • base.py (_purge_stale_checkpoints): reads the step from both step-N and <staging_dir_prefix>step-N with _parse_step (replacing the staging regex) and skips every entry with step >= saving_step; such a directory may be rewritten by this or a later save. Entries before saving_step are handled as before. base.py is shared, so DCP's CheckpointManager gets the same change: a step-N past saving_step, complete or not, is neither purged nor counted against keep_latest_k until a later save passes it.
  • Tests (two existing tests, renamed and extended; both fail on main):
    • test_purge_preserves_checkpoints_at_or_past_saving_step (test_checkpoint.py): incomplete step-3/step-5 and valid step-4 at or past saving_step=3 are neither queued nor counted against keep_latest_k.
    • test_purge_preserves_staging_directories_at_or_past_saving_step: tmp_step-3 and tmp_step-6 are left alone at saving_step=3, tmp_step-2 is queued, and the non-canonical tmp_step-02 is ignored.

Commits: the behavior change and its staging-directory test; then reuse of _parse_step and the shared retention test.

Alternatives considered

  • Drain purge_queue before saving: only rank 0 purges, so slow remote deletes (gs://) would block rank 0 while other ranks enter collectives.
  • Deduplicate queued deletes in purge_thread: still races with a delete already running, and adds state shared between save() and the thread.

Numerics / performance

No numerics change. Retention only, with no extra storage calls.

Testing

Known issues / follow-ups

@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label Nov 25, 2026
@pytorch-bot

pytorch-bot Bot commented Nov 25, 2026 •

Copy link
Copy Markdown

Workflows were awaiting approval. CI has now been triggered for the ciflow labels on this PR.

@tianyu-l

Copy link
Copy Markdown
Contributor

@claude review

@claude

claude Bot commented Nov 27, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @tianyu-l's task in 2m 30s —— View job


Needs discussion: the purge fix is correct, but merged alone it makes TorchCheckpointingManager raise FileExistsError until #6374 lands, and it takes the opposite rollback policy from #6145 -- review

@claude claude Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Verdict: Needs discussion -- the purge change itself is correct and small, but it can't land on its own. Merged alone, it makes TorchCheckpointingManager regress: a resumed run that reaches a leftover step-N fails with FileExistsError. It also conflicts with #6145 on how to handle rollback, so maintainers need to choose the merge order and the policy.

What this PR does. _purge_stale_checkpoints used to skip only step-{saving_step} and <prefix>step-{saving_step}. Now it parses the step from both kinds of names and skips every entry with step >= saving_step. Those entries are not deleted and do not count toward keep_latest_k. Entries before saving_step are handled as before.

Example. Old run: interval=5, crashed while saving step 20. New run: interval=1, resumes from step-15, keep_latest_k=2.

folder: step-10, step-15 (valid), step-20 (no metadata), tmp_step-20
main, save@16: queues step-10, step-20, tmp_step-20 on purge_thread
               -> on GCS the step-20 delete can still be running at step 20,
                  after the new step-20 commits -> load(20) FileNotFoundError
PR,   save@16: queues step-10 only; step-20/tmp_step-20 untouched
      save@20: DCP: overwrites in place (OK)
               TorchCheckpointing @ current pin: FileExistsError (needs #6374)

Must fix

  1. Merge-order hazard (coordination). The description says this PR must not merge before #6374. #6374 is blocked on meta-pytorch/torch_checkpointing#18 plus a pin bump. As two independent PRs, nothing enforces that order. If this one lands first, the case above becomes a crash loop on main for TorchCheckpointingManager, where today a background delete usually avoids it. Smallest fix: stack this PR on #6374 (set #6374's branch as the base) or fold it into #6374, so they can only merge together.
  2. Policy conflict with #6145 (maintainer decision). #6145 ("Reject unsafe in-place checkpoint rollback") makes an explicit load_step older than the newest resumable checkpoint raise when saves are enabled. That is the only path I found that leaves a valid step-N past the resume point: auto-resume always picks the newest resumable step, and changing interval only leaves incomplete leftovers. This PR goes the other way: it keeps those valid future checkpoints, leaves them out of keep_latest_k, and lets later saves overwrite them. Maintainers should pick one policy. If #6145 lands, the valid-checkpoint half of this PR (and the step-4 case in test_purge_preserves_checkpoints_at_or_past_saving_step) becomes unreachable. The incomplete/staging half still matters.

Should consider

  • torchtitan/components/checkpointer/base.py:595 -- the docstring leaves out that a slot is still saved for this save (inline).
Details

Necessity. On main, the race needs a later directory that this run will save again more than one save later. Directories at exactly saving_step are already skipped. Examples: a smaller interval after a crash mid-save, or an explicit load_step rollback. It is narrow but real on slow remote deletes. The description says it was reproduced on GCS. Fixing it in purge is the right place: the purge decides which paths are safe to delete in the background. The alternatives the description rules out (draining the queue on rank 0, dedup in the thread) are worse for the reasons it gives.

Correctness. Within one run, saving_step only increases, so every delete queued earlier targets a step below the current save. After this change, no queued delete can target a path a later save in this run will write. maybe_wait_for_saving() runs before purge in both managers (dcp.py:429, torch_checkpointing.py:460), so the previous save's staging dir is finished before it can be counted as abandoned. Leftovers past the last training step, or off the new interval grid, stay on disk until a later saving_step passes them. That is disk only: _find_load_step ignores non-resumable directories. A valid old-run step-20 kept after a rollback can still be auto-resumed after a crash, but that already happens on main (it takes a retention slot there and survives), and #6145 is the PR addressing it.

Overlapping PRs. Searched "purge checkpoint", "base.py checkpointer", "torch_checkpointing". #6374 (dependency, above). #6145 (policy conflict, above). #6322 (draft) also edits _purge_stale_checkpoints and keys its slot reservation off saving_dirnames, which this PR deletes, so whichever lands second needs a rebase.

Tests. Both tests extend existing ones and guard the new >= boundary for each kind of name (published and staging). The tmp_step-02 case pins behavior that already exists on main (the old regex also rejected it), but it costs only one list entry.

Not verified: couldn't run the unit tests in this environment (pytest needed approval); the GCS reproduction claim.

Before merge: the human-written summary is filled in; no action needed.

A maintainer still needs to review (core checkpointer code).

staging_dir_prefix: str | None = None,
) -> None:
"""Delete abandoned entries and reserve one retained slot for this save."""
"""Queue abandoned and excess entries before ``saving_step`` for deletion."""

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should consider: the new docstring leaves out that retention still saves a slot for this save (num_to_keep = self.keep_latest_k - 1 at L627). Without that, a reader can't see why only k - 1 checkpoints before saving_step are kept.

Suggested change
"""Queue abandoned and excess entries before ``saving_step`` for deletion."""
"""Queue abandoned entries before ``saving_step`` for deletion and keep
``keep_latest_k - 1`` valid checkpoints before it, saving one slot for this save."""

…g async purge

_purge_stale_checkpoints queued every abandoned or out-of-retention step-N
and tmp_step-N except the exact saving_step, including steps after it.
After a resume that skipped an interrupted later save (or changing
keep_latest_k, load_step, or interval across runs), a later save in the
same run then writes a directory the background purge thread may still be
deleting. On GCS flat and HNS buckets, with a purge backlog longer than
one interval, step-20 was committed and then deleted by the purge queued
at step 15; load(20) raised FileNotFoundError. Valid future step-N
directories also consumed keep_latest_k slots and evicted earlier
checkpoints below saving_step.

Skip any step-N or tmp_step-N at or past saving_step instead of only the
current save's directories. They may be rewritten by this or a later save
(DCP overwrites in place; TorchCheckpointingManager destination
replacement follows in a separate PR), and once the run moves past them a
later purge removes what is left. No wait is added to the save path, so
rank 0 never stalls behind a slow delete while the other ranks continue
into collectives.
Reuse BaseCheckpointManager._parse_step for staging directory prefixes in
_purge_stale_checkpoints instead of duplicating _STEP_DIR_PATTERN, update
stale comments, cover step >= saving_step in TestSharedDiscoveryAndRetention
(staging_dir_prefix=None), and fold future staging coverage into
test_torch_checkpointing.py.
@zhixiangli
zhixiangli force-pushed the torch-checkpointing-purge-drain branch from d56dcfb to ee6320d Compare November 28, 2026 16:32
@zhixiangli zhixiangli changed the title [checkpoint] Leave directories at or past the saving step to the save that rewrites them [checkpoint] Don't purge directories at or past the saving step Nov 28, 2026
@tianyu-l

Copy link
Copy Markdown
Contributor

@claude review again

@claude

claude Bot commented Nov 29, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @tianyu-l's task in 2m 13s —— View job


Approve: both earlier must-fix items are resolved, and the two commits since then have no new findings -- review

@claude claude Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Verdict: Approve -- the purge change is correct and small, and the revised description shows that both earlier must-fix items reduce to states main already doesn't support or already handles the same way.

What this PR does. _purge_stale_checkpoints now gets the step from both step-N and <staging_dir_prefix>step-N through _parse_step, which replaces the duplicate staging regex. It skips every entry with step >= saving_step. Those entries are neither queued on the background purge thread nor counted toward keep_latest_k. Entries before saving_step are handled as before.

Example.

old run (interval=3): step-3, crash while saving 6 -> tmp_step-6
new run (interval=2), resumes from step-3:
main, save@4: queues tmp_step-6; on GCS the delete can land after save@6 -> step-6 missing
PR,   save@4: tmp_step-6 untouched; save@6 reuses it -> step-6 committed

Earlier must-fix items

  1. Merge-order hazard with #6374 -- resolved. The only case where this PR keeps a directory that a later save then can't write is an incomplete published step-N past the resume point. On atomic-rename storage (local disk, GCS HNS/Rapid), the commit is a rename, so that directory doesn't arise there. It needs a flat GCS bucket, and README.md:114 already says not to use flat buckets because they leave half-committed step-N directories that resume selects. A leftover tmp_step-N reached later is the same situation main already handles when a resumed run keeps the same interval: main skips tmp_step-{saving_step} too. So this PR adds no new requirement on the writer. The description now says this under "Known issues".
  2. Policy conflict with #6145 -- resolved. The two PRs compose. #6145 stops valid checkpoints past the resume point from appearing. This PR only declines to count or delete them, using the same >= check that the staging half needs anyway, and it adds no code specific to rollback. Whichever PR lands first, the other doesn't change behavior.
  3. Docstring (should-consider) -- resolved. The docstring is back to main's wording, and the new inline comment at base.py:739-742 explains the >= boundary.

No new findings in the two commits. _parse_step(dirname.removeprefix(prefix)) accepts the same names as the old fullmatch regex, step-N is parsed before the prefix check (so a name can't count as both kinds), and re is still used by _parse_step.

Details

Correctness. Within one run saving_step only increases, so every delete queued earlier targets a step below every later save. maybe_wait_for_saving() runs before purge in both managers (dcp.py:434, torch_checkpointing.py:461-463), so the previous save's staging directory has finished before it can be counted as abandoned. Leftovers past the last training step stay on disk. That costs disk space only: _find_load_step ignores directories it can't resume from. Valid-but-not-resumable step-N past saving_step (old-style model-only exports) no longer take a retention slot. That is an improvement.

Tests. Both tests extend existing ones, and both fail against main's base.py. On main, the test_checkpoint.py case would purge step-2 and step-5, and the staging case would queue tmp_step-6. They guard the new >= boundary for published and staging names.

Overlapping PRs. Searched "purge checkpoint", "_purge_stale_checkpoints". #6374 (writer replace-existing, open draft): independent, see item 1. #6145 (open): composes, see item 2. #6322 (draft) edits the same function; whichever lands second rebases.

Not verified: couldn't run the unit tests here (pytest needs approval), and the torch_checkpointing source at the pin 5c45dc3 wasn't available, so I didn't confirm that a stale tmp_step-N is reused. main already depends on that for same-interval resume.

A maintainer still needs to review (core checkpointer code).

@tianyu-l
tianyu-l merged commit 076f2e8 into pytorch:main Nov 29, 2026
29 checks passed
@github-project-automation github-project-automation Bot moved this from Todo to Done in TorchTitan Development Nov 29, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ciflow/fake-pg Run 1-GPU Fake PG integration tests ciflow/rl CLA Signed This label is managed by the Meta Open Source bot.

Projects

Status: Done

Development

Successfully merging this pull request may close these issues.

[checkpoint] Background purge races with future saves and miscounts keep_latest_k after resuming from an earlier step

2 participants