Repository navigation
Do not save step 0 again on a resume from step_0 - #782
Merged
Merged
Conversation
amazloumi
self-requested a review
December 5, 2026 20:59
Codecov Report✅ All modified and coverable lines are covered by tests.
... and 1 file with indirect coverage changes 🚀 New features to boost your workflow:
|
amazloumi
approved these changes
Dec 6, 2026
amazloumi
left a comment
Member
There was a problem hiding this comment.
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.
5 of 7 tasks
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Built on #772 (
fix/cpu-setup-and-unapplied-loader-position, head6495e70d): its end-to-end test startsrun_trainingon one CPU process through #772'ssetup_distributed, and it changes the sameload()that #772's last commit changed. #772 has merged, andca403cebmerges main38999091, which brings it in with #771, #736, #737 and #774.14c1bedaand972989d5apply the review fixes.Summary
#319, what remains: a run that resumes from
step_0no longer saves step 0 again#734 made
train_state.ptandmetadata.jsonsafe 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>.distcpwith"wb", and at the end removes the old.metadatabefore it renames the new one into place; torch 2.14.1'sFileSystemWriter). One path in the repo still made that save. With adyn_ckpt_windowthat starts at 0,run_training_loopsaves step 0 before its first step, and a run that resumed fromstep_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 thatlatestnamed. A kill during that write would leavelateston shards that do not match their index (reasoned from DCP's writer, as in #734, not run).CheckpointManager.resumed_step: the step of the train state the lastload()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 withoutexact_resume, a weights-only load, a load of a checkpoint withouttrain_state.pt, and a load that finds no checkpoint. Eachload()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_loopskips the step-0 save whenresumed_stepis 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. Noon_checkpoint_savehook runs for step 0 then, and nocheckpoint/save_secis logged for it._agreed_load_dir), takes rank 0's answer on whethertrain_state.ptexists (_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, andexact_resumeis the same on every rank. The gloo test that saves and resumes every pipeline stage throughbuild_checkpoint_managerandrestore_checkpointnow checksresumed_stepon every rank, in all six of its layouts.restore_checkpointalready passesexact_resume=Truefor a resume fromcheckpoint.dir, sorun_training(scripts/train.py) and the assembled-run example, which callsrestore_checkpointandrun_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 ofload()(exact_resume) andrun_training_loopname 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 notrain_state.pt, the one case in which the run still saves step 0 again, and its README,_resume_ofand the hook's class docstring say so.startrow of[checkpoint.dyn_ckpt_window]inconfig-sections.md, the checkpoint row of the periodic-work table intraining-loop.md, and an edge case inauto-resume.md.codebase-map.json: the property, the loop's skip, the new test classes, and thetest_checkpoint.pycount (374 to 381 against main).Behavior a user will notice:
step_0with adyn_ckpt_windowfrom 0 logs the INFO line above in place of the step-0 save'sSync checkpoint savedandCheckpoint committedlines, DCP no longer warnsDetected an existing checkpoint in .../step_0, overwriting, and the restart makes one save fewer.latestdoes not move until the run's next save.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.Risks:
on_checkpoint_save(0, ...)call on every run, rather than one per saved checkpoint, no longer gets it on a resume fromstep_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.step_0withouttrain_state.ptrestores no train state, so it is still saved again, as today. Auto-resume reaches one through thestep_Nscan, after a first save killed between its shards and itstrain_state.pt;latestnames one only if the file was lost after the save, sincelatestmoves only after rank 0 writestrain_state.pt.step_0that later loses itsmetadata.jsonis 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 asis_complete_checkpoint, skip step 0.Decisions (defaults chosen for this PR; each is easy to change):
save()a step whose directorylatestnames (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_flushandTestDurableTrainState::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 onstep_Nnames.Main and the open PRs: the merge of main
38999091(ca403ceb) conflicted only incodebase-map.json, on thetest_checkpoint.pycount (366 here, 374 on main after #737), resolved to 380, and 381 since14c1bedaadded a case; every other file of the merge is main's plus exactly this branch's changes. At the head972989d5,git merge-treewith 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 mergeca403cebincluded)uv run ruff format --check .passes (at every commit, the mergeca403cebincluded)uv run pyright kempnerforge/passes (0 errors, at every commit, the mergeca403cebincluded)uv run pytest tests/unit/ -v --timeout=60passes, 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, withCXXset for the compile tests, at0a638519, before the merge of main, whose tree differs fromdec126b5only 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 aretest_vlm_dataset.py(35) andtest_video_dataset.py(3), which need the Hugging Facegpt2files 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 hitsOSError: [Errno 39] Directory not emptywhen a rank removes its temporary directory; it imports neither module this PR changes, so it runs the same code at6495e70d, 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 needsRUN_HF_TESTS=1and network access. In that run every line this PR adds underkempnerforge/that coverage counts runs (12: 7 inmanager.py, 5 inloop.py), with no partial branches.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 stateload()already broadcasts, and the gloo test of six pipeline layouts checks that every rank records it.uv run pytest tests/e2e/ --e2e -v: not run, it needs GPUs. The loop change is the step-0 save on a resume fromstep_0, which the unit tests run on CPU, once throughrun_trainingin one process.Failing first, at #772's head
6495e70dwith this branch's tests:TestRunTrainingLoop::test_a_resume_from_step_0_does_not_save_it_again, with a fake manager whoseresumed_stepis 0:assert [0, 1, 2] == [1, 2], so step 0 is saved again.TestResumeFromStepZero::test_the_resumed_run_leaves_the_step_0_checkpoint_untouched, tworun_trainingruns on one CPU process: the resumed run rewritesstep_0.__0_0.distcpkeeps its inode and gets a new mtime, and.metadata,metadata.jsonandtrain_state.ptare replaced (new inodes). With that check left out, it fails on DCP's warningDetected an existing checkpoint in .../step_0, overwriting.TestResumedStep(7 cases):AttributeError: 'CheckpointManager' object has no attribute 'resumed_step'.TestPipelineCheckpointSaveAndResume(6 layouts): the sameAttributeError, at the new assertion.examples/image_understanding:test_the_hook_says_step_zero_is_not_saved_again_when_the_run_resumes_its_train_statefails with('begin', (run, 0, True)) == ('begin', (run, 0, False)).test_the_hook_says_the_run_saves_a_step_zero_without_train_state_againpasses at6495e70dtoo; 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:
load(), all 5test_a_load_that_resumes_no_step_records_nonecases fail withassert 5 is None(at14c1beda).raisescase fails withassert 5 is Noneand the other 6 pass.6495e70d.Also checked:
762be199,test_checkpoint.py,test_train_entry.py,test_pipeline_checkpoint.pyand the docs-page test (857 passed); atdec126b5,examples/image_understanding/tests/evaluation/test_periodic.pyand the docs-page test (103 passed).dec126b5,examples/image_understanding/tests(1586 passed), and at0a638519, whose tree differs only in two lines of the example's_resume_of,examples/assembled_run/tests(9 passed) andexamples/vlm/testswithout its eval integration tier (407 passed), asci-example.ymlruns them.-W: no warnings.codebase-map.jsonparses, and its counts match its classes excepttest_moe.py(119 vs 97) andtest_dataloader_iter.py(6 vs 3), as on main.ca403ceb: ruff, ruff format and pyright (0 errors) pass, Sphinx-Wis clean, the map counts hold as above, and the test files this branch touches pass with those main's side changed or that reusetest_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.pyand the docs-page test (1001 passed),examples/assembled_run/tests(9 passed) andtest_periodic.py(102 passed).14c1beda, ruff, ruff format and pyright (0 errors) pass andtest_checkpoint.pypasses (445 passed), andTestResumedSteppassed in each of 10 separate runs (7 passed each); itsnonecase 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. At972989d5, ruff, ruff format and pyright (0 errors) pass, Sphinx-Wis clean, the map counts hold as above, and the docs-page test andtest_periodic.pypass (103 passed).test_checkpoint.pycount sums the classes it lists, 381 with this branch's 7. On main it already leaves outTestPluginsRecord,TestScheduleFreeCheckpointandTestBlindRankLoadsWhatRankZeroResolvesand 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