Skip to content

Do not save step 0 again on a resume from step_0 - #782

Merged
amazloumi merged 5 commits into
mainfrom
fix/no-repeated-step-0-save-on-resume
Dec 6, 2026
Merged

amazloumi merged 5 commits into
mainfrom
fix/no-repeated-step-0-save-on-resume

Conversation

@Naeemkh

@Naeemkh Naeemkh commented Dec 5, 2026

Copy link
Copy Markdown
Member

Built on #772 (fix/cpu-setup-and-unapplied-loader-position, head 6495e70d): its end-to-end test starts run_training on one CPU process through #772's setup_distributed, and it changes the same load() that #772's last commit changed. #772 has merged, and ca403ceb merges main 38999091, which brings it in with #771, #736, #737 and #774. 14c1beda and 972989d5 apply the review fixes.

Summary

#319, what remains: a run that resumes from step_0 no longer saves step 0 again

#734 made train_state.pt and metadata.json safe in a save of a step that is already saved, and left one part of #319 open: such a save still rewrites the step's DCP shards in place (DCP opens each __<rank>_<n>.distcp with "wb", and at the end removes the old .metadata before it renames the new one into place; torch 2.14.1's FileSystemWriter). One path in the repo still made that save. With a dyn_ckpt_window that starts at 0, run_training_loop saves step 0 before its first step, and a run that resumed from step_0, as after a kill between that save and the next one, starts at step 0 and saved step 0 again, into the checkpoint it had just loaded and that latest named. A kill during that write would leave latest on shards that do not match their index (reasoned from DCP's writer, as in #734, not run).

  • New read-only property CheckpointManager.resumed_step: the step of the train state the last load() restored on an exact resume (exact_resume=True). It is None before any load, and after a load that resumes no step: a warm start or any other load without exact_resume, a weights-only load, a load of a checkpoint without train_state.pt, and a load that finds no checkpoint. Each load() resets it first, next to Start one process without a GPU, and stop a run whose loaded data position was never applied #772's reset of the kept data position.
  • run_training_loop skips the step-0 save when resumed_step is 0, and logs one INFO line: Not saving step 0 again: the run resumed from step_0, and a second save would rewrite its shards in place. No on_checkpoint_save hook runs for step 0 then, and no checkpoint/save_sec is logged for it.
  • Every rank decides the same way, so no rank waits in a save the others skip: every rank loads the directory rank 0 resolves (_agreed_load_dir), takes rank 0's answer on whether train_state.pt exists (_train_state_exists) and reads the step from the train state rank 0 broadcasts (_broadcast_train_state), all on the default group, so every pipeline stage does too, and exact_resume is the same on every rank. The gloo test that saves and resumes every pipeline stage through build_checkpoint_manager and restore_checkpoint now checks resumed_step on every rank, in all six of its layouts.
  • restore_checkpoint already passes exact_resume=True for a resume from checkpoint.dir, so run_training (scripts/train.py) and the assembled-run example, which calls restore_checkpoint and run_training_loop, get the guard with no change of their own.
  • save()'s docstring says that a save of a step that is already saved rewrites its shards in place, and that the loop saves each step at most once per run and does not save step 0 again on a run that resumed it. The docstrings of load() (exact_resume) and run_training_loop name the property and the skip.
  • examples/image_understanding: the periodic evaluation hook deferred step 0 on a resume from a dynamic milestone, since the run saved it again (_resume_of). It now defers it only when that checkpoint has no train_state.pt, the one case in which the run still saves step 0 again, and its README, _resume_of and the hook's class docstring say so.
  • Docs: the start row of [checkpoint.dyn_ckpt_window] in config-sections.md, the checkpoint row of the periodic-work table in training-loop.md, and an edge case in auto-resume.md. codebase-map.json: the property, the loop's skip, the new test classes, and the test_checkpoint.py count (374 to 381 against main).

Behavior a user will notice:

  • A run that resumes from step_0 with a dyn_ckpt_window from 0 logs the INFO line above in place of the step-0 save's Sync checkpoint saved and Checkpoint committed lines, DCP no longer warns Detected an existing checkpoint in .../step_0, overwriting, and the restart makes one save fewer. latest does not move until the run's next save.
  • On that run, on_checkpoint_save(0, ...) hooks do not run for step 0; they ran when the first run saved it. MLflow checkpoint registration loses nothing after a synchronous step-0 save, which commits before the MLflow run starts, so step 0 was never registered. An asynchronous one was registered under the first run's MLflow run; the resumed run, which opens a new MLflow run since step 0 records none, no longer registers step 0 under its own.
  • In the image-understanding example, such a resume takes up step 0 for periodic evaluation at once instead of after the next save; its records from the first run still count, as before.

