Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 9 additions & 4 deletions codebase-map.json
Original file line number Diff line number Diff line change
Expand Up @@ -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; 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",
Expand Down Expand Up @@ -1047,7 +1047,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": {
Expand All @@ -1068,6 +1069,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",
Expand Down Expand Up @@ -1509,6 +1511,7 @@
"release_dir() (marks the <dir>/.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)",
Expand Down Expand Up @@ -1585,7 +1588,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": {
Expand Down Expand Up @@ -2080,11 +2084,12 @@
"TestComponentSwapOnResume(1)",
"TestWeightDecayScopeOnResume(46)",
"TestRestoredExtra(2)",
"TestResumedStep(7)",
"TestUnreadableTrainStateAcrossRanks(1)",
"TestTornStageAcrossRanks(1)",
"TestOptimizerTypeChangeOnResume(6)"
],
"count": 374
"count": 381
},
"tests/unit/test_checkpoint_publish.py": {
"classes": [
Expand Down
6 changes: 6 additions & 0 deletions docs/checkpointing/auto-resume.md
Original file line number Diff line number Diff line change
Expand Up @@ -469,6 +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 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
Expand Down
2 changes: 1 addition & 1 deletion docs/configuration/config-sections.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 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) |

Expand Down
2 changes: 1 addition & 1 deletion docs/training/training-loop.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 |
| 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
Expand Down
3 changes: 2 additions & 1 deletion examples/image_understanding/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
23 changes: 14 additions & 9 deletions examples/image_understanding/evaluation/periodic.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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

Expand Down Expand Up @@ -670,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__(
Expand Down
12 changes: 11 additions & 1 deletion examples/image_understanding/tests/evaluation/test_periodic.py
Original file line number Diff line number Diff line change
Expand Up @@ -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))


Expand Down
26 changes: 25 additions & 1 deletion kempnerforge/checkpoint/manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -2418,6 +2419,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
Expand Down Expand Up @@ -2678,7 +2686,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
Expand Down Expand Up @@ -2765,6 +2774,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
Expand Down Expand Up @@ -3033,6 +3043,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, {}
Expand Down Expand Up @@ -3393,6 +3405,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.
Expand Down
41 changes: 27 additions & 14 deletions kempnerforge/training/loop.py
Original file line number Diff line number Diff line change
Expand Up @@ -1044,6 +1044,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
Expand Down Expand Up @@ -1083,21 +1090,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 = {}
Expand Down
Loading
Loading