Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions codebase-map.json
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down
4 changes: 4 additions & 0 deletions docs/data/huggingface.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
115 changes: 91 additions & 24 deletions kempnerforge/training/data_pipeline.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@

from __future__ import annotations

import traceback
from dataclasses import dataclass, field
from typing import Any, Protocol

Expand Down Expand Up @@ -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"<unprintable {type(error).__name__}>"


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.

Expand All @@ -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
Expand All @@ -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 "
Expand Down
28 changes: 2 additions & 26 deletions scripts/eval.py
Original file line number Diff line number Diff line change
Expand Up @@ -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__)
Expand Down Expand Up @@ -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:
Expand Down
84 changes: 83 additions & 1 deletion tests/unit/test_eval_script.py
Original file line number Diff line number Diff line change
@@ -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():
Expand All @@ -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):
Expand Down Expand Up @@ -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}",
}
Loading
Loading