Skip to content

[checkpoint] Don't reserve a keep_latest_k slot for a final model-only export - #6322

Draft
sepehrasgarian wants to merge 1 commit into
pytorch:mainfrom
sepehrasgarian:fix/keep-latest-k-model-only-export
Draft

sepehrasgarian wants to merge 1 commit into
pytorch:mainfrom
sepehrasgarian:fix/keep-latest-k-model-only-export

Conversation

@sepehrasgarian

Copy link
Copy Markdown

Summary (human-written)

Why

With last_save_model_only=True (the default), #5748 moved the final save to exports/step-N. _purge_stale_checkpoints still runs before that save, and it still keeps keep_latest_k - 1 checkpoints so it can leave one slot for "this save" in the checkpoint folder. The export never fills that slot, so a run ends with only keep_latest_k - 1 resumable checkpoints. With keep_latest_k=2, that is a single rollback point.

Example. interval=1, keep_latest_k=2, last_save_model_only=True, saves at steps 1 and 2, then save(3, last_step=True):

main:     checkpoint/ = exports/step-3, step-2
this PR:  checkpoint/ = exports/step-3, step-1, step-2

What changed

  • _purge_stale_checkpoints (base.py) now takes last_step. It reserves a slot only if this save's id, from _create_last_step_id or _create_checkpoint_id, is in the checkpoint folder. This reuses the existing path logic, so the step-0 seed checkpoint and last_save_model_only=False behave as before.
  • dcp.py and torch_checkpointing.py pass last_step through. These are the only two callers.
  • Tests:
    • A new test, test_final_model_only_export_keeps_latest_k_checkpoints, sits next to test_auto_resume_skips_final_model_only_export.
    • Two existing mocks of _purge_stale_checkpoints now accept the new keyword.

Alternatives considered

Testing

macOS, CPU, torch 2.16.0.dev20261121, commit dbc6a89:

pytest tests/unit_tests/cpu/components/checkpointer
# 125 passed, 2 failed in 28.04s
  • The 2 failures (test_hf_load_reads_a_real_safetensors_export and test_hf_load_leaves_parameters_the_export_does_not_carry) also fail on main on macOS with AttributeError: module 'os' has no attribute 'O_DIRECT'.
  • The new test fails on main with ['exports', 'step-2'] != ['exports', 'step-1', 'step-2'].
  • pre-commit run --files <changed files> passes, except pyrefly. Pyrefly reports os.sched_getaffinity in torchtitan/distributed/offloading.py, which this PR does not touch and which is a macOS-only error.

AI-assisted (per the PyTorch AI policy): an AI tool helped find this bug and draft the fix, the tests and every section of this description except the Summary.

…y export

With last_save_model_only=True, the final save goes to exports/step-N, but
the purge before it still reserved a slot in the checkpoint folder for it,
so only keep_latest_k - 1 resumable checkpoints were left after training.
@meta-cla

meta-cla Bot commented Nov 22, 2026

Copy link
Copy Markdown

Hi @sepehrasgarian!

Thank you for your pull request and welcome to our community.

Action Required

In order to merge any pull request (code, docs, etc.), we require contributors to sign our Contributor License Agreement, and we don't seem to have one on file for you.

Process

In order for us to review and merge your suggested changes, please sign at https://code.facebook.com/cla. If you are contributing on behalf of someone else (eg your employer), the individual CLA may not be sufficient and your employer may need to sign the corporate CLA.

Once the CLA is signed, our tooling will perform checks and validations. Afterwards, the pull request will be tagged with CLA signed. The tagging process may take up to 1 hour after signing. Please give it that time before contacting us about it.

If you have received this in error or have any questions, please contact us at [email protected]. Thanks!

@pytorch-bot

pytorch-bot Bot commented Nov 22, 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

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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant