From a7bca708fa12a71818c7be2a82958678e08fd1fd Mon Sep 17 00:00:00 2001 From: amazloumi Date: Sun, 6 Dec 2026 03:03:09 -0500 Subject: [PATCH 1/3] Keep a rank's own error when the gather of the data position checks fails apply_dataloader_state has every rank check the kept data position with its loader's check_state, and _position_refusals shares the verdicts with one all_gather_object on the manager's gloo group. When that gather itself failed, for example with a gloo timeout because another rank reached it only after the group's timeout, a rank whose check had failed or refused raised the gather's error alone. The gather now runs through run_keeping_own_error, with the rank's refusal built as a DataPositionError before it: such a rank raises its own error with the gather's failure in a note, and a rank whose check passed raises the gather's error with a note naming the check. A refusal is kept only where it raises, on a resume: after a warm start or on a carried position it only restarts the data, so there the rank raises the gather's failure. The success path and the path without a process group are unchanged. A two-rank gloo test lets the gather time out on a rank whose check failed or refused, and a test with the gather made to fail covers the warm start. --- codebase-map.json | 6 +- kempnerforge/checkpoint/manager.py | 30 ++++++- tests/unit/test_data_position.py | 132 ++++++++++++++++++++++++++++- 3 files changed, 159 insertions(+), 9 deletions(-) diff --git a/codebase-map.json b/codebase-map.json index 014d3070d..5b1dd5a27 100644 --- a/codebase-map.json +++ b/codebase-map.json @@ -1519,7 +1519,7 @@ "_check_model_fits(dcp_state, every_rank, dcp_dir, restaged, saved_keys, planner) (before any tensor is read: every rank sends rank 0 its index and its model entries' global shapes, keyed as DCP's load planner reads the state the load's _NeverSteppedStatePlanner leaves it from that index, with every EP rank's expert names; rank 0 reads each index once and refuses, for every rank alike, model tensors no rank loads, of another size, or that a rank loads and the index lacks; a rank that cannot list its entries sends why, as rank 0 does when comparing fails, and every rank raises; if the gather or the broadcast itself fails, a rank with an error, rank 0's refusal included, still raises it, with that failure in a note; checkpoint.ignore_extra_model_tensors leaves the extra ones unread with a warning, and a refusal names it only when the indexes hold every tensor the ranks load at its size)", "_model_misfit_error(gathered, known, lone_stage) -> Exception | None (rank 0's verdict for _check_model_fits)", "apply_dataloader_state(dataloader) (every rank checks the position and the ranks share their verdicts before any rank applies it; a position some rank cannot place raises DataPositionError on every rank on a resume and starts the data fresh on every rank, with a warning, on a warm start or a carried position; a carried position goes only to a StatefulDataLoader or StreamingDataLoader)", - "_position_refusals(dataloader, state) -> (refusals, world) (each rank's check_state verdict, gathered on every rank on the gloo group; a check that fails another way raises on every rank)", + "_position_refusals(dataloader, state, *, refusal_raises) -> (refusals, world) (each rank's check_state verdict, gathered on every rank on the gloo group; a check that fails another way raises on every rank; if the gather itself fails, a rank whose check failed, or refused where refusal_raises (a resume, not a warm start or a carried position), still raises that error, with that failure in a note)", "claim_dir() (rank 0 claims /.owner through claim_checkpoint_dir, then removes the temp files of saves killed mid-write (_remove_stale_temp_files); every rank agrees on the outcome)", "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)", @@ -2634,8 +2634,8 @@ "count": 7 }, "tests/unit/test_data_position.py": { - "note": "Module-level pytest functions (no Test* classes): the data position across data-parallel and batch size changes, the in-step clamp, mixture and legacy refusals, seed and dataset-length warnings, load_path warm starts through restore_checkpoint and load(dataloader=...), gloo CheckpointManager resume on another world size; a load that restores no position (weights only, a step without train_state.pt, a train state without one) after one that kept a position leaves none pending, and a loader applied after it starts at its first sample; a resume through run_training_loop and a real CheckpointManager: without apply_dataloader_state it raises before its hooks and its first step, with it the data continues, and a run without a loader starts with the position pending; gloo CheckpointManager auto-resume (exact_resume) saved on 4 ranks: on 2 ranks with ignore_rank_state_mismatch at the exact global position with fresh RNG, refused on every rank without it, a mixture restarting with a warning, and the saved layout restoring each rank's own state; check_state's verdicts", - "count": 28 + "note": "Module-level pytest functions (no Test* classes): the data position across data-parallel and batch size changes, the in-step clamp, mixture and legacy refusals, seed and dataset-length warnings, load_path warm starts through restore_checkpoint and load(dataloader=...), gloo CheckpointManager resume on another world size; a load that restores no position (weights only, a step without train_state.pt, a train state without one) after one that kept a position leaves none pending, and a loader applied after it starts at its first sample; a resume through run_training_loop and a real CheckpointManager: without apply_dataloader_state it raises before its hooks and its first step, with it the data continues, and a run without a loader starts with the position pending; gloo CheckpointManager auto-resume (exact_resume) saved on 4 ranks: on 2 ranks with ignore_rank_state_mismatch at the exact global position with fresh RNG, refused on every rank without it, a mixture restarting with a warning, and the saved layout restoring each rank's own state; check_state's verdicts; a gather of the checks that fails: on 2 gloo ranks with rank 0 late past the group timeout, rank 1's failed or refused check raised as its own error with the gather's failure in a note, and after a warm start a failed check kept but a refusal not", + "count": 30 }, "tests/unit/test_mixture_phase_change.py": { "note": "Module-level pytest functions (no Test* classes): a data phase that changes the mixture weights inside an epoch draws the rest of the epoch from the undrawn samples, with no repeat for a dataset no weighting oversamples (pipeline, loop-style reset); resumes before, at and after two changes in one epoch and in the next epoch match the uninterrupted run; resume at another batch size; weights that differ at a resume (an added anneal or phase, an edited base weight or temperature) apply from the saved position; a run without a change records only the epoch's starting weights; fixed-weight lists against a reference of the sampler's draw; undrawn-first order, caps and overflow, several changes, a dataset entering mid-epoch split the same way on every rank, also beside a one-sample dataset padded across three ranks; the epoch_weights record (pending, applied, restarted in the next epoch), its replay with and without a temperature, a state without it, and one for another dataset count; the change and a resume with dataloader workers; a change at the largest seed", diff --git a/kempnerforge/checkpoint/manager.py b/kempnerforge/checkpoint/manager.py index 8bb9bdd27..5dc3cd17d 100644 --- a/kempnerforge/checkpoint/manager.py +++ b/kempnerforge/checkpoint/manager.py @@ -3488,6 +3488,11 @@ def apply_dataloader_state(self, dataloader: Any) -> None: that holds no data position, such as a streaming checkpoint saved before streaming positions were recorded, leaves a stateful loader at its first sample, with a warning. + + If sharing the verdicts itself fails, as on a rank that waited in it past + the group's timeout, a rank whose check failed, or refused where a refusal + raises, still raises its own error, with that failure in a note (see + ``run_keeping_own_error``). """ missing, self._pending_dataloader_missing = self._pending_dataloader_missing, False if self._pending_dataloader_state is None: @@ -3524,7 +3529,9 @@ def apply_dataloader_state(self, dataloader: Any) -> None: return logger.info("Applied stashed dataloader state") return - refusals, world = self._position_refusals(dataloader, state) + refusals, world = self._position_refusals( + dataloader, state, refusal_raises=not (warm_start or carried) + ) if refusals: mine = refusals.get(self._rank) first = min(refusals) @@ -3550,7 +3557,7 @@ def apply_dataloader_state(self, dataloader: Any) -> None: logger.info("Applied stashed dataloader state") def _position_refusals( - self, dataloader: Any, state: dict[str, Any] + self, dataloader: Any, state: dict[str, Any], *, refusal_raises: bool ) -> tuple[dict[int, str], int]: """Why each rank's loader cannot place ``state``, gathered on every rank. @@ -3561,7 +3568,13 @@ def _position_refusals( too, so every rank raises together. Collective on the dedicated gloo group; ``apply_dataloader_state`` calls it whenever a position is pending for one of the loaders that check it, which the broadcast train state and the - configured loader decide alike on every rank. + configured loader decide alike on every rank. ``refusal_raises`` says whether + a refusal raises ``DataPositionError``, as on a resume, rather than restarting + the data. If the gather itself raises, as on a rank that waited in it past the + group's timeout, a rank whose check failed, or refused where ``refusal_raises``, + still raises that error, with the gather's failure in a note, and any other + rank raises the gather's failure, with a note naming the check (see + ``run_keeping_own_error``). Returns: Global rank -> why its loader cannot place the position (empty when @@ -3570,20 +3583,29 @@ def _position_refusals( Raises: Exception: On a rank whose check failed other than with ``DataPositionError``, that error; ``RuntimeError`` on every other rank. + DataPositionError: If the gather itself raises, on a rank whose check + refused where ``refusal_raises``. """ failure: Exception | None = None + refusal: DataPositionError | None = None verdict: tuple[str, str] | None = None try: dataloader.check_state(state) except DataPositionError as e: verdict = ("refused", str(e)) + if refusal_raises: + refusal = DataPositionError(str(e)) except Exception as e: failure = e verdict = ("failed", f"{type(e).__name__}: {_error_text(e)}") verdicts: dict[int, tuple[str, str] | None] = {self._rank: verdict} if dist.is_initialized(): gathered: list[Any] = [None] * dist.get_world_size(self._sync_group) - dist.all_gather_object(gathered, verdict, group=self._sync_group) + run_keeping_own_error( + lambda: dist.all_gather_object(gathered, verdict, group=self._sync_group), + failure if failure is not None else refusal, + "Checking the saved data position", + ) verdicts = dict(enumerate(gathered)) if failure is not None: raise failure diff --git a/tests/unit/test_data_position.py b/tests/unit/test_data_position.py index cd84158e2..9d5e2ab14 100644 --- a/tests/unit/test_data_position.py +++ b/tests/unit/test_data_position.py @@ -9,7 +9,9 @@ The loop tests resume through ``run_training_loop``, which refuses to start while the position a restore kept is still waiting for ``apply_dataloader_state``. The changed-topology tests auto-resume each rank's per-rank state, as the training entry -does, with and without ``checkpoint.ignore_rank_state_mismatch``. +does, with and without ``checkpoint.ignore_rank_state_mismatch``. The gather tests make +the gather of every rank's check of the position fail, as on a rank that waited in it +past the group's timeout: a rank keeps the error its own check would raise. """ from __future__ import annotations @@ -29,10 +31,22 @@ from kempnerforge.data.dataloader import DataPositionError, StatefulDataLoader from kempnerforge.data.sampler import DistributedSampler, MixtureSampler from kempnerforge.training.hooks import HookRunner, TrainingHook -from tests.gloo_ranks import gloo_group, spawn +from tests.gloo_ranks import ( + gloo_group, + mark, + run_to_outcomes, + spawn, + wait_for_outcome, + write_outcome, +) SEED = 42 _CONFIG = DataConfig(num_workers=0, pin_memory=False) +GATHER_TIMEOUT_S = 5 +CHECK_NOT_AGREED = "Checking the saved data position could not be agreed across ranks: " +CHECK_SUCCEEDED_HERE = ( + "Checking the saved data position succeeded on this rank but could not be agreed across ranks" +) class _Indices(torch.utils.data.Dataset): @@ -419,6 +433,55 @@ def test_auto_resume_refuses_a_position_that_cannot_carry_over(tmp_path): manager.apply_dataloader_state(_loader(_Indices(4_096), 2, 0, 4)) +def _failing_check(kind: str): + """A ``check_state`` that raises at once: ``FileNotFoundError`` for ``"failed"``, as for a + data file this rank cannot see, and ``DataPositionError`` for ``"refused"``, as when this + rank sees a data file at another size.""" + + def check_state(state: dict) -> None: + if kind == "failed": + raise FileNotFoundError(2, "No such file or directory", "train-00001.jsonl") + raise DataPositionError("The data changed since the save: a data file changed size") + + return check_state + + +@pytest.mark.parametrize( + ("kind", "raised"), + [("failed", FileNotFoundError), ("refused", RuntimeError)], + ids=["failed", "refused"], +) +def test_after_a_warm_start_a_failed_gather_keeps_a_failed_check_but_not_a_refusal( + tmp_path, monkeypatch, kind, raised +): + """The gather of the checks raises, as on a rank of two that waited in it past the + group's timeout. A check that failed is this rank's own error on a warm start too: it + raises it, with the gather's failure in a note. A refusal only restarts the data after a + warm start, so a rank whose check refused raises the gather's failure, with a note naming + the check, as a rank whose check passed does.""" + from kempnerforge.checkpoint import manager as manager_module + + _save_loader_state(tmp_path / "saved", _legacy_state(1, 100)) + manager = _restore(tmp_path, warm_start=True) + failure = RuntimeError("Timed out waiting 5000ms for recv operation to complete") + + def all_gather_object(object_list, obj, group=None): + raise failure + + monkeypatch.setattr(manager_module.dist, "is_initialized", lambda: True) + monkeypatch.setattr(manager_module.dist, "get_world_size", lambda group=None: 2) + monkeypatch.setattr(manager_module.dist, "all_gather_object", all_gather_object) + loader = _loader(_Indices(4_096), 2, 0, 4) + loader.check_state = _failing_check(kind) + with pytest.raises(raised) as caught: + manager.apply_dataloader_state(loader) + if kind == "failed": + assert caught.value.__notes__ == [f"{CHECK_NOT_AGREED}RuntimeError: {failure}"] + else: + assert caught.value is failure + assert failure.__notes__ == [CHECK_SUCCEEDED_HERE] + + _RELOADS = ["weights_only", "no_train_state", "no_position"] @@ -825,3 +888,68 @@ def test_the_saved_layout_restores_each_ranks_own_state(four_rank_checkpoints, l if "ignore_rank_state_mismatch" in w or "data position" in w.lower() ] assert about_the_position == [], about_the_position + + +def _check_with_rank_0_late( + rank: int, world: int, port: int, kind: str, root: str, out_dir: str +) -> None: + """One rank of a 2-rank gloo job in which rank 1's check of the kept position fails at once. + + Both ranks save step 1 with a loader and load it, which keeps the loader's position. Rank + 1's check then raises as ``_failing_check(kind)`` does, and rank 0 applies the position + only once rank 1 has written its outcome, so rank 1's wait in the gather of the checks + runs past the manager group's ``GATHER_TIMEOUT_S`` first. Writes how + ``apply_dataloader_state`` ended on this rank: a line for the error and one for each of + its notes. + """ + from kempnerforge.checkpoint.manager import CheckpointManager + from kempnerforge.config.checkpoint import CheckpointConfig + + with gloo_group(rank, world, port): + model = torch.nn.Linear(2, 2) + optimizer = torch.optim.SGD(model.parameters(), lr=0.1) + config = CheckpointConfig(dir=root) + manager = CheckpointManager(config, model, optimizer, group_timeout_sec=GATHER_TIMEOUT_S) + loader = _loader(_Indices(64), world, rank, 4) + manager.save(step=1, dataloader=loader) + manager.load() + if rank == 1: + loader.check_state = _failing_check(kind) + mark(out_dir, rank) + if rank == 0: + wait_for_outcome(out_dir, 1) + try: + manager.apply_dataloader_state(loader) + outcome = "applied" + except Exception as e: + outcome = "\n".join([f"{type(e).__name__}: {e}", *getattr(e, "__notes__", ())]) + write_outcome(out_dir, rank, outcome) + + +@pytest.mark.timeout(360) +@pytest.mark.parametrize( + ("kind", "own_error"), + [ + ("failed", "FileNotFoundError: [Errno 2] No such file or directory: 'train-00001.jsonl'"), + ("refused", "DataPositionError: The data changed since the save: a data file changed size"), + ], + ids=["failed", "refused"], +) +def test_a_check_that_failed_or_refused_raises_its_own_error_when_the_gather_times_out( + tmp_path, kind, own_error +): + """Rank 1's check of the kept position fails at once, and rank 0 checks only once rank 1's + wait in the gather of the checks has timed out. Rank 1 still raises its own error, with + the gather's failure in a note, and rank 0's error notes the check that could not be + agreed. The ranks get 240 s to reach the check, 45 s in it and 60 s to exit; the 360 s + timeout covers all three and the 5 s grace period for stopping the ranks.""" + outcomes = run_to_outcomes( + _check_with_rank_0_late, + 2, + (kind, str(tmp_path / "ckpt")), + tmp_path / "outcomes", + part="apply_dataloader_state with rank 0 late to the gather", + part_s=45, + ) + assert outcomes[1].startswith(f"{own_error}\n{CHECK_NOT_AGREED}"), outcomes[1] + assert outcomes[0].endswith(f"\n{CHECK_SUCCEEDED_HERE}"), outcomes[0] From a9b36a32625a19897af97765233a0a854b5f2745 Mon Sep 17 00:00:00 2001 From: amazloumi Date: Sun, 6 Dec 2026 07:31:01 -0500 Subject: [PATCH 2/3] Log a rank's refusal when the gather of the data position checks fails After a warm start, or on a position carried by checkpoint.ignore_rank_state_mismatch, a refusal only restarts the data, so a rank whose check refused raises the gather's failure when the gather of the checks itself fails, and its refusal showed nowhere. That rank now first logs why its check refused, as a warning that says the run stops. It still raises the gather's failure, and the logs when the gather completes are unchanged. The test with the gather made to fail now covers a resume, a warm start and a position carried onto a changed world size, for a failed check and a refusal, with the warning. The docstring of _position_refusals lists the gather's own failure under Raises. --- codebase-map.json | 4 +- kempnerforge/checkpoint/manager.py | 29 ++++++++--- tests/unit/test_data_position.py | 79 +++++++++++++++++++++++------- 3 files changed, 86 insertions(+), 26 deletions(-) diff --git a/codebase-map.json b/codebase-map.json index fdcea2453..6414a7f63 100644 --- a/codebase-map.json +++ b/codebase-map.json @@ -1541,7 +1541,7 @@ "_check_model_fits(dcp_state, every_rank, dcp_dir, restaged, saved_keys, planner) (before any tensor is read: every rank sends rank 0 its index and its model entries' global shapes, keyed as DCP's load planner reads the state the load's _NeverSteppedStatePlanner leaves it from that index, with every EP rank's expert names; rank 0 reads each index once and refuses, for every rank alike, model tensors no rank loads, of another size, or that a rank loads and the index lacks; a rank that cannot list its entries sends why, as rank 0 does when comparing fails, and every rank raises; if the gather or the broadcast itself fails, a rank with an error, rank 0's refusal included, still raises it, with that failure in a note; checkpoint.ignore_extra_model_tensors leaves the extra ones unread with a warning, and a refusal names it only when the indexes hold every tensor the ranks load at its size)", "_model_misfit_error(gathered, known, lone_stage) -> Exception | None (rank 0's verdict for _check_model_fits)", "apply_dataloader_state(dataloader) (every rank checks the position and the ranks share their verdicts before any rank applies it; a position some rank cannot place raises DataPositionError on every rank on a resume and starts the data fresh on every rank, with a warning, on a warm start or a carried position; a carried position goes only to a StatefulDataLoader or StreamingDataLoader)", - "_position_refusals(dataloader, state, *, refusal_raises) -> (refusals, world) (each rank's check_state verdict, gathered on every rank on the gloo group; a check that fails another way raises on every rank; if the gather itself fails, a rank whose check failed, or refused where refusal_raises (a resume, not a warm start or a carried position), still raises that error, with that failure in a note)", + "_position_refusals(dataloader, state, *, refusal_raises) -> (refusals, world) (each rank's check_state verdict, gathered on every rank on the gloo group; a check that fails another way raises on every rank; if the gather itself fails, a rank whose check failed, or refused where refusal_raises (a resume, not a warm start or a carried position), still raises that error, with that failure in a note; after a warm start or on a carried position, a rank whose check refused logs why as a warning, then raises that failure)", "claim_dir() (rank 0 claims /.owner through claim_checkpoint_dir, then removes the temp files of saves killed mid-write (_remove_stale_temp_files); every rank agrees on the outcome)", "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)", @@ -2666,7 +2666,7 @@ "count": 7 }, "tests/unit/test_data_position.py": { - "note": "Module-level pytest functions (no Test* classes): the data position across data-parallel and batch size changes, the in-step clamp, mixture and legacy refusals, seed and dataset-length warnings, load_path warm starts through restore_checkpoint and load(dataloader=...), gloo CheckpointManager resume on another world size; a load that restores no position (weights only, a step without train_state.pt, a train state without one) after one that kept a position leaves none pending, and a loader applied after it starts at its first sample; a resume through run_training_loop and a real CheckpointManager: without apply_dataloader_state it raises before its hooks and its first step, with it the data continues, and a run without a loader starts with the position pending; gloo CheckpointManager auto-resume (exact_resume) saved on 4 ranks: on 2 ranks with ignore_rank_state_mismatch at the exact global position with fresh RNG, refused on every rank without it, a mixture restarting with a warning, and the saved layout restoring each rank's own state; check_state's verdicts; a gather of the checks that fails: on 2 gloo ranks with rank 0 late past the group timeout, rank 1's failed or refused check raised as its own error with the gather's failure in a note, and after a warm start a failed check kept but a refusal not", + "note": "Module-level pytest functions (no Test* classes): the data position across data-parallel and batch size changes, the in-step clamp, mixture and legacy refusals, seed and dataset-length warnings, load_path warm starts through restore_checkpoint and load(dataloader=...), gloo CheckpointManager resume on another world size; a load that restores no position (weights only, a step without train_state.pt, a train state without one) after one that kept a position leaves none pending, and a loader applied after it starts at its first sample; a resume through run_training_loop and a real CheckpointManager: without apply_dataloader_state it raises before its hooks and its first step, with it the data continues, and a run without a loader starts with the position pending; gloo CheckpointManager auto-resume (exact_resume) saved on 4 ranks: on 2 ranks with ignore_rank_state_mismatch at the exact global position with fresh RNG, refused on every rank without it, a mixture restarting with a warning, and the saved layout restoring each rank's own state; check_state's verdicts; a gather of the checks that fails: on 2 gloo ranks with rank 0 late past the group timeout, rank 1's failed or refused check raised as its own error with the gather's failure in a note, and in one process after a resume, a warm start and a carried position (ignore_rank_state_mismatch on a changed world size): a failed check kept after each, a refusal kept on the resume, and after the other two a refusal logged as a warning, then the gather's failure raised", "count": 30 }, "tests/unit/test_mixture_phase_change.py": { diff --git a/kempnerforge/checkpoint/manager.py b/kempnerforge/checkpoint/manager.py index 4d71e28a2..b3c7f7d0f 100644 --- a/kempnerforge/checkpoint/manager.py +++ b/kempnerforge/checkpoint/manager.py @@ -3495,7 +3495,9 @@ def apply_dataloader_state(self, dataloader: Any) -> None: If sharing the verdicts itself fails, as on a rank that waited in it past the group's timeout, a rank whose check failed, or refused where a refusal raises, still raises its own error, with that failure in a note (see - ``run_keeping_own_error``). + ``run_keeping_own_error``). After a ``warm_start`` load, or on a carried + position, a rank whose check refused logs why as a warning, then raises + that failure, as a rank whose check passed does. """ missing, self._pending_dataloader_missing = self._pending_dataloader_missing, False if self._pending_dataloader_state is None: @@ -3577,7 +3579,8 @@ def _position_refusals( group's timeout, a rank whose check failed, or refused where ``refusal_raises``, still raises that error, with the gather's failure in a note, and any other rank raises the gather's failure, with a note naming the check (see - ``run_keeping_own_error``). + ``run_keeping_own_error``). A rank whose check refused where ``refusal_raises`` + is false logs why as a warning first. Returns: Global rank -> why its loader cannot place the position (empty when @@ -3588,6 +3591,9 @@ def _position_refusals( ``DataPositionError``, that error; ``RuntimeError`` on every other rank. DataPositionError: If the gather itself raises, on a rank whose check refused where ``refusal_raises``. + BaseException: If the gather itself raises, on a rank whose check passed, or + refused where ``refusal_raises`` is false, what the gather raised, with a + note naming the check. """ failure: Exception | None = None refusal: DataPositionError | None = None @@ -3604,11 +3610,20 @@ def _position_refusals( verdicts: dict[int, tuple[str, str] | None] = {self._rank: verdict} if dist.is_initialized(): gathered: list[Any] = [None] * dist.get_world_size(self._sync_group) - run_keeping_own_error( - lambda: dist.all_gather_object(gathered, verdict, group=self._sync_group), - failure if failure is not None else refusal, - "Checking the saved data position", - ) + try: + run_keeping_own_error( + lambda: dist.all_gather_object(gathered, verdict, group=self._sync_group), + failure if failure is not None else refusal, + "Checking the saved data position", + ) + except BaseException: + if not refusal_raises and verdict is not None and verdict[0] == "refused": + logger.warning( + f"The saved data position does not carry over to this run on rank " + f"{self._rank}, and sharing the ranks' checks of it failed, so the run " + f"stops: {verdict[1]}" + ) + raise verdicts = dict(enumerate(gathered)) if failure is not None: raise failure diff --git a/tests/unit/test_data_position.py b/tests/unit/test_data_position.py index 9d5e2ab14..a32cc144d 100644 --- a/tests/unit/test_data_position.py +++ b/tests/unit/test_data_position.py @@ -11,7 +11,8 @@ changed-topology tests auto-resume each rank's per-rank state, as the training entry does, with and without ``checkpoint.ignore_rank_state_mismatch``. The gather tests make the gather of every rank's check of the position fail, as on a rank that waited in it -past the group's timeout: a rank keeps the error its own check would raise. +past the group's timeout: a rank keeps the error its own check would raise, and logs why +its check refused where a refusal would only restart the data. """ from __future__ import annotations @@ -446,23 +447,53 @@ def check_state(state: dict) -> None: return check_state -@pytest.mark.parametrize( - ("kind", "raised"), - [("failed", FileNotFoundError), ("refused", RuntimeError)], - ids=["failed", "refused"], -) -def test_after_a_warm_start_a_failed_gather_keeps_a_failed_check_but_not_a_refusal( - tmp_path, monkeypatch, kind, raised +def _restore_on_a_changed_topology(tmp_path: Path): + """Auto-resume ``tmp_path / "saved"``, saved on one rank, as rank 0 of two. + + ``checkpoint.ignore_rank_state_mismatch`` lets the exact resume onto the changed + topology and carries the saved data position over to it. + """ + from kempnerforge.checkpoint.manager import CheckpointManager + from kempnerforge.config.checkpoint import CheckpointConfig + + config = CheckpointConfig(dir=str(tmp_path / "saved"), ignore_rank_state_mismatch=True) + model = torch.nn.Linear(2, 2) + optimizer = torch.optim.SGD(model.parameters(), lr=0.1) + manager = CheckpointManager(config, model, optimizer) + manager._world_size = 2 + assert manager.load(exact_resume=True)[0] == 3 + assert manager._pending_dataloader_carried + return manager + + +_RESTORES = { + "resume": lambda tmp_path: _restore(tmp_path, warm_start=False), + "warm_start": lambda tmp_path: _restore(tmp_path, warm_start=True), + "carried": _restore_on_a_changed_topology, +} + + +@pytest.mark.parametrize("kind", ["failed", "refused"]) +@pytest.mark.parametrize("start", ["resume", "warm_start", "carried"]) +def test_a_failed_gather_keeps_a_ranks_own_error_and_logs_a_refusal_that_does_not_raise( + tmp_path, caplog, monkeypatch, start, kind ): """The gather of the checks raises, as on a rank of two that waited in it past the - group's timeout. A check that failed is this rank's own error on a warm start too: it - raises it, with the gather's failure in a note. A refusal only restarts the data after a - warm start, so a rank whose check refused raises the gather's failure, with a note naming - the check, as a rank whose check passed does.""" + group's timeout. A check that failed is this rank's own error after any restore, and so + is a refusal on a resume: the rank raises it, with the gather's failure in a note, and + logs nothing. After a warm start, or on a position that + ``checkpoint.ignore_rank_state_mismatch`` carried onto a changed topology, a refusal only + restarts the data when the gather completes, so a rank whose check refused logs why as a + warning that says the run stops, then raises the gather's failure, with a note naming the + check, as a rank whose check passed does. + + The ``kempnerforge`` logger stops propagation once configured, so the test lets records + reach ``caplog`` after the restore. + """ from kempnerforge.checkpoint import manager as manager_module _save_loader_state(tmp_path / "saved", _legacy_state(1, 100)) - manager = _restore(tmp_path, warm_start=True) + manager = _RESTORES[start](tmp_path) failure = RuntimeError("Timed out waiting 5000ms for recv operation to complete") def all_gather_object(object_list, obj, group=None): @@ -471,15 +502,29 @@ def all_gather_object(object_list, obj, group=None): monkeypatch.setattr(manager_module.dist, "is_initialized", lambda: True) monkeypatch.setattr(manager_module.dist, "get_world_size", lambda group=None: 2) monkeypatch.setattr(manager_module.dist, "all_gather_object", all_gather_object) + monkeypatch.setattr(logging.getLogger("kempnerforge"), "propagate", True) loader = _loader(_Indices(4_096), 2, 0, 4) loader.check_state = _failing_check(kind) - with pytest.raises(raised) as caught: + restarts = kind == "refused" and start != "resume" + own = FileNotFoundError if kind == "failed" else DataPositionError + caplog.clear() + with ( + caplog.at_level(logging.WARNING, logger="kempnerforge.checkpoint.manager"), + pytest.raises(RuntimeError if restarts else own) as caught, + ): manager.apply_dataloader_state(loader) - if kind == "failed": - assert caught.value.__notes__ == [f"{CHECK_NOT_AGREED}RuntimeError: {failure}"] - else: + logged = [record.getMessage() for record in caplog.records] + if restarts: assert caught.value is failure assert failure.__notes__ == [CHECK_SUCCEEDED_HERE] + assert logged == [ + "The saved data position does not carry over to this run on rank 0, and sharing " + "the ranks' checks of it failed, so the run stops: The data changed since the " + "save: a data file changed size" + ] + else: + assert caught.value.__notes__ == [f"{CHECK_NOT_AGREED}RuntimeError: {failure}"] + assert logged == [] _RELOADS = ["weights_only", "no_train_state", "no_position"] From 84154b7cd2c8d6d60c4b806d087eeb77c9c98704 Mon Sep 17 00:00:00 2001 From: amazloumi Date: Sun, 6 Dec 2026 07:55:32 -0500 Subject: [PATCH 3/3] Let a failed gather's refusal warning through on any rank The warning that a rank whose check refused logs when the gather of the checks fails, after a warm start or on a carried position, went through the training log's handler, which drops a record on any rank but 0 unless it is marked for every rank. Only that rank knows why its check refused, so the warning is now marked every_rank, and the test checks that it passes the rank-0 filter on rank 1. --- codebase-map.json | 4 ++-- kempnerforge/checkpoint/manager.py | 9 +++++---- tests/unit/test_data_position.py | 6 +++++- 3 files changed, 12 insertions(+), 7 deletions(-) diff --git a/codebase-map.json b/codebase-map.json index 6414a7f63..3706b7c53 100644 --- a/codebase-map.json +++ b/codebase-map.json @@ -1541,7 +1541,7 @@ "_check_model_fits(dcp_state, every_rank, dcp_dir, restaged, saved_keys, planner) (before any tensor is read: every rank sends rank 0 its index and its model entries' global shapes, keyed as DCP's load planner reads the state the load's _NeverSteppedStatePlanner leaves it from that index, with every EP rank's expert names; rank 0 reads each index once and refuses, for every rank alike, model tensors no rank loads, of another size, or that a rank loads and the index lacks; a rank that cannot list its entries sends why, as rank 0 does when comparing fails, and every rank raises; if the gather or the broadcast itself fails, a rank with an error, rank 0's refusal included, still raises it, with that failure in a note; checkpoint.ignore_extra_model_tensors leaves the extra ones unread with a warning, and a refusal names it only when the indexes hold every tensor the ranks load at its size)", "_model_misfit_error(gathered, known, lone_stage) -> Exception | None (rank 0's verdict for _check_model_fits)", "apply_dataloader_state(dataloader) (every rank checks the position and the ranks share their verdicts before any rank applies it; a position some rank cannot place raises DataPositionError on every rank on a resume and starts the data fresh on every rank, with a warning, on a warm start or a carried position; a carried position goes only to a StatefulDataLoader or StreamingDataLoader)", - "_position_refusals(dataloader, state, *, refusal_raises) -> (refusals, world) (each rank's check_state verdict, gathered on every rank on the gloo group; a check that fails another way raises on every rank; if the gather itself fails, a rank whose check failed, or refused where refusal_raises (a resume, not a warm start or a carried position), still raises that error, with that failure in a note; after a warm start or on a carried position, a rank whose check refused logs why as a warning, then raises that failure)", + "_position_refusals(dataloader, state, *, refusal_raises) -> (refusals, world) (each rank's check_state verdict, gathered on every rank on the gloo group; a check that fails another way raises on every rank; if the gather itself fails, a rank whose check failed, or refused where refusal_raises (a resume, not a warm start or a carried position), still raises that error, with that failure in a note; after a warm start or on a carried position, a rank whose check refused logs why as a warning in its own log (every_rank), then raises that failure)", "claim_dir() (rank 0 claims /.owner through claim_checkpoint_dir, then removes the temp files of saves killed mid-write (_remove_stale_temp_files); every rank agrees on the outcome)", "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)", @@ -2666,7 +2666,7 @@ "count": 7 }, "tests/unit/test_data_position.py": { - "note": "Module-level pytest functions (no Test* classes): the data position across data-parallel and batch size changes, the in-step clamp, mixture and legacy refusals, seed and dataset-length warnings, load_path warm starts through restore_checkpoint and load(dataloader=...), gloo CheckpointManager resume on another world size; a load that restores no position (weights only, a step without train_state.pt, a train state without one) after one that kept a position leaves none pending, and a loader applied after it starts at its first sample; a resume through run_training_loop and a real CheckpointManager: without apply_dataloader_state it raises before its hooks and its first step, with it the data continues, and a run without a loader starts with the position pending; gloo CheckpointManager auto-resume (exact_resume) saved on 4 ranks: on 2 ranks with ignore_rank_state_mismatch at the exact global position with fresh RNG, refused on every rank without it, a mixture restarting with a warning, and the saved layout restoring each rank's own state; check_state's verdicts; a gather of the checks that fails: on 2 gloo ranks with rank 0 late past the group timeout, rank 1's failed or refused check raised as its own error with the gather's failure in a note, and in one process after a resume, a warm start and a carried position (ignore_rank_state_mismatch on a changed world size): a failed check kept after each, a refusal kept on the resume, and after the other two a refusal logged as a warning, then the gather's failure raised", + "note": "Module-level pytest functions (no Test* classes): the data position across data-parallel and batch size changes, the in-step clamp, mixture and legacy refusals, seed and dataset-length warnings, load_path warm starts through restore_checkpoint and load(dataloader=...), gloo CheckpointManager resume on another world size; a load that restores no position (weights only, a step without train_state.pt, a train state without one) after one that kept a position leaves none pending, and a loader applied after it starts at its first sample; a resume through run_training_loop and a real CheckpointManager: without apply_dataloader_state it raises before its hooks and its first step, with it the data continues, and a run without a loader starts with the position pending; gloo CheckpointManager auto-resume (exact_resume) saved on 4 ranks: on 2 ranks with ignore_rank_state_mismatch at the exact global position with fresh RNG, refused on every rank without it, a mixture restarting with a warning, and the saved layout restoring each rank's own state; check_state's verdicts; a gather of the checks that fails: on 2 gloo ranks with rank 0 late past the group timeout, rank 1's failed or refused check raised as its own error with the gather's failure in a note, and in one process after a resume, a warm start and a carried position (ignore_rank_state_mismatch on a changed world size): a failed check kept after each, a refusal kept on the resume, and after the other two a refusal logged as a warning that the rank-0 log filter passes on rank 1, then the gather's failure raised", "count": 30 }, "tests/unit/test_mixture_phase_change.py": { diff --git a/kempnerforge/checkpoint/manager.py b/kempnerforge/checkpoint/manager.py index b3c7f7d0f..9bdb115d6 100644 --- a/kempnerforge/checkpoint/manager.py +++ b/kempnerforge/checkpoint/manager.py @@ -3496,8 +3496,8 @@ def apply_dataloader_state(self, dataloader: Any) -> None: the group's timeout, a rank whose check failed, or refused where a refusal raises, still raises its own error, with that failure in a note (see ``run_keeping_own_error``). After a ``warm_start`` load, or on a carried - position, a rank whose check refused logs why as a warning, then raises - that failure, as a rank whose check passed does. + position, a rank whose check refused logs why as a warning in its own log, + then raises that failure, as a rank whose check passed does. """ missing, self._pending_dataloader_missing = self._pending_dataloader_missing, False if self._pending_dataloader_state is None: @@ -3580,7 +3580,7 @@ def _position_refusals( still raises that error, with the gather's failure in a note, and any other rank raises the gather's failure, with a note naming the check (see ``run_keeping_own_error``). A rank whose check refused where ``refusal_raises`` - is false logs why as a warning first. + is false logs why as a warning in its own log first. Returns: Global rank -> why its loader cannot place the position (empty when @@ -3621,7 +3621,8 @@ def _position_refusals( logger.warning( f"The saved data position does not carry over to this run on rank " f"{self._rank}, and sharing the ranks' checks of it failed, so the run " - f"stops: {verdict[1]}" + f"stops: {verdict[1]}", + extra={"every_rank": True}, ) raise verdicts = dict(enumerate(gathered)) diff --git a/tests/unit/test_data_position.py b/tests/unit/test_data_position.py index a32cc144d..ac684f857 100644 --- a/tests/unit/test_data_position.py +++ b/tests/unit/test_data_position.py @@ -31,6 +31,7 @@ from kempnerforge.config.schema import DataConfig from kempnerforge.data.dataloader import DataPositionError, StatefulDataLoader from kempnerforge.data.sampler import DistributedSampler, MixtureSampler +from kempnerforge.metrics.logger import _RankFilter from kempnerforge.training.hooks import HookRunner, TrainingHook from tests.gloo_ranks import ( gloo_group, @@ -485,7 +486,8 @@ def test_a_failed_gather_keeps_a_ranks_own_error_and_logs_a_refusal_that_does_no ``checkpoint.ignore_rank_state_mismatch`` carried onto a changed topology, a refusal only restarts the data when the gather completes, so a rank whose check refused logs why as a warning that says the run stops, then raises the gather's failure, with a note naming the - check, as a rank whose check passed does. + check, as a rank whose check passed does. Only that rank knows why, so the warning must + pass the training log's rank-0 filter on the other ranks. The ``kempnerforge`` logger stops propagation once configured, so the test lets records reach ``caplog`` after the restore. @@ -522,6 +524,8 @@ def all_gather_object(object_list, obj, group=None): "the ranks' checks of it failed, so the run stops: The data changed since the " "save: a data file changed size" ] + monkeypatch.setenv("RANK", "1") + assert _RankFilter(rank=0).filter(caplog.records[0]), "the training log would drop it" else: assert caught.value.__notes__ == [f"{CHECK_NOT_AGREED}RuntimeError: {failure}"] assert logged == []