Repository navigation
[checkpoint] TorchCheckpointingManager: replace existing destinations through the writer - #6374
zhixiangli wants to merge 3 commits into
Conversation
|
The following ciflow label(s) have been added but CI has not been triggered yet because the workflows are awaiting approval:
Once a maintainer approves the workflows (scroll to the bottom of the PR page), the corresponding CI jobs will be triggered automatically. Please ping one of the reviewers if you do not have access to approve and run workflows. |
84f8627 to
0df97e5
Compare
0df97e5 to
54b4d52
Compare
|
@claude review |
|
Claude finished @tianyu-l's task in 2m 26s —— View job Needs discussion: this can't merge until meta-pytorch/torch_checkpointing#18 lands and the pin is bumped. See the review for details. |
There was a problem hiding this comment.
Verdict: Needs discussion -- The torchtitan change is right and small. It can't merge until meta-pytorch/torch_checkpointing#18 merges and this PR bumps the pin to that commit.
What this PR does. _writer_config now ties two writer flags to use_barrier: write_to_temp_dir and replace_existing. Saving configs stage in a temp dir and replace an existing destination at commit. Load-only configs do neither, which also removes the upstream warning about using a temp dir without a barrier. The upstream writer clears a leftover tmp_<dir>, deletes an occupied destination only after rename refuses it with FileExistsError, and publishes metadata.pkl last. Because of that, the flat-GCS TODO in _is_resumable_checkpoint is deleted. Each round-trip test gains one rerun or leftover scenario.
Example.
folder: step-2 (valid), step-3/model_98.pt (no metadata.pkl), tmp_step-3/model_99.pt
resume -> _find_load_step skips step-3 (base.py:585) -> resumes at 2 -> reaches 3
main: purge keeps step-3/tmp_step-3 (saving_step) -> FileExistsError, crash-loop
PR: writer clears tmp_step-3, stages, renames onto step-3 -> refused -> deletes it
(metadata first), renames again, publishes metadata.pkl -> clean step-3
Must fix
.ci/docker/requirements.txt:25(not in diff) -- the pin is still5c45dc3, andCheckpointWriterConfigat that commit has noreplace_existing. At HEAD, building any savingTorchCheckpointingManagerpasses an argument the pinned version doesn't accept. Once torch_checkpointing#18 merges, bump the pin to the merged SHA in this PR. Re-run the 50 tests against that SHA too, in case upstream review changes the semantics. That last part needs another look, which is why this isn't an Approve.
Should consider
torchtitan/components/checkpointer/README.md:124-127-- if an HF rerun is interrupted during consolidation, the export holds a mix of old and new weights and still loads without error. The README doesn't say so (inline comment).
Details
- Gate. All three problems happen on
main: a partialstep-Nor a re-saved seed raisesFileExistsError; an HF rerun fails when committingsharded/; load-only configs emit 20 warnings. Fixing this at the writer, the layer that owns commits, is the right call. Deletingstep-Nin torchtitan before saving would destroy a valid checkpoint if the save then failed, and the writer avoids that. It also matches the counterpart: DCPCheckpointManageralready overwritesstep-Nin place. - Upstream contract checked (
gh pr diffof torch_checkpointing#18,docs/storage.md,tests/test_checkpoint_writer.py):replace_existing=Truerequireswrite_to_temp_dir=Trueand a barrier, otherwiseValueError. That is why both flags followuse_barrier.- The old directory is deleted only after the write barrier, and only on
FileExistsError. A move cut short by a timeout is not replaced. - Every
use_barrier=Falsecaller (torch_checkpointing.py:313,403,430) is a load-only manager, so the new comment at :171 is accurate.
- Interrupted replace of a seed. If replacing
step-0(the only checkpoint) is interrupted aftermetadata.pklis deleted,_find_load_stepreturns -1. The next training run then starts from random init with no error. The README tells users to rerun the save, which is enough for a rare case. It would be worth stating this consequence explicitly, though. - Tests. All three extend existing tests. The description reports that both round-trip tests fail with
replace_existing=False, so they guard the new behavior. No new test entries. - Overlap. Searched open PRs for
torch_checkpointingandTorchCheckpointingManager. #6373 depends on this PR (merge order is stated). #6197, #6179 and #5167 touch the same file but not_writer_config. No conflict found.
Not verified: that HEAD fails against the current pin (inferred from the upstream diff and the description's "CI fails until then"); behavior on real flat or HNS GCS buckets.
Before merge: fill in the human-written summary. A maintainer still needs to review.
| An HF export rerun at the same path overwrites the files whose names match and replaces | ||
| `sharded/`. Files an earlier export with a different layout left there (a native export, | ||
| or a different shard count) are not removed, so export to a fresh path when the layout | ||
| changes. |
There was a problem hiding this comment.
Should consider: this paragraph covers the layout-change case but not the interrupted-rerun case, which is worse because nothing flags it. pre_finalize_callback (torch_checkpointing.py:608-618) consolidates straight into output_dir = exports/step-N, not into the staging dir. The writer only replaces sharded/ at commit. If a rerun with the same layout dies partway through consolidation, exports/step-N ends up with some new shard files, some old ones, the same index, and the old complete sharded/. _is_hf_checkpoint accepts that directory, and it loads a mix of the two exports without any error.
main has the same exposure, since it consolidates before failing on FileExistsError. This PR doesn't cause it, but it is the PR that makes reruns supported. A sentence saying that an interrupted rerun leaves mixed weights that still load, and that a fresh path avoids this, would make the doc accurate.
…lace Load-only managers have no barrier to commit a staging directory behind, but left write_to_temp_dir at its default True, so torch_checkpointing warned on every load-only manager it built (20 times in test_torch_checkpointing.py) that the combination will become an error.
… through the writer Saving managers set replace_existing on the torch_checkpointing writer, so a save to a path that already holds a checkpoint replaces it instead of crash-looping on FileExistsError: a final export a relaunch reaches again (default config), a seed checkpoint saved again, a step past the resume point, or an HF export rerun at the same step, where the writer replaces sharded/ and consolidation overwrites its files by name. Requires the torch_checkpointing commit that adds replace_existing (meta-pytorch/torch_checkpointing#18).
Say which saves replace an existing checkpoint, that a save interrupted while deleting the old one leaves no loadable checkpoint at that path until it is saved again, and what to do when an HF export rerun fails or changes the number of shard files.
a1ef9e8 to
14f7088
Compare
## 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): ```text 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 - `test_torch_checkpointing.py` + `test_checkpoint.py` at each commit, against the current `torch_checkpointing` pin: all pass except `test_hf_save_skips_index_entries_the_model_does_not_write`, which fails locally on an unrelated `attn_gym` import mismatch (CI pins `attn-gym`). - Both boundary tests fail against `main`'s `base.py`. - Real GCS HNS and Rapid (zonal) buckets, together with #6374 and meta-pytorch/torch_checkpointing#18: the example above leaves `tmp_step-6` unqueued and commits `step-6`. - `pre-commit run` on changed files: passed (pyrefly not installed locally). ## Known issues / follow-ups - On storage with atomic directory rename (local disk, GCS HNS or Rapid), this PR has no dependency. A kept leftover `tmp_step-N` is reused when the run reaches N until meta-pytorch/torch_checkpointing#18 is in the pin; that only leaves extra files in `step-N`, and loading is unaffected. - On a flat GCS bucket a commit copies object by object, so an interrupted commit can leave an incomplete `step-N`. This PR keeps it, and the save at N raises `FileExistsError` until #6374. Flat buckets are not recommended for checkpoints (see `README.md`). - #6322 (open) changes how many slots `_purge_stale_checkpoints` reserves; `git merge-tree` against it is conflict-free. #6145 (open) rejects in-place rollback: if it lands, valid checkpoints past the resume point no longer occur, but a leftover `tmp_step-N` after an `interval` change still does.
Summary (human-written)
Fixes #6410
Depends on
CheckpointWriter: recover cleanly from interrupted and repeated saves meta-pytorch/torch_checkpointing#18 (open), which addsCheckpointWriterConfig.replace_existingand clears a leftover staging directory before writing. Once it merges, this PR bumps thetorch_checkpointingpin in.ci/docker/requirements.txt(currently5c45dc3); CI fails until then, so this PR is a draft.Why
With the writer's default,
TorchCheckpointingManagerraisesFileExistsErrorwhenever a save reaches a path that already holds a checkpoint, and load-only managers trigger a warning that will become an error. All of these were reproduced on local disk:last_save_model_only=Truewrites the final save toexports/step-T, and validation at step T runs after it. If the job dies after the export, the relaunch resumes from the last interval checkpoint, retrains to T, and fails onexports/step-T, every time.create_seed_checkpointrun twice fails onstep-0.exports/step-N/sharded/.write_to_temp_dir=True. torch_checkpointing warns on each one (20 times intest_torch_checkpointing.py) thatbarrier_config=Nonerequireswrite_to_temp_dir=Falseand will become an error.Example.
What changed
Three commits:
_writer_configsetswrite_to_temp_dir=use_barrier; saving managers keep the default.test_load_only_uses_synchronous_backendasserts the warning is gone. This one also works with the current pin._writer_configsetsreplace_existing=use_barrier. The writer deletes the old destination only after every rank has written the new one, and only when the commit rename finds it occupied. An HF export rerun at the same step works the same way: the writer replacessharded/, and consolidation overwrites its output files by name. New tests:test_final_export_rerun_replaces_the_export: the default-config final export, saved again, holds the new weights.test_hf_export_rerun_replaces_the_previous_export: an HF export rerun at the same step holds the new weights, with the same file list.Alternatives considered
save(): if the save then fails, a valid checkpoint is already gone.exports/step-N/before HF consolidation: only matters when an HF rerun fails or changes the number of shard files; the README says to rerun instead.Numerics / performance
No numerics change. Checkpoint I/O only: a replacing commit costs one delete per old file.
Testing
test_torch_checkpointing.py+test_checkpoint.py -W error::UserWarningat each commit (commit 1 against the current pin, commits 2-3 againstCheckpointWriter: recover cleanly from interrupted and repeated saves meta-pytorch/torch_checkpointing#18 at65b9e93): all pass excepttest_hf_save_skips_index_entries_the_model_does_not_write, which fails locally on an unrelatedattn_gymimport mismatch (CI pinsattn-gym).FileExistsErrorwithoutreplace_existing.write_to_temp_dirwarnings on load-only managers. 18/18 scenarios passed.pre-commit runon changed files: passed (pyrefly not installed locally).Known issues / follow-ups
step-0, the next run starts from scratch (documented in the README).