Skip to content

Reject unsafe in-place checkpoint rollback - #6145

Closed
Z-Ghostshell wants to merge 1 commit into
pytorch:mainfrom
Z-Ghostshell:export-D132413092
Closed

Z-Ghostshell wants to merge 1 commit into
pytorch:mainfrom
Z-Ghostshell:export-D132413092

Conversation

@Z-Ghostshell

Copy link
Copy Markdown
Contributor

Summary:

Summary (human-written)

Why

With resumable step-2 and step-6 in the same output folder, an explicit load_step=2 with saves enabled can overwrite the abandoned run's checkpoints and a later automatic restart can select step 6 from that run. Issue: #6064

What changed

  • BaseCheckpointManager.load rejects an explicit step older than the newest resumable output checkpoint when saving is enabled. Existing missing-folder, missing-step and incomplete-metadata errors run first; the guard runs before state selection/native loading.
  • The error points to the existing fresh-folder initial_load_path route with initial_load_model_only=False and load_step=-1; local paths are absolute and remote URIs are preserved.
  • load_only=True, automatic latest and fresh-folder initial loading are unchanged. No checkpoint retirement/deletion, marker, fsync or upstream DCP workaround is added.
  • CLI/config/README docs explain rollback and remove the persistent load_step=5 example.
  • Six paired-backend CPU methods cover actual checkpoint directories/state restoration and rejection. The synchronous test writer reuses normal metadata/item configuration. Two existing tracing-only mock fields are initialized for the current load contract.

Validation limits

INTERNAL DRAFT for author inspection only. Tested base: 2c48abe251ac82eb431dc1fd1a43ab2028e3541d, not current-master/full-model/distributed training acceptance.
Private normal Python 3.12.16+meta / Torch 2.15.0+cu132 / TorchAO 0.18.0 / torch_checkpointing 0.1.1 cohort; all 135 package versions and eight entry hashes unchanged pre/post. The source's exact torch_remat Git 6c05e8d8d6895a60dcc02674af0774b28155b5af pin is unfulfilled (actual package 0.2.2); no stubs, module shadowing or source backports were used.
Arc owning-target Pyrefly skipped untyped torchtitan_lib, not a typing pass. Forced-file Pyrefly reports the same 151 diagnostics on guarded/guard-absent source and no added-class diagnostics. Full pre-commit ran zero hooks because the ordinary physical export is not a Git repository; no fake Git setup was used. No GPU/async-staging/multi-rank/loss-parity or upstream-ready claim.

Differential Revision: D132413092

Summary:
## Summary (human-written)
<!-- The author must write this before any upstream review or GitHub export. -->

## Why
With resumable `step-2` and `step-6` in the same output folder, an explicit `load_step=2` with saves enabled can overwrite the abandoned run's checkpoints and a later automatic restart can select step 6 from that run. Issue: pytorch#6064

## What changed
- `BaseCheckpointManager.load` rejects an explicit step older than the newest resumable output checkpoint when saving is enabled. Existing missing-folder, missing-step and incomplete-metadata errors run first; the guard runs before state selection/native loading.
- The error points to the existing fresh-folder `initial_load_path` route with `initial_load_model_only=False` and `load_step=-1`; local paths are absolute and remote URIs are preserved.
- `load_only=True`, automatic latest and fresh-folder initial loading are unchanged. No checkpoint retirement/deletion, marker, fsync or upstream DCP workaround is added.
- CLI/config/README docs explain rollback and remove the persistent `load_step=5` example.
- Six paired-backend CPU methods cover actual checkpoint directories/state restoration and rejection. The synchronous test writer reuses normal metadata/item configuration. Two existing tracing-only mock fields are initialized for the current load contract.

## Validation limits
INTERNAL DRAFT for author inspection only. Tested base: `2c48abe251ac82eb431dc1fd1a43ab2028e3541d`, not current-master/full-model/distributed training acceptance.
Private normal Python 3.12.16+meta / Torch 2.15.0+cu132 / TorchAO 0.18.0 / torch_checkpointing 0.1.1 cohort; all 135 package versions and eight entry hashes unchanged pre/post. The source's exact torch_remat Git `6c05e8d8d6895a60dcc02674af0774b28155b5af` pin is unfulfilled (actual package 0.2.2); no stubs, module shadowing or source backports were used.
Arc owning-target Pyrefly skipped untyped `torchtitan_lib`, not a typing pass. Forced-file Pyrefly reports the same 151 diagnostics on guarded/guard-absent source and no added-class diagnostics. Full pre-commit ran zero hooks because the ordinary physical export is not a Git repository; no fake Git setup was used. No GPU/async-staging/multi-rank/loss-parity or upstream-ready claim.