Risks:

  • A hook that expects an on_checkpoint_save(0, ...) call on every run, rather than one per saved checkpoint, no longer gets it on a resume from step_0, nor does one that relied on that repeated call to redo work a kill cut short in the first run, such as an upload.
  • A step_0 without train_state.pt restores no train state, so it is still saved again, as today. Auto-resume reaches one through the step_N scan, after a first save killed between its shards and its train_state.pt; latest names one only if the file was lost after the save, since latest moves only after rank 0 writes train_state.pt.
  • A committed step_0 that later loses its metadata.json is no longer repaired on a resume from it: the repeated save rewrote that file, and the run now skips that save, so the file stays missing and readers that need a complete step, such as is_complete_checkpoint, skip step 0.

Decisions (defaults chosen for this PR; each is easy to change):

  • The repeated save is skipped in the loop. The alternatives: refuse in save() a step whose directory latest names (two tests save a step again on purpose and would change: TestSaveCheckpointRegistration::test_an_async_step_saved_again_is_committed_and_registered_once_after_its_last_flush and TestDurableTrainState::test_a_resave_killed_inside_torch_save_leaves_a_checkpoint_that_loads), or write a repeated save into a new directory and swap it in, which is large: a non-empty directory cannot be renamed over atomically, and resume, retention and the temp-file sweep all key on step_N names.
  • The pipeline check is one assertion in the existing gloo save-and-resume test rather than a new spawned test.
  • The image-understanding change was not in the plan for this issue. Without it the hook stays correct and only defers step 0 when it need not, but its docstring, its README and a test name would describe a save the loop no longer makes.

