From 762be199652a54d4fe1043d5a6a35444e6f0a6d3 Mon Sep 17 00:00:00 2001 From: naeemkh Date: Sat, 5 Dec 2026 12:25:16 -0500 Subject: [PATCH 1/4] Do not save step 0 again on a resume from step_0 --- codebase-map.json | 13 ++-- docs/checkpointing/auto-resume.md | 4 ++ docs/configuration/config-sections.md | 2 +- docs/training/training-loop.md | 2 +- kempnerforge/checkpoint/manager.py | 26 +++++++- kempnerforge/training/loop.py | 41 +++++++----- tests/unit/test_checkpoint.py | 56 +++++++++++++++++ tests/unit/test_pipeline_checkpoint.py | 6 +- tests/unit/test_train_entry.py | 87 ++++++++++++++++++++++++++ 9 files changed, 215 insertions(+), 22 deletions(-) diff --git a/codebase-map.json b/codebase-map.json index 74fc8d895..f8dc3448f 100644 --- a/codebase-map.json +++ b/codebase-map.json @@ -1012,7 +1012,7 @@ } }, "functions": [ - "run_training_loop(session, step, tokens_seen) -> tuple[int, int] (raises RuntimeError before anything else when the session has a loader and the checkpointer still holds a data position that load kept and apply_dataloader_state never applied)", + "run_training_loop(session, step, tokens_seen) -> tuple[int, int] (raises RuntimeError before anything else when the session has a loader and the checkpointer still holds a data position that load kept and apply_dataloader_state never applied; inside a dyn_ckpt_window from 0, saves step 0 before the first step unless the checkpointer's resumed_step is 0, which logs at INFO that step 0 is not saved again)", "select_step_fn(config) -> StepFn", "text_step(session, step) -> StepResult", "vlm_step(session, step) -> StepResult", @@ -1044,7 +1044,8 @@ "tests/unit/test_schedule_state.py", "tests/unit/test_train_entry.py::TestDrainAFinishedSave", "tests/unit/test_checkpoint_publish.py::TestAFinishedAsyncSaveIsPublished", - "tests/unit/test_data_position.py" + "tests/unit/test_data_position.py", + "tests/unit/test_train_entry.py::TestResumeFromStepZero" ] }, "kempnerforge/training/entry.py": { @@ -1064,6 +1065,7 @@ "tests/unit/test_train_entry.py::TestResumeACheckpointThatLeftTheModuleOut", "tests/unit/test_train_entry.py::TestStageChangeWarmStart", "tests/unit/test_train_entry.py::TestNanCountAcrossResume", + "tests/unit/test_train_entry.py::TestResumeFromStepZero", "tests/unit/test_schedule_state.py", "tests/e2e/test_training_e2e.py", "tests/smoke/test_smoke.py", @@ -1495,6 +1497,7 @@ "release_dir() (marks the /.owner record this rank's claim_dir wrote released, at a clean exit)", "restored_optimizer (property: whether the last load restored this rank's optimizer state; the loop starts any other optimizer on its schedule)", "restored_extra (property: the extra keys the last load restored)", + "resumed_step (property: the step of the train state the last load restored on an exact resume, None before a load and after any other; every load first drops it; run_training_loop does not save step 0 again when it is 0)", "has_pending_dataloader_state (property: whether the last load kept a data position that apply_dataloader_state has not taken, since each load first drops one an earlier load kept; run_training_loop raises while it is and the session has a loader)", "_resolve_load_path(path)", "_agreed_load_dir(path, fall_back) -> (Path | None, SavedLayout | None, rank 0's metadata read | None) (every load: rank 0 resolves the checkpoint, on an exact resume that reads shards takes the newest complete step_N beside it when that one is not complete, reads its metadata.json once for the whole load and its saved layout, and broadcasts the directory and the layout or its error)", @@ -1569,7 +1572,8 @@ "tests/unit/test_pipeline_checkpoint_layouts.py", "tests/unit/test_pipeline_checkpoint.py::TestAFailedReadFailsEveryRank", "tests/unit/test_checkpoint_resharding.py", - "tests/unit/test_checkpoint_publish.py::TestAFinishedAsyncSaveIsPublished" + "tests/unit/test_checkpoint_publish.py::TestAFinishedAsyncSaveIsPublished", + "tests/unit/test_checkpoint.py::TestResumedStep" ] }, "kempnerforge/checkpoint/layout.py": { @@ -2063,11 +2067,12 @@ "TestComponentSwapOnResume(1)", "TestWeightDecayScopeOnResume(46)", "TestRestoredExtra(2)", + "TestResumedStep(6)", "TestUnreadableTrainStateAcrossRanks(1)", "TestTornStageAcrossRanks(1)", "TestOptimizerTypeChangeOnResume(6)" ], - "count": 360 + "count": 366 }, "tests/unit/test_checkpoint_publish.py": { "classes": [ diff --git a/docs/checkpointing/auto-resume.md b/docs/checkpointing/auto-resume.md index 78d73c152..1e9cecf10 100644 --- a/docs/checkpointing/auto-resume.md +++ b/docs/checkpointing/auto-resume.md @@ -457,6 +457,10 @@ committed and the save still succeeds on every rank. paths in resume. - **Empty checkpoint directory** — `resolve_resume_path` returns `None`, training starts from step 0. No error. +- **A resume from `step_0`**: a run that resumes from the step-0 + checkpoint of a `dyn_ckpt_window` that starts at 0 does not save + step 0 again, and logs that at INFO, since that save would rewrite in + place the DCP shards of the checkpoint it just loaded. - **`latest` points at a removed or damaged checkpoint**: if the link's target is gone, the resolver goes straight to the `step_N` scan; if the target is there but is not a complete save, it warns, naming diff --git a/docs/configuration/config-sections.md b/docs/configuration/config-sections.md index fc733130a..fc1d9a87b 100644 --- a/docs/configuration/config-sections.md +++ b/docs/configuration/config-sections.md @@ -322,7 +322,7 @@ dynamics at fine granularity. | Field | Type | Default | Purpose | |-------|------|---------|---------| -| `start` | `int` | `0` | first step of the dense window; `0` captures the initial weights before any training step | +| `start` | `int` | `0` | first step of the dense window; `0` captures the initial weights before any training step, and a run that resumes from that `step_0` does not save it again | | `stop` | `int` | `512` | last step of the dense window | | `strategy` | `str` | `"power2"` | name of a registered strategy (see below) | diff --git a/docs/training/training-loop.md b/docs/training/training-loop.md index 1f9b225c7..0cc9ed028 100644 --- a/docs/training/training-loop.md +++ b/docs/training/training-loop.md @@ -231,7 +231,7 @@ After the step body, before advancing: | NCCL health | `step % tc.nccl_health_check_interval == 0` | Small all-reduce; if it failed on any rank, every rank stops without saving and the loop raises `RuntimeError` | | Eval | `step % eval_config.interval == 0` | [`run_eval`](evaluation.md), `on_eval_end` hook | | Profiler | every step | `prof.step()` advances the schedule | -| Checkpoint | `checkpoint.should_save(step)`: `dyn_ckpt_window` milestones inside the window, every `checkpoint.interval` steps outside it | `ckpt_mgr.save(step)`, logged as `checkpoint/save_sec`, then the `on_checkpoint_save` hook | +| Checkpoint | `checkpoint.should_save(step)`: `dyn_ckpt_window` milestones inside the window, every `checkpoint.interval` steps outside it | `ckpt_mgr.save(step)`, logged as `checkpoint/save_sec`, then the `on_checkpoint_save` hook. A window that starts at 0 also saves step 0 before the first step, except on a run that resumed from that `step_0` (`ckpt_mgr.resumed_step == 0`), which logs at INFO that it does not save step 0 again | | Shutdown | SIGTERM / SIGUSR1 pending on any rank | `ckpt_mgr.save(step)` (`checkpoint/save_sec`), or `ckpt_mgr.wait()` when the checkpoint tick just saved this step (`checkpoint/wait_sec` if that save is still pending); then break | The two stop rows are votes. Each row all-reduces the ranks' own diff --git a/kempnerforge/checkpoint/manager.py b/kempnerforge/checkpoint/manager.py index 9c801954e..73260c1cb 100644 --- a/kempnerforge/checkpoint/manager.py +++ b/kempnerforge/checkpoint/manager.py @@ -1671,6 +1671,7 @@ def __init__( self._pending_dataloader_missing = False self._restored_extra: dict[str, Any] = {} self._restored_optimizer = False + self._resumed_step: int | None = None self._pending_finalize: tuple[int, Path] | None = None self._inflight_dir: Path | None = None self._tracking_source: TrackingSource | None = None @@ -2341,6 +2342,13 @@ def save( ) -> None: """Save a checkpoint at the given step. + A save of a step that is already saved writes into the same ``step_N``. Its + ``train_state.pt`` and ``metadata.json`` are replaced atomically, but DCP rewrites the + shard files in place, so a save killed during that write can leave a checkpoint that + does not load, under a ``latest`` that may name it. The training loop saves each step + at most once per run, and a run whose load resumed step 0 (see ``resumed_step``) does + not save step 0 again. + An optimizer that evaluates at another point than it trains at, as schedule-free AdamW does, has the model saved at its evaluation point, the averaged weights ``x``, so every reader of the model entry alone gets them; the parameters are back at the @@ -2603,7 +2611,8 @@ def load( topology, or a checkpoint with no per-rank state, then keeps the saved data position where the loader can place it and restarts the random streams. Every - rank must pass the same value. False (a ``load_path`` warm + rank must pass the same value. Such a load that restores a train + state records its step as ``resumed_step``. False (a ``load_path`` warm start, evaluation, any other load) restores the single-copy ``rng``/``dataloader`` keys (rank 0's) on every rank with no topology check. The weights-only ``exclude_keys`` pair reads no @@ -2690,6 +2699,7 @@ def load( more such all-reduce (see ``_agreed_dcp_keys``). """ self._restored_optimizer = False + self._resumed_step = None self._pending_dataloader_state = None self._pending_dataloader_warm_start = False self._pending_dataloader_carried = False @@ -2958,6 +2968,8 @@ def restore_unsaved() -> None: ) if scheduler is not None and "scheduler" in train_state and taken_scheduled: _rate_taken_groups(self.optimizer, scheduler, taken_scheduled) + if exact_resume: + self._resumed_step = step logger.info(f"Resumed from step {step}, {tokens_seen:,} tokens seen") else: step, tokens_seen, extra = 0, 0, {} @@ -3318,6 +3330,18 @@ def restored_optimizer(self) -> bool: """ return self._restored_optimizer + @property + def resumed_step(self) -> int | None: + """The step of the train state the last ``load()`` restored on an exact resume. + + None before a load, and after a load that resumed 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 one that found no checkpoint. Every rank reads the same value, + since every rank loads the checkpoint rank 0 resolves and takes the step from the train + state rank 0 broadcasts. ``run_training_loop`` does not save step 0 again when it is 0. + """ + return self._resumed_step + @property def has_pending_dataloader_state(self) -> bool: """Whether ``load()`` kept a data position that ``apply_dataloader_state`` has not taken. diff --git a/kempnerforge/training/loop.py b/kempnerforge/training/loop.py index 081bcfd43..de2f7babd 100644 --- a/kempnerforge/training/loop.py +++ b/kempnerforge/training/loop.py @@ -1023,6 +1023,13 @@ def run_training_loop( loader built from the config, as ``build_data_pipeline`` builds it, exists on every rank or on none, pipeline stages included, so every rank raises together. + + A run that starts at step 0 inside a ``dyn_ckpt_window`` that starts at 0 + saves step 0 before its first step, unless ``session.checkpointer`` + resumed step 0 (``resumed_step``): that save would rewrite in place the + shards of the checkpoint the run loaded, so the loop logs that it skips + it, and no ``on_checkpoint_save`` hook runs for step 0. Every rank skips + it or none does, since every rank reads the same broadcast train state. """ config = session.config tc = config.train @@ -1062,21 +1069,27 @@ def run_training_loop( prof.start() if step == 0 and config.checkpoint.is_dynamic_milestone(0): - with _logged_time(tracker, "checkpoint/save_sec", 0): - ckpt_mgr.save( - step=0, - tokens_seen=0, - scheduler=scheduler, - dataloader=data.dataloader, - extra=checkpoint_extra( - config, - 0, - phases, - session.documents_seen, - consecutive_nans=session.nan_detector.state.consecutive_nans, - ), + if ckpt_mgr.resumed_step == 0: + logger.info( + "Not saving step 0 again: the run resumed from step_0, and a second save " + "would rewrite its shards in place" ) - hooks.on_checkpoint_save(0, config.checkpoint.dir) + else: + with _logged_time(tracker, "checkpoint/save_sec", 0): + ckpt_mgr.save( + step=0, + tokens_seen=0, + scheduler=scheduler, + dataloader=data.dataloader, + extra=checkpoint_extra( + config, + 0, + phases, + session.documents_seen, + consecutive_nans=session.nan_detector.state.consecutive_nans, + ), + ) + hooks.on_checkpoint_save(0, config.checkpoint.dir) completed_normally = False ckpt_extra: dict = {} diff --git a/tests/unit/test_checkpoint.py b/tests/unit/test_checkpoint.py index 8f24d0b6f..aeee18ce0 100644 --- a/tests/unit/test_checkpoint.py +++ b/tests/unit/test_checkpoint.py @@ -6108,3 +6108,59 @@ def test_a_load_that_finds_nothing_restores_no_extra(self, tmp_path): manager._restored_extra = {"documents_seen": 3} assert manager.load() == (0, 0, {}) assert manager.restored_extra == {} + + +class TestResumedStep: + """The manager records the step an exact resume restored, for the loop to read (#319).""" + + @staticmethod + def _manager(ckpt_dir: Path): + from kempnerforge.checkpoint.manager import CheckpointManager + + model = torch.nn.Linear(4, 4) + optimizer = torch.optim.AdamW(model.parameters(), lr=1e-3) + return CheckpointManager(CheckpointConfig(dir=str(ckpt_dir)), model, optimizer) + + def _run(self, run_dir: Path) -> None: + """Save step 0 before the first update, as a ``dyn_ckpt_window`` from 0 does, then + step 5 after one.""" + saver = self._manager(run_dir) + saver.save(step=0) + saver.model(torch.ones(2, 4)).sum().backward() + saver.optimizer.step() + saver.save(step=5, tokens_seen=500) + + @pytest.mark.parametrize("step", [0, 5]) + def test_an_exact_resume_records_the_step_it_restored(self, tmp_path, step): + self._run(tmp_path) + manager = self._manager(tmp_path) + assert manager.resumed_step is None + assert manager.load(path=str(tmp_path / f"step_{step}"), exact_resume=True)[0] == step + assert manager.resumed_step == step + + @pytest.mark.parametrize("second", ["warm_start", "weights_only", "no_train_state", "none"]) + def test_a_load_that_resumes_no_step_records_none(self, tmp_path, second): + """Each load starts with no step recorded, so a load after an exact resume that + resumes no step leaves none: a warm start, the weights alone, a step_0 that lost its + train_state.pt, or no checkpoint at all.""" + self._run(tmp_path) + manager = self._manager(tmp_path) + assert manager.load(exact_resume=True)[0] == 5 + assert manager.resumed_step == 5 + step_0, step_5 = tmp_path / "step_0", tmp_path / "step_5" + if second == "warm_start": + assert manager.load(path=str(step_5), warm_start=True)[0] == 5 + elif second == "weights_only": + weights_only = ["optimizer", "train_state"] + assert manager.load(path=str(step_5), exclude_keys=weights_only)[0] == 0 + elif second == "no_train_state": + (step_0 / "train_state.pt").unlink() + assert manager.load(path=str(step_0), exact_resume=True)[0] == 0 + else: + import shutil + + (tmp_path / "latest").unlink() + shutil.rmtree(step_0) + shutil.rmtree(step_5) + assert manager.load(exact_resume=True) == (0, 0, {}) + assert manager.resumed_step is None diff --git a/tests/unit/test_pipeline_checkpoint.py b/tests/unit/test_pipeline_checkpoint.py index b0c812e56..e398ffa56 100644 --- a/tests/unit/test_pipeline_checkpoint.py +++ b/tests/unit/test_pipeline_checkpoint.py @@ -119,7 +119,10 @@ def _check_save_and_resume( ckpt_dir: str, async_mode: AsyncCheckpointMode, ) -> None: - """Save every stage through ``build_checkpoint_manager``, then resume a fresh model from it.""" + """Save every stage through ``build_checkpoint_manager``, then resume a fresh model from it. + + Every rank records the step it resumed, which the loop reads to skip saving step 0 again. + """ with gloo_group(rank, world, port): mesh = init_device_mesh("cpu", shape, mesh_dim_names=names) pp_size = mesh["pp"].size() @@ -150,6 +153,7 @@ def _check_save_and_resume( config, runtime, resumed, resumed_optimizer, pipeline ) assert restore_checkpoint(config, resumed, None, resume_manager) == (STEP, TOKENS) + assert resume_manager.resumed_step == STEP _assert_same(resumed.state_dict(), saved.state_dict()) _assert_same(resumed_optimizer.state_dict()["state"], saved_optimizer.state_dict()["state"]) diff --git a/tests/unit/test_train_entry.py b/tests/unit/test_train_entry.py index cc76b4bc8..e29e25745 100644 --- a/tests/unit/test_train_entry.py +++ b/tests/unit/test_train_entry.py @@ -84,6 +84,7 @@ def __init__(self) -> None: self.restored_extra: dict = {} self.restored_optimizer = False self.has_pending_dataloader_state = False + self.resumed_step: int | None = None @property def flushing(self) -> bool: @@ -776,6 +777,28 @@ def test_resume_skips_the_initial_save(self): ckpt: FakeCheckpointManager = session.checkpointer # type: ignore[assignment] assert 0 not in ckpt.saved_steps + def test_a_resume_from_step_0_does_not_save_it_again(self, monkeypatch, caplog): + """The run loaded step 0, which a second save would rewrite in place (#319); the + window's later steps are still saved, each with its hook.""" + import logging + + config = make_config(max_steps=2) + config.checkpoint.dyn_ckpt_window = DynamicCheckpointWindow(start=0, stop=8) + ckpt = FakeCheckpointManager() + ckpt.resumed_step = 0 + hook = RecordingHook() + session = make_session(config, checkpointer=ckpt, hooks=HookRunner([hook])) + monkeypatch.setattr(logging.getLogger("kempnerforge"), "propagate", True) + with caplog.at_level(logging.INFO, logger="kempnerforge"): + run_training_loop(session, step=0) + assert ckpt.saved_steps == [1, 2] + assert hook.saves == [1, 2] + skips = [r.getMessage() for r in caplog.records if "step 0 again" in r.getMessage()] + assert skips == [ + "Not saving step 0 again: the run resumed from step_0, and a second save would " + "rewrite its shards in place" + ] + def test_resume_continues_the_token_count(self): config = make_config(max_steps=3) session = make_session(config) @@ -1997,6 +2020,70 @@ def test_a_checkpoint_without_the_count_resumes_counting_from_zero(self, monkeyp assert _run_through_nans(monkeypatch, tmp_path, nan_steps) == [2, 3, 4] +class TestResumeFromStepZero: + """A run resumed from the step-0 checkpoint of a ``dyn_ckpt_window`` leaves it as it was. + + Both runs go through ``run_training`` on one CPU process, with the real distributed + setup, model, checkpoint manager and restore. The first run saves step 0, trains one + step and saves step 1; the second resumes from step 0, as after a kill between the two + saves (#319). + """ + + @staticmethod + def _train(monkeypatch, ckpt_dir: Path) -> None: + import kempnerforge.training.entry as entry + + monkeypatch.setenv("RANK", "0") + monkeypatch.setenv("LOCAL_RANK", "0") + monkeypatch.setenv("WORLD_SIZE", "1") + monkeypatch.setattr(torch.cuda, "is_available", lambda: False) + monkeypatch.setattr(entry, "ShutdownHandler", lambda **_kw: FakeShutdownHandler()) + config = make_config(max_steps=1) + config.checkpoint.dir = str(ckpt_dir) + config.checkpoint.dyn_ckpt_window = DynamicCheckpointWindow(start=0, stop=0) + entry.run_training(config) + + def test_the_resumed_run_leaves_the_step_0_checkpoint_untouched( + self, monkeypatch, caplog, tmp_path + ): + """No file of step_0 is written or replaced, and DCP warns of no overwrite. Every + file's time is set back first, so a rewrite shows even on coarse timestamps. Step 1 + is moved out of the directory rather than removed, since NFS can refuse to remove a + directory whose files were written a moment before.""" + import logging + import os + import warnings + + ckpt = tmp_path / "ckpt" + self._train(monkeypatch, ckpt) + assert sorted(p.name for p in ckpt.glob("step_*")) == ["step_0", "step_1"] + (ckpt / "step_1").rename(tmp_path / "first_run_step_1") + (ckpt / "latest").unlink() + (ckpt / "latest").symlink_to("step_0") + step_0 = ckpt / "step_0" + stamp = 1_000_000_000 * 10**9 + for path in step_0.iterdir(): + os.utime(path, ns=(stamp, stamp)) + before = {p.name: (p.stat().st_ino, p.stat().st_mtime_ns) for p in step_0.iterdir()} + assert {"__0_0.distcp", ".metadata", "train_state.pt"} <= set(before) + + monkeypatch.setattr(logging.getLogger("kempnerforge"), "propagate", True) + with ( + caplog.at_level(logging.INFO, logger="kempnerforge"), + warnings.catch_warnings(record=True) as caught, + ): + warnings.simplefilter("always") + self._train(monkeypatch, ckpt) + + after = {p.name: (p.stat().st_ino, p.stat().st_mtime_ns) for p in step_0.iterdir()} + assert after == before + assert not [w for w in caught if "Detected an existing checkpoint" in str(w.message)] + messages = [r.getMessage() for r in caplog.records] + assert "Resumed from step 0, 0 tokens seen" in messages + assert sum(m.startswith("Not saving step 0 again") for m in messages) == 1 + assert (ckpt / "latest").resolve() == (ckpt / "step_1").resolve() + + class TestBuildPhaseHelpers: def test_checkpoint_manager_has_no_pp_scoping_without_pipeline(self, tmp_path): from kempnerforge.training.entry import build_checkpoint_manager From dec126b54675708dd59ab7b09ec05f5bbdcc9c5f Mon Sep 17 00:00:00 2001 From: naeemkh Date: Sat, 5 Dec 2026 12:25:16 -0500 Subject: [PATCH 2/4] Defer a resumed step 0 in periodic evaluation only when the run saves it again --- examples/image_understanding/README.md | 3 ++- .../image_understanding/evaluation/periodic.py | 17 +++++++++++------ .../tests/evaluation/test_periodic.py | 12 +++++++++++- 3 files changed, 24 insertions(+), 8 deletions(-) diff --git a/examples/image_understanding/README.md b/examples/image_understanding/README.md index 7c06f1b22..84a6adcb4 100644 --- a/examples/image_understanding/README.md +++ b/examples/image_understanding/README.md @@ -641,7 +641,8 @@ Each such step is deferred: it is evaluated once a later step has been saved, or the end of training, never while it may be half rewritten. If the run does save it again, it holds new weights, so its earlier `results.json` and `launched.json` are removed, with a warning, and it is evaluated again. A run that resumes from step 0 -of a dynamic checkpoint window saves step 0 again with the weights it loaded, so +of a dynamic checkpoint window does not save step 0 again, unless that step has no +`train_state.pt`: the run then saves step 0 again with the weights it loaded, so that step is deferred too, and its records still count. If the step directories cannot be looked at when training begins, which ones exist is unknown, so every step the run saves is treated as one it saves again, with a warning. diff --git a/examples/image_understanding/evaluation/periodic.py b/examples/image_understanding/evaluation/periodic.py index 7765fb733..fbac342a6 100644 --- a/examples/image_understanding/evaluation/periodic.py +++ b/examples/image_understanding/evaluation/periodic.py @@ -46,6 +46,7 @@ from evaluation.checkpoint import step_dir_complete from evaluation.evaluator import RESULTS_FILE from evaluation.tasks import load_tasks +from kempnerforge.checkpoint.layout import TRAIN_STATE_FILE from kempnerforge.config.job import JobConfig from kempnerforge.metrics.logger import get_logger from kempnerforge.resilience.elastic import resolve_resume_path @@ -247,16 +248,20 @@ def _resume_of(config: JobConfig) -> tuple[int | None, bool]: only through rank 0's writes, inside a save the other ranks wait for, so the answer holds still while rank 0 looks, even once the other ranks begin to save step 0. It is None when no checkpoint is found, when the one found is not named ``step_N``, or when - the look raised. The run saves the step again when it is step 0 and a dynamic - checkpoint milestone, as the loop then saves step 0 before its first step. Never - raises, and logs nothing: the run logged this same look, so what it logs here is - dropped. + the look raised. The run saves the step again when it is step 0, a dynamic checkpoint + milestone, and the checkpoint has no ``train_state.pt``: the loop saves step 0 before + its first step unless the run resumed step 0's train state (see + ``CheckpointManager.resumed_step``). Never raises, and logs nothing: the run logged + this same look, so what it logs here is dropped. """ try: with _unlogged(_RESUME_LOGGERS): path = resolve_resume_path(config.checkpoint.dir, config.distributed.pp) - step = None if path is None else _step_of(path.name) - return step, step == 0 and config.checkpoint.is_dynamic_milestone(0) + if path is None: + return None, False + step = _step_of(path.name) + dynamic_zero = step == 0 and config.checkpoint.is_dynamic_milestone(0) + return step, dynamic_zero and not (path / TRAIN_STATE_FILE).exists() except Exception: return None, False diff --git a/examples/image_understanding/tests/evaluation/test_periodic.py b/examples/image_understanding/tests/evaluation/test_periodic.py index e8290e493..06b35ab9b 100644 --- a/examples/image_understanding/tests/evaluation/test_periodic.py +++ b/examples/image_understanding/tests/evaluation/test_periodic.py @@ -1280,11 +1280,21 @@ def refuse(checkpoint_dir: str, num_stages: int | None = None) -> Path | None: assert core_log.loggers == set(periodic._RESUME_LOGGERS) -def test_the_hook_says_the_run_saves_step_zero_again_when_it_resumes_from_a_dynamic_milestone( +def test_the_hook_says_step_zero_is_not_saved_again_when_the_run_resumes_its_train_state( tmp_path: Path, run: Path, rank_zero: None ) -> None: + """The run resumed step 0 of a dynamic window, so the loop does not save it again.""" save_step(run, 0) (run / "latest").symlink_to("step_0") + assert first_look(tmp_path, dynamic_config(run)) == ("begin", (str(run), 0, False)) + + +def test_the_hook_says_the_run_saves_a_step_zero_without_train_state_again( + tmp_path: Path, run: Path, rank_zero: None +) -> None: + """A step 0 without ``train_state.pt`` restores no train state, so the run saves it again.""" + (save_step(run, 0) / TRAIN_STATE_FILE).unlink() + (run / "latest").symlink_to("step_0") assert first_look(tmp_path, dynamic_config(run)) == ("begin", (str(run), 0, True)) From 14c1bedaf26afe1f7cfcda9c9b143e03550c5bd2 Mon Sep 17 00:00:00 2001 From: naeemkh Date: Sat, 5 Dec 2026 14:46:40 -0500 Subject: [PATCH 3/4] Move the step directories aside and test a raising load in TestResumedStep --- codebase-map.json | 4 ++-- tests/unit/test_checkpoint.py | 17 +++++++++++------ 2 files changed, 13 insertions(+), 8 deletions(-) diff --git a/codebase-map.json b/codebase-map.json index 8dfd797df..ee41504a1 100644 --- a/codebase-map.json +++ b/codebase-map.json @@ -2084,12 +2084,12 @@ "TestComponentSwapOnResume(1)", "TestWeightDecayScopeOnResume(46)", "TestRestoredExtra(2)", - "TestResumedStep(6)", + "TestResumedStep(7)", "TestUnreadableTrainStateAcrossRanks(1)", "TestTornStageAcrossRanks(1)", "TestOptimizerTypeChangeOnResume(6)" ], - "count": 380 + "count": 381 }, "tests/unit/test_checkpoint_publish.py": { "classes": [ diff --git a/tests/unit/test_checkpoint.py b/tests/unit/test_checkpoint.py index d136a89dd..f773f5dc4 100644 --- a/tests/unit/test_checkpoint.py +++ b/tests/unit/test_checkpoint.py @@ -6441,11 +6441,15 @@ def test_an_exact_resume_records_the_step_it_restored(self, tmp_path, step): assert manager.load(path=str(tmp_path / f"step_{step}"), exact_resume=True)[0] == step assert manager.resumed_step == step - @pytest.mark.parametrize("second", ["warm_start", "weights_only", "no_train_state", "none"]) + @pytest.mark.parametrize( + "second", ["warm_start", "weights_only", "no_train_state", "none", "raises"] + ) def test_a_load_that_resumes_no_step_records_none(self, tmp_path, second): """Each load starts with no step recorded, so a load after an exact resume that resumes no step leaves none: a warm start, the weights alone, a step_0 that lost its - train_state.pt, or no checkpoint at all.""" + train_state.pt, no checkpoint at all, or a load that raises. The step directories are + moved aside rather than removed, since NFS can refuse to remove a directory whose + files were written a moment before.""" self._run(tmp_path) manager = self._manager(tmp_path) assert manager.load(exact_resume=True)[0] == 5 @@ -6459,11 +6463,12 @@ def test_a_load_that_resumes_no_step_records_none(self, tmp_path, second): elif second == "no_train_state": (step_0 / "train_state.pt").unlink() assert manager.load(path=str(step_0), exact_resume=True)[0] == 0 + elif second == "raises": + with pytest.raises(FileNotFoundError): + manager.load(path=str(tmp_path / "step_9"), exact_resume=True) else: - import shutil - (tmp_path / "latest").unlink() - shutil.rmtree(step_0) - shutil.rmtree(step_5) + step_0.rename(tmp_path / "moved_step_0") + step_5.rename(tmp_path / "moved_step_5") assert manager.load(exact_resume=True) == (0, 0, {}) assert manager.resumed_step is None From 972989d5f42dd545a74c94c16a73cc77def3d570 Mon Sep 17 00:00:00 2001 From: naeemkh Date: Sat, 5 Dec 2026 14:48:24 -0500 Subject: [PATCH 4/4] Say which runs save step 0 again in the docs, the map and the example hook --- codebase-map.json | 2 +- docs/checkpointing/auto-resume.md | 10 ++++++---- docs/configuration/config-sections.md | 2 +- docs/training/training-loop.md | 2 +- examples/image_understanding/evaluation/periodic.py | 6 +++--- 5 files changed, 12 insertions(+), 10 deletions(-) diff --git a/codebase-map.json b/codebase-map.json index ee41504a1..a1f91d655 100644 --- a/codebase-map.json +++ b/codebase-map.json @@ -1012,7 +1012,7 @@ } }, "functions": [ - "run_training_loop(session, step, tokens_seen) -> tuple[int, int] (raises RuntimeError before anything else when the session has a loader and the checkpointer still holds a data position that load kept and apply_dataloader_state never applied; inside a dyn_ckpt_window from 0, saves step 0 before the first step unless the checkpointer's resumed_step is 0, which logs at INFO that step 0 is not saved again)", + "run_training_loop(session, step, tokens_seen) -> tuple[int, int] (raises RuntimeError before anything else when the session has a loader and the checkpointer still holds a data position that load kept and apply_dataloader_state never applied; for a run that starts at step 0 inside a dyn_ckpt_window from 0, saves step 0 before its first step unless the checkpointer's resumed_step is 0, which logs at INFO that step 0 is not saved again)", "select_step_fn(config) -> StepFn", "text_step(session, step) -> StepResult", "vlm_step(session, step) -> StepResult", diff --git a/docs/checkpointing/auto-resume.md b/docs/checkpointing/auto-resume.md index 2e0efb78e..8f665e9d9 100644 --- a/docs/checkpointing/auto-resume.md +++ b/docs/checkpointing/auto-resume.md @@ -469,10 +469,12 @@ committed and the save still succeeds on every rank. paths in resume. - **Empty checkpoint directory** — `resolve_resume_path` returns `None`, training starts from step 0. No error. -- **A resume from `step_0`**: a run that resumes from the step-0 - checkpoint of a `dyn_ckpt_window` that starts at 0 does not save - step 0 again, and logs that at INFO, since that save would rewrite in - place the DCP shards of the checkpoint it just loaded. +- **A resume from `step_0`**: a run that resumes the train state of + the step-0 checkpoint of a `dyn_ckpt_window` that starts at 0 does + not save step 0 again, and logs that at INFO, since that save would + rewrite in place the DCP shards of the checkpoint it just loaded. A + `step_0` without `train_state.pt` restores no train state, so the run + still saves step 0 again. - **`latest` points at a removed or damaged checkpoint**: if the link's target is gone, the resolver goes straight to the `step_N` scan; if the target is there but is not a complete save, it warns, naming diff --git a/docs/configuration/config-sections.md b/docs/configuration/config-sections.md index 6a2ad58be..96e4c230b 100644 --- a/docs/configuration/config-sections.md +++ b/docs/configuration/config-sections.md @@ -322,7 +322,7 @@ dynamics at fine granularity. | Field | Type | Default | Purpose | |-------|------|---------|---------| -| `start` | `int` | `0` | first step of the dense window; `0` captures the initial weights before any training step, and a run that resumes from that `step_0` does not save it again | +| `start` | `int` | `0` | first step of the dense window; `0` captures the initial weights before any training step, and a run that resumes the train state of that `step_0` does not save it again | | `stop` | `int` | `512` | last step of the dense window | | `strategy` | `str` | `"power2"` | name of a registered strategy (see below) | diff --git a/docs/training/training-loop.md b/docs/training/training-loop.md index ab6cd37c9..d151dd531 100644 --- a/docs/training/training-loop.md +++ b/docs/training/training-loop.md @@ -241,7 +241,7 @@ After the step body, before advancing: | NCCL health | `step % tc.nccl_health_check_interval == 0` | Small all-reduce; if it failed on any rank, every rank stops without saving and the loop raises `RuntimeError` | | Eval | `step % eval_config.interval == 0` | [`run_eval`](evaluation.md), `on_eval_end` hook | | Profiler | every step | `prof.step()` advances the schedule | -| Checkpoint | `checkpoint.should_save(step)`: `dyn_ckpt_window` milestones inside the window, every `checkpoint.interval` steps outside it | `ckpt_mgr.save(step)`, logged as `checkpoint/save_sec`, then the `on_checkpoint_save` hook. A window that starts at 0 also saves step 0 before the first step, except on a run that resumed from that `step_0` (`ckpt_mgr.resumed_step == 0`), which logs at INFO that it does not save step 0 again | +| Checkpoint | `checkpoint.should_save(step)`: `dyn_ckpt_window` milestones inside the window, every `checkpoint.interval` steps outside it | `ckpt_mgr.save(step)`, logged as `checkpoint/save_sec`, then the `on_checkpoint_save` hook. A run that starts at step 0 inside a window that starts at 0 also saves step 0 before its first step, unless it resumed from that `step_0` (`ckpt_mgr.resumed_step == 0`): it then logs at INFO that it does not save step 0 again | | Shutdown | SIGTERM / SIGUSR1 pending on any rank | `ckpt_mgr.save(step)` (`checkpoint/save_sec`), or `ckpt_mgr.wait()` when the checkpoint tick just saved this step (`checkpoint/wait_sec` if that save is still pending); then break | The two stop rows are votes. Each row all-reduces the ranks' own diff --git a/examples/image_understanding/evaluation/periodic.py b/examples/image_understanding/evaluation/periodic.py index fbac342a6..6e72c9f0d 100644 --- a/examples/image_understanding/evaluation/periodic.py +++ b/examples/image_understanding/evaluation/periodic.py @@ -675,9 +675,9 @@ class PeriodicEvaluationHook(TrainingHook): At train begin the hook looks once, on the training thread, for the step the run resumed from, found as the run found it, and whether the run saves that step again - (step 0 of a dynamic checkpoint window); the launcher defers the steps the run may save - again, so none is evaluated while it may be half rewritten. That look never raises and - logs nothing. + (step 0 of a dynamic checkpoint window whose checkpoint has no ``train_state.pt``); + the launcher defers the steps the run may save again, so none is evaluated while it + may be half rewritten. That look never raises and logs nothing. """ def __init__(