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
10 changes: 7 additions & 3 deletions codebase-map.json
Original file line number Diff line number Diff line change
Expand Up @@ -1022,7 +1022,8 @@
"_start_lr_schedule(session) (an optimizer the checkpointer did not restore starts at the scheduler's last rate times the active lr_scale)",
"_batch_counts(batch, image_positions) -> (documents, image_tokens, text_tokens, encoder_images)",
"_step_counts(session, result) -> (tokens, documents, encoder_images) over the DP ranks",
"_shutdown_if_requested(session, step, tokens_seen, saved_this_step, nan_skipped) -> bool (the per-step vote, one all-reduce of the shutdown flag and CheckpointManager.flushing: a shutdown on any rank writes or drains the emergency checkpoint; otherwise a pending async save that no rank is still writing is drained, which moves latest)"
"_shutdown_if_requested(session, step, tokens_seen, saved_this_step, nan_skipped, log_vote) -> bool (the per-step vote, one all-reduce of the shutdown flag and CheckpointManager.flushing: a shutdown on any rank writes or drains the emergency checkpoint; otherwise a pending async save that no rank is still writing is drained, which moves latest; the all-reduce is timed, and with log_vote, set on a logged step, the mean since the last logged vote is logged as distributed/shutdown_vote_ms)",
"_record_vote(session, seconds, step, log) (adds a vote's time and, with log, logs the mean in ms as distributed/shutdown_vote_ms; nothing without a control group)"
],
"tested_by": [
"tests/unit/test_train_entry.py::TestLoopPeriodicWork",
Expand All @@ -1044,6 +1045,8 @@
"tests/unit/test_dp_info.py::TestLoggedMetricsOverDataParallel",
"tests/e2e/test_training_e2e.py",
"tests/unit/test_shutdown_agreement.py::TestLoopStopsOnEveryRank",
"tests/unit/test_shutdown_agreement.py::TestShutdownVoteTime",
"tests/unit/test_train_entry.py::TestShutdownVoteTime",
"tests/unit/test_schedule_state.py",
"tests/unit/test_train_entry.py::TestDrainAFinishedSave",
"tests/unit/test_checkpoint_publish.py::TestAFinishedAsyncSaveIsPublished",
Expand Down Expand Up @@ -2033,9 +2036,10 @@
"tests/unit/test_shutdown_agreement.py": {
"classes": [
"TestAnyRank(6)",
"TestLoopStopsOnEveryRank(7)"
"TestLoopStopsOnEveryRank(7)",
"TestShutdownVoteTime(1)"
],
"count": 13
"count": 14
},
"tests/unit/test_schedule_state.py": {
"classes": [
Expand Down
11 changes: 7 additions & 4 deletions docs/metrics-and-profiling/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -41,11 +41,14 @@ smoothed/mfu smoothed/step_time
```

Plus eval metrics (via `tracker.log_eval`): eval loss, MoE aux loss and
router stats, per-dataset losses and token counts for mixtures, and the
router stats, per-dataset losses and token counts for mixtures, the
time each checkpoint save and async drain took (`checkpoint/save_sec`,
`checkpoint/wait_sec`). The eval loss and the per-dataset losses and
token counts cover every data-parallel rank, not rank 0 alone; the MoE
series are still rank 0's own values.
`checkpoint/wait_sec`), and, in a distributed run, the mean time of the
per-step shutdown vote since the last logged step
(`distributed/shutdown_vote_ms`). The eval loss and the per-dataset
losses and token counts cover every data-parallel rank, not rank 0
alone; the MoE series are still rank 0's own values, and the vote time
is rank 0's own time in the vote.

## Config

Expand Down
15 changes: 14 additions & 1 deletion docs/metrics-and-profiling/metrics-tracker.md
Original file line number Diff line number Diff line change
Expand Up @@ -201,7 +201,8 @@ def log_eval(self, metrics: dict[str, float], step: int) -> None:

Eval metrics don't touch the smoothing table — they're reported raw. The
training loop calls `log_eval` after `run_eval`, and separately for per-module
learning rates, MoE and per-dataset breakdowns, and checkpoint times:
learning rates, MoE and per-dataset breakdowns, checkpoint times and the
shutdown vote's time:

```python
# training/loop.py
Expand All @@ -211,6 +212,7 @@ tracker.log_eval(ds_metrics, step) # loss/<name>, data/<name>/tokens
tracker.log_eval(data_metrics, step) # VLM: data/text_tokens_trained, data/image_tokens, data/text_tokens, data/documents_seen
tracker.log_eval(eval_metrics, step) # eval loss
tracker.log_eval(save_metrics, step) # checkpoint/save_sec, checkpoint/wait_sec
tracker.log_eval(vote_metrics, step) # distributed/shutdown_vote_ms
```

The eval loss and the per-source metrics are reduced over the same
Expand All @@ -223,6 +225,17 @@ shutdown finds this step already saved, and when a freeze stage
flushes. Neither is in `step_time`, except a freeze stage's flush,
which runs inside its step.

`distributed/shutdown_vote_ms` is the mean time, in milliseconds, of the
shutdown votes (see
[SLURM preemption](../resilience/slurm-preemption.md#why-cooperative-not-sysexit))
since the last logged step, a step skipped for a NaN loss included. The
loop times the vote's all-reduce alone with `time.perf_counter`, with no
synchronization added, and logs the mean after the vote of each step
whose metrics were logged. It is rank 0's time from entering the
all-reduce to leaving it, so it includes any wait for a rank that reached
the vote later, and it is not in `step_time`. A single process has no
process group, so its vote reduces nothing and is not logged.

A VLM run's data metrics are each summed over the data-parallel ranks:
`data/text_tokens_trained` counts the supervised text tokens of the step,
`data/text_tokens` every text token of its documents (prompt included,
Expand Down
15 changes: 15 additions & 0 deletions docs/resilience/slurm-preemption.md
Original file line number Diff line number Diff line change
Expand Up @@ -146,6 +146,21 @@ in a different order on different ranks. On a gloo group of its own,
the vote also completes when NCCL is wedged. The NCCL liveness check
votes the same way (see [NCCL liveness](nccl-liveness.md)).

The vote is a blocking all-reduce at every step, after
`tracker.end_step`, so `step_time`, `tok/s` and MFU leave it out. A
distributed run logs its cost instead on each logged step, as
`distributed/shutdown_vote_ms`: the mean time rank 0 spent in the votes
since the last logged step, including any wait for a rank that reached
the vote later (see
[Metrics tracker § Eval path](../metrics-and-profiling/metrics-tracker.md#eval-path)).
Its value from a multi-node run decides whether the vote's two flags should
ride on the all-reduce that `NaNDetector.check_loss` already makes at
every step instead, which would drop one collective per step
([#564](https://github.com/KempnerInstitute/KempnerForge/issues/564)).
Folding would save only the all-reduce's own latency: time rank 0 spends
waiting for a rank that reached the vote later would move to the next
collective rather than go away.

### Forced-exit timer

Cooperative shutdown assumes the loop reaches the polling point. If a
Expand Down
6 changes: 5 additions & 1 deletion docs/training/training-loop.md
Original file line number Diff line number Diff line change
Expand Up @@ -283,7 +283,11 @@ emergency or final) logs the time the loop waited for it as
saved, the wait at the first step at which no rank is still writing a
pending save, a freeze stage's flush) logs `checkpoint/wait_sec`; a drain with
nothing pending logs nothing. A freeze stage's flush runs inside its
step, so it is also in that step's `step_time`.
step, so it is also in that step's `step_time`. The shutdown vote's
all-reduce is timed too: after the vote of each logged step, a
distributed run logs the mean of the votes since the last logged step
as `distributed/shutdown_vote_ms` (see
[Metrics tracker § Eval path](../metrics-and-profiling/metrics-tracker.md#eval-path)).

## Entry-point setup

Expand Down
40 changes: 38 additions & 2 deletions kempnerforge/training/loop.py
Original file line number Diff line number Diff line change
Expand Up @@ -217,6 +217,8 @@ class TrainingSession:
documents_seen: int | None = None
_batch_stream: BatchStream | None = field(default=None, init=False, repr=False)
_dp_groups: tuple | None = field(default=None, init=False, repr=False)
_vote_seconds: float = field(default=0.0, init=False, repr=False)
_vote_count: int = field(default=0, init=False, repr=False)

@property
def batches(self) -> BatchStream:
Expand Down Expand Up @@ -927,13 +929,31 @@ def _apply_step_transitions(session: TrainingSession, step: int) -> None:
session.batches.reset()


def _record_vote(session: TrainingSession, seconds: float, step: int, *, log: bool) -> None:
"""Add one shutdown vote's time; with ``log``, log the votes' mean and start over.

The mean, in milliseconds, of the votes since the last logged mean is logged at ``step``
as ``distributed/shutdown_vote_ms``. Without a control group the vote is this rank's own
flags, with no all-reduce to time, so nothing is recorded.
"""
if session.control_group is None:
return
session._vote_seconds += seconds
session._vote_count += 1
if log:
mean_ms = 1000 * session._vote_seconds / session._vote_count
session.tracker.log_eval({"distributed/shutdown_vote_ms": mean_ms}, step)
session._vote_seconds, session._vote_count = 0.0, 0


def _shutdown_if_requested(
session: TrainingSession,
step: int,
tokens_seen: int,
*,
saved_this_step: bool,
nan_skipped: bool = False,
log_vote: bool = False,
) -> bool:
"""Write the emergency checkpoint when a shutdown is pending on any rank.

Expand Down Expand Up @@ -962,11 +982,20 @@ def _shutdown_if_requested(
gradient norm were finite) they are not, and their checkpoint would
become ``latest`` and count toward ``keep_last_n``, which can prune the
last good one.

The vote's all-reduce alone is timed, with ``time.perf_counter`` and no
synchronization added, so the time includes any wait for a rank that
reaches the vote later. With ``log_vote``, which the loop sets on a step
whose metrics were logged, the mean over the votes since the last logged
one is logged as ``distributed/shutdown_vote_ms`` (see ``_record_vote``).
"""
session.shutdown_handler.reinstall()
requested_here = session.shutdown_handler.should_shutdown()
ckpt_mgr = session.checkpointer
requested, flushing = any_rank_each([requested_here, ckpt_mgr.flushing], session.control_group)
flags = [requested_here, ckpt_mgr.flushing]
start = time.perf_counter()
requested, flushing = any_rank_each(flags, session.control_group)
_record_vote(session, time.perf_counter() - start, step, log=log_vote)
if not requested:
if ckpt_mgr.has_pending_save and not flushing:
with _logged_time(session.tracker, "checkpoint/wait_sec", step):
Expand Down Expand Up @@ -1105,6 +1134,7 @@ def run_training_loop(
owns_control_group = session.control_group is None
if owns_control_group:
session.control_group = new_control_group(config.distributed.nccl_timeout_sec)
session._vote_seconds, session._vote_count = 0.0, 0

try:
while step < tc.max_steps:
Expand Down Expand Up @@ -1236,7 +1266,13 @@ def run_training_loop(
)
hooks.on_checkpoint_save(step, config.checkpoint.dir)

if _shutdown_if_requested(session, step, tokens_seen, saved_this_step=saved_this_step):
if _shutdown_if_requested(
session,
step,
tokens_seen,
saved_this_step=saved_this_step,
log_vote=step_metrics is not None,
):
break

if step >= tc.max_steps:
Expand Down
23 changes: 23 additions & 0 deletions tests/unit/test_shutdown_agreement.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
control group it made, and a NaN loss on one rank skips the step on every rank
(#375). A run resumed partway through a run of NaN steps restores the same NaN
count on every rank, so every rank stops at the step the uninterrupted run stops at.
Every rank times the shutdown vote and logs its mean on each logged step (#564).

Two gloo ranks run the real ``run_training_loop``, or ``run_training`` for the
resume, and only one of them sees the event. The loop tests start the ranks with
Expand Down Expand Up @@ -152,6 +153,10 @@ def _run_loop(rank: int, world: int, port: int, case: str, root: str, out_dir: s
if case == "health":
config.train.nccl_health_check_interval = 2
loop.check_nccl_health = lambda: rank != 1
logged: list[tuple[int, dict]] = []
if case == "vote-time":
config.metrics.log_interval = 3
session.tracker.log_eval = lambda m, s: logged.append((s, dict(m)))
mark(out_dir, rank)
if case == "groups":
outcome = _group_lifetime(loop, session)
Expand All @@ -163,6 +168,10 @@ def _run_loop(rank: int, world: int, port: int, case: str, root: str, out_dir: s
if case == "timer":
outcome += f" armed={session.shutdown_handler._timer is not None}"
session.shutdown_handler.finish()
if case == "vote-time":
key = "distributed/shutdown_vote_ms"
ms = {s: m[key] for s, m in logged if key in m}
outcome += f" vote_ms_at={list(ms)} positive={all(v > 0 for v in ms.values())}"
except BaseException as e:
outcome = f"{type(e).__name__}: {e}"
write_outcome(out_dir, rank, outcome)
Expand Down Expand Up @@ -343,3 +352,17 @@ def test_a_resume_in_a_nan_run_stops_every_rank_where_the_run_would(self, tmp_pa
"save": {r: "steps=[0, 1] counts=[0, 1]" for r in range(WORLD)},
"resume": {r: "steps=[2] counts=[2]" for r in range(WORLD)},
}


@pytest.mark.timeout(360)
class TestShutdownVoteTime:
@pytest.fixture(autouse=True)
def _hide_cuda(self, monkeypatch):
"""Start the ranks with CUDA hidden, so the loop's NaN check reduces a CPU flag."""
monkeypatch.setenv("CUDA_VISIBLE_DEVICES", "")

def test_every_rank_times_the_vote_on_the_loops_control_group(self, tmp_path):
"""With a metrics interval of 3, steps 1, 3 and 6 log a positive mean on both ranks."""
outcomes = _outcomes(tmp_path, "vote-time")
expected = "step=6 saves=[6] nans=0 vote_ms_at=[1, 3, 6] positive=True"
assert outcomes == {r: expected for r in range(WORLD)}
107 changes: 107 additions & 0 deletions tests/unit/test_train_entry.py
Original file line number Diff line number Diff line change
Expand Up @@ -6073,6 +6073,113 @@ def counted(flags, group):
assert TestCheckpointTiming._times(logged, "checkpoint/wait_sec") == [(2, 2.0), (4, 2.0)]


class TestShutdownVoteTime:
"""Each logged step of a run with a control group logs ``distributed/shutdown_vote_ms``,
the mean time of the shutdown votes since the last logged step, for #564."""

KEY = "distributed/shutdown_vote_ms"

@staticmethod
def _session(monkeypatch, config, stop_after=None, **overrides):
"""A session on a control group the loop keeps, whose ``k``-th vote takes ``k`` ms.

The handler's reinstall and check before each vote take 1 s each, which the vote's
time leaves out; with ``stop_after``, the handler asks to stop at that check.
Returns the session, what its backend got as ``(step, metrics)`` and the flags of
each vote.
"""
import time

import kempnerforge.training.loop as loop

clock = [0.0]
monkeypatch.setattr(time, "perf_counter", lambda: clock[0])
votes: list[list[bool]] = []

def timed_vote(flags, group):
votes.append(list(flags))
clock[0] += len(votes) / 1000
return [bool(flag) for flag in flags]

class SlowHandler(FakeShutdownHandler):
def reinstall(self):
clock[0] += 1.0
super().reinstall()

def should_shutdown(self):
clock[0] += 1.0
return super().should_shutdown()

monkeypatch.setattr(loop, "any_rank_each", timed_vote)
session = make_session(
config, control_group=object(), shutdown_handler=SlowHandler(stop_after), **overrides
)
logged: list[tuple[int, dict]] = []

class Recorder:
def log(self, metrics, step):
logged.append((step, dict(metrics)))

session.tracker._backends.append(Recorder())
return session, logged, votes

@classmethod
def _vote_times(cls, logged: list[tuple[int, dict]]) -> list[tuple[int, float]]:
return [(step, metrics[cls.KEY]) for step, metrics in logged if cls.KEY in metrics]

def test_each_logged_step_logs_the_mean_of_its_votes(self, monkeypatch):
"""Steps 1, 3 and 6 log 1, (2 + 3) / 2 and (4 + 5 + 6) / 3 ms; step 7's vote is
never logged, and no step that logs nothing logs the key."""
config = make_config(max_steps=7)
config.metrics.log_interval = 3
session, logged, votes = self._session(monkeypatch, config)
run_training_loop(session)
assert len(votes) == 7
assert [step for step, metrics in logged if "train/loss" in metrics] == [1, 3, 6]
times = self._vote_times(logged)
assert times == [(1, pytest.approx(1.0)), (3, pytest.approx(2.5)), (6, pytest.approx(5.0))]
assert all(isinstance(ms, float) and ms >= 0 for _, ms in times)

def test_a_skipped_steps_vote_counts_toward_the_next_logged_mean(self, monkeypatch):
"""Step 2 is skipped for a NaN loss and logs nothing; step 3 logs (2 + 3) / 2 ms."""
config = make_config(max_steps=3)
config.metrics.log_interval = 1
session, logged, votes = self._session(monkeypatch, config, step_fn=_nan_on({1}))
run_training_loop(session)
assert len(votes) == 3
assert [step for step, metrics in logged if "train/loss" in metrics] == [1, 3]
assert self._vote_times(logged) == [(1, pytest.approx(1.0)), (3, pytest.approx(2.5))]

def test_a_new_loop_starts_its_own_interval(self, monkeypatch):
"""The first loop's unlogged step-2 vote is not in the second loop's first mean."""
config = make_config(max_steps=2)
session, logged, votes = self._session(monkeypatch, config)
run_training_loop(session)
run_training_loop(session)
assert len(votes) == 4
assert self._vote_times(logged) == [(1, pytest.approx(1.0)), (1, pytest.approx(3.0))]

def test_a_stop_at_a_logged_step_logs_its_vote(self, monkeypatch):
"""A shutdown asked at step 3, a logged step, logs (2 + 3) / 2 ms there."""
config = make_config(max_steps=7)
config.metrics.log_interval = 3
session, logged, votes = self._session(monkeypatch, config, stop_after=3)
run_training_loop(session)
assert len(votes) == 3
assert self._vote_times(logged) == [(1, pytest.approx(1.0)), (3, pytest.approx(2.5))]

def test_a_run_without_a_control_group_logs_no_vote_time(self, monkeypatch):
"""One process has no process group, so its vote reduces nothing and is not logged."""
config = make_config(max_steps=3)
config.metrics.log_interval = 1
session = make_session(config)
logged: list[tuple[int, dict]] = []
monkeypatch.setattr(session.tracker, "log_eval", lambda m, s: logged.append((s, dict(m))))
run_training_loop(session)
assert session.control_group is None
assert self._vote_times(logged) == []


class TestFreezeStageFence:
"""The stage hook must drain an in-flight save before flipping requires_grad.

Expand Down
Loading