Main and the open PRs: the merge of main 38999091 (ca403ceb) conflicted only in codebase-map.json, on the test_checkpoint.py count (366 here, 374 on main after #737), resolved to 380, and 381 since 14c1beda added a case; every other file of the merge is main's plus exactly this branch's changes. At the head 972989d5, git merge-tree with main and with every open PR (#775, #776 at f0b5d71 after its merge of main, #777, #770, #709 and #648) finds no conflict.

Testing

All on a CPU node (GPUs hidden), Python 3.14.2 and torch 2.14.1.

  • uv run ruff check . passes (at every commit, the merge ca403ceb included)
  • uv run ruff format --check . passes (at every commit, the merge ca403ceb included)
  • uv run pyright kempnerforge/ passes (0 errors, at every commit, the merge ca403ceb included)
  • uv run pytest tests/unit/ -v --timeout=60 passes, apart from failures this CPU node causes, not the branch: 6593 passed, 14 skipped and 39 failed in 55 min (pytest tests/unit -q --timeout=60 --cov=kempnerforge --cov-branch, with CXX set for the compile tests, at 0a638519, before the merge of main, whose tree differs from dec126b5 only in two lines of the example's _resume_of; the merge's and the review fixes' own runs are below; the fixes change tests, docs and an example docstring only). 38 are test_vlm_dataset.py (35) and test_video_dataset.py (3), which need the Hugging Face gpt2 files this node's offline cache no longer holds. The other, test_hooks.py::TestActivationStoreParallel::test_whole_block_outputs_are_gathered_to_the_full_tensor[dp_shard2_tp2], passes its checks and then hits OSError: [Errno 39] Directory not empty when a rank removes its temporary directory; it imports neither module this PR changes, so it runs the same code at 6495e70d, and in 24 interleaved runs of it at each commit it failed 3 times here and 0 times there, the last 12 pairs all passing. The skips: 13 need CUDA, 1 needs RUN_HF_TESTS=1 and network access. In that run every line this PR adds under kempnerforge/ that coverage counts runs (12: 7 in manager.py, 5 in loop.py), with no partial branches.
  • If distributed code changed: uv run torchrun --nproc_per_node=4 -m pytest tests/distributed/ -v: not run, it needs 4 GPUs and this round ran on CPU only. The change adds no collective: every rank reads the step from the train state load() already broadcasts, and the gloo test of six pipeline layouts checks that every rank records it.
  • If training loop / parallelism / optimizers changed: uv run pytest tests/e2e/ --e2e -v: not run, it needs GPUs. The loop change is the step-0 save on a resume from step_0, which the unit tests run on CPU, once through run_training in one process.

Failing first, at #772's head 6495e70d with this branch's tests:

  • TestRunTrainingLoop::test_a_resume_from_step_0_does_not_save_it_again, with a fake manager whose resumed_step is 0: assert [0, 1, 2] == [1, 2], so step 0 is saved again.
  • TestResumeFromStepZero::test_the_resumed_run_leaves_the_step_0_checkpoint_untouched, two run_training runs on one CPU process: the resumed run rewrites step_0. __0_0.distcp keeps its inode and gets a new mtime, and .metadata, metadata.json and train_state.pt are replaced (new inodes). With that check left out, it fails on DCP's warning Detected an existing checkpoint in .../step_0, overwriting.
  • TestResumedStep (7 cases): AttributeError: 'CheckpointManager' object has no attribute 'resumed_step'.
  • TestPipelineCheckpointSaveAndResume (6 layouts): the same AttributeError, at the new assertion.
  • examples/image_understanding: test_the_hook_says_step_zero_is_not_saved_again_when_the_run_resumes_its_train_state fails with ('begin', (run, 0, True)) == ('begin', (run, 0, False)). test_the_hook_says_the_run_saves_a_step_zero_without_train_state_again passes at 6495e70d too; it guards the case in which the run still saves step 0 again.

Each new check fails when the line it covers is taken out of this branch's code:

  • Without the reset at the start of load(), all 5 test_a_load_that_resumes_no_step_records_none cases fail with assert 5 is None (at 14c1beda).
  • With the reset moved to the loads that return, so that one that raises keeps the step an earlier load recorded, the raises case fails with assert 5 is None and the other 6 pass.
  • With the step recorded on any load that restores a train state, not only on an exact resume, the warm-start case fails.
  • Without the loop's skip, the loop test and the end-to-end test fail as at 6495e70d.

Also checked:

  • Each commit passes the test files it touches: at 762be199, test_checkpoint.py, test_train_entry.py, test_pipeline_checkpoint.py and the docs-page test (857 passed); at dec126b5, examples/image_understanding/tests/evaluation/test_periodic.py and the docs-page test (103 passed).
  • The end-to-end test, run five times in a row: it passed each time, in 3 to 4 s.
  • At dec126b5, examples/image_understanding/tests (1586 passed), and at 0a638519, whose tree differs only in two lines of the example's _resume_of, examples/assembled_run/tests (9 passed) and examples/vlm/tests without its eval integration tier (407 passed), as ci-example.yml runs them.
  • Sphinx with -W: no warnings.
  • codebase-map.json parses, and its counts match its classes except test_moe.py (119 vs 97) and test_dataloader_iter.py (6 vs 3), as on main.
  • At the merge ca403ceb: ruff, ruff format and pyright (0 errors) pass, Sphinx -W is clean, the map counts hold as above, and the test files this branch touches pass with those main's side changed or that reuse test_train_entry.py's fake manager: test_checkpoint.py, test_train_entry.py, test_pipeline_checkpoint.py, test_data_position.py, test_checkpoint_publish.py, test_shutdown_agreement.py, test_schedule_state.py, test_dp_info.py and the docs-page test (1001 passed), examples/assembled_run/tests (9 passed) and test_periodic.py (102 passed).
  • Review fixes: at 14c1beda, ruff, ruff format and pyright (0 errors) pass and test_checkpoint.py passes (445 passed), and TestResumedStep passed in each of 10 separate runs (7 passed each); its none case now moves the step directories aside instead of removing them, as the end-to-end test does, since a removal right after the save failed once in 25 runs on netscratch. At 972989d5, ruff, ruff format and pyright (0 errors) pass, Sphinx -W is clean, the map counts hold as above, and the docs-page test and test_periodic.py pass (103 passed).
  • The map's test_checkpoint.py count sums the classes it lists, 381 with this branch's 7. On main it already leaves out TestPluginsRecord, TestScheduleFreeCheckpoint and TestBlindRankLoadsWhatRankZeroResolves and counts some parametrized classes by function, so the file collects 445 cases here and 438 on main; this PR leaves that as it is.

Contribution terms

Closes #319

@Naeemkh Naeemkh added the core Affecting core label Dec 5, 2026
@amazloumi
amazloumi self-requested a review December 5, 2026 20:59
@codecov

codecov Bot commented Dec 5, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.

Files with missing lines Coverage Δ
kempnerforge/checkpoint/manager.py 99.17% <100.00%> (+<0.01%) ⬆️
kempnerforge/training/loop.py 99.67% <100.00%> (+<0.01%) ⬆️

... and 1 file with indirect coverage changes

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@amazloumi amazloumi left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Approve. The loop no longer saves step 0 again on a resume from step_0, so the checkpoint it just loaded stays byte for byte as it was, while a fresh run still saves step 0 and every later save is unchanged. This held with FSDP and with two pipeline stages on four GPUs, and resumed losses matched an uninterrupted run. The new tests fail when any line they cover is removed.

@amazloumi
amazloumi merged commit 3584450 into main Dec 6, 2026
15 checks passed
@amazloumi
amazloumi deleted the fix/no-repeated-step-0-save-on-resume branch December 6, 2026 01:14
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

core Affecting core

Projects

None yet

Development

Successfully merging this pull request may close these issues.

train_state.pt and metadata.json are written in place, so an interrupted same-step re-save leaves latest on a checkpoint that cannot load

2 participants