diff --git a/codebase-map.json b/codebase-map.json index 3a91fff46..ae22d6ddb 100644 --- a/codebase-map.json +++ b/codebase-map.json @@ -990,11 +990,14 @@ "functions": [ "build_data_pipeline(config, runtime, *, tokens_per_image=None) -> DataPipeline", "build_eval_dataloader(config, runtime) -> DataLoader | None", + "broadcast_hf_eval_set(config, dataset_name, device) -> Tensor (the Hugging Face eval set rank 0 packs, on every rank, on CPU; rank 0 broadcasts its build error in place of the rows, so every rank raises at once, naming it; build_eval_dataloader and scripts/eval.py call it)", "build_phase_state(config, data, step) -> PhaseState", "advance_phases(state, data, step) -> bool" ], "tested_by": [ "tests/unit/test_train_entry.py::TestBuildDataPipeline", + "tests/unit/test_train_entry.py::TestEvalDataloaderBuilder", + "tests/unit/test_train_entry.py::TestHuggingFaceEvalSetAcrossRanks", "tests/unit/test_train_entry.py::TestPhaseState", "tests/unit/test_train_entry.py::TestAdvancePhases", "tests/unit/test_schedule_state.py" diff --git a/docs/data/huggingface.md b/docs/data/huggingface.md index 8ceb64610..a711d2ab5 100644 --- a/docs/data/huggingface.md +++ b/docs/data/huggingface.md @@ -154,6 +154,10 @@ For HF eval sets, rank 0 tokenizes and broadcasts the packed tensor to all ranks via `torch.distributed.broadcast`. This is a deliberate choice to avoid `load_dataset` file-lock (`flock`) failures on cluster filesystems (Lustre, VAST) where parallel opens crash. +When rank 0 cannot build the set, it broadcasts why in place of the +tensor: it raises its own error, and every other rank raises a +`RuntimeError` naming it at once, instead of waiting in the broadcast +until the process-group timeout. ## Limitations diff --git a/kempnerforge/training/data_pipeline.py b/kempnerforge/training/data_pipeline.py index 1cb062fa5..0433e92ab 100644 --- a/kempnerforge/training/data_pipeline.py +++ b/kempnerforge/training/data_pipeline.py @@ -7,6 +7,7 @@ from __future__ import annotations +import traceback from dataclasses import dataclass, field from typing import Any, Protocol @@ -456,6 +457,92 @@ def build_data_pipeline( return DataPipeline(dp_rank=dp_rank, dp_size=dp_size) +def _error_summary(error: BaseException) -> str: + """``error``'s type and message as a traceback ends with them, or its type's name when + they cannot be formatted; never raises.""" + try: + return "".join(traceback.format_exception_only(error)).strip() + except Exception: + return f"" + + +def broadcast_hf_eval_set( + config: JobConfig, dataset_name: str, device: torch.device +) -> torch.Tensor: + """Return the Hugging Face eval set ``dataset_name`` as rank 0 packs it, on every rank. + + Rank 0 alone builds the rows and broadcasts them over the default process group, or in + their place why it could not, so every rank evaluates the same rows or every rank raises at + once, instead of the others waiting in the broadcast for a rank that has raised. Every rank + calls this or none does. Rank 0's outcome goes first, over torch's object-collective + device: the CPU under the default ``cpu:gloo,cuda:nccl`` backend and under ``gloo``, the + current GPU under ``nccl`` alone. The rows then go over ``device``. + + Args: + config: The job config. ``eval.hf_dataset_split``, ``eval.hf_dataset_config``, + ``data.hf_dataset_text_field`` and ``data.tokenizer_path`` say what to build, and + ``train.seq_len`` sets the width of the rows. + dataset_name: The Hugging Face dataset the set is built from. + device: A device the default group's backend broadcasts on, such as this rank's GPU + under NCCL. + + Returns: + The packed rows, ``train.seq_len + 1`` tokens each, on the CPU. + + Raises: + Exception: On rank 0, or without a process group, what building the set raised. When + rank 0 could not send it to the other ranks, a note on it says why. + RuntimeError: On every other rank, naming rank 0's error. + BaseException: On a rank without a build error, what the broadcast of rank 0's + outcome raised when it failed, as on a rank that waited in it past the group's + timeout, with a note naming the eval set. + """ + eval_config = config.eval + eval_set = f"the eval set from {dataset_name} ({eval_config.hf_dataset_split})" + width = config.train.seq_len + 1 + rows = torch.empty(0, width, dtype=torch.long) + error: Exception | None = None + if not dist.is_initialized() or dist.get_rank() == 0: + try: + eval_ds = HuggingFaceDataset( + dataset_name=dataset_name, + split=eval_config.hf_dataset_split, + text_field=config.data.hf_dataset_text_field, + seq_len=config.train.seq_len, + tokenizer_path=config.data.tokenizer_path, + dataset_config=eval_config.hf_dataset_config, + ) + rows = torch.from_numpy(np.stack(eval_ds._packed_sequences)) + except Exception as e: + error = e + if not dist.is_initialized(): + if error is not None: + raise error + return rows + outcome: list[tuple[int, str | None]] = [ + (rows.shape[0], None if error is None else _error_summary(error)) + ] + try: + dist.broadcast_object_list(outcome, src=0) + except BaseException as send_error: + if error is None: + send_error.add_note(f"Rank 0's outcome for {eval_set} could not be broadcast") + raise + error.add_note( + f"Rank 0 could not send this error to the other ranks: {_error_summary(send_error)}" + ) + if error is not None: + raise error + n_rows, reason = outcome[0] + if reason is not None: + raise RuntimeError(f"Rank 0 could not build {eval_set}: {reason}") + if dist.get_rank() != 0: + rows = torch.empty(n_rows, width, dtype=torch.long) + on_device = rows.to(device) + dist.broadcast(on_device, src=0) + return on_device.cpu() + + def build_eval_dataloader(config: JobConfig, runtime: RuntimeContext) -> Any | None: """Build the eval dataloader, or None when eval is off or unsupported. @@ -465,6 +552,9 @@ def build_eval_dataloader(config: JobConfig, runtime: RuntimeContext) -> Any | N Raises: ValueError: Under pipeline parallelism, the eval set gives a data-parallel rank less than one full batch. + Exception: On rank 0, what building a Hugging Face eval set raised; every + other rank then raises a ``RuntimeError`` naming it (see + ``broadcast_hf_eval_set``). """ tc = config.train eval_config = config.eval @@ -490,30 +580,7 @@ def build_eval_dataloader(config: JobConfig, runtime: RuntimeContext) -> Any | N ) logger.info(f"Eval dataset: {len(eval_dataset):,} samples from {eval_config.dataset_path}") elif eval_config.hf_dataset_name: - if runtime.rank == 0: - eval_ds = HuggingFaceDataset( - dataset_name=eval_config.hf_dataset_name, - split=eval_config.hf_dataset_split, - text_field=config.data.hf_dataset_text_field, - seq_len=tc.seq_len, - tokenizer_path=config.data.tokenizer_path, - dataset_config=eval_config.hf_dataset_config, - ) - packed = torch.from_numpy(np.stack(eval_ds._packed_sequences)) - n_seqs = torch.tensor([packed.shape[0]], device=device) - else: - packed = torch.empty(0, dtype=torch.long) - n_seqs = torch.tensor([0], device=device) - - if dist.is_initialized(): - dist.broadcast(n_seqs, src=0) - if runtime.rank != 0: - packed = torch.empty(int(n_seqs.item()), tc.seq_len + 1, dtype=torch.long) - packed_gpu = packed.to(device) - dist.broadcast(packed_gpu, src=0) - packed = packed_gpu.cpu() - del packed_gpu - + packed = broadcast_hf_eval_set(config, eval_config.hf_dataset_name, device) eval_dataset = _EvalTensorDataset(packed) logger.info( f"Eval dataset: {len(eval_dataset):,} packed sequences from " diff --git a/scripts/eval.py b/scripts/eval.py index f86cbb7dd..2786075b6 100644 --- a/scripts/eval.py +++ b/scripts/eval.py @@ -41,6 +41,7 @@ from kempnerforge.metrics.logger import get_logger from kempnerforge.resilience.elastic import resolve_resume_path from kempnerforge.training import build_loss_fn, run_eval +from kempnerforge.training.data_pipeline import broadcast_hf_eval_set from kempnerforge.training.runtime import apply_matmul_precision logger = get_logger(__name__) @@ -136,32 +137,7 @@ def main() -> None: token_dtype=eval_config.token_dtype, ) elif eval_config.hf_dataset_name: - import numpy as np - - from kempnerforge.data.dataset import HuggingFaceDataset - - if rank == 0: - eval_ds = HuggingFaceDataset( - dataset_name=eval_config.hf_dataset_name, - split=eval_config.hf_dataset_split, - text_field=config.data.hf_dataset_text_field, - seq_len=tc.seq_len, - tokenizer_path=config.data.tokenizer_path, - dataset_config=eval_config.hf_dataset_config, - ) - packed = torch.from_numpy(np.stack(eval_ds._packed_sequences)) - n_seqs = torch.tensor([packed.shape[0]], device=device) - else: - n_seqs = torch.tensor([0], device=device) - - if dist.is_initialized(): - dist.broadcast(n_seqs, src=0) - if rank != 0: - packed = torch.empty(n_seqs.item(), tc.seq_len + 1, dtype=torch.long) - packed_gpu = packed.to(device) - dist.broadcast(packed_gpu, src=0) - packed = packed_gpu.cpu() - del packed_gpu + packed = broadcast_hf_eval_set(config, eval_config.hf_dataset_name, device) class _EvalTensorDataset(torch.utils.data.Dataset): def __init__(self, data: torch.Tensor) -> None: diff --git a/tests/unit/test_eval_script.py b/tests/unit/test_eval_script.py index 722bb351a..71bf20953 100644 --- a/tests/unit/test_eval_script.py +++ b/tests/unit/test_eval_script.py @@ -1,16 +1,23 @@ -"""Unit tests for the checkpoint that ``scripts/eval.py`` loads.""" +"""Unit tests for the checkpoint that ``scripts/eval.py`` loads and the eval set it builds.""" from __future__ import annotations import importlib.util import sys +from datetime import timedelta from pathlib import Path import pytest import torch import torch.distributed.checkpoint as dcp +from tests.gloo_ranks import gloo_group, mark, run_to_outcomes, write_outcome + SCRIPT = Path(__file__).resolve().parents[2] / "scripts" / "eval.py" +EVAL_SET = "no-such-org/no-such-eval-set" +UNREACHABLE = f"ConnectionError: Couldn't reach '{EVAL_SET}' on the Hub (OfflineModeIsEnabled)" +DEADLINE_S = 30 +PG_TIMEOUT_S = 60 def _eval_script(): @@ -34,6 +41,55 @@ class _Picked(Exception): """Stops ``main`` once it has chosen the checkpoint to load.""" +class _LoadedManager: + """A ``CheckpointManager`` whose load returns step 10 and reads nothing.""" + + def __init__(self, *args, **kwargs) -> None: + pass + + def load(self, **kwargs): + return 10, 0, {} + + +def _unreachable_eval_set(self, *, dataset_name: str, **kwargs) -> None: + """``HuggingFaceDataset.__init__`` for an eval set the Hub cannot serve offline.""" + raise ConnectionError(f"Couldn't reach '{dataset_name}' on the Hub (OfflineModeIsEnabled)") + + +def _evaluate_on_gloo_ranks(rank: int, world: int, port: int, run_dir: str, out_dir: str) -> None: + """Run ``main`` on each gloo rank on an eval set rank 0 cannot build; record what it raised. + + A rank that raises stays in the group: a rank's exit ends a gloo collective its peers wait in + at once, while NCCL leaves them waiting, so a rank left waiting here fails the test's deadline + as under NCCL. + """ + from kempnerforge.data.dataset import HuggingFaceDataset + + script = _eval_script() + argv = [ + str(Path(run_dir) / "eval.toml"), + f"--checkpoint.load_path={run_dir}/step_10", + f"--eval.hf_dataset_name={EVAL_SET}", + ] + with gloo_group(rank, world, port, timeout=timedelta(seconds=PG_TIMEOUT_S)): + try: + with pytest.MonkeyPatch.context() as patch: + patch.setattr(HuggingFaceDataset, "__init__", _unreachable_eval_set) + patch.setattr(script, "get_world_info", lambda: (rank, rank, world)) + patch.setattr(script, "init_distributed", lambda *args, **kwargs: None) + patch.setattr( + script, "build_parallel_model", lambda *args, **kwargs: torch.nn.Linear(2, 2) + ) + patch.setattr(script, "CheckpointManager", _LoadedManager) + patch.setattr(sys, "argv", ["eval.py", *argv]) + mark(out_dir, rank) + script.main() + outcome = "evaluated" + except Exception as e: + outcome = f"{type(e).__name__}: {e}" + write_outcome(out_dir, rank, outcome) + + class TestEvalScriptCheckpoint: @pytest.mark.parametrize("rank", [0, 1]) def test_only_rank_zero_looks_for_the_checkpoint(self, monkeypatch, rank): @@ -205,3 +261,29 @@ def run_eval(*args, **kwargs) -> dict[str, float]: script.main() assert [call.get("dp_groups") for call in calls] == [groups] + + +class TestEvalScriptHuggingFaceEvalSet: + @pytest.mark.timeout(360) + def test_an_error_building_it_on_rank_zero_raises_on_every_rank(self, tmp_path, monkeypatch): + """Rank 0 raises its own error, and the other rank one naming it, at once, instead of + waiting for an eval set that rank 0 never sends. + + The ranks get 240 s to start, ``DEADLINE_S`` in ``main`` and 60 s to exit, so a rank left + waiting fails the test within the deadline; the 360 s timeout covers all three. + """ + monkeypatch.setenv("CUDA_VISIBLE_DEVICES", "") + (tmp_path / "eval.toml").write_text("") + outcomes = run_to_outcomes( + _evaluate_on_gloo_ranks, + 2, + (str(tmp_path),), + tmp_path / "outcomes", + part="main()", + part_s=DEADLINE_S, + ) + assert outcomes == { + 0: UNREACHABLE, + 1: f"RuntimeError: Rank 0 could not build the eval set from {EVAL_SET} " + f"(validation): {UNREACHABLE}", + } diff --git a/tests/unit/test_train_entry.py b/tests/unit/test_train_entry.py index b4fb36ef8..48f580f2a 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,15 @@ 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 +EVAL_SET = "no-such-org/no-such-eval-set" +UNREACHABLE = f"ConnectionError: Couldn't reach '{EVAL_SET}' on the Hub (OfflineModeIsEnabled)" +EVAL_SET_DEADLINE_S = 30 +EVAL_SET_PG_TIMEOUT_S = 60 def _fake_batches(n: int) -> list[dict[str, torch.Tensor]]: @@ -4541,6 +4547,47 @@ def test_image_vlm_without_a_dataset_is_rejected(self): dp.build_data_pipeline(config, _runtime()) +def _unreachable_eval_set(self, *, dataset_name: str, **kwargs: Any) -> None: + """``HuggingFaceDataset.__init__`` for an eval set the Hub cannot serve offline.""" + raise ConnectionError(f"Couldn't reach '{dataset_name}' on the Hub (OfflineModeIsEnabled)") + + +def _three_eval_rows(self, *, seq_len: int, **kwargs: Any) -> None: + """``HuggingFaceDataset.__init__`` packing three rows of ``seq_len + 1`` tokens, counting up.""" + import numpy as np + + self._packed_sequences = list(np.arange(3 * (seq_len + 1)).reshape(3, seq_len + 1)) + + +def _build_hf_eval_set(rank: int, world: int, port: int, builds: bool, out_dir: str) -> None: + """Build the loader of a Hugging Face eval set on each gloo rank; record its rows or the error. + + The set packs three rows when ``builds`` and cannot be reached otherwise. A rank that raises + stays in the group: a rank's exit ends a gloo collective its peers wait in at once, while NCCL + leaves them waiting, so a rank left waiting here fails the test's deadline as under NCCL. + """ + from kempnerforge.config.eval import EvalConfig + from kempnerforge.data.dataset import HuggingFaceDataset + from kempnerforge.training.data_pipeline import build_eval_dataloader + + with gloo_group(rank, world, port, timeout=timedelta(seconds=EVAL_SET_PG_TIMEOUT_S)): + try: + with pytest.MonkeyPatch.context() as patch: + init = _three_eval_rows if builds else _unreachable_eval_set + patch.setattr(HuggingFaceDataset, "__init__", init) + config = make_config() + config.eval = EvalConfig(enabled=True, hf_dataset_name=EVAL_SET) + runtime = dataclasses.replace( + _runtime(), rank=rank, local_rank=rank, world_size=world + ) + mark(out_dir, rank) + dataset = build_eval_dataloader(config, runtime).dataset + outcome = str([dataset[i]["input_ids"].tolist() for i in range(len(dataset))]) + except Exception as e: + outcome = f"{type(e).__name__}: {e}" + write_outcome(out_dir, rank, outcome) + + class TestEvalDataloaderBuilder: def test_mmap_eval_source(self, monkeypatch, mmap_data_dir): import kempnerforge.training.data_pipeline as dp @@ -4579,6 +4626,96 @@ def _boom(*a, **k): config.eval = EvalConfig(enabled=True, hf_dataset_name="wikitext") assert dp.build_eval_dataloader(config, _runtime()) == "torch_loader_OBJ" + def test_hf_eval_raises_its_build_error_when_not_distributed(self, monkeypatch): + import kempnerforge.training.data_pipeline as dp + from kempnerforge.config.eval import EvalConfig + + monkeypatch.setattr(dp.HuggingFaceDataset, "__init__", _unreachable_eval_set) + monkeypatch.setattr(dp.dist, "is_initialized", lambda: False) + config = make_config() + config.eval = EvalConfig(enabled=True, hf_dataset_name=EVAL_SET) + with pytest.raises(ConnectionError, match="Couldn't reach") as raised: + dp.build_eval_dataloader(config, _runtime()) + assert not hasattr(raised.value, "__notes__") + + def test_rank_zero_raises_its_own_build_error_when_it_cannot_send_it(self, monkeypatch): + """A failed send of rank 0's outcome leaves rank 0 raising its build error, noting the + failure, so the cause of the run's end stays on rank 0.""" + import kempnerforge.training.data_pipeline as dp + from kempnerforge.config.eval import EvalConfig + + def lost_peer(objects, src): + raise RuntimeError("Connection closed by peer") + + monkeypatch.setattr(dp.HuggingFaceDataset, "__init__", _unreachable_eval_set) + monkeypatch.setattr(dp.dist, "is_initialized", lambda: True) + monkeypatch.setattr(dp.dist, "get_rank", lambda: 0) + monkeypatch.setattr(dp.dist, "broadcast_object_list", lost_peer) + config = make_config() + config.eval = EvalConfig(enabled=True, hf_dataset_name=EVAL_SET) + with pytest.raises(ConnectionError, match="Couldn't reach") as raised: + dp.build_eval_dataloader(config, _runtime()) + assert raised.value.__notes__ == [ + "Rank 0 could not send this error to the other ranks: " + "RuntimeError: Connection closed by peer" + ] + + @pytest.mark.parametrize("rank", [0, 1]) + def test_a_rank_without_a_build_error_raises_a_failed_send_naming_the_eval_set( + self, monkeypatch, rank + ): + """A failed broadcast of rank 0's outcome raises on a rank without a build error, rank 0 + after it built the set included, with a note naming the eval set, so a bare collective + error still says which step of the run it ended.""" + import kempnerforge.training.data_pipeline as dp + from kempnerforge.config.eval import EvalConfig + + def lost_peer(objects, src): + raise RuntimeError("Connection closed by peer") + + monkeypatch.setattr(dp.HuggingFaceDataset, "__init__", _three_eval_rows) + monkeypatch.setattr(dp.dist, "is_initialized", lambda: True) + monkeypatch.setattr(dp.dist, "get_rank", lambda: rank) + monkeypatch.setattr(dp.dist, "broadcast_object_list", lost_peer) + config = make_config() + config.eval = EvalConfig(enabled=True, hf_dataset_name=EVAL_SET) + with pytest.raises(RuntimeError, match="Connection closed by peer") as raised: + dp.build_eval_dataloader(config, _runtime()) + assert raised.value.__notes__ == [ + f"Rank 0's outcome for the eval set from {EVAL_SET} (validation) could not be broadcast" + ] + + def test_rank_zero_sends_a_build_error_it_cannot_format(self, monkeypatch): + """Rank 0 sends a build error whose summary cannot be formatted, a malformed + ``SyntaxError`` here, by its type's name and then raises it, so no other rank is left + waiting for an outcome that rank 0 never sends.""" + import kempnerforge.training.data_pipeline as dp + from kempnerforge.config.eval import EvalConfig + + class Unprintable: + def __str__(self) -> str: + raise RuntimeError("no message") + + malformed = SyntaxError(Unprintable(), ("eval.py", 1, 1, "eval set\n")) + sent: list = [] + + def raise_malformed(self, **kwargs: Any) -> None: + raise malformed + + def record(objects, src): + sent.extend(objects) + + monkeypatch.setattr(dp.HuggingFaceDataset, "__init__", raise_malformed) + monkeypatch.setattr(dp.dist, "is_initialized", lambda: True) + monkeypatch.setattr(dp.dist, "get_rank", lambda: 0) + monkeypatch.setattr(dp.dist, "broadcast_object_list", record) + config = make_config() + config.eval = EvalConfig(enabled=True, hf_dataset_name=EVAL_SET) + with pytest.raises(SyntaxError) as raised: + dp.build_eval_dataloader(config, _runtime()) + assert raised.value is malformed + assert sent == [(0, "")] + def test_no_source_configured_returns_none(self): import kempnerforge.training.data_pipeline as dp from kempnerforge.config.eval import EvalConfig @@ -4597,6 +4734,39 @@ def test_broadcast_tensor_dataset_yields_shifted_pairs(self): assert item["labels"].tolist() == [1, 2, 3, 4] +def _eval_set_outcomes(tmp_path: Path, builds: bool) -> dict[int, str]: + """How building the Hugging Face eval set's loader ended on each of two gloo ranks. + + The ranks get 240 s to start, ``EVAL_SET_DEADLINE_S`` to build and 60 s to exit, so a rank + left waiting fails the test within the deadline; each test's 360 s timeout covers all three. + """ + return run_to_outcomes( + _build_hf_eval_set, + 2, + (builds,), + tmp_path / "outcomes", + part="build_eval_dataloader()", + part_s=EVAL_SET_DEADLINE_S, + ) + + +class TestHuggingFaceEvalSetAcrossRanks: + @pytest.mark.timeout(360) + def test_every_rank_gets_the_rows_rank_zero_built(self, tmp_path): + rows = "[[0, 1, 2, 3], [5, 6, 7, 8], [10, 11, 12, 13]]" + assert _eval_set_outcomes(tmp_path, builds=True) == {0: rows, 1: rows} + + @pytest.mark.timeout(360) + def test_an_error_building_it_on_rank_zero_raises_on_every_rank(self, tmp_path): + """Rank 0 raises its own error, and the other rank one naming it, at once, instead of + waiting for rows that rank 0 never sends.""" + assert _eval_set_outcomes(tmp_path, builds=False) == { + 0: UNREACHABLE, + 1: f"RuntimeError: Rank 0 could not build the eval set from {EVAL_SET} " + f"(validation): {UNREACHABLE}", + } + + class FakeSchedule: def __init__(self, loss=2.0) -> None: self.loss = loss