diff --git a/codebase-map.json b/codebase-map.json index c30e63d5..3706b7c5 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) -> (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; 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,8 +2666,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 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": { "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 91788b0d..9bdb115d 100644 --- a/kempnerforge/checkpoint/manager.py +++ b/kempnerforge/checkpoint/manager.py @@ -3491,6 +3491,13 @@ 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``). After a ``warm_start`` load, or on a carried + 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: @@ -3527,7 +3534,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) @@ -3553,7 +3562,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. @@ -3564,7 +3573,14 @@ 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``). A rank whose check refused where ``refusal_raises`` + is false logs why as a warning in its own log first. Returns: Global rank -> why its loader cannot place the position (empty when @@ -3573,20 +3589,42 @@ 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``. + 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 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) + 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]}", + extra={"every_rank": True}, + ) + 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 cd84158e..ac684f85 100644 --- a/tests/unit/test_data_position.py +++ b/tests/unit/test_data_position.py @@ -9,7 +9,10 @@ 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, and logs why +its check refused where a refusal would only restart the data. """ from __future__ import annotations @@ -28,11 +31,24 @@ 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, 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 +435,102 @@ 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 + + +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 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. 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. + """ + from kempnerforge.checkpoint import manager as manager_module + + _save_loader_state(tmp_path / "saved", _legacy_state(1, 100)) + 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): + 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) + monkeypatch.setattr(logging.getLogger("kempnerforge"), "propagate", True) + loader = _loader(_Indices(4_096), 2, 0, 4) + loader.check_state = _failing_check(kind) + 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) + 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" + ] + 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 == [] + + _RELOADS = ["weights_only", "no_train_state", "no_position"] @@ -825,3 +937,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]