From 0438d52c877dc993bf2e1a3bc8a792d3eb3b2411 Mon Sep 17 00:00:00 2001 From: amazloumi Date: Fri, 4 Dec 2026 20:31:04 -0500 Subject: [PATCH 1/8] Agree on the data build across ranks and name a refused step-0 data phase run_training passes each rank's data pipeline build and partition check to the checkpoint manager's rank agreement before it applies a saved data position. A build that raises on one rank now raises on every rank, the others with an error naming it, instead of leaving them in the training loop's first collective until the process-group timeout. The mixture builder re-raises the sampler's refusal of the weights a data phase at step 0 sets with the "Data phase at step 0: " prefix a later phase's refusal carries. --- codebase-map.json | 6 +- docs/data/sampler.md | 3 +- docs/training/training-loop.md | 5 +- kempnerforge/training/data_pipeline.py | 40 +++++--- kempnerforge/training/entry.py | 54 ++++++++-- tests/unit/test_train_entry.py | 130 ++++++++++++++++++++++++- 6 files changed, 210 insertions(+), 28 deletions(-) diff --git a/codebase-map.json b/codebase-map.json index 0be160a91..019480bfa 100644 --- a/codebase-map.json +++ b/codebase-map.json @@ -1054,7 +1054,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 to the checkpoint manager's agreement before any rank goes on)" ], "tested_by": [ "tests/unit/test_train_entry.py::TestRunTraining", @@ -1067,7 +1068,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": { diff --git a/docs/data/sampler.md b/docs/data/sampler.md index 899950b6e..68abb526b 100644 --- a/docs/data/sampler.md +++ b/docs/data/sampler.md @@ -139,7 +139,8 @@ 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. +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. `build_phase_state` 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 diff --git a/docs/training/training-loop.md b/docs/training/training-loop.md index 719a67f80..071190cdd 100644 --- a/docs/training/training-loop.md +++ b/docs/training/training-loop.md @@ -304,7 +304,10 @@ 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`. + still comes from `build_eval_dataloader`. Every rank reports whether its + training pipeline built, over the checkpoint manager's gloo group, before + any rank goes on, so a build that raises on one rank stops every rank, + the others with an error naming it. The full list with links lives in [Data flow § Startup, once](../architecture/data-flow.md#startup-once). diff --git a/kempnerforge/training/data_pipeline.py b/kempnerforge/training/data_pipeline.py index 1cb062fa5..eba175753 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, @@ -419,7 +433,9 @@ def __call__( The builder shards its own loader over the data-parallel ranks and returns the ``dp_rank`` and ``dp_size`` it used, which must be ``get_dp_info(runtime.device_mesh)``: the loop scales token counts by - ``dp_size``, and ``run_training`` refuses any other pair. Annealing + ``dp_size``, and ``run_training`` refuses any other pair. An error it + raises on any rank, or that refusal, fails ``run_training`` on every + rank before training. Annealing 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 @@ -603,7 +619,7 @@ def _check_phase_weights(state: PhaseState, data: DataPipeline) -> None: 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 6ece83cb4..e3ecba478 100644 --- a/kempnerforge/training/entry.py +++ b/kempnerforge/training/entry.py @@ -46,6 +46,7 @@ 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, @@ -262,6 +263,43 @@ 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 + 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 raised. + + Raises: + Exception: On a rank whose ``data_fn`` raised, that error; ``ValueError`` on one whose + pipeline records another partition. + 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))" + ) + 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. @@ -491,7 +529,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 before any rank applies a saved data position, so a build that raises + 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). @@ -550,14 +591,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/unit/test_train_entry.py b/tests/unit/test_train_entry.py index 06e1f80e9..3a0823a94 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,13 @@ vlm_step, ) from kempnerforge.training.runtime import RuntimeContext +from tests.gloo_ranks import gloo_group, mark, run_to_outcomes, write_outcome from tests.loader_workers import worker_sockets_fit VOCAB = 16 DIM = 8 +DATA_PG_TIMEOUT_S = 30 +DATA_BUILD_DEADLINE_S = 15 def _fake_batches(n: int) -> list[dict[str, torch.Tensor]]: @@ -83,11 +87,18 @@ def __init__(self) -> None: self.write_ended = False self.restored_extra: dict = {} self.restored_optimizer = False + self.agreements: list[tuple[str, BaseException | None]] = [] @property 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 {}))) @@ -1571,17 +1582,45 @@ 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_defaults_to_the_registry_selected_step_body(self, monkeypatch): from kempnerforge.training.entry import run_training @@ -1928,6 +1967,64 @@ def build_optimizer(_model, _config, module_patterns=None): assert (expected is not None) is vlm +def _fail_the_data_on_the_last_rank( + rank: int, world: int, port: int, ckpt_dir: str, out_dir: str +) -> None: + """Run ``run_training`` on one gloo rank, with a ``data_fn`` that raises on the last rank. + + 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. + """ + 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 = DATA_PG_TIMEOUT_S + runtime = dataclasses.replace(_runtime(), rank=rank, local_rank=rank, world_size=world) + + def data_fn(cfg, runtime, *, tokens_per_image=None): + mark(out_dir, rank) + if rank == world - 1: + raise RuntimeError(f"data_fn failed on rank {rank}") + 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 = f"{type(e).__name__}: {e}" + 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_fn`` raises. + + The ranks get 240 s to reach the data build, ``DATA_BUILD_DEADLINE_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. + """ + + def test_every_rank_raises_well_inside_the_process_group_timeout(self, tmp_path): + """The rank whose build succeeded 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, + (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]", + 1: "RuntimeError: data_fn failed on rank 1", + } + + def _run_through_nans( monkeypatch, ckpt_dir: Path, nan_steps: set[int], shutdown_after: int | None = None ) -> list[int]: @@ -2210,6 +2307,33 @@ 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()) + @pytest.mark.parametrize( "later", [{"tiny": 0.5}, {"web": 2.0}], ids=["weights_it", "leaves_it_at_its_base_weight"] ) From b39ecc27debdecbaa7449085d73a34c916e06c96 Mon Sep 17 00:00:00 2001 From: amazloumi Date: Fri, 4 Dec 2026 22:51:09 -0500 Subject: [PATCH 2/8] Agree on every data phase's weights with the data build A builder that splits sources per rank can leave a source too small on some ranks only, so a later data phase's weights could be refused there and nowhere else, after the ranks had agreed on the build. check_phase_weights, the check build_phase_state ran first, is now public, and run_training runs it inside the ranks' agreement on the data build, so that refusal fails every rank too. build_phase_state still runs it. --- codebase-map.json | 3 +- docs/data/sampler.md | 5 +- docs/training/training-loop.md | 9 +-- kempnerforge/training/data_pipeline.py | 43 +++++++----- kempnerforge/training/entry.py | 13 ++-- tests/unit/test_train_entry.py | 96 ++++++++++++++++++++++---- 6 files changed, 127 insertions(+), 42 deletions(-) diff --git a/codebase-map.json b/codebase-map.json index 019480bfa..09b98b9ba 100644 --- a/codebase-map.json +++ b/codebase-map.json @@ -990,6 +990,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": [ @@ -1055,7 +1056,7 @@ "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)", - "_agreed_data_pipeline(config, runtime, data_fn, tokens_per_image, agree) -> DataPipeline (every rank reports its data build to the checkpoint manager's agreement before any rank goes on)" + "_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", diff --git a/docs/data/sampler.md b/docs/data/sampler.md index 68abb526b..0e1edf9ce 100644 --- a/docs/data/sampler.md +++ b/docs/data/sampler.md @@ -141,10 +141,11 @@ 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; weights the sampler refuses there stop the build with an error that names the phase. -`build_phase_state` checks every phase's weights with `check_weights` +`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 071190cdd..8d1537a24 100644 --- a/docs/training/training-loop.md +++ b/docs/training/training-loop.md @@ -304,10 +304,11 @@ 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`. Every rank reports whether its - training pipeline built, over the checkpoint manager's gloo group, before - any rank goes on, so a build that raises on one rank stops every rank, - the others with an error naming it. + 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. The full list with links lives in [Data flow § Startup, once](../architecture/data-flow.md#startup-once). diff --git a/kempnerforge/training/data_pipeline.py b/kempnerforge/training/data_pipeline.py index eba175753..e17225f71 100644 --- a/kempnerforge/training/data_pipeline.py +++ b/kempnerforge/training/data_pipeline.py @@ -433,16 +433,15 @@ def __call__( The builder shards its own loader over the data-parallel ranks and returns the ``dp_rank`` and ``dp_size`` it used, which must be ``get_dp_info(runtime.device_mesh)``: the loop scales token counts by - ``dp_size``, and ``run_training`` refuses any other pair. An error it - raises on any rank, or that refusal, fails ``run_training`` on every - rank before training. Annealing + ``dp_size``, and ``run_training`` refuses any other pair. Annealing 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. A resume restores the loader's position + only if it has ``state_dict`` and ``load_state_dict``. """ ... @@ -578,11 +577,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 @@ -595,7 +595,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: @@ -609,13 +609,22 @@ 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: diff --git a/kempnerforge/training/entry.py b/kempnerforge/training/entry.py index e3ecba478..dc1e2290b 100644 --- a/kempnerforge/training/entry.py +++ b/kempnerforge/training/entry.py @@ -50,6 +50,7 @@ build_data_pipeline, build_eval_dataloader, build_phase_state, + check_phase_weights, ) from kempnerforge.training.freeze import ( apply_freeze_specs, @@ -274,12 +275,13 @@ def _agreed_data_pipeline( ``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 raised. + 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. + 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 @@ -293,6 +295,7 @@ def _agreed_data_pipeline( 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") @@ -530,9 +533,9 @@ def run_training( ``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. Every rank reports whether its data pipeline - built before any rank applies a saved data position, so a build that raises - on one rank fails the run on every rank, the others with an error naming - it. A custom + 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). diff --git a/tests/unit/test_train_entry.py b/tests/unit/test_train_entry.py index 3a0823a94..fabb2fdfe 100644 --- a/tests/unit/test_train_entry.py +++ b/tests/unit/test_train_entry.py @@ -1622,6 +1622,19 @@ def apply_dataloader_state(self, dataloader) -> None: ) 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 @@ -1967,13 +1980,45 @@ 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, ckpt_dir: str, out_dir: str + 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 raises on the last rank. + """Run ``run_training`` on one gloo rank, with a ``data_fn`` that fails on the last rank. - 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. + ``"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. 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. """ with gloo_group(rank, world, port, timeout=timedelta(seconds=DATA_PG_TIMEOUT_S)): try: @@ -1983,10 +2028,15 @@ def _fail_the_data_on_the_last_rank( config.checkpoint.dir = ckpt_dir config.distributed.nccl_timeout_sec = 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 rank == world - 1: + 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}") return DataPipeline() @@ -2002,27 +2052,34 @@ def data_fn(cfg, runtime, *, tokens_per_image=None): @pytest.mark.timeout(360) class TestADataPipelineErrorFailsEveryRank: - """Two gloo ranks run ``run_training``, and only the last rank's ``data_fn`` raises. + """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 and 60 s to exit; the 360 s timeout covers all three and the 5 s grace period for stopping the ranks. """ - def test_every_rank_raises_well_inside_the_process_group_timeout(self, tmp_path): - """The rank whose build succeeded raises an error naming the rank that failed, which + @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, - (str(tmp_path / "ckpt"),), + (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]", - 1: "RuntimeError: data_fn failed on rank 1", - } + assert outcomes[0] == "RuntimeError: Data pipeline build failed on ranks [1]" + assert outcomes[1].startswith(own_error), outcomes[1] def _run_through_nans( @@ -2334,6 +2391,19 @@ def test_a_step_zero_phase_whose_weights_the_sampler_refuses_is_named( 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 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)) + @pytest.mark.parametrize( "later", [{"tiny": 0.5}, {"web": 2.0}], ids=["weights_it", "leaves_it_at_its_base_weight"] ) From a675888e4703ccc0136aa0bf619993e780439929 Mon Sep 17 00:00:00 2001 From: amazloumi Date: Sat, 5 Dec 2026 02:01:09 -0500 Subject: [PATCH 3/8] Agree on the data build across ranks in the assembled-run example build_data mirrors run_training's data phase, which passes each rank's data build and data-phase weight check to the checkpoint manager's rank agreement before it applies a saved data position. build_data now does the same with build_data_pipeline, check_phase_weights and CheckpointManager.agree, so a build that fails on one rank fails the run on every rank instead of leaving the others in a later collective. The partition check run_training applies to a data_fn stays out: the example calls build_data_pipeline, which shards by get_dp_info, and its docstring already states that contract for a builder of your own. build_data's docstring and the README's ordering constraints gain the step, and three tests cover a build error and a refused data phase reaching the agreement, and the agreement coming before apply_dataloader_state. --- examples/assembled_run/README.md | 23 ++++- .../assembled_run/tests/test_assembled_run.py | 93 ++++++++++++++++++- examples/assembled_run/train.py | 25 ++++- 3 files changed, 129 insertions(+), 12 deletions(-) diff --git a/examples/assembled_run/README.md b/examples/assembled_run/README.md index 616ee3d67..a069bef2b 100644 --- a/examples/assembled_run/README.md +++ b/examples/assembled_run/README.md @@ -112,23 +112,34 @@ 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 position and this call applies it. Called before the restore it finds nothing to apply. 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 @@ -180,6 +191,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 4fa7e7a3c..3bceb0be8 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 @@ -187,8 +189,8 @@ def test_without_the_loader_state_a_resume_silently_trains_on_the_first_batches_ assert resumed.losses != full.losses[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 @@ -201,9 +203,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 @@ -304,6 +304,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 e6c2a17e8..2380c90b5 100644 --- a/examples/assembled_run/train.py +++ b/examples/assembled_run/train.py @@ -47,6 +47,7 @@ build_data_pipeline, build_eval_dataloader, build_phase_state, + check_phase_weights, ) from kempnerforge.training.entry import ( build_checkpoint_manager, @@ -196,8 +197,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. Leave it out and the model, optimizer and scheduler still resume, the run still logs that it resumed from @@ -214,7 +225,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) From 9bd19734568913675bb6994fd797386658d376c8 Mon Sep 17 00:00:00 2001 From: amazloumi Date: Sat, 5 Dec 2026 03:45:43 -0500 Subject: [PATCH 4/8] Keep a failed rank's own error when the rank agreement itself fails agree_across_ranks raised the all-reduce's error alone when the all-reduce itself failed, for example with a gloo timeout because a healthy rank's work ran past the group's timeout, so a rank whose own part had failed reported only the timeout. Such a rank now re-raises its own error with the all-reduce's failure in a note, its cause left as it was, and a rank whose part succeeded raises the all-reduce's error with a note naming what the ranks were agreeing on. Every caller gets it, such as the checkpoint manager's agree, which saves, loads, the directory claim, the MoT warm start and the data build use. The success path and the path without a process group are unchanged. The check_phase_weights test gains a refused data phase at step 0, the data-flow startup list gains the data-build agreement, and the DataFn docstring says its promise holds for a builder that runs no collective of its own that a failing rank never enters. --- codebase-map.json | 7 ++- docs/architecture/data-flow.md | 6 +++ kempnerforge/distributed/utils.py | 24 ++++++++-- kempnerforge/training/data_pipeline.py | 6 ++- tests/unit/test_distributed.py | 55 ++++++++++++++++++++++- tests/unit/test_train_entry.py | 61 ++++++++++++++++++++++---- 6 files changed, 141 insertions(+), 18 deletions(-) diff --git a/codebase-map.json b/codebase-map.json index 09b98b9ba..7d72dcffa 100644 --- a/codebase-map.json +++ b/codebase-map.json @@ -1427,10 +1427,12 @@ "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)", + "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, 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" @@ -1990,6 +1992,7 @@ "tests/unit/test_distributed.py": { "classes": [ "TestClipGradNorm(4)", + "TestAgreeAcrossRanks(3)", "TestBuildBlockTPPlan(7)", "TestBuildCrossAttentionTPPlan(3)", "TestDetectIBInterface(5)", @@ -2000,7 +2003,7 @@ "TestBuildParallelModelVLM(6)", "TestFsdpWrapTransformerBlocksHelper(1)" ], - "count": 38 + "count": 41 }, "tests/unit/test_resilience.py": { "classes": [ diff --git a/docs/architecture/data-flow.md b/docs/architecture/data-flow.md index c886bc9d9..5ad8acec6 100644 --- a/docs/architecture/data-flow.md +++ b/docs/architecture/data-flow.md @@ -84,6 +84,12 @@ 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). +- **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. - **Eval dataloader and `torch.profiler`** (optional). - **Phase schedule** (optional): for curriculum training, rebalances a `[[data.datasets]]` mixture and scales the LR, on any run, from diff --git a/kempnerforge/distributed/utils.py b/kempnerforge/distributed/utils.py index 41015ec76..e528bcb2a 100644 --- a/kempnerforge/distributed/utils.py +++ b/kempnerforge/distributed/utils.py @@ -290,15 +290,31 @@ 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, 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 + error with a note naming ``what``. 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) - failed = flags.nonzero().flatten().tolist() + try: + dist.all_reduce(flags, group=group) + except Exception 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 + error.add_note( + f"{what} could not be agreed across ranks: " + f"{type(collective_error).__name__}: {collective_error}" + ) + else: + failed = flags.nonzero().flatten().tolist() if error is not None: raise error if failed: diff --git a/kempnerforge/training/data_pipeline.py b/kempnerforge/training/data_pipeline.py index e17225f71..fab25643f 100644 --- a/kempnerforge/training/data_pipeline.py +++ b/kempnerforge/training/data_pipeline.py @@ -440,8 +440,10 @@ def __call__( 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. A resume restores the loader's position - only if it has ``state_dict`` and ``load_state_dict``. + 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``. """ ... diff --git a/tests/unit/test_distributed.py b/tests/unit/test_distributed.py index 0f29e356e..9604d598b 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.transformer import Transformer, TransformerBlock @@ -58,6 +59,58 @@ 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" + + @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) + + def all_reduce(tensor, group=None): + raise error + + 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) + 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}" + ] + + 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_train_entry.py b/tests/unit/test_train_entry.py index fabb2fdfe..ed9e0be4d 100644 --- a/tests/unit/test_train_entry.py +++ b/tests/unit/test_train_entry.py @@ -11,6 +11,7 @@ import dataclasses import json import math +import time from collections.abc import Iterator from datetime import timedelta from pathlib import Path @@ -55,6 +56,7 @@ 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]]: @@ -2009,6 +2011,12 @@ def _web_and_tiny(tiny_samples: int) -> DataPipeline: ) +def _wait_for_outcome(out_dir: str, rank: int) -> None: + """Return once ``rank`` has written its outcome.""" + while not Path(out_dir, "outcome", f"rank{rank}").exists(): + time.sleep(0.1) + + def _fail_the_data_on_the_last_rank( rank: int, world: int, port: int, case: str, ckpt_dir: str, out_dir: str ) -> None: @@ -2016,9 +2024,12 @@ def _fail_the_data_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. 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. + 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: @@ -2026,7 +2037,9 @@ def _fail_the_data_on_the_last_rank( config = make_config() config.checkpoint.dir = ckpt_dir - config.distributed.nccl_timeout_sec = DATA_PG_TIMEOUT_S + 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": @@ -2038,6 +2051,8 @@ def data_fn(cfg, runtime, *, tokens_per_image=None): 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: @@ -2046,7 +2061,7 @@ def data_fn(cfg, runtime, *, tokens_per_image=None): entry.run_training(config, data_fn=data_fn) outcome = "returned" except BaseException as e: - outcome = f"{type(e).__name__}: {e}" + outcome = "\n".join([f"{type(e).__name__}: {e}", *getattr(e, "__notes__", ())]) write_outcome(out_dir, rank, outcome) @@ -2054,8 +2069,9 @@ def data_fn(cfg, runtime, *, tokens_per_image=None): 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 and 60 s to - exit; the 360 s timeout covers all three and the 5 s grace period for stopping the ranks. + 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( @@ -2081,6 +2097,27 @@ def test_every_rank_raises_well_inside_the_process_group_timeout( 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 @@ -2392,8 +2429,8 @@ def test_a_step_zero_phase_whose_weights_the_sampler_refuses_is_named( dp.build_data_pipeline(config, _runtime()) def test_check_phase_weights_checks_every_phase_against_the_built_mixture(self): - """Every configured phase is checked against the sampler a builder made, and a pipeline - without a mixture is not checked.""" + """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() @@ -2404,6 +2441,12 @@ def test_check_phase_weights_checks_every_phase_against_the_built_mixture(self): 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"] ) From b3b145b6eee9273160fa0e7bc97914235de2ff54 Mon Sep 17 00:00:00 2001 From: amazloumi Date: Sat, 5 Dec 2026 03:57:52 -0500 Subject: [PATCH 5/8] Let an interrupt in the rank agreement propagate, noting the rank's error agree_across_ranks caught only an Exception from its all-reduce, so a KeyboardInterrupt, or any other failure that is not an Exception, still dropped the error of a rank whose own part had failed. It now catches every failure. An Exception still gives way to the rank's own error, which notes it, while an interrupt propagates as itself, so it still stops the run as an interrupt, with the rank's error in a note. --- codebase-map.json | 6 +++--- kempnerforge/distributed/utils.py | 13 ++++++++++--- tests/unit/test_distributed.py | 26 +++++++++++++++++++++----- 3 files changed, 34 insertions(+), 11 deletions(-) diff --git a/codebase-map.json b/codebase-map.json index 7d72dcffa..739176e1d 100644 --- a/codebase-map.json +++ b/codebase-map.json @@ -1428,7 +1428,7 @@ "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)", - "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, a rank with an error still raises its own, with that failure in a note)" + "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, a rank with an error still raises its own, with that failure in a note, unless the failure is not an Exception (an interrupt), which propagates noting the rank's error)" ], "tested_by": [ "tests/unit/test_distributed.py::TestClipGradNorm", @@ -1992,7 +1992,7 @@ "tests/unit/test_distributed.py": { "classes": [ "TestClipGradNorm(4)", - "TestAgreeAcrossRanks(3)", + "TestAgreeAcrossRanks(4)", "TestBuildBlockTPPlan(7)", "TestBuildCrossAttentionTPPlan(3)", "TestDetectIBInterface(5)", @@ -2003,7 +2003,7 @@ "TestBuildParallelModelVLM(6)", "TestFsdpWrapTransformerBlocksHelper(1)" ], - "count": 41 + "count": 42 }, "tests/unit/test_resilience.py": { "classes": [ diff --git a/kempnerforge/distributed/utils.py b/kempnerforge/distributed/utils.py index e528bcb2a..0469ce5a8 100644 --- a/kempnerforge/distributed/utils.py +++ b/kempnerforge/distributed/utils.py @@ -294,8 +294,10 @@ def agree_across_ranks( itself raises, as on a rank that waited in it past the group's timeout, 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 - error with a note naming ``what``. Without an initialized process group, - ``error`` is raised if set. + error with a note naming ``what``. A failure that is not an ``Exception``, + such as ``KeyboardInterrupt``, propagates instead of a rank's own error, + which it notes. Without an initialized process group, ``error`` is raised + if set. """ failed: list[int] = [] if dist.is_initialized(): @@ -303,12 +305,17 @@ def agree_across_ranks( flags[dist.get_rank(group)] = int(error is not None) try: dist.all_reduce(flags, group=group) - except Exception as collective_error: + 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 + if not isinstance(collective_error, Exception): + collective_error.add_note( + f"{what} failed on this rank: {type(error).__name__}: {error}" + ) + raise error.add_note( f"{what} could not be agreed across ranks: " f"{type(collective_error).__name__}: {collective_error}" diff --git a/tests/unit/test_distributed.py b/tests/unit/test_distributed.py index 9604d598b..64b942a2e 100644 --- a/tests/unit/test_distributed.py +++ b/tests/unit/test_distributed.py @@ -65,18 +65,23 @@ class TestAgreeAcrossRanks: TIMED_OUT = "Timed out waiting 5000ms for send operation to complete" - @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) + @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 error + 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): @@ -110,6 +115,17 @@ def test_an_error_keeps_the_cause_it_already_has(self, collective_error): f"Data pipeline build could not be agreed across ranks: RuntimeError: {self.TIMED_OUT}" ] + def test_an_interrupt_propagates_noting_the_ranks_own_error(self, monkeypatch): + interrupt = KeyboardInterrupt() + self._all_reduce_raises(monkeypatch, interrupt) + error = OSError(28, "No space left on device") + with pytest.raises(KeyboardInterrupt) as raised: + agree_across_ranks(error, "Checkpoint save") + assert raised.value is interrupt + assert interrupt.__notes__ == [ + "Checkpoint save failed on this rank: OSError: [Errno 28] No space left on device" + ] + class TestBuildBlockTPPlan: def test_plan_with_sequence_parallel(self): From 9b02474c6c8711d200c3bda387711ff9591ead8e Mon Sep 17 00:00:00 2001 From: amazloumi Date: Sat, 5 Dec 2026 04:08:25 -0500 Subject: [PATCH 6/8] Raise a failed rank's own error even when the agreement is interrupted A rank whose own part failed now raises that error whatever the all-reduce raised, an interrupt such as KeyboardInterrupt included, with the failure in a note and the error's cause left as it was, instead of letting the interrupt replace it. The note gives the failure as Python prints it, so an interrupt with no message reads "KeyboardInterrupt". A rank without an error still raises the all-reduce's failure, noting what the ranks were agreeing on. --- codebase-map.json | 2 +- kempnerforge/distributed/utils.py | 23 ++++++++--------------- tests/unit/test_distributed.py | 20 +++++++++++--------- 3 files changed, 20 insertions(+), 25 deletions(-) diff --git a/codebase-map.json b/codebase-map.json index 739176e1d..960fc14ee 100644 --- a/codebase-map.json +++ b/codebase-map.json @@ -1428,7 +1428,7 @@ "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)", - "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, a rank with an error still raises its own, with that failure in a note, unless the failure is not an Exception (an interrupt), which propagates noting the rank's error)" + "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", diff --git a/kempnerforge/distributed/utils.py b/kempnerforge/distributed/utils.py index 0469ce5a8..1006d3c60 100644 --- a/kempnerforge/distributed/utils.py +++ b/kempnerforge/distributed/utils.py @@ -8,6 +8,7 @@ import logging import math +import traceback from collections import defaultdict from collections.abc import Sequence from datetime import timedelta @@ -291,12 +292,11 @@ def agree_across_ranks( 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. If the all-reduce - itself raises, as on a rank that waited in it past the group's timeout, 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 - error with a note naming ``what``. A failure that is not an ``Exception``, - such as ``KeyboardInterrupt``, propagates instead of a rank's own error, - which it notes. Without an initialized process group, ``error`` is raised + 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``. Without an initialized process group, ``error`` is raised if set. """ failed: list[int] = [] @@ -311,15 +311,8 @@ def agree_across_ranks( f"{what} succeeded on this rank but could not be agreed across ranks" ) raise - if not isinstance(collective_error, Exception): - collective_error.add_note( - f"{what} failed on this rank: {type(error).__name__}: {error}" - ) - raise - error.add_note( - f"{what} could not be agreed across ranks: " - f"{type(collective_error).__name__}: {collective_error}" - ) + failure = traceback.format_exception_only(collective_error)[0].strip() + error.add_note(f"{what} could not be agreed across ranks: {failure}") else: failed = flags.nonzero().flatten().tolist() if error is not None: diff --git a/tests/unit/test_distributed.py b/tests/unit/test_distributed.py index 64b942a2e..e73913846 100644 --- a/tests/unit/test_distributed.py +++ b/tests/unit/test_distributed.py @@ -115,15 +115,17 @@ def test_an_error_keeps_the_cause_it_already_has(self, collective_error): f"Data pipeline build could not be agreed across ranks: RuntimeError: {self.TIMED_OUT}" ] - def test_an_interrupt_propagates_noting_the_ranks_own_error(self, monkeypatch): - interrupt = KeyboardInterrupt() - self._all_reduce_raises(monkeypatch, interrupt) - error = OSError(28, "No space left on device") - with pytest.raises(KeyboardInterrupt) as raised: - agree_across_ranks(error, "Checkpoint save") - assert raised.value is interrupt - assert interrupt.__notes__ == [ - "Checkpoint save failed on this rank: OSError: [Errno 28] No space left on device" + 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" ] From d3cfab3d52911b5f995a1146d1737bcf30ccfaa8 Mon Sep 17 00:00:00 2001 From: amazloumi Date: Sat, 5 Dec 2026 04:17:21 -0500 Subject: [PATCH 7/8] Note every line Python prints for a failed rank agreement The note on a failed rank's error took only the first line Python prints for the all-reduce's failure, which for a failure printed on several lines, such as a SyntaxError, is a location line without the type or the message. It now keeps every line. --- codebase-map.json | 4 ++-- kempnerforge/distributed/utils.py | 2 +- tests/unit/test_distributed.py | 12 ++++++++++++ 3 files changed, 15 insertions(+), 3 deletions(-) diff --git a/codebase-map.json b/codebase-map.json index 960fc14ee..c7bc0dc72 100644 --- a/codebase-map.json +++ b/codebase-map.json @@ -1992,7 +1992,7 @@ "tests/unit/test_distributed.py": { "classes": [ "TestClipGradNorm(4)", - "TestAgreeAcrossRanks(4)", + "TestAgreeAcrossRanks(5)", "TestBuildBlockTPPlan(7)", "TestBuildCrossAttentionTPPlan(3)", "TestDetectIBInterface(5)", @@ -2003,7 +2003,7 @@ "TestBuildParallelModelVLM(6)", "TestFsdpWrapTransformerBlocksHelper(1)" ], - "count": 42 + "count": 43 }, "tests/unit/test_resilience.py": { "classes": [ diff --git a/kempnerforge/distributed/utils.py b/kempnerforge/distributed/utils.py index 1006d3c60..09c089749 100644 --- a/kempnerforge/distributed/utils.py +++ b/kempnerforge/distributed/utils.py @@ -311,7 +311,7 @@ def agree_across_ranks( f"{what} succeeded on this rank but could not be agreed across ranks" ) raise - failure = traceback.format_exception_only(collective_error)[0].strip() + failure = "".join(traceback.format_exception_only(collective_error)).strip() error.add_note(f"{what} could not be agreed across ranks: {failure}") else: failed = flags.nonzero().flatten().tolist() diff --git a/tests/unit/test_distributed.py b/tests/unit/test_distributed.py index e73913846..87a0e06e1 100644 --- a/tests/unit/test_distributed.py +++ b/tests/unit/test_distributed.py @@ -128,6 +128,18 @@ def test_an_interrupt_still_raises_the_ranks_own_error(self, monkeypatch): "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): From d4e569bf86826e00132f3b0e8e968af7836f7bb4 Mon Sep 17 00:00:00 2001 From: amazloumi Date: Sat, 5 Dec 2026 16:53:44 -0500 Subject: [PATCH 8/8] Keep a failed rank's own error when a checkpoint agreement's collective fails Four steps of the checkpoint manager run a collective of their own on its gloo group: the agreement before a save's write, the save's gather of every rank's loader and RNG state, a load's agreement on whether any rank's DCP index holds optimizer state, and the load's model check. When that collective itself failed, for example with a gloo timeout because another rank reached it only after the group's timeout, a rank whose own part had failed raised the collective's error alone. Each step now runs its collective through run_keeping_own_error, which agree_across_ranks now uses too: such a rank re-raises its own error with the collective's failure in a note, its cause left as it was, and a rank whose part succeeded raises the collective's error with a note naming the step. Rank 0 keeps its refusal of a checkpoint that does not fit the model the same way, and a save keeps an error its write raised before the gather. The success paths and the paths without a process group are unchanged. Tests make each step's collective fail, and a two-rank gloo test lets the agreement before the write time out on a rank that cannot create the step directory. The wait for another rank's outcome moves into tests/gloo_ranks.py, and the save() excerpt in the train-state page passes the gather its new argument. --- codebase-map.json | 21 +++-- docs/checkpointing/train-state.md | 2 +- kempnerforge/checkpoint/manager.py | 64 +++++++++---- kempnerforge/distributed/utils.py | 46 ++++++---- tests/gloo_ranks.py | 7 ++ tests/unit/test_checkpoint.py | 105 ++++++++++++++++++++++ tests/unit/test_checkpoint_load_checks.py | 89 ++++++++++++++++++ tests/unit/test_checkpoint_per_rank.py | 54 +++++++++++ tests/unit/test_pipeline_checkpoint.py | 60 ++++++++++++- tests/unit/test_train_entry.py | 11 +-- 10 files changed, 405 insertions(+), 54 deletions(-) diff --git a/codebase-map.json b/codebase-map.json index 02062fced..504dd4790 100644 --- a/codebase-map.json +++ b/codebase-map.json @@ -1440,6 +1440,7 @@ "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)", + "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": [ @@ -1496,6 +1497,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)", @@ -1505,8 +1507,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)", @@ -2071,7 +2074,7 @@ "TestWeightsOnlyWarmStart(8)", "TestLoadVLMFreezeCompare(9)", "TestAsyncLatestSymlinkSafety(32)", - "TestAFailedSaveCommitsNothing(20)", + "TestAFailedSaveCommitsNothing(23)", "TestDurableTrainState(6)", "TestSyncBarrierGroup(6)", "TestCheckpointManagerLoad(3)", @@ -2084,13 +2087,13 @@ "TestOptimizerChecksAcrossStages(5)", "TestCheckpointEveryOptimizer(8)", "TestComponentSwapOnResume(1)", - "TestWeightDecayScopeOnResume(46)", + "TestWeightDecayScopeOnResume(48)", "TestRestoredExtra(2)", "TestUnreadableTrainStateAcrossRanks(1)", "TestTornStageAcrossRanks(1)", "TestOptimizerTypeChangeOnResume(6)" ], - "count": 374 + "count": 379 }, "tests/unit/test_checkpoint_publish.py": { "classes": [ @@ -2117,7 +2120,7 @@ "TestPerRankEnvelopeSchema(17)", "TestEnvelopeValidatedBeforeSelection(6)", "TestGatherMustCoverTheWorld(2)", - "TestAFailedCaptureFailsEveryRank(4)", + "TestAFailedCaptureFailsEveryRank(6)", "TestFourRankSaveLoad(6)", "TestLegacyAndTopology(10)", "TestDataParallelLayout(12)", @@ -2125,7 +2128,7 @@ "TestWeightsOnlyWarmStart(3)", "TestMidSaveInterruption(1)" ], - "count": 63 + "count": 65 }, "tests/unit/test_observability.py": { "classes": [ @@ -2300,10 +2303,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/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/kempnerforge/checkpoint/manager.py b/kempnerforge/checkpoint/manager.py index 1f2d2c155..e73d9ce89 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__) @@ -1852,7 +1852,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: @@ -1867,7 +1869,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: @@ -1974,7 +1978,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. @@ -1999,7 +2005,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: @@ -2013,7 +2023,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 @@ -2219,19 +2234,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: @@ -2249,7 +2267,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) @@ -2479,7 +2501,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 @@ -3111,7 +3133,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: @@ -3121,7 +3145,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 09c089749..ae4bcda31 100644 --- a/kempnerforge/distributed/utils.py +++ b/kempnerforge/distributed/utils.py @@ -10,7 +10,7 @@ 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 @@ -283,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: @@ -296,25 +322,15 @@ def agree_across_ranks( 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``. Without an initialized process group, ``error`` is raised - if set. + 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) - try: - dist.all_reduce(flags, group=group) - 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: - failed = flags.nonzero().flatten().tolist() + 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 if failed: diff --git a/tests/gloo_ranks.py b/tests/gloo_ranks.py index cd4599640..62ed4a649 100644 --- a/tests/gloo_ranks.py +++ b/tests/gloo_ranks.py @@ -180,6 +180,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 1000f13ad..f884e9221 100644 --- a/tests/unit/test_checkpoint.py +++ b/tests/unit/test_checkpoint.py @@ -3125,6 +3125,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.""" @@ -3358,6 +3361,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 ): @@ -6312,6 +6371,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_pipeline_checkpoint.py b/tests/unit/test_pipeline_checkpoint.py index c83d3ce1a..a9618ad69 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]: @@ -319,6 +327,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(): @@ -492,6 +528,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 1d367e925..7da47fe01 100644 --- a/tests/unit/test_train_entry.py +++ b/tests/unit/test_train_entry.py @@ -11,7 +11,6 @@ import dataclasses import json import math -import time from collections.abc import Iterator from datetime import timedelta from pathlib import Path @@ -49,7 +48,7 @@ vlm_step, ) from kempnerforge.training.runtime import RuntimeContext -from tests.gloo_ranks import gloo_group, mark, run_to_outcomes, write_outcome +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 @@ -2035,12 +2034,6 @@ def _web_and_tiny(tiny_samples: int) -> DataPipeline: ) -def _wait_for_outcome(out_dir: str, rank: int) -> None: - """Return once ``rank`` has written its outcome.""" - while not Path(out_dir, "outcome", f"rank{rank}").exists(): - time.sleep(0.1) - - def _fail_the_data_on_the_last_rank( rank: int, world: int, port: int, case: str, ckpt_dir: str, out_dir: str ) -> None: @@ -2076,7 +2069,7 @@ def data_fn(cfg, runtime, *, tokens_per_image=None): if last: raise RuntimeError(f"data_fn failed on rank {rank}") if case == "agreement_times_out": - _wait_for_outcome(out_dir, world - 1) + wait_for_outcome(out_dir, world - 1) return DataPipeline() with pytest.MonkeyPatch.context() as patch: