Skip to content

[checkpoint] TorchCheckpointingManager: replace existing destinations through the writer - #6374

Draft
zhixiangli wants to merge 3 commits into
pytorch:mainfrom
zhixiangli:torch-checkpointing-replace-existing
Draft

zhixiangli wants to merge 3 commits into
pytorch:mainfrom
zhixiangli:torch-checkpointing-replace-existing

Conversation

@zhixiangli

@zhixiangli zhixiangli commented Nov 25, 2026 •

Copy link
Copy Markdown
Contributor

Summary (human-written)

  • Before: Saving a checkpoint where one already existed (e.g., on a rerun or relaunch) failed with an error, and load-only runs triggered a configuration warning.
  • After: Saving safely overwrites existing checkpoints once the new save is ready, and load-only runs no longer emit the warning.

Fixes #6410

Depends on

Why

With the writer's default, TorchCheckpointingManager raises FileExistsError whenever 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:

  1. Final export rerun after a relaunch (default config). last_save_model_only=True writes the final save to exports/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 on exports/step-T, every time.
  2. Seed checkpoint saved again. create_seed_checkpoint run twice fails on step-0.
  3. HF export rerun. Fails when committing exports/step-N/sharded/.
  4. Load-only warning. Load-only managers have no barrier but leave write_to_temp_dir=True. torch_checkpointing warns on each one (20 times in test_torch_checkpointing.py) that barrier_config=None requires write_to_temp_dir=False and will become an error.

Example.

relaunch reaches the final step again; exports/step-5 holds the previous export
main:    save(5, last_step=True) -> FileExistsError: ... exports/step-5 is occupied
this PR: the writer stages the new export, then replaces exports/step-5 at commit

What changed

Three commits:

  1. Load-only managers write in place. _writer_config sets write_to_temp_dir=use_barrier; saving managers keep the default. test_load_only_uses_synchronous_backend asserts the warning is gone. This one also works with the current pin.
  2. Saving managers replace existing destinations. _writer_config sets replace_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 replaces sharded/, 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.
  3. README: a section on saving over an existing checkpoint and its limits.

Alternatives considered

  • Delete the destination in torchtitan before save(): if the save then fails, a valid checkpoint is already gone.
  • Clear 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::UserWarning at each commit (commit 1 against the current pin, commits 2-3 against CheckpointWriter: recover cleanly from interrupted and repeated saves meta-pytorch/torch_checkpointing#18 at 65b9e93): 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 rerun tests fail with FileExistsError without replace_existing.
  • Real GCS HNS and Rapid (zonal) buckets (gcsfs 2026.10.1), together with [checkpoint] Don't purge directories at or past the saving step #6373 and torch_checkpointing#18: final export rerun after a 2-rank relaunch, seed rerun, a 2-rank HF export rerun at the same step, an interrupted replace that resume falls back from and the next save recovers, 2-rank async saves, and 0 write_to_temp_dir warnings on load-only managers. 18/18 scenarios passed.
  • pre-commit run on changed files: passed (pyrefly not installed locally).

Known issues / follow-ups

  • A save interrupted while deleting the old checkpoint leaves that path without a loadable checkpoint until it is saved again. If it was the only checkpoint, such as a seed step-0, the next run starts from scratch (documented in the README).
  • An HF export rerun that fails mid-consolidation can leave a mix of old and new files, and one that writes a different number of shard files leaves the old ones next to the new; the README says to rerun.

@pytorch-bot

pytorch-bot Bot commented Nov 25, 2026 •

Copy link
Copy Markdown

The following ciflow label(s) have been added but CI has not been triggered yet because the workflows are awaiting approval:

  • ciflow/rl
  • ciflow/fake-pg

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.

@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 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.

@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 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

  1. .ci/docker/requirements.txt:25 (not in diff) -- the pin is still 5c45dc3, and CheckpointWriterConfig at that commit has no replace_existing. At HEAD, building any saving TorchCheckpointingManager passes 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 partial step-N or a re-saved seed raises FileExistsError; an HF rerun fails when committing sharded/; load-only configs emit 20 warnings. Fixing this at the writer, the layer that owns commits, is the right call. Deleting step-N in torchtitan before saving would destroy a valid checkpoint if the save then failed, and the writer avoids that. It also matches the counterpart: DCP CheckpointManager already overwrites step-N in place.
  • Upstream contract checked (gh pr diff of torch_checkpointing#18, docs/storage.md, tests/test_checkpoint_writer.py):
    • replace_existing=True requires write_to_temp_dir=True and a barrier, otherwise ValueError. That is why both flags follow use_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=False caller (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 after metadata.pkl is deleted, _find_load_step returns -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_checkpointing and TorchCheckpointingManager. #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.

Comment on lines +124 to +127
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.

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: 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.
@zhixiangli
zhixiangli force-pushed the torch-checkpointing-replace-existing branch from a1ef9e8 to 14f7088 Compare November 28, 2026 16:32
@zhixiangli
zhixiangli marked this pull request as draft November 28, 2026 16:33
@pytorch-bot pytorch-bot Bot removed the ciflow/fake-pg Run 1-GPU Fake PG integration tests label Nov 28, 2026
tianyu-l pushed a commit that referenced this pull request Nov 29, 2026
## 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.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ciflow/rl CLA Signed This label is managed by the Meta Open Source bot.

Projects

Status: Todo

Development

Successfully merging this pull request may close these issues.

[checkpoint] TorchCheckpointingManager fails with FileExistsError or commits stale shards when saving to an occupied path

2 participants