Repository navigation
[checkpoint] Don't purge directories at or past the saving step - #6373
Conversation
|
|
|
@claude review |
There was a problem hiding this comment.
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
- 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
mainforTorchCheckpointingManager, 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. - Policy conflict with #6145 (maintainer decision). #6145 ("Reject unsafe in-place checkpoint rollback") makes an explicit
load_stepolder than the newest resumable checkpoint raise when saves are enabled. That is the only path I found that leaves a validstep-Npast the resume point: auto-resume always picks the newest resumable step, and changingintervalonly leaves incomplete leftovers. This PR goes the other way: it keeps those valid future checkpoints, leaves them out ofkeep_latest_k, and lets later saves overwrite them. Maintainers should pick one policy. If #6145 lands, the valid-checkpoint half of this PR (and thestep-4case intest_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.""" |
There was a problem hiding this comment.
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.
| """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.
d56dcfb to
ee6320d
Compare
|
@claude review again |
There was a problem hiding this comment.
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
- 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-Npast 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, andREADME.md:114already says not to use flat buckets because they leave half-committedstep-Ndirectories that resume selects. A leftovertmp_step-Nreached later is the same situationmainalready handles when a resumed run keeps the same interval:mainskipstmp_step-{saving_step}too. So this PR adds no new requirement on the writer. The description now says this under "Known issues". - 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. - Docstring (should-consider) -- resolved. The docstring is back to
main's wording, and the new inline comment atbase.py:739-742explains 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).
Summary (human-written)
Fixes #6409
Why
_purge_stale_checkpointsqueues deletes onto a backgroundpurge_threadand skips onlysaving_stepitself. A run resumed from an earlier step, or one with a changedinterval/keep_latest_k, can have directories from later steps, such as atmp_step-Nleft by a crash mid-save. Onmain, those directories are:keep_latest_kif they are valid, which evicts older checkpoints belowsaving_step.Example (reproduced on local disk with a slowed delete, and on real GCS HNS and Rapid buckets):
What changed
base.py(_purge_stale_checkpoints): reads the step from bothstep-Nand<staging_dir_prefix>step-Nwith_parse_step(replacing the staging regex) and skips every entry withstep >= saving_step; such a directory may be rewritten by this or a later save. Entries beforesaving_stepare handled as before.base.pyis shared, so DCP'sCheckpointManagergets the same change: astep-Npastsaving_step, complete or not, is neither purged nor counted againstkeep_latest_kuntil a later save passes it.main):test_purge_preserves_checkpoints_at_or_past_saving_step(test_checkpoint.py): incompletestep-3/step-5and validstep-4at or pastsaving_step=3are neither queued nor counted againstkeep_latest_k.test_purge_preserves_staging_directories_at_or_past_saving_step:tmp_step-3andtmp_step-6are left alone atsaving_step=3,tmp_step-2is queued, and the non-canonicaltmp_step-02is ignored.Commits: the behavior change and its staging-directory test; then reuse of
_parse_stepand the shared retention test.Alternatives considered
purge_queuebefore saving: only rank 0 purges, so slow remote deletes (gs://) would block rank 0 while other ranks enter collectives.purge_thread: still races with a delete already running, and adds state shared betweensave()and the thread.Numerics / performance
No numerics change. Retention only, with no extra storage calls.
Testing
test_torch_checkpointing.py+test_checkpoint.pyat each commit, against the currenttorch_checkpointingpin: all pass excepttest_hf_save_skips_index_entries_the_model_does_not_write, which fails locally on an unrelatedattn_gymimport mismatch (CI pinsattn-gym).main'sbase.py.CheckpointWriter: recover cleanly from interrupted and repeated saves meta-pytorch/torch_checkpointing#18: the example above leavestmp_step-6unqueued and commitsstep-6.pre-commit runon changed files: passed (pyrefly not installed locally).Known issues / follow-ups
tmp_step-Nis reused when the run reaches N untilCheckpointWriter: recover cleanly from interrupted and repeated saves meta-pytorch/torch_checkpointing#18 is in the pin; that only leaves extra files instep-N, and loading is unaffected.step-N. This PR keeps it, and the save at N raisesFileExistsErroruntil [checkpoint] TorchCheckpointingManager: replace existing destinations through the writer #6374. Flat buckets are not recommended for checkpoints (seeREADME.md)._purge_stale_checkpointsreserves;git merge-treeagainst it is conflict-free. Reject unsafe in-place checkpoint rollback #6145 (open) rejects in-place rollback: if it lands, valid checkpoints past the resume point no longer occur, but a leftovertmp_step-Nafter anintervalchange still does.