diff --git a/codebase-map.json b/codebase-map.json index 948a93a55..c30e63d56 100644 --- a/codebase-map.json +++ b/codebase-map.json @@ -1013,6 +1013,7 @@ "build_data_pipeline(config, runtime, *, tokens_per_image=None) -> DataPipeline", "build_eval_dataloader(config, runtime) -> DataLoader | None", "build_phase_state(config, data, step) -> PhaseState", + "check_phase_weights(config, data) (every data phase's weights against the pipeline's mixture sampler; the refusal names the phase)", "advance_phases(state, data, step) -> bool" ], "tested_by": [ @@ -1083,7 +1084,8 @@ "build_checkpoint_manager(config, runtime, model, optimizer, pipeline) -> CheckpointManager", "restore_checkpoint(config, model, scheduler, ckpt_mgr) -> tuple[int, int]", "_trainable_for_the_run(model, config) (trainable_for_the_run for a VLM with a freeze schedule, else a context that changes nothing)", - "_apply_effective_freeze(model, vlm_cfg, step) (vlm.freeze and every FreezeStage up to step, at a fresh start and on a resume)" + "_apply_effective_freeze(model, vlm_cfg, step) (vlm.freeze and every FreezeStage up to step, at a fresh start and on a resume)", + "_agreed_data_pipeline(config, runtime, data_fn, tokens_per_image, agree) -> DataPipeline (every rank reports its data build, partition check and check_phase_weights to the checkpoint manager's agreement before any rank goes on)" ], "tested_by": [ "tests/unit/test_train_entry.py::TestRunTraining", @@ -1098,7 +1100,8 @@ "tests/e2e/test_training_e2e.py", "tests/smoke/test_smoke.py", "tests/unit/test_slurm_scripts.py", - "tests/unit/test_shutdown_timeout.py::TestResolveShutdownTimeouts" + "tests/unit/test_shutdown_timeout.py::TestResolveShutdownTimeouts", + "tests/unit/test_train_entry.py::TestADataPipelineErrorFailsEveryRank" ] }, "kempnerforge/data/dataset.py": { @@ -1465,10 +1468,13 @@ "clip_grad_norm_(model, max_norm, foreach, pp_group) -> Tensor", "new_control_group(timeout_sec) -> ProcessGroup | None", "any_rank(flag, group) -> bool", - "any_rank_each(flags, group) -> list[bool] (each flag reduced over the group, all in one MAX all-reduce)" + "any_rank_each(flags, group) -> list[bool] (each flag reduced over the group, all in one MAX all-reduce)", + "run_keeping_own_error(collective, error, what) (runs a collective every rank enters with the outcome of its part of what; if the collective itself fails, an interrupt included, a rank with an error still raises its own, with that failure in a note, and a rank without one raises the failure with a note naming what; agree_across_ranks and the checkpoint manager's own agreements run their collectives through it)", + "agree_across_ranks(error, what, *, group=None) (one all-reduce on group: a rank with an error re-raises it, the others raise naming the failed ranks; if the all-reduce itself fails, an interrupt included, a rank with an error still raises its own, with that failure in a note)" ], "tested_by": [ "tests/unit/test_distributed.py::TestClipGradNorm", + "tests/unit/test_distributed.py::TestAgreeAcrossRanks", "tests/unit/test_dp_info.py::TestDataParallelReduction", "tests/unit/test_shutdown_agreement.py::TestAnyRank", "tests/unit/test_ep_gradients.py::TestClipUnderExpertParallelism", @@ -1520,6 +1526,7 @@ "_resume_past_mismatch(view, envelope, error) -> (view, carried) (with ignore_rank_state_mismatch: a changed topology keeps the saved data position if the envelope is sound where it was saved, rank 0's or for a stream on the saved data-parallel size its own data-parallel rank's, else drops it; never restores RNG)", "_resume_without_rank_state(train_state) -> (view, carried) (with ignore_rank_state_mismatch, a checkpoint with no per-rank state resumes as if the topology changed: rank 0's data position kept, its RNG dropped)", "_read_saved_keys(dcp_dir) -> (keys, restored_on_any_rank) (this rank's DCP keys; with a scope or multipliers an all-reduce on the gloo group tells every rank whether any rank's index holds optimizer state)", + "_optimizer_saved_on_any_rank(error, holds) -> bool (that all-reduce: a rank whose read failed re-raises its error, the others raise naming it; if the all-reduce itself fails, a rank whose read failed still raises its error, with that failure in a note)", "_agreed_dcp_keys(dcp_dir) -> dict (this rank's DCP keys, read under one all-reduce on the gloo group, so a rank whose read fails raises on every rank; the derived-buffer read of a load without optimizer state)", "_broadcast_metadata(ckpt_dir, read) -> (meta, error) (rank 0 shares the read _agreed_load_dir made, or reads metadata.json, and broadcasts the object or why it could not; the layout, scope, multipliers and group-layout checks all decide from one read per load)", "_check_plugins(metadata, ckpt_dir, expected) (every rank refuses another plugins list before any state is read, unless checkpoint.ignore_plugins_mismatch)", @@ -1529,8 +1536,9 @@ "_check_lr_multipliers(metadata, ckpt_dir) -> saved group modules | None (every rank refuses other multipliers or patterns; a run without multipliers loads past an unreadable record with a warning; runs once per load, before loading optimizer state on any rank or before restoring a scheduler from train_state.pt)", "_present_experts(dcp_state, load_from, saved_keys) (before a load: EP experts placed among all of them; refuses a checkpoint of fewer experts than the model; the ranks agree before DCP)", "_prepare_save(ckpt_dir, dcp_dir) -> (dcp_state, layout) (this rank's part of a save before the write, with no collective: creates the step and stage directories, builds the model, optimizer and never-stepped state, and places EP experts among all of them)", - "_agree_to_write(error, flush_error) (one all-reduce on the gloo group before any rank dispatches a save's DCP write: a failure on any rank, of _prepare_save or of the wait for its previous async write, raises on every rank, naming the failed ranks; the pending async checkpoint is first committed when every rank's write of it ended well, else dropped)", - "_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; 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)", + "_agree_to_write(error, flush_error) (one all-reduce on the gloo group before any rank dispatches a save's DCP write: a failure on any rank, of _prepare_save or of the wait for its previous async write, raises on every rank, naming the failed ranks; the pending async checkpoint is first committed when every rank's write of it ended well, else dropped; if the all-reduce itself fails, the pending checkpoint stays pending and a rank with an error still raises its own, with that failure in a note)", + "_gather_rank_states(dataloader, error) -> (envelope | None, error | None) (every rank's loader/RNG payload, gathered on the gloo group into the per-rank envelope; a rank whose capture fails enters the gather with no payload; if the gather itself fails, a rank with error, what its part of the save raised so far, or else with its capture's error still raises it, with that failure in a note)", + "_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)", @@ -2038,6 +2046,7 @@ "tests/unit/test_distributed.py": { "classes": [ "TestClipGradNorm(4)", + "TestAgreeAcrossRanks(5)", "TestBuildBlockTPPlan(8)", "TestApplyTensorParallelSequenceParallel(3)", "TestBuildCrossAttentionTPPlan(3)", @@ -2050,7 +2059,7 @@ "TestFsdpWrapTransformerBlocksHelper(1)", "TestApplyFsdp2GuardedAttributes(3)" ], - "count": 45 + "count": 50 }, "tests/unit/test_resilience.py": { "classes": [ @@ -2099,7 +2108,7 @@ "TestWeightsOnlyWarmStart(8)", "TestLoadVLMFreezeCompare(9)", "TestAsyncLatestSymlinkSafety(32)", - "TestAFailedSaveCommitsNothing(20)", + "TestAFailedSaveCommitsNothing(23)", "TestDurableTrainState(6)", "TestSyncBarrierGroup(6)", "TestCheckpointManagerLoad(3)", @@ -2112,14 +2121,14 @@ "TestOptimizerChecksAcrossStages(5)", "TestCheckpointEveryOptimizer(8)", "TestComponentSwapOnResume(1)", - "TestWeightDecayScopeOnResume(46)", + "TestWeightDecayScopeOnResume(48)", "TestRestoredExtra(2)", "TestResumedStep(7)", "TestUnreadableTrainStateAcrossRanks(1)", "TestTornStageAcrossRanks(1)", "TestOptimizerTypeChangeOnResume(6)" ], - "count": 385 + "count": 390 }, "tests/unit/test_checkpoint_publish.py": { "classes": [ @@ -2146,7 +2155,7 @@ "TestPerRankEnvelopeSchema(17)", "TestEnvelopeValidatedBeforeSelection(6)", "TestGatherMustCoverTheWorld(2)", - "TestAFailedCaptureFailsEveryRank(4)", + "TestAFailedCaptureFailsEveryRank(6)", "TestFourRankSaveLoad(6)", "TestLegacyAndTopology(10)", "TestDataParallelLayout(12)", @@ -2154,7 +2163,7 @@ "TestWeightsOnlyWarmStart(3)", "TestMidSaveInterruption(1)" ], - "count": 63 + "count": 65 }, "tests/unit/test_observability.py": { "classes": [ @@ -2338,10 +2347,10 @@ "TestPipelineCheckpointSaveAndResume(6)", "TestResumeScanNeedsEveryStage(1)", "TestLatestWaitsForEveryStage(2)", - "TestAFailedSaveFailsEveryRank(18)", + "TestAFailedSaveFailsEveryRank(19)", "TestAFailedReadFailsEveryRank(9)" ], - "count": 36 + "count": 37 }, "tests/unit/test_ep_checkpoint.py": { "classes": [ diff --git a/docs/architecture/data-flow.md b/docs/architecture/data-flow.md index d5a1406be..2e4d3ead0 100644 --- a/docs/architecture/data-flow.md +++ b/docs/architecture/data-flow.md @@ -86,7 +86,13 @@ initializes the collaborators: streaming dataset, wrapped by `StreamingDataLoader` with no sampler. Both loaders are in [`kempnerforge.data`](https://github.com/KempnerInstitute/KempnerForge/tree/main/kempnerforge/data). - `ckpt_mgr.apply_dataloader_state` then hands the loader the position the +- **Data-build agreement**: every rank reports, over the checkpoint + manager's gloo group (`ckpt_mgr.agree`), whether its pipeline built + with the data-parallel partition `get_dp_info` gives it and a sampler + that takes every data phase's weights (`check_phase_weights`), before + any rank goes on, so a build that fails on one rank stops every rank, + the others with an error naming it. Right after that agreement, + `ckpt_mgr.apply_dataloader_state` hands the loader the position the load kept; without that call `run_training_loop` stops before its first step. - **Eval dataloader and `torch.profiler`** (optional). diff --git a/docs/checkpointing/train-state.md b/docs/checkpointing/train-state.md index 90ad27631..cbec15571 100644 --- a/docs/checkpointing/train-state.md +++ b/docs/checkpointing/train-state.md @@ -44,7 +44,7 @@ Entry points, both in ```python # manager.py, inside save() (abridged) -per_rank, gather_error = self._gather_rank_states(dataloader) # every rank +per_rank, gather_error = self._gather_rank_states(dataloader, error) # every rank if error is None: error = gather_error diff --git a/docs/data/sampler.md b/docs/data/sampler.md index 899950b6e..0e1edf9ce 100644 --- a/docs/data/sampler.md +++ b/docs/data/sampler.md @@ -139,11 +139,13 @@ its share of the epoch goes to the others, so every rank yields `len()` samples, also when a temperature gives a zero weight a small probability. The training pipeline builds the sampler with the weights a data phase at -step 0 sets, so such a phase can give a small source weight 0. -`build_phase_state` checks every phase's weights with `check_weights` +step 0 sets, so such a phase can give a small source weight 0; weights the +sampler refuses there stop the build with an error that names the phase. +`check_phase_weights` checks every phase's weights with `check_weights` before training starts, also against a mixture a `data_fn` built, so a phase that would weight a small source stops the run then, not when it -begins. +begins. `run_training` runs it with the data build on every rank, and +`build_phase_state` runs it too. Each `__iter__()` then does: diff --git a/docs/training/training-loop.md b/docs/training/training-loop.md index 40614b122..b9bd2d7b3 100644 --- a/docs/training/training-loop.md +++ b/docs/training/training-loop.md @@ -322,10 +322,14 @@ in order, then hands a `TrainingSession` to `run_training_loop`: `run_training(config, data_fn=...)` builds the training pipeline with `data_fn` in place of `build_data_pipeline`, following the `DataFn` contract in `kempnerforge/training/data_pipeline.py`; the eval loader - still comes from `build_eval_dataloader`. Right after the training - pipeline, `ckpt_mgr.apply_dataloader_state` hands its loader the data - position the restore kept; `run_training_loop` raises before its first - step while that position is unapplied and the run has a loader. + still comes from `build_eval_dataloader`. Every rank reports, over the + checkpoint manager's gloo group, whether its training pipeline built with + a sampler that takes every data phase's weights (`check_phase_weights`) + before any rank goes on, so a build that fails on one rank stops every + rank, the others with an error naming it. Right after that agreement, + `ckpt_mgr.apply_dataloader_state` hands its loader the data position the + restore kept; `run_training_loop` raises before its first step while that + position is unapplied and the run has a loader. The full list with links lives in [Data flow ยง Startup, once](../architecture/data-flow.md#startup-once). diff --git a/examples/assembled_run/README.md b/examples/assembled_run/README.md index 0b528e00f..3286ac718 100644 --- a/examples/assembled_run/README.md +++ b/examples/assembled_run/README.md @@ -113,7 +113,18 @@ code; the names after it are the core pieces it orders. `CheckpointManager.set_tracking_source` and `set_checkpoint_registrar`). The backends continue the runs the restore named, and every checkpoint records them. -10. **`apply_dataloader_state` after the restore and the loader, and before the +10. **The ranks' agreement on the data build before `apply_dataloader_state`** + (`build_data`; `build_data_pipeline`, `check_phase_weights`, + `CheckpointManager.agree`). Every rank reports whether it built its data, + with a sampler that takes every data phase's weights, before any rank goes + on, so a build that fails on one rank fails the run on every rank, the + others with an error naming it. Leave the agreement out and the other ranks + go on into collectives that rank never joins, such as the training loop's + first, which holds them until the process-group timeout + (`distributed.nccl_timeout_sec`, 1800 s by default) or the launcher's kill. + On a resume, the check of the data position can fail on them first, with a + lost-connection error that does not say what failed. +11. **`apply_dataloader_state` after the restore and the loader, and before the loader's first batch** (`build_data`; `CheckpointManager.apply_dataloader_state`). The case above: the data is built after the restore, as `run_training` builds it, so the load keeps the @@ -121,16 +132,16 @@ code; the names after it are the core pieces it orders. before its first step. Called before the restore it finds nothing to apply, and the loop then raises as if it were left out. Every rank calls it, since the ranks check the position together before any of them applies it. -11. **The phases after the restore and the data** (`build_data`; +12. **The phases after the restore and the data** (`build_data`; `build_phase_state`). It applies each data phase that starts at or before the restored step, so the run starts in the phase it stopped in, at that phase's `lr_scale` and, on a mixture, with its weights on the sampler. -12. **The NaN count and the documents seen after the restore** (`train`; +13. **The NaN count and the documents seen after the restore** (`train`; `NaNDetector`, `TrainingSession`). The detector continues the count of NaN steps in a row that the checkpoint saved, so a resumed run stops at the step an uninterrupted one stops at, and the session continues the count of documents seen, for a step body that reports documents. -13. **The teardown on the success path only** (`train`; +14. **The teardown on the success path only** (`train`; `CheckpointManager.release_dir`, `destroy_distributed`, `ShutdownHandler.finish`). The tracker closes on every path, since its backends are rank-local. Releasing `checkpoint.dir`, destroying the process @@ -177,6 +188,10 @@ it in the same `checkpoint.dir`: - The signal leaves the emergency checkpoint as `latest`, the claim on `checkpoint.dir` released and the `SIGTERM` and `SIGUSR1` handlers as they were. A run whose hook raises keeps its claim and its shutdown handler. +- A data build that fails, on a token directory with no shards or on a data + phase whose weights the sampler refuses, goes through the ranks' agreement on + the build. When the agreement reports that another rank's build failed, a + resume stops there, before `apply_dataloader_state`. - A VLM config is refused before anything is built, and the entry point passes the config and its overrides through. diff --git a/examples/assembled_run/tests/test_assembled_run.py b/examples/assembled_run/tests/test_assembled_run.py index f606b5687..aae2e13fe 100644 --- a/examples/assembled_run/tests/test_assembled_run.py +++ b/examples/assembled_run/tests/test_assembled_run.py @@ -36,6 +36,8 @@ MAX_STEPS = 6 STOP_AT = 3 SHUTDOWN_SIGNALS = (signal.SIGTERM, signal.SIGUSR1) +DATA_BUILD = "Data pipeline build" +APPLIED = "apply_dataloader_state" @dataclass @@ -186,8 +188,8 @@ def test_without_the_loader_state_a_resume_stops_before_its_first_step( assert sorted(path.name for path in split.glob("step_*")) == [f"step_{STOP_AT}"] -def _mixture_config(tmp_path: Path) -> Path: - """The tiny config on a mixture of two token shards that a phase reweights at step 2. +def _mixture_config(tmp_path: Path, weights: str = "{ a = 0.9, b = 0.1 }") -> Path: + """The tiny config on a mixture of two token shards that a phase sets to ``weights`` at step 2. Only a reweighting shows a resume that starts in the wrong phase: after a phase that changes only ``lr_scale``, the restored optimizer already holds the scaled rate, and the @@ -200,9 +202,7 @@ def _mixture_config(tmp_path: Path) -> Path: f'[[data.datasets]]\npath = "{_write_tokens(tmp_path / name, seed)}"\nname = "{name}"\n' for name, seed in (("a", 1), ("b", 2)) ] - phase = ( - "[[data.phases]]\nstart_step = 2\ndataset_weights = { a = 0.9, b = 0.1 }\nlr_scale = 0.5\n" - ) + phase = f"[[data.phases]]\nstart_step = 2\ndataset_weights = {weights}\nlr_scale = 0.5\n" path = tmp_path / "mixture.toml" path.write_text(text.replace(placeholder, "") + "\n" + "\n".join([*sources, phase])) return path @@ -303,6 +303,89 @@ def test_a_run_that_raises_keeps_its_claim_and_its_shutdown_handler( assert all(signal.getsignal(sig) != handler for sig, handler in handlers.items()) +@dataclass +class Startup: + """The rank agreements on the data build and the data positions applied, in order. + + Each event is the ``(what, error)`` an agreement on the data build got, or + ``("apply_dataloader_state", None)``. With ``failed_elsewhere``, an agreement on a build + that succeeded raises what ``agree_across_ranks`` raises there when rank 1's build failed. + """ + + events: list[tuple[str, BaseException | None]] = dataclasses.field(default_factory=list) + failed_elsewhere: bool = False + + +@pytest.fixture +def startup(monkeypatch: pytest.MonkeyPatch) -> Startup: + """Records every run's agreements on the data build and its ``apply_dataloader_state``.""" + record = Startup() + agree = CheckpointManager.agree + apply = CheckpointManager.apply_dataloader_state + + def recording_agree( + manager: CheckpointManager, error: BaseException | None, what: str = "Checkpoint save" + ) -> None: + if what == DATA_BUILD: + record.events.append((what, error)) + if record.failed_elsewhere and error is None: + raise RuntimeError(f"{what} failed on ranks [1]") + agree(manager, error, what) + + def recording_apply(manager: CheckpointManager, dataloader: Any) -> None: + record.events.append((APPLIED, None)) + apply(manager, dataloader) + + monkeypatch.setattr(CheckpointManager, "agree", recording_agree) + monkeypatch.setattr(CheckpointManager, "apply_dataloader_state", recording_apply) + return record + + +def test_a_data_build_error_reaches_the_rank_agreement( + example: Any, monkeypatch: pytest.MonkeyPatch, tmp_path: Path, startup: Startup +) -> None: + """The rank whose build failed hands its error to the agreement, which raises it there and + on every other rank an error naming the rank, so no rank waits for it in a later + collective. With no process group the error comes through unchanged.""" + empty = tmp_path / "tokens" + empty.mkdir() + with pytest.raises(FileNotFoundError, match="No files matching") as raised: + _train(example, monkeypatch, empty, tmp_path / "run") + + assert startup.events == [(DATA_BUILD, raised.value)] + + +def test_the_ranks_agree_on_the_data_build_before_a_resume_applies_its_position( + example: Any, monkeypatch: pytest.MonkeyPatch, tokens: Path, tmp_path: Path, startup: Startup +) -> None: + """Every rank joins ``apply_dataloader_state``'s check of a resumed position, so the ranks + agree on the build first: when another rank's build failed, this rank stops at the + agreement with an error naming that rank, and applies no position.""" + run_dir = tmp_path / "run" + _train(example, monkeypatch, tokens, run_dir, stop_at=STOP_AT) + assert startup.events == [(DATA_BUILD, None), (APPLIED, None)] + + startup.events.clear() + startup.failed_elsewhere = True + with pytest.raises(RuntimeError, match=r"Data pipeline build failed on ranks \[1\]"): + _train(example, monkeypatch, tokens, run_dir) + + assert startup.events == [(DATA_BUILD, None)] + + +def test_a_data_phase_the_sampler_refuses_fails_the_run_through_the_rank_agreement( + example: Any, monkeypatch: pytest.MonkeyPatch, tmp_path: Path, startup: Startup +) -> None: + """Every phase's weights are checked with the build, also a later phase's, so a refusal, + which on sources split per rank can come on some ranks only, reaches the agreement before + any position is applied.""" + config = _mixture_config(tmp_path, weights="{ a = 0.0, b = 0.0 }") + with pytest.raises(ValueError, match="Data phase at step 2: ") as raised: + _train(example, monkeypatch, None, tmp_path / "run", config=config) + + assert startup.events == [(DATA_BUILD, raised.value)] + + def test_a_vlm_config_is_refused_before_anything_is_built( example: Any, monkeypatch: pytest.MonkeyPatch, tmp_path: Path ) -> None: diff --git a/examples/assembled_run/train.py b/examples/assembled_run/train.py index c704789bd..628a427fb 100644 --- a/examples/assembled_run/train.py +++ b/examples/assembled_run/train.py @@ -45,6 +45,7 @@ build_data_pipeline, build_eval_dataloader, build_phase_state, + check_phase_weights, ) from kempnerforge.training.entry import ( build_checkpoint_manager, @@ -169,8 +170,18 @@ def build_data( Mirrors ``run_training``, which builds the data after the model, so that a VLM run can read its ``tokens_per_image`` off the built model, and after the restore: - - ``apply_dataloader_state`` after the restore and right after the loader is built, - before the loop draws a batch from it. The restore ran before the loader existed, so + - ``CheckpointManager.agree`` on the build before ``apply_dataloader_state``: every rank + reports whether ``build_data_pipeline`` built its data, with a sampler that takes every + data phase's weights (``check_phase_weights``), before any rank goes on. A rank whose + build failed raises its own error, and every other rank a ``RuntimeError`` naming it. + Leave it out and a build that fails on one rank stops that rank alone: the others go + on into collectives it never joins, such as the training loop's first, which holds + them until the process-group timeout, ``distributed.nccl_timeout_sec`` (1800 s by + default), or the launcher's kill. On a resume, ``apply_dataloader_state``'s check of + the position can fail on them first, with a lost-connection error that does not say + what failed. + - ``apply_dataloader_state`` after the restore and the agreement on the build, before + the loop draws a batch from the loader. The restore ran before the loader existed, so the load kept the saved data position rather than applying it, and this call applies it; called before the restore, it would find nothing to apply, and the loop would raise as if it were left out. Left out, the model, optimizer and scheduler would @@ -187,7 +198,15 @@ def build_data( builder of your own in its place must return that ``dp_rank`` and ``dp_size``, which ``run_training`` checks of a ``data_fn``: the loop scales its token counts by them. """ - data = build_data_pipeline(config, runtime) + data: DataPipeline | None = None + error: Exception | None = None + try: + data = build_data_pipeline(config, runtime) + check_phase_weights(config, data) + except Exception as exc: + error = exc + ckpt_mgr.agree(error, "Data pipeline build") + assert data is not None if data.dataloader is not None: ckpt_mgr.apply_dataloader_state(data.dataloader) eval_dataloader = build_eval_dataloader(config, runtime) diff --git a/kempnerforge/checkpoint/manager.py b/kempnerforge/checkpoint/manager.py index 6c40429ee..91788b0da 100644 --- a/kempnerforge/checkpoint/manager.py +++ b/kempnerforge/checkpoint/manager.py @@ -112,7 +112,7 @@ StatefulDataLoader, StreamingDataLoader, ) -from kempnerforge.distributed.utils import agree_across_ranks +from kempnerforge.distributed.utils import agree_across_ranks, run_keeping_own_error logger = logging.getLogger(__name__) @@ -1856,7 +1856,9 @@ def _agree_to_write( ``latest`` commit: rank 0 commits it when every rank's write of it ended well, and it is dropped when any rank's failed. Then a rank with an error re-raises its own, and every other rank raises a ``RuntimeError`` naming the ranks that failed (see - ``agree``). + ``agree``). If the all-reduce itself raises, that checkpoint stays pending, and a + rank with an error still raises its own, with the all-reduce's failure in a note + (see ``run_keeping_own_error``). """ own = error if error is not None else flush_error if error is not None and flush_error is not None: @@ -1871,7 +1873,9 @@ def _agree_to_write( rank = dist.get_rank(self._sync_group) flags[0, rank] = int(own is not None) flags[1, rank] = int(flush_failed) - dist.all_reduce(flags, group=self._sync_group) + run_keeping_own_error( + lambda: dist.all_reduce(flags, group=self._sync_group), own, "Checkpoint save" + ) failed = flags[0].nonzero().flatten().tolist() flush_failed = bool(flags[1].any()) if own is None and not failed: @@ -1978,7 +1982,9 @@ def _check_model_fits( A rank that cannot list its entries still enters every collective, sending why in their place, and rank 0 still broadcasts a verdict when comparing them fails, with why in its place: the rank that failed raises its own error and every other rank a - ``RuntimeError`` naming it. + ``RuntimeError`` naming it. If one of these collectives itself raises, a rank with an + error still raises its own, as rank 0 does its refusal, with the collective's failure + in a note (see ``run_keeping_own_error``). Raises: ValueError: The checkpoint does not fit the model. @@ -2003,7 +2009,11 @@ def _check_model_fits( gathered: list[Any] | None = [mine] if distributed: gathered = [None] * dist.get_world_size(self._sync_group) if self._rank == 0 else None - dist.gather_object(mine, gathered, dst=0, group=self._sync_group) + run_keeping_own_error( + lambda: dist.gather_object(mine, gathered, dst=0, group=self._sync_group), + local_error, + "Checkpoint load", + ) outcome: list[Exception | None] = [None] comparison_error: Exception | None = None if gathered is not None: @@ -2017,7 +2027,12 @@ def _check_model_fits( f"{type(e).__name__}: {_error_text(e)}" ) if distributed: - dist.broadcast_object_list(outcome, src=0, group=self._sync_group) + own = local_error if local_error is not None else comparison_error + run_keeping_own_error( + lambda: dist.broadcast_object_list(outcome, src=0, group=self._sync_group), + own if own is not None else outcome[0], + "Checkpoint load", + ) for error in (local_error, comparison_error, outcome[0]): if error is not None: raise error @@ -2223,19 +2238,22 @@ def _record(self, step: int, ckpt_dir: Path, backend: str, fields: dict[str, str ) def _gather_rank_states( - self, dataloader: Any | None + self, dataloader: Any | None, error: BaseException | None ) -> tuple[dict[str, Any] | None, BaseException | None]: """Collect every rank's own loader/RNG payload into a versioned envelope. Collective: every rank calls it once per ``save()``, whatever its own part of - the save has raised so far. Uses the dedicated gloo group so the gather cannot - interleave with DCP collectives an in-flight async flush is issuing on the - default group from its background thread. Each rank captures and serializes - its payload before the gather, and a rank whose capture raises enters the - gather with no payload, so no rank is left waiting in it. Entries are keyed by - each payload's own global rank rather than by gather position, so the envelope - is correct under any group ordering. Each rank's ``dp_info`` rides along to - record the data-parallel layout. + the save has raised so far, which it passes as ``error``. Uses the dedicated gloo + group so the gather cannot interleave with DCP collectives an in-flight async + flush is issuing on the default group from its background thread. Each rank + captures and serializes its payload before the gather, and a rank whose capture + raises enters the gather with no payload, so no rank is left waiting in it. + Entries are keyed by each payload's own global rank rather than by gather + position, so the envelope is correct under any group ordering. Each rank's + ``dp_info`` rides along to record the data-parallel layout. If the gather itself + raises, a rank with ``error``, or else with an error from its own capture, still + raises that error, with the gather's failure in a note (see + ``run_keeping_own_error``). Returns: The envelope and ``None``; or ``None`` and the error this rank reports: @@ -2253,7 +2271,11 @@ def _gather_rank_states( gathered: list[Any] = [mine] if dist.is_initialized(): gathered = [None] * self._world_size - dist.all_gather_object(gathered, mine, group=self._sync_group) + run_keeping_own_error( + lambda: dist.all_gather_object(gathered, mine, group=self._sync_group), + error if error is not None else capture_error, + "Checkpoint save", + ) if capture_error is not None: return None, capture_error failed = sorted(int(rank) for rank, _, data in gathered if data is None) @@ -2490,7 +2512,7 @@ def save( if drain_error is not None: error = drain_error - per_rank, gather_error = self._gather_rank_states(dataloader) + per_rank, gather_error = self._gather_rank_states(dataloader, error) if error is None: error = gather_error @@ -3126,7 +3148,9 @@ def _optimizer_saved_on_any_rank(self, error: Exception | None, holds: bool) -> Every rank passes the error its read of its index raised, or ``None``, and whether its index holds optimizer state. After one all-reduce on the manager's gloo group a rank with an error re-raises it, and every other rank raises a ``RuntimeError`` naming the - ranks that failed. Without an initialized process group, ``error`` is raised if set. + ranks that failed. If the all-reduce itself raises, a rank with an error still raises + it, with the all-reduce's failure in a note (see ``run_keeping_own_error``). Without an + initialized process group, ``error`` is raised if set. """ if not dist.is_initialized(): if error is not None: @@ -3136,7 +3160,9 @@ def _optimizer_saved_on_any_rank(self, error: Exception | None, holds: bool) -> rank = dist.get_rank(self._sync_group) flags[0, rank] = int(error is not None) flags[1, rank] = int(holds) - dist.all_reduce(flags, group=self._sync_group) + run_keeping_own_error( + lambda: dist.all_reduce(flags, group=self._sync_group), error, "Checkpoint load" + ) if error is not None: raise error failed = flags[0].nonzero().flatten().tolist() diff --git a/kempnerforge/distributed/utils.py b/kempnerforge/distributed/utils.py index 41015ec76..ae4bcda31 100644 --- a/kempnerforge/distributed/utils.py +++ b/kempnerforge/distributed/utils.py @@ -8,8 +8,9 @@ import logging import math +import traceback from collections import defaultdict -from collections.abc import Sequence +from collections.abc import Callable, Sequence from datetime import timedelta from typing import cast @@ -282,6 +283,32 @@ def any_rank_each(flags: Sequence[bool], group: dist.ProcessGroup | None) -> lis return [bool(value) for value in t.tolist()] +def run_keeping_own_error( + collective: Callable[[], object], error: BaseException | None, what: str +) -> None: + """Run ``collective``, which every rank enters with the outcome of its own part of ``what``. + + ``error`` is what this rank's part raised, or ``None``. If ``collective`` itself raises, + as on a rank that waited in it past the group's timeout or on an interrupt such as + ``KeyboardInterrupt``, a rank with an error still raises its own, with the collective's + failure in a note, not chained to it, and a rank without one raises the collective's + failure with a note naming ``what``. + """ + try: + collective() + except BaseException as collective_error: + if error is None: + collective_error.add_note( + f"{what} succeeded on this rank but could not be agreed across ranks" + ) + raise + failure = "".join(traceback.format_exception_only(collective_error)).strip() + error.add_note(f"{what} could not be agreed across ranks: {failure}") + else: + return + raise error + + def agree_across_ranks( error: BaseException | None, what: str, *, group: dist.ProcessGroup | None = None ) -> None: @@ -290,14 +317,19 @@ def agree_across_ranks( Every rank passes the error its own part of ``what`` raised, or ``None``. A rank with an error re-raises it; when any rank has one, every other rank raises a ``RuntimeError`` naming the ranks that failed, so no rank is left - waiting in a later collective for a rank that has raised. Without an - initialized process group, ``error`` is raised if set. + waiting in a later collective for a rank that has raised. If the all-reduce + itself raises, as on a rank that waited in it past the group's timeout or on + an interrupt such as ``KeyboardInterrupt``, a rank with an error still + re-raises its own, with the all-reduce's failure in a note, not chained to + it, and a rank without one raises the all-reduce's failure with a note + naming ``what`` (see ``run_keeping_own_error``). Without an initialized + process group, ``error`` is raised if set. """ failed: list[int] = [] if dist.is_initialized(): flags = torch.zeros(dist.get_world_size(group), dtype=torch.int32) flags[dist.get_rank(group)] = int(error is not None) - dist.all_reduce(flags, group=group) + run_keeping_own_error(lambda: dist.all_reduce(flags, group=group), error, what) failed = flags.nonzero().flatten().tolist() if error is not None: raise error diff --git a/kempnerforge/training/data_pipeline.py b/kempnerforge/training/data_pipeline.py index 1cb062fa5..fab25643f 100644 --- a/kempnerforge/training/data_pipeline.py +++ b/kempnerforge/training/data_pipeline.py @@ -242,6 +242,11 @@ def _phase_weights(phase: TrainingPhase, base: dict[str, float], names: list[str return [phase.dataset_weights.get(name, base[name]) for name in names] +def _phase_refusal(phase: TrainingPhase, error: ValueError) -> ValueError: + """The mixture sampler's refusal ``error`` of ``phase``'s weights, naming the phase.""" + return ValueError(f"Data phase at step {phase.start_step}: {error}") + + def _build_mixture_pipeline( config: JobConfig, dp_rank: int, dp_size: int, eos_token_id: int | None ) -> DataPipeline: @@ -250,6 +255,10 @@ def _build_mixture_pipeline( The sampler is built with the weights a data phase at step 0 sets, if one does, so such a phase can turn off a source the sampler would refuse to weight; ``build_phase_state`` checks every phase's weights before training. + + Raises: + ValueError: The sampler refuses the weights it is built with; the message + names the data phase at step 0 when that phase set them. """ tc = config.train @@ -287,16 +296,21 @@ def _build_mixture_pipeline( mixture_dataset = MixtureDataset(sub_datasets, names) base: dict[str, float] = dict(zip(names, weights, strict=True)) first = next((phase for phase in _configured_phases(config) if phase.start_step == 0), None) - sampler = MixtureSampler( - cumulative_sizes=mixture_dataset.cumulative_sizes, - weights=weights if first is None else _phase_weights(first, base, names), - num_replicas=dp_size, - rank=dp_rank, - shuffle=True, - seed=tc.effective_data_seed, - temperature=config.data.mix_temperature, - names=names, - ) + try: + sampler = MixtureSampler( + cumulative_sizes=mixture_dataset.cumulative_sizes, + weights=weights if first is None else _phase_weights(first, base, names), + num_replicas=dp_size, + rank=dp_rank, + shuffle=True, + seed=tc.effective_data_seed, + temperature=config.data.mix_temperature, + names=names, + ) + except ValueError as error: + if first is None: + raise + raise _phase_refusal(first, error) from error dataloader = StatefulDataLoader( mixture_dataset, batch_size=tc.batch_size, @@ -423,10 +437,13 @@ def __call__( phases need ``mixture_dataset``, ``mixture_sampler`` and ``mixture_weights``. Build the sampler with the weights a data phase at step 0 sets, if one does: ``MixtureSampler`` refuses a positive weight on - a sub-dataset that gives no rank a sample, and ``build_phase_state`` - checks every phase's weights against it before training. A resume - restores the loader's position only if it has ``state_dict`` and - ``load_state_dict``. + a sub-dataset that gives no rank a sample, and ``check_phase_weights`` + checks every phase's weights against it before training. An error the + builder raises, or either refusal, on any rank fails ``run_training`` + on every rank before training, unless the builder runs a collective of + its own that a failing rank never enters: the other ranks then wait in + it until its timeout. A resume restores the loader's position only if + it has ``state_dict`` and ``load_state_dict``. """ ... @@ -562,11 +579,12 @@ def build_phase_state(config: JobConfig, data: DataPipeline, step: int) -> Phase """Resolve data-annealing phases and apply each one active at ``step``, the run's first. On a mixture, every phase's weights are first checked against the sampler, whichever - builder made it, so weights it would refuse stop the run before training, also for a - phase that starts after ``max_steps``. Every phase with ``start_step <= step`` is then - applied in order, so a phase at step 0 sets the ``lr_scale``, and on a mixture the - sampler weights, the first step of a fresh run uses, and a resume re-derives the phase - it stopped in. The ``lr_scale`` applies with or without a mixture. + builder made it (``check_phase_weights``), so weights it would refuse stop the run before + training, also for a phase that starts after ``max_steps``. Every phase with + ``start_step <= step`` is then applied in order, so a phase at step 0 sets the + ``lr_scale``, and on a mixture the sampler weights, the first step of a fresh run uses, + and a resume re-derives the phase it stopped in. The ``lr_scale`` applies with or without + a mixture. Raises: ValueError: The sampler refuses a phase's weights; the message names its @@ -579,7 +597,7 @@ def build_phase_state(config: JobConfig, data: DataPipeline, step: int) -> Phase original_weights=dict(data.mixture_weights), temperature=config.data.mix_temperature, ) - _check_phase_weights(state, data) + check_phase_weights(config, data) for i, phase in enumerate(phases): if step >= phase.start_step: @@ -593,17 +611,26 @@ def build_phase_state(config: JobConfig, data: DataPipeline, step: int) -> Phase return state -def _check_phase_weights(state: PhaseState, data: DataPipeline) -> None: - """Refuse a phase whose weights ``data``'s mixture sampler refuses, naming its start.""" +def check_phase_weights(config: JobConfig, data: DataPipeline) -> None: + """Refuse a data phase whose weights ``data``'s mixture sampler refuses; change nothing. + + Every phase ``config`` sets is checked with ``MixtureSampler.check_weights``, also one + that starts after ``max_steps``, whichever builder made the sampler. A pipeline without + a mixture is not checked. + + Raises: + ValueError: The sampler refuses a phase's weights; the message names its + ``start_step``. + """ mixture, sampler = data.mixture_dataset, data.mixture_sampler if mixture is None or sampler is None: return - for phase in state.phases: - weights = _phase_weights(phase, state.original_weights, mixture.dataset_names) + for phase in _configured_phases(config): + weights = _phase_weights(phase, data.mixture_weights, mixture.dataset_names) try: sampler.check_weights(weights) except ValueError as error: - raise ValueError(f"Data phase at step {phase.start_step}: {error}") from error + raise _phase_refusal(phase, error) from error def _apply_phase(phase: TrainingPhase, state: PhaseState, data: DataPipeline) -> bool: diff --git a/kempnerforge/training/entry.py b/kempnerforge/training/entry.py index dfdf8a138..acb932cf8 100644 --- a/kempnerforge/training/entry.py +++ b/kempnerforge/training/entry.py @@ -46,9 +46,11 @@ from kempnerforge.resilience.signal_handler import ShutdownHandler, resolve_shutdown_timeouts from kempnerforge.training.data_pipeline import ( DataFn, + DataPipeline, build_data_pipeline, build_eval_dataloader, build_phase_state, + check_phase_weights, ) from kempnerforge.training.freeze import ( apply_freeze_specs, @@ -267,6 +269,45 @@ def _mot_text_warm_start( logger.info(f"MoT warm-start: copied dense block weights from {vlm_cfg.mot_warm_start_path}") +def _agreed_data_pipeline( + config: JobConfig, + runtime: RuntimeContext, + data_fn: DataFn, + tokens_per_image: int | None, + agree: Callable[[BaseException | None, str], None], +) -> DataPipeline: + """This rank's training data pipeline from ``data_fn``, once every rank has built its own. + + ``agree`` is the checkpoint manager's rank agreement. Every rank reports whether its build + succeeded with the data-parallel partition ``get_dp_info(runtime.device_mesh)`` gives it + and a mixture sampler that takes every data phase's weights (``check_phase_weights``) + before any rank goes on, so no rank is left waiting in the training loop's first + collective, until the process-group timeout, for a rank whose build failed. + + Raises: + Exception: On a rank whose ``data_fn`` raised, that error; ``ValueError`` on one whose + pipeline records another partition or whose sampler refuses a phase's weights. + RuntimeError: On every other rank, naming the ranks that failed. + """ + data: DataPipeline | None = None + error: Exception | None = None + try: + data = data_fn(config, runtime, tokens_per_image=tokens_per_image) + expected = get_dp_info(runtime.device_mesh) + if (data.dp_rank, data.dp_size) != expected: + raise ValueError( + f"data_fn returned dp_rank={data.dp_rank}, dp_size={data.dp_size}, but this " + f"rank's data-parallel partition is dp_rank={expected[0]}, " + f"dp_size={expected[1]} (get_dp_info(runtime.device_mesh))" + ) + check_phase_weights(config, data) + except Exception as exc: + error = exc + agree(error, "Data pipeline build") + assert data is not None + return data + + def _resume_path_on_rank_zero(checkpoint_dir: str, num_stages: int | None) -> Path | None: """``resolve_resume_path`` on rank 0, broadcast to every rank with any error it raised. @@ -496,7 +537,10 @@ def run_training( All default to what ``scripts/train.py`` uses; ``data_fn`` is called as ``build_data_pipeline`` is, after the model is built, so it receives the model's ``tokens_per_image`` on a packed or multi-image VLM run, and must - follow the ``DataFn`` contract. A custom + follow the ``DataFn`` contract. Every rank reports whether its data pipeline + built, with a sampler that takes every data phase's weights, before any rank + applies a saved data position, so a build that fails on one rank fails the + run on every rank, the others with an error naming it. A custom ``step_fn`` must run its forward and loss under ``session.autocast()``, which casts fp32 master weights to the compute dtype when no FSDP2 wrap does (one GPU, a pp-only mesh). @@ -555,14 +599,9 @@ def run_training( laid_out = config.data.pack_sequences or config.data.hf_max_images != 1 tokens_per_image = packed_tokens_per_image(model) if config.is_vlm and laid_out else None - data = (data_fn or build_data_pipeline)(config, runtime, tokens_per_image=tokens_per_image) - expected = get_dp_info(runtime.device_mesh) - if (data.dp_rank, data.dp_size) != expected: - raise ValueError( - f"data_fn returned dp_rank={data.dp_rank}, dp_size={data.dp_size}, but this " - f"rank's data-parallel partition is dp_rank={expected[0]}, " - f"dp_size={expected[1]} (get_dp_info(runtime.device_mesh))" - ) + data = _agreed_data_pipeline( + config, runtime, data_fn or build_data_pipeline, tokens_per_image, ckpt_mgr.agree + ) if data.dataloader is not None: ckpt_mgr.apply_dataloader_state(data.dataloader) diff --git a/tests/gloo_ranks.py b/tests/gloo_ranks.py index f4822be77..28055c354 100644 --- a/tests/gloo_ranks.py +++ b/tests/gloo_ranks.py @@ -215,6 +215,13 @@ def write_outcome(out_dir: str | Path, rank: int, outcome: str) -> None: Path(out_dir, "outcome", f"rank{rank}").write_text(outcome) +def wait_for_outcome(out_dir: str | Path, rank: int) -> None: + """Return once ``rank`` has written its outcome, so this rank acts only after that rank has + left the timed part.""" + while not Path(out_dir, "outcome", f"rank{rank}").exists(): + time.sleep(0.1) + + def _ranks(directory: Path) -> set[int]: """The ranks that left a ``rank{N}`` file in ``directory``.""" return {int(p.name[4:]) for p in directory.iterdir() if p.name.startswith("rank")} diff --git a/tests/unit/test_checkpoint.py b/tests/unit/test_checkpoint.py index 1b7727409..83aef9837 100644 --- a/tests/unit/test_checkpoint.py +++ b/tests/unit/test_checkpoint.py @@ -3126,6 +3126,9 @@ def _no_space(*args: object, **kwargs: object) -> None: raise OSError(28, "No space left on device") +TIMED_OUT = "Timed out waiting 5000ms for recv operation to complete" + + class TestAFailedSaveCommitsNothing: """A part of a save that raises reaches the caller, and that save is never committed.""" @@ -3359,6 +3362,62 @@ def rank_one_failed(flags: torch.Tensor, group: object = None) -> None: assert (tmp_path / "latest").resolve() == (tmp_path / "step_1").resolve() assert not mgr.has_pending_save + def _save_step_2_as_its_agreement_fails(self, tmp_path, monkeypatch, flush_error=None): + """Save step 1 as rank 0 of two, then have the all-reduce of the agreement before step + 2's write, the first collective of that save, raise as on a rank that waited in it past + the group's timeout. ``flush_error`` fails step 1's flush. + + Returns the manager, the checkpoint ids the saves were dispatched to, and the failure. + """ + mgr = self._mgr(tmp_path, AsyncCheckpointMode.async_) + dispatched = self._flushes(monkeypatch, flush_error) + _fake_world_of_two(mgr, monkeypatch) + mgr.save(step=1) + failure = RuntimeError(TIMED_OUT) + + def all_reduce(flags: torch.Tensor, group: object = None) -> None: + raise failure + + monkeypatch.setattr("kempnerforge.checkpoint.manager.dist.all_reduce", all_reduce) + return mgr, dispatched, failure + + @pytest.mark.parametrize("failed", ["its_part", "its_flush"]) + def test_a_rank_whose_part_failed_keeps_its_error_when_the_agreement_fails( + self, tmp_path, monkeypatch, failed + ): + """The agreement before step 2's write fails. The rank still raises what its part of + the save raised, the error creating its step directory or the one its flush of step 1 + ended with, with the all-reduce's failure in a note. Step 2 is never dispatched, and + step 1 not committed.""" + flush_error = OSError(5, "Input/output error") if failed == "its_flush" else None + mgr, dispatched, _ = self._save_step_2_as_its_agreement_fails( + tmp_path, monkeypatch, flush_error + ) + if failed == "its_part": + self._no_space_for(monkeypatch, "step_2") + with pytest.raises(OSError) as raised: + mgr.save(step=2) + assert raised.value.errno == (5 if failed == "its_flush" else 28) + assert raised.value.__notes__ == [ + f"Checkpoint save could not be agreed across ranks: RuntimeError: {TIMED_OUT}" + ] + assert dispatched == [str(tmp_path / "step_1")] + assert not (tmp_path / "latest").exists() + + def test_a_rank_whose_part_succeeded_names_the_save_when_the_agreement_fails( + self, tmp_path, monkeypatch + ): + """The agreement before step 2's write fails on a rank whose part of the save + succeeded: it raises the all-reduce's failure, with a note naming the save.""" + mgr, dispatched, failure = self._save_step_2_as_its_agreement_fails(tmp_path, monkeypatch) + with pytest.raises(RuntimeError) as raised: + mgr.save(step=2) + assert raised.value is failure + assert failure.__notes__ == [ + "Checkpoint save succeeded on this rank but could not be agreed across ranks" + ] + assert dispatched == [str(tmp_path / "step_1")] + def test_a_failed_part_after_a_failed_flush_raises_the_part_and_logs_the_flush( self, tmp_path, monkeypatch ): @@ -6382,6 +6441,52 @@ def test_a_rank_that_cannot_read_its_index_still_reports_before_raising( manager.load(path=str(step_dir)) assert self._past_the_path(calls) == [("all_reduce", "GLOO_GROUP", [[0, 1], [0, 0]])] + @staticmethod + def _all_reduce_fails(monkeypatch) -> RuntimeError: + """Make every all-reduce raise the returned error, as on a rank that waited in it past + the group's timeout.""" + import kempnerforge.checkpoint.manager as mgr_mod + + failure = RuntimeError(TIMED_OUT) + + def all_reduce(flags, group=None): + raise failure + + monkeypatch.setattr(mgr_mod.dist, "all_reduce", all_reduce) + return failure + + def test_a_rank_that_cannot_read_its_index_keeps_its_error_when_the_all_reduce_fails( + self, tmp_path, monkeypatch + ): + """The all-reduce itself raises: the rank still raises its read's error, with the + all-reduce's failure in a note.""" + step_dir = self._save(tmp_path, "adamw", DEFAULT_SCOPE) + (step_dir / ".metadata").unlink() + _, _, manager = self._resume(tmp_path, "adamw", DEFAULT_SCOPE) + self._as_rank(monkeypatch, manager, 1) + self._all_reduce_fails(monkeypatch) + with pytest.raises(FileNotFoundError) as raised: + manager.load(path=str(step_dir)) + assert raised.value.__notes__ == [ + f"Checkpoint load could not be agreed across ranks: RuntimeError: {TIMED_OUT}" + ] + + def test_a_rank_that_read_its_index_names_the_load_when_the_all_reduce_fails( + self, tmp_path, monkeypatch + ): + """The all-reduce itself raises on a rank whose read succeeded: it raises that failure, + with a note naming the load.""" + self._save(tmp_path, "adamw", DEFAULT_SCOPE) + _, _, manager = self._resume(tmp_path, "adamw", DEFAULT_SCOPE) + self._as_rank(monkeypatch, manager, 0) + failure = self._all_reduce_fails(monkeypatch) + with pytest.raises(RuntimeError) as raised: + manager.load() + assert raised.value is failure + assert failure.__notes__ == [ + "Checkpoint load succeeded on this rank but could not be agreed across ranks" + ] + def test_a_single_process_raises_its_own_read_failure(self, tmp_path): """Without a process group a failed read of the DCP index raises as it is.""" step_dir = self._save(tmp_path, "adamw", DEFAULT_SCOPE) diff --git a/tests/unit/test_checkpoint_load_checks.py b/tests/unit/test_checkpoint_load_checks.py index 167c11818..b2ec7b10f 100644 --- a/tests/unit/test_checkpoint_load_checks.py +++ b/tests/unit/test_checkpoint_load_checks.py @@ -46,6 +46,7 @@ TOKENS = 96 GROUP_TIMEOUT_S = 30 COMPARISON_FAILURE = "cannot compare the saved sizes" +TIMED_OUT = "Timed out waiting 5000ms for recv operation to complete" EXTRA = r"holds \d+ model tensors this run's model does not have, such as \['model\.layers\.2\." OVERRIDE = r"checkpoint\.ignore_extra_model_tensors = true" @@ -247,6 +248,94 @@ def _failing_comparison(_held, _saved): raise TypeError(COMPARISON_FAILURE) +def _as_rank_0_of_two(monkeypatch, manager: CheckpointManager, failing: str) -> RuntimeError: + """Run ``manager`` as rank 0 of two, whose ``failing`` collective of the model check raises + the returned error, as on a rank that waited in it past the group's timeout. + + ``failing`` is ``"gather"``, the gather of every rank's model entries, or ``"broadcast"``, + rank 0's broadcast of its verdict; before that broadcast the gather hands rank 0 its own + entries for both ranks. Every other collective finds nothing amiss. + """ + failure = RuntimeError(TIMED_OUT) + + def gather_object(obj, object_gather_list=None, dst=0, group=None): + if failing == "gather": + raise failure + object_gather_list[:] = [obj, obj] + + def broadcast_object_list(objects, src, group=None): + if failing == "broadcast" and group is not None: + raise failure + + monkeypatch.setattr(manager_module.dist, "is_initialized", lambda: True) + monkeypatch.setattr(manager_module.dist, "get_rank", lambda group=None: 0) + monkeypatch.setattr(manager_module.dist, "get_world_size", lambda group=None: 2) + monkeypatch.setattr(manager_module.dist, "all_reduce", lambda flags, group=None: None) + monkeypatch.setattr(manager_module.dist, "gather_object", gather_object) + monkeypatch.setattr(manager_module.dist, "broadcast_object_list", broadcast_object_list) + manager._sync_group = "GLOO_GROUP" + return failure + + +class TestACollectiveOfTheModelCheckThatFails: + """A collective of the model check raises: a rank with an error of its own, rank 0's + refusal of the checkpoint among them, still raises it, with the collective's failure in a + note, and a rank without one raises that failure, with a note naming the load.""" + + NOTE = f"Checkpoint load could not be agreed across ranks: RuntimeError: {TIMED_OUT}" + + def test_a_rank_that_cannot_list_its_entries_keeps_its_error_when_the_gather_fails( + self, tmp_path, monkeypatch + ): + _save(tmp_path) + _, _, manager = _run(tmp_path) + _as_rank_0_of_two(monkeypatch, manager, "gather") + listing = ValueError("duplicated flatten key model.a.b") + + def fail(*_args): + raise listing + + monkeypatch.setattr(manager_module, "_held_model_entries", fail) + with pytest.raises(ValueError) as caught: + manager.load() + assert caught.value is listing + assert listing.__notes__ == [self.NOTE] + + def test_a_comparison_that_fails_keeps_its_error_when_the_broadcast_fails( + self, tmp_path, monkeypatch + ): + _save(tmp_path) + _, _, manager = _run(tmp_path) + _as_rank_0_of_two(monkeypatch, manager, "broadcast") + monkeypatch.setattr(manager_module, "_model_misfit", _failing_comparison) + with pytest.raises(TypeError, match=COMPARISON_FAILURE) as caught: + manager.load() + assert caught.value.__notes__ == [self.NOTE] + + def test_rank_0_keeps_its_refusal_when_the_broadcast_fails(self, tmp_path, monkeypatch): + _save(tmp_path) + model, _, manager = _run(tmp_path, replace(MODEL, n_layers=2)) + before = _snapshot(model) + _as_rank_0_of_two(monkeypatch, manager, "broadcast") + with pytest.raises(ValueError, match=rf"step_{STEP} {EXTRA}") as caught: + manager.load() + assert caught.value.__notes__ == [self.NOTE] + assert _holds(model, before) + + def test_a_check_that_found_nothing_names_the_load_when_the_broadcast_fails( + self, tmp_path, monkeypatch + ): + _save(tmp_path) + _, _, manager = _run(tmp_path) + failure = _as_rank_0_of_two(monkeypatch, manager, "broadcast") + with pytest.raises(RuntimeError) as caught: + manager.load() + assert caught.value is failure + assert failure.__notes__ == [ + "Checkpoint load succeeded on this rank but could not be agreed across ranks" + ] + + class _ExtraState(torch.nn.Module): """A module whose extra state is a dict of tensors of the given sizes, which DCP stores as one entry per tensor.""" diff --git a/tests/unit/test_checkpoint_per_rank.py b/tests/unit/test_checkpoint_per_rank.py index 5f02e2166..7cc6739a8 100644 --- a/tests/unit/test_checkpoint_per_rank.py +++ b/tests/unit/test_checkpoint_per_rank.py @@ -716,6 +716,60 @@ def test_an_envelope_that_cannot_be_built_reaches_the_agreement(self, tmp_path, assert not (tmp_path / "step_1" / "train_state.pt").exists() assert not (tmp_path / "latest").exists() + @staticmethod + def _gather_fails(m) -> RuntimeError: + """Make the gather raise the returned error, as on a rank that waited in it past the + group's timeout.""" + failure = RuntimeError("Timed out waiting 5000ms for recv operation to complete") + + def fake_all_gather(obj_list, obj, group=None): + raise failure + + m.setattr(mgr_mod.dist, "all_gather_object", fake_all_gather) + return failure + + @pytest.mark.parametrize( + ("failed", "own"), + [("its_capture", "cursor unavailable"), ("its_write", "No space left on device")], + ) + def test_a_rank_whose_part_failed_keeps_its_error_when_the_gather_fails( + self, tmp_path, monkeypatch, failed, own + ): + """The gather itself raises. A rank whose loader raised, or whose write of the shards + did before the gather, still raises that error, with the gather's failure in a note, + and no ``train_state.pt`` is written.""" + with monkeypatch.context() as m: + _install_capture_world(m, 0, failing=set(), events=[]) + failure = self._gather_fails(m) + mgr = _mock_mgr(tmp_path, m) + if failed == "its_write": + mgr._async_ckpt.save.side_effect = OSError(28, own) + loader = _BrokenLoader() if failed == "its_capture" else None + with pytest.raises(OSError, match=own) as raised: + mgr.save(step=1, dataloader=loader) + + assert raised.value.__notes__ == [ + f"Checkpoint save could not be agreed across ranks: RuntimeError: {failure}" + ] + assert not (tmp_path / "step_1" / "train_state.pt").exists() + + def test_a_rank_whose_part_succeeded_names_the_save_when_the_gather_fails( + self, tmp_path, monkeypatch + ): + """The gather itself raises on a rank whose part of the save succeeded: it raises that + failure, with a note naming the save.""" + with monkeypatch.context() as m: + _install_capture_world(m, 0, failing=set(), events=[]) + failure = self._gather_fails(m) + mgr = _mock_mgr(tmp_path, m) + with pytest.raises(RuntimeError) as raised: + mgr.save(step=1) + + assert raised.value is failure + assert failure.__notes__ == [ + "Checkpoint save succeeded on this rank but could not be agreed across ranks" + ] + class TestFourRankSaveLoad: def test_each_rank_restores_its_own_loader_and_rng(self, tmp_path, monkeypatch): diff --git a/tests/unit/test_distributed.py b/tests/unit/test_distributed.py index 315f24f51..e798215fe 100644 --- a/tests/unit/test_distributed.py +++ b/tests/unit/test_distributed.py @@ -8,6 +8,7 @@ import pytest import torch +import torch.distributed as dist from torch.distributed.tensor import Replicate from torch.distributed.tensor.parallel import ColwiseParallel, RowwiseParallel, SequenceParallel @@ -17,7 +18,7 @@ from kempnerforge.distributed.pipeline_parallel import PipelineStageModule from kempnerforge.distributed.setup import _detect_ib_interface, _set_nccl_env, get_world_info from kempnerforge.distributed.tensor_parallel import _build_block_tp_plan -from kempnerforge.distributed.utils import clip_grad_norm_ +from kempnerforge.distributed.utils import agree_across_ranks, clip_grad_norm_ from kempnerforge.model.moma import MoMaBlock from kempnerforge.model.transformer import Transformer, TransformerBlock @@ -59,6 +60,88 @@ def test_no_grads_returns_zero(self): assert norm.item() == 0.0 +class TestAgreeAcrossRanks: + """``agree_across_ranks`` when its all-reduce raises, as it does on a rank that waited in it + past the group's timeout.""" + + TIMED_OUT = "Timed out waiting 5000ms for send operation to complete" + + @staticmethod + def _all_reduce_raises(monkeypatch, failure: BaseException) -> None: + """Make this rank 0 of 2 in a process group whose all-reduce raises ``failure``.""" + + def all_reduce(tensor, group=None): + raise failure + + monkeypatch.setattr(dist, "is_initialized", lambda: True) + monkeypatch.setattr(dist, "get_world_size", lambda group=None: 2) + monkeypatch.setattr(dist, "get_rank", lambda group=None: 0) + monkeypatch.setattr(dist, "all_reduce", all_reduce) + + @pytest.fixture + def collective_error(self, monkeypatch) -> RuntimeError: + """Make this rank 0 of 2 in a process group whose all-reduce raises the returned error.""" + error = RuntimeError(self.TIMED_OUT) + self._all_reduce_raises(monkeypatch, error) + return error + + def test_a_rank_with_an_error_raises_it_noting_the_failure(self, collective_error): + error = OSError(28, "No space left on device") + with pytest.raises(OSError) as raised: + agree_across_ranks(error, "Checkpoint save") + assert raised.value is error + assert error.__notes__ == [ + f"Checkpoint save could not be agreed across ranks: RuntimeError: {self.TIMED_OUT}" + ] + assert error.__cause__ is None + assert error.__context__ is None + + def test_a_rank_without_an_error_raises_the_failure_naming_what(self, collective_error): + with pytest.raises(RuntimeError) as raised: + agree_across_ranks(None, "Checkpoint save") + assert raised.value is collective_error + assert collective_error.__notes__ == [ + "Checkpoint save succeeded on this rank but could not be agreed across ranks" + ] + + def test_an_error_keeps_the_cause_it_already_has(self, collective_error): + cause = ValueError("weights must sum to > 0") + error = ValueError("Data phase at step 0: weights must sum to > 0") + error.__cause__ = cause + with pytest.raises(ValueError) as raised: + agree_across_ranks(error, "Data pipeline build") + assert raised.value is error + assert error.__cause__ is cause + assert error.__notes__ == [ + f"Data pipeline build could not be agreed across ranks: RuntimeError: {self.TIMED_OUT}" + ] + + def test_an_interrupt_still_raises_the_ranks_own_error(self, monkeypatch): + self._all_reduce_raises(monkeypatch, KeyboardInterrupt()) + cause = ValueError("weights must sum to > 0") + error = ValueError("Data phase at step 0: weights must sum to > 0") + error.__cause__ = cause + with pytest.raises((ValueError, KeyboardInterrupt)) as raised: + agree_across_ranks(error, "Data pipeline build") + assert raised.value is error + assert error.__cause__ is cause + assert error.__notes__ == [ + "Data pipeline build could not be agreed across ranks: KeyboardInterrupt" + ] + + def test_a_failure_python_prints_on_several_lines_is_noted_whole(self, monkeypatch): + failure = SyntaxError("bad syntax", ("generated.py", 3, 1, "x =\n")) + self._all_reduce_raises(monkeypatch, failure) + error = OSError(28, "No space left on device") + with pytest.raises(OSError) as raised: + agree_across_ranks(error, "Checkpoint save") + assert raised.value is error + (note,) = error.__notes__ + assert note.startswith("Checkpoint save could not be agreed across ranks: ") + assert 'File "generated.py", line 3' in note + assert note.endswith("\nSyntaxError: bad syntax") + + class TestBuildBlockTPPlan: def test_plan_with_sequence_parallel(self): """Plan should include SequenceParallel for norms and Shard(1) layouts.""" diff --git a/tests/unit/test_pipeline_checkpoint.py b/tests/unit/test_pipeline_checkpoint.py index 488c4cced..30dbce566 100644 --- a/tests/unit/test_pipeline_checkpoint.py +++ b/tests/unit/test_pipeline_checkpoint.py @@ -29,11 +29,19 @@ from kempnerforge.model.transformer import Transformer from kempnerforge.training.entry import build_checkpoint_manager, restore_checkpoint from kempnerforge.training.runtime import PipelineBundle, RuntimeContext -from tests.gloo_ranks import gloo_group, mark, run_to_outcomes, spawn, write_outcome +from tests.gloo_ranks import ( + gloo_group, + mark, + run_to_outcomes, + spawn, + wait_for_outcome, + write_outcome, +) MODEL = ModelConfig(dim=32, n_layers=4, n_heads=4, vocab_size=64, max_seq_len=16) STEP = 3 TOKENS = 96 +AGREEMENT_TIMEOUT_S = 5 def _stage_members(rank: int, shape: tuple[int, ...], names: tuple[str, ...]) -> list[int]: @@ -323,6 +331,34 @@ def _outcomes( ) +def _check_a_save_whose_agreement_times_out( + rank: int, world: int, port: int, ckpt_dir: str, out_dir: str +) -> None: + """The last rank cannot create the step directory, and rank 0 starts its save only once the + last rank has written its outcome, so the last rank's wait in the agreement before the write + runs past the manager group's ``AGREEMENT_TIMEOUT_S`` first. Writes how ``save`` ended on + this rank: a line for the error and one for each of its notes. + """ + with gloo_group(rank, world, port): + mesh = init_device_mesh("cpu", (world,), mesh_dim_names=("dp_shard",)) + config, runtime, pipeline = _job(rank, world, mesh, ckpt_dir, AsyncCheckpointMode.disabled) + config.distributed.nccl_timeout_sec = AGREEMENT_TIMEOUT_S + stage = _stage(mesh, seed=0) + manager = build_checkpoint_manager( + config, runtime, stage, _stepped_optimizer(stage), pipeline + ) + _fail_part(rank, world, "mkdir") + mark(out_dir, rank) + if rank == 0: + wait_for_outcome(out_dir, world - 1) + try: + manager.save(STEP, tokens_seen=TOKENS) + outcome = "returned" + except BaseException as e: + outcome = "\n".join([f"{type(e).__name__}: {e}", *getattr(e, "__notes__", ())]) + write_outcome(out_dir, rank, outcome) + + def _assert_every_rank_raised(outcomes: dict[int, str], failed: list[int]) -> None: """The ranks in ``failed`` raised the failure itself, every other rank an error naming them.""" for rank, outcome in outcomes.items(): @@ -496,6 +532,28 @@ def test_a_failure_before_the_write_stops_every_rank_before_it( assert [p for p in (tmp_path / "ckpt").rglob("*") if p.is_file()] == [] assert not (tmp_path / "ckpt" / "latest").is_symlink() + def test_the_failed_rank_raises_its_own_error_when_the_agreement_times_out(self, tmp_path): + """The last rank cannot create the step directory, and rank 0 enters the agreement + before the write only once the last rank's wait in it has timed out. The last rank + still raises its own error, with the agreement's failure in a note, and rank 0's error + notes the save that could not be agreed. No rank writes a file.""" + outcomes = run_to_outcomes( + _check_a_save_whose_agreement_times_out, + 2, + (str(tmp_path / "ckpt"),), + tmp_path / "outcomes", + part="save() with rank 0 late to the agreement before the write", + part_s=45, + ) + assert outcomes[1].startswith( + "OSError: [Errno 28] No space left on device\n" + "Checkpoint save could not be agreed across ranks: " + ), outcomes[1] + assert outcomes[0].endswith( + "\nCheckpoint save succeeded on this rank but could not be agreed across ranks" + ), outcomes[0] + assert [p for p in (tmp_path / "ckpt").rglob("*") if p.is_file()] == [] + @pytest.mark.parametrize( ("shape", "names", "async_mode"), [ diff --git a/tests/unit/test_train_entry.py b/tests/unit/test_train_entry.py index b4fb36ef8..171a53160 100644 --- a/tests/unit/test_train_entry.py +++ b/tests/unit/test_train_entry.py @@ -12,6 +12,7 @@ import json import math from collections.abc import Iterator +from datetime import timedelta from pathlib import Path from typing import Any @@ -47,10 +48,14 @@ vlm_step, ) from kempnerforge.training.runtime import RuntimeContext +from tests.gloo_ranks import gloo_group, mark, run_to_outcomes, wait_for_outcome, write_outcome from tests.loader_workers import worker_sockets_fit VOCAB = 16 DIM = 8 +DATA_PG_TIMEOUT_S = 30 +DATA_BUILD_DEADLINE_S = 15 +AGREEMENT_TIMEOUT_S = 5 def _fake_batches(n: int) -> list[dict[str, torch.Tensor]]: @@ -83,6 +88,7 @@ def __init__(self) -> None: self.write_ended = False self.restored_extra: dict = {} self.restored_optimizer = False + self.agreements: list[tuple[str, BaseException | None]] = [] self.has_pending_dataloader_state = False self.resumed_step: int | None = None @@ -90,6 +96,12 @@ def __init__(self) -> None: def flushing(self) -> bool: return self.has_pending_save and not self.write_ended + def agree(self, error: BaseException | None, what: str = "Checkpoint save") -> None: + """Record what the ranks agree on; one rank, so its own error is the outcome.""" + self.agreements.append((what, error)) + if error is not None: + raise error + def save(self, step, tokens_seen=0, scheduler=None, dataloader=None, extra=None) -> None: self.saves.append((step, tokens_seen, dict(extra or {}))) @@ -1618,17 +1630,58 @@ def __iter__(self): @pytest.mark.parametrize("partition", [(1, 1), (0, 2)]) def test_a_data_fn_with_another_partition_is_refused(self, monkeypatch, partition): - """A builder whose dp_rank/dp_size differ from the mesh's is refused before training.""" + """A builder whose dp_rank/dp_size differ from the mesh's is refused before training, + through the ranks' agreement on the data build.""" from kempnerforge.training.entry import run_training - _stub_entry(monkeypatch, nn.Linear(4, 4)) + ckpt = _stub_entry(monkeypatch, nn.Linear(4, 4)) rank, size = partition def data_fn(cfg, runtime, *, tokens_per_image=None): return DataPipeline(dp_rank=rank, dp_size=size) - with pytest.raises(ValueError, match=rf"dp_rank={rank}, dp_size={size}, but"): + with pytest.raises(ValueError, match=rf"dp_rank={rank}, dp_size={size}, but") as refused: run_training(_vlm_config(), data_fn=data_fn) + assert ckpt.agreements == [("Data pipeline build", refused.value)] + + def test_the_ranks_agree_on_the_data_build_before_its_loader_state_is_applied( + self, monkeypatch + ): + """The saved loader position is applied only once every rank reported its build.""" + import kempnerforge.training.entry as entry + from kempnerforge.training.entry import run_training + + class Applied(Exception): + pass + + applied: list[tuple[object, list]] = [] + + class Recording(FakeCheckpointManager): + def apply_dataloader_state(self, dataloader) -> None: + applied.append((dataloader, list(self.agreements))) + raise Applied + + _stub_entry(monkeypatch, nn.Linear(4, 4)) + monkeypatch.setattr(entry, "build_checkpoint_manager", lambda *_a, **_k: Recording()) + loader = object() + with pytest.raises(Applied): + run_training( + make_config(), data_fn=lambda _c, _r, **_k: DataPipeline(dataloader=loader) + ) + assert applied == [(loader, [("Data pipeline build", None)])] + + def test_a_data_phase_the_built_sampler_refuses_fails_through_the_agreement(self, monkeypatch): + """The builder's sampler refuses a later phase's weights; that refusal is this rank's + outcome in the ranks' agreement on the data build.""" + from kempnerforge.training.entry import run_training + + ckpt = _stub_entry(monkeypatch, nn.Linear(4, 4)) + config = make_config() + config.data = _tiny_phases() + + with pytest.raises(ValueError, match=r"^Data phase at step 50: Sub-dataset 'tiny'") as no: + run_training(config, data_fn=lambda _c, _r, **_k: _web_and_tiny(0)) + assert ckpt.agreements == [("Data pipeline build", no.value)] def test_defaults_to_the_registry_selected_step_body(self, monkeypatch): from kempnerforge.training.entry import run_training @@ -1975,6 +2028,137 @@ def build_optimizer(_model, _config, module_patterns=None): assert (expected is not None) is vlm +def _tiny_phases() -> DataConfig: + """Data phases that turn source 'tiny' off from step 0 and weight it again from step 50.""" + return DataConfig( + phases=[ + TrainingPhase(start_step=0, dataset_weights={"tiny": 0.0}), + TrainingPhase(start_step=50, dataset_weights={"tiny": 0.5}), + ] + ) + + +def _web_and_tiny(tiny_samples: int) -> DataPipeline: + """A mixture a builder split for this rank itself: 'web' of 50 samples, 'tiny' of + ``tiny_samples``, sampled with the step-0 weight 0 of ``_tiny_phases`` on 'tiny'.""" + from torch.utils.data import TensorDataset + + from kempnerforge.data.dataset import MixtureDataset + from kempnerforge.data.sampler import MixtureSampler + + names = ["web", "tiny"] + sources = [TensorDataset(torch.arange(50)), TensorDataset(torch.arange(tiny_samples))] + mixture = MixtureDataset(sources, names) + sampler = MixtureSampler( + mixture.cumulative_sizes, [1.0, 0.0], num_replicas=1, rank=0, names=names + ) + return DataPipeline( + mixture_dataset=mixture, mixture_sampler=sampler, mixture_weights={"web": 1.0, "tiny": 1.0} + ) + + +def _fail_the_data_on_the_last_rank( + rank: int, world: int, port: int, case: str, ckpt_dir: str, out_dir: str +) -> None: + """Run ``run_training`` on one gloo rank, with a ``data_fn`` that fails on the last rank. + + ``"raises"``: the last rank's ``data_fn`` raises. ``"refuses_a_phase"``: each rank's + ``data_fn`` returns ``_web_and_tiny``, with 'tiny' empty on the last rank only, so only that + rank's sampler refuses the data phase at step 50. ``"agreement_times_out"``: the last rank's + ``data_fn`` raises at once, and every other rank's returns only once the last rank has + written its outcome, so the last rank's wait in the agreement runs past the manager group's + ``AGREEMENT_TIMEOUT_S`` before any other rank enters it. The checkpoint manager and the + restore are real, so the ranks share a real gloo group of the manager's. Writes how + ``run_training`` ended on this rank, a line for the error and one for each of its notes. + """ + with gloo_group(rank, world, port, timeout=timedelta(seconds=DATA_PG_TIMEOUT_S)): + try: + import kempnerforge.training.entry as entry + + config = make_config() + config.checkpoint.dir = ckpt_dir + config.distributed.nccl_timeout_sec = ( + AGREEMENT_TIMEOUT_S if case == "agreement_times_out" else DATA_PG_TIMEOUT_S + ) + runtime = dataclasses.replace(_runtime(), rank=rank, local_rank=rank, world_size=world) + last = rank == world - 1 + if case == "refuses_a_phase": + config.data = _tiny_phases() + + def data_fn(cfg, runtime, *, tokens_per_image=None): + mark(out_dir, rank) + if case == "refuses_a_phase": + return _web_and_tiny(0 if last else 4) + if last: + raise RuntimeError(f"data_fn failed on rank {rank}") + if case == "agreement_times_out": + wait_for_outcome(out_dir, world - 1) + return DataPipeline() + + with pytest.MonkeyPatch.context() as patch: + _stub_entry(patch, TinyTextModel(), real_checkpoints=True) + patch.setattr(entry, "setup_distributed", lambda _config: runtime) + entry.run_training(config, data_fn=data_fn) + outcome = "returned" + except BaseException as e: + outcome = "\n".join([f"{type(e).__name__}: {e}", *getattr(e, "__notes__", ())]) + write_outcome(out_dir, rank, outcome) + + +@pytest.mark.timeout(360) +class TestADataPipelineErrorFailsEveryRank: + """Two gloo ranks run ``run_training``, and only the last rank's data fails. + + The ranks get 240 s to reach the data build, ``DATA_BUILD_DEADLINE_S`` in it, twice + ``AGREEMENT_TIMEOUT_S`` more when the agreement times out, and 60 s to exit; the 360 s + timeout covers all three and the 5 s grace period for stopping the ranks. + """ + + @pytest.mark.parametrize( + ("case", "own_error"), + [ + ("raises", "RuntimeError: data_fn failed on rank 1"), + ("refuses_a_phase", "ValueError: Data phase at step 50: Sub-dataset 'tiny' has no"), + ], + ) + def test_every_rank_raises_well_inside_the_process_group_timeout( + self, tmp_path, case, own_error + ): + """The rank whose data is fine raises an error naming the rank that failed, which + raises its own error, within half the process-group timeout.""" + outcomes = run_to_outcomes( + _fail_the_data_on_the_last_rank, + 2, + (case, str(tmp_path / "ckpt")), + tmp_path / "outcomes", + part="the data pipeline build", + part_s=DATA_BUILD_DEADLINE_S, + ) + assert outcomes[0] == "RuntimeError: Data pipeline build failed on ranks [1]" + assert outcomes[1].startswith(own_error), outcomes[1] + + def test_the_failed_rank_raises_its_own_error_when_the_agreement_times_out(self, tmp_path): + """The last rank's ``data_fn`` raises at once, and the other rank enters the agreement + only once the last rank's wait in it has timed out. The last rank still raises its own + error, with the agreement's failure in a note, and the other rank's error notes the + agreement that failed.""" + outcomes = run_to_outcomes( + _fail_the_data_on_the_last_rank, + 2, + ("agreement_times_out", str(tmp_path / "ckpt")), + tmp_path / "outcomes", + part="the data pipeline build", + part_s=DATA_BUILD_DEADLINE_S + 2 * AGREEMENT_TIMEOUT_S, + ) + assert outcomes[1].startswith( + "RuntimeError: data_fn failed on rank 1\n" + "Data pipeline build could not be agreed across ranks: " + ), outcomes[1] + assert outcomes[0].endswith( + "\nData pipeline build succeeded on this rank but could not be agreed across ranks" + ), outcomes[0] + + def _run_through_nans( monkeypatch, ckpt_dir: Path, nan_steps: set[int], shutdown_after: int | None = None ) -> list[int]: @@ -2321,6 +2505,52 @@ def test_a_small_source_that_a_step_zero_phase_turns_off_builds( assert len(drawn) == len(sampler) assert not any(index < 2 for index in drawn) + @pytest.mark.parametrize( + ("weights", "refusal"), + [ + ({"tiny": 0.5}, r"Sub-dataset 'tiny' has fewer samples \(2\) than data-parallel ranks"), + ({"web": 2.0}, r"Sub-dataset 'tiny' has fewer samples \(2\) than data-parallel ranks"), + ( + {"tiny": 0.0, "web": 0.0}, + r"MixtureSampler\(weights=\.\.\.\): weights must sum to > 0", + ), + ], + ids=["weights_the_small_source", "leaves_it_at_its_base_weight", "zeroes_every_source"], + ) + def test_a_step_zero_phase_whose_weights_the_sampler_refuses_is_named( + self, monkeypatch, tmp_path, weights, refusal + ): + """The sampler, built with a step-0 phase's weights, refuses them on 3 data-parallel + ranks; the error names the phase, as a later phase's does.""" + import kempnerforge.training.data_pipeline as dp + + config = self._small_source_mixture( + tmp_path, phases=[TrainingPhase(start_step=0, dataset_weights=weights)] + ) + monkeypatch.setattr(dp, "get_dp_info", lambda _mesh: (1, 3)) + + with pytest.raises(ValueError, match=rf"^Data phase at step 0: {refusal}"): + dp.build_data_pipeline(config, _runtime()) + + def test_check_phase_weights_checks_every_phase_against_the_built_mixture(self): + """Every configured phase, one at step 0 too, is checked against the sampler a builder + made, and a pipeline without a mixture is not checked.""" + import kempnerforge.training.data_pipeline as dp + + config = make_config() + config.data = _tiny_phases() + dp.check_phase_weights(config, _web_and_tiny(4)) + dp.check_phase_weights(config, DataPipeline()) + + with pytest.raises(ValueError, match=r"^Data phase at step 50: Sub-dataset 'tiny' has no"): + dp.check_phase_weights(config, _web_and_tiny(0)) + + config.data = DataConfig( + phases=[TrainingPhase(start_step=0, dataset_weights={"tiny": 0.5})] + ) + with pytest.raises(ValueError, match=r"^Data phase at step 0: Sub-dataset 'tiny' has no"): + dp.check_phase_weights(config, _web_and_tiny(0)) + @pytest.mark.parametrize( "later", [{"tiny": 0.5}, {"web": 2.0}], ids=["weights_it", "leaves_it_at_its_base_weight"] )