Differential Revision: D132413092
@pytorch-bot pytorch-bot Bot added ciflow/fake-pg Run 1-GPU Fake PG integration tests ciflow/rl labels Nov 16, 2026
@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label Nov 16, 2026
@meta-codesync

meta-codesync Bot commented Nov 16, 2026

Copy link
Copy Markdown

@Z-Ghostshell has exported this pull request. If you are a Meta employee, you can view the originating Diff in D132413092.

Comment on lines +387 to +391
if (
explicit_step
and not self.load_only
and (newest_step := self._find_load_step()) > step
):

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.

I think the concern is valid, although I'm not sure if the new UX makes the most sense.

If I could never load a non-last step with in the folder, then why would we allow user to specify explicit step in the first place?

@tianyu-l

Copy link
Copy Markdown
Contributor

@claude review my review and give your suggestions

@claude

claude Bot commented Nov 17, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @tianyu-l's task in 1m 24s —— View job


Request changes: tianyu-l's comment is correct. After this PR, an explicit load_step in a training run either does what -1 does or is rejected. I suggested banning load_step != -1 without load_only at config time instead. 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: Request changes -- @tianyu-l's comment is correct. With the runtime guard, load_step can no longer do anything in a training run, so the knob should be banned at config time instead of being kept as a check on folder contents.

What this PR does. In BaseCheckpointManager.load, an explicit load_step=K with load_only=False now raises if the folder has a newer resumable step-N. The error message, README and --resume-step help send users to a fresh folder with initial_load_path=.../step-K and initial_load_model_only=False.

Example.

folder: step-2, step-6 (both resumable)
load_step=2, load_only=False  -> main: loads 2, re-saves over step-4/6 (issue #6064)
                                 PR:   ValueError
load_step=6, load_only=False  -> loads 6, which is exactly what load_step=-1 does
load_step=2, load_only=True   -> loads 2, no saves

load() already requires step-K to exist and be resumable (base.py:355, base.py:378), so K <= newest. The guard at base.py:387-391 then rejects every K < newest. The only value left in training is K == newest, which is the same as -1.

On the maintainer's review

base.py:391 (tianyu-l) -- Correct. In a training run, an explicit step is now either redundant or rejected. A rule that depends on what happens to be in the folder also makes the same config pass or fail depending on folder state, with no extra safety. Two coherent options:

  1. Ban it (recommended). In BaseCheckpointManager.Config.__post_init__ (base.py:~710), raise ValueError when load_step != -1 and not load_only, and say in the message that rollback goes through a fresh folder plus initial_load_path/initial_load_model_only=False. Then:

    • Delete the runtime guard, explicit_step, the import os, and the remote/abspath handling (about -25 LoC in base.py).
    • Make --resume-step (loader.py:97-170) require load_only, or delete the flag. Its only remaining use would be evaluation.
    • Replace CheckpointRollbackTest (+212) with one config-validation case, and drop the two mock fields in test_checkpoint.py.

    This follows the repo rule of raising on an unsupported combination at config time (CLAUDE.md principle 8, config.md). It also handles every case in #6064, including "flag left in the job command", which the runtime guard only catches while a newer step exists.

  2. Make in-place rollback actually work. Retire step-N > K before the first save, by renaming them aside on the checkpoint owner and then a barrier. This keeps the knob meaningful, but it is destructive. A restart that still has --resume-step K in the command would then rewind again and retire the new run's progress, which is worse than main. I'd not take this path.

Must fix

  1. PR description: "Summary (human-written)" is empty, and "Validation limits" is internal draft text ("INTERNAL DRAFT for author inspection only"). The author needs to write the summary and drop the internal notes before this can be reviewed for landing.

Should consider (only if the runtime guard is kept)

  • test_torch_checkpointing.py -- test_missing_and_incomplete_explicit_steps_keep_their_errors, test_incomplete_exports_and_noncanonical_steps_do_not_block_load and test_fresh_folder_initial_load_then_restart_uses_new_run re-test behavior the PR doesn't change, which overlaps test_load_latest_ignores_incomplete_checkpoint_directories. test_rollback_rejected_... parses the error message with split(...) to pull out a path, which is brittle.

A maintainer still needs to review (this touches core checkpointing).

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.
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. meta-exported

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants