Skip to content

Bound the wait for an async checkpoint write with checkpoint.wait_timeout_sec - #788

Open
Naeemkh wants to merge 7 commits into
mainfrom
fix/bounded-checkpoint-wait
Open

Naeemkh wants to merge 7 commits into
mainfrom
fix/bounded-checkpoint-wait

Conversation

@Naeemkh

@Naeemkh Naeemkh commented Dec 5, 2026 •

Copy link
Copy Markdown
Member

Summary

This is item 2 of #556; #723 did items 1 and 3. An async save's background write is waited for by the next save(), a freeze stage's flush_pending_save(), the loop's final wait() and a shutdown's wait(). AsyncCheckpointer.wait() called future.result() with no timeout, so a write that hangs, as on a stalled filesystem, blocked the run with no error. During a shutdown only the forced-exit timer ended it, and its Graceful shutdown timed out line could not say whether the write was slow or hung.

  • New checkpoint.wait_timeout_sec (float | None, default None). Unset, every wait is as before. When set, it must be a finite number of seconds > 0, and async_mode must be "async" or "async_with_pinned_mem".
  • AsyncCheckpointer(mode, wait_timeout_sec=None) waits with future.result(timeout=...). A write still running when the wait runs out raises the new CheckpointWriteTimeout, a TimeoutError exported from kempnerforge.checkpoint. Its message names the checkpoint being written (its step_N directory, or step_N/ppK under PP) and the timeout, says the writer thread is still running and cannot be stopped, and says to exit rather than save again. The save stays pending under Fail a checkpoint save on every rank before any rank writes, and raise a failed async write once #737's _ended_with rule for an interrupted wait: the next wait or save waits for the same write, no second write starts beside it, and latest never names a step whose write did not finish (see decision 6). A TimeoutError the write itself raised is still the write's own error, raised once.
  • Every rank fails together, with no new collective. The agreement that already follows each wait carries the timeout like any failed flush: _agree_to_write in save(), the barrier that ends wait() and flush_pending_save(), and the stage agreement under PP. The rank that timed out raises CheckpointWriteTimeout, and every other rank raises RuntimeError naming it. That agreement runs on the manager's gloo group, whose collective timeout is group_timeout_sec (distributed.nccl_timeout_sec in training). So the barrier after the flush already has a timeout of its own, and this PR adds no second mechanism for it.
  • No change to the shutdown's forced-exit timer.

What a user notices: nothing unless the field is set. With it set, a hung write fails the run at the next wait with an error naming the checkpoint, instead of blocking; a write slower than the timeout fails the same way; and a config that sets it with async_mode = "disabled" is refused when it loads.

Docs: the [checkpoint] table and the validation rules; a new "A bounded wait" section in the DCP model page; the failure semantics in auto-resume; and the forced-exit timer section of SLURM preemption. Also codebase-map.json.

Decisions taken without waiting (each one you can reverse)

  1. A config field, checkpoint.wait_timeout_sec, default None, which keeps today's behavior exactly; validated as a finite number of seconds > 0.
  2. On a timeout, raise a TimeoutError subclass, CheckpointWriteTimeout, naming the checkpoint, the timeout and the running writer thread, and keep the save pending.
  3. Every rank fails together through the existing agreements and the sync group's existing timeout, with no new collective and no separate timeout for the barrier.
  4. No change to the shutdown's forced-exit timer.
  5. The field is refused with async_mode = "disabled", where nothing would read it, as Refuse [data] fields the run never reads #714 does for unread [data] fields. The message says how to fix it, and --checkpoint.wait_timeout_sec=None unsets it on the command line. Reversing it means accepting the field there silently, or with a warning.
  6. A timed-out write counts as a failed one for the latest commit waiting on it. A save() drops that commit on every rank, and so does every wait under PP, so latest never names the step, even if the write ends later; a later wait() drains the write without committing it. In wait() and flush_pending_save() without PP, rank 0 commits on its own wait's outcome, as before this PR: if the ranks reach the wait far enough apart that the write ends after one rank's timeout but before rank 0's, rank 0 commits the step, whose write has then ended on every rank, since one DCP write spans them. So latest never names a step whose write did not finish. Dropping the commit there too would need one more all-reduce per wait. Keeping it for later would need the agreements to carry a third state per rank (still running, as opposed to failed), since a commit must stay dropped when any rank's write failed. The error tells the process to exit, and the training loop never waits again after it, so the loop loses nothing either way.
  7. The error names the DCP checkpoint directory (<dir>/step_N, or <dir>/step_N/ppK under PP) rather than a bare step number, since AsyncCheckpointer only knows the checkpoint id.
  8. CheckpointWriteTimeout is exported from kempnerforge.checkpoint, and the AsyncCheckpointer constructor validates wait_timeout_sec too, since the class is public API.
  9. checkpoint.wait_timeout_sec must stay below distributed.nccl_timeout_sec, the collective timeout of the agreement that follows each wait. Above it, a rank whose wait has ended, such as one on a pipeline stage whose write did not hang, times out in that agreement first, and the ranks fail with gloo timeout errors instead of CheckpointWriteTimeout. The docs and the field's docstring say so, but validation does not enforce it. Reversing this means refusing a larger value in JobConfig.__post_init__, where both sections are visible.

Open question: exiting after the error

The writer thread cannot be stopped, and Python joins it when the process exits, so a hung writer thread keeps the process alive after CheckpointWriteTimeout. During a shutdown, the forced-exit timer still ends it. Outside one, without PP every rank's write is the same DCP collective, so every rank sits at exit together, the launcher sees no task exit, and the job ends only at its time limit or a cancel. This PR makes the hang diagnosable and fails every rank together; it does not make the process exit by itself. An os._exit in the entry point after CheckpointWriteTimeout may deserve its own issue; it is not part of this PR.

Testing

All on CPU with the CI replica venv (Python 3.14.2, torch 2.14.1), as batch jobs on the shared CPU node. The branch merges main at 3899909 (#772); every gate below ran again at that merge. The review round that followed (three commits, ending at afab6c3) changes wording, tests and codebase-map.json only, so its gates are ruff, pyright, Sphinx -W, the map counts and the two touched test files; the full tests/unit result below is from 68f6cf6.

  • uv run ruff check . passes
  • uv run ruff format --check . passes
  • uv run pyright kempnerforge/ passes (0 errors)
  • uv run pytest tests/unit/ -v --timeout=60 passes, apart from known failures of the shared CPU node: 6650 passed, 14 skipped and 39 failed at the merge head (68f6cf6). 38 of the failures are in test_vlm_dataset.py and test_video_dataset.py, from the purged gpt2 Hugging Face cache (LocalEntryNotFoundError under offline mode); they fail on main too. The 39th is a test_hooks.py case that hit OSError: [Errno 39] Directory not empty in a netscratch temp-directory cleanup; the file passes alone (43 passed). The head before the merge failed the same way (6640 passed).
  • If distributed code changed: uv run torchrun --nproc_per_node=4 -m pytest tests/distributed/ -v. Not run: there are no GPUs on the batch node. No distributed code path changes beyond the manager's existing gloo agreements, which a two-rank gloo test below exercises on CPU.
  • If training loop / parallelism / optimizers changed: uv run pytest tests/e2e/ --e2e -v. Not run: none of them changed, and the e2e tests need GPUs.

New tests: tests/unit/test_checkpoint.py::TestWaitTimeout (13) and four tests (7 items) in tests/unit/test_config.py::TestCheckpointConfig.

  • With a writer thread held on an Event, AsyncCheckpointer.wait() with a 0.5 s timeout raises CheckpointWriteTimeout, imported from kempnerforge.checkpoint, after about 0.5 s, naming the checkpoint, the timeout and the running writer thread. The save stays pending and flushing, and once the event is set, the next wait() drains it.
  • A save() behind a write that ran out dispatches nothing.
  • With the timeout unset, wait() passes no timeout and returns once the write ends (a pin of today's behavior, which passes on main too).
  • A TimeoutError the write itself raised is the write's own error, raised once.
  • The constructor refuses 0, -1, NaN and infinity.
  • Manager: a hung previous write makes save() raise CheckpointWriteTimeout instead of blocking. It writes nothing of its own step, leaves no latest, and never commits the hung step, even once its write ends; the next save commits as usual. The same holds for wait() and flush_pending_save() on one rank.
  • Two real gloo ranks: rank 1's write hangs, and both ranks' save(step=2) raise together after about the 1 s timeout. Rank 1 raises CheckpointWriteTimeout and rank 0 raises RuntimeError: Checkpoint save failed on ranks [1], with no latest. Both ranks then stay in step for the next wait() and save().
  • Two gloo ranks, each saving a pipeline stage of its own: rank 1's write hangs, and wait() raises on both ranks through the stage agreement. Rank 1's error names step_1/pp1, nothing is committed for step 1, even once its write ends, and the next save commits. Removing that stage agreement makes this test fail, as removing the package export makes the export import fail.
  • Config: unset by default; a CLI value loads as seconds; 0, -1, NaN and infinity are refused; and the field is refused with async_mode = "disabled", from TOML too, while --checkpoint.wait_timeout_sec=None unsets it.

Failing first, with these test files on main (3899909): 19 of the 20 new items fail, and the unset-timeout pin passes, as intended. The failures are TypeError: AsyncCheckpointer.__init__() got an unexpected keyword argument 'wait_timeout_sec'; ImportError: cannot import name 'CheckpointWriteTimeout'; TypeError: CheckpointConfig.__init__() got an unexpected keyword argument 'wait_timeout_sec'; AttributeError: 'CheckpointConfig' object has no attribute 'wait_timeout_sec'; ValueError: Unknown config keys in CheckpointConfig: ['wait_timeout_sec']; and the two-rank tests' ProcessRaisedException from the same TypeError. All pass on this branch.

The gap, shown with a probe in which the previous write hangs and save(step=2) runs on a thread for 5 s:

main:                          save(step=2) still blocked after 5.00 s
this branch, timeout unset:    save(step=2) still blocked after 5.00 s
this branch, 0.5 s:            CheckpointWriteTimeout after 0.50 s: The async checkpoint write of .../step_1 did not end within checkpoint.wait_timeout_sec=0.5 s. Its writer thread is still running and cannot be stopped, so the save stays pending. Exit this process rather than save again: the next save would wait for the same write.

latest did not exist after any of the three. A second probe backs the open question above. A process whose ThreadPoolExecutor worker hangs, which is how DCP runs an async write, does not exit after its main thread raises (killed by timeout at 15 s). With a daemon timer that calls os._exit(1), as the forced-exit timer does, it exits at 2.09 s with code 1.

Also checked: at afab6c3, after the review round, test_checkpoint.py and test_config.py (1014 passed), ruff, pyright and Sphinx -W; at the merge head, test_checkpoint.py, test_config.py, test_data_position.py, test_collective_timeouts.py, test_distributed_seed.py and test_train_entry.py (1495 passed); before it, tests/unit/test_checkpoint.py (450 passed), and test_config.py, test_checkpoint_per_rank.py, test_pipeline_checkpoint.py, test_checkpoint_publish.py, test_collective_timeouts.py and test_shutdown_timeout.py (782 passed). Sphinx -W builds clean, and the new #a-bounded-wait anchor resolves from the three pages that link to it. The codebase-map.json counts show only main's known mismatches. The TestCheckpointConfig count goes from a stale 2 to the 40 items it collects.

Main moved after the review round: #782 changed the same tests/unit/test_checkpoint.py count line in codebase-map.json, so this branch no longer merged. 89d601c8 merges main bdaf4a4 and resolves that line to 394 (374 + 13 + 7), the sum of the merged class list; nothing else conflicted. At 89d601c8: ruff, ruff format and pyright (0 errors) pass, test_checkpoint.py and test_config.py pass (1021 passed), the two classes the merge brings together in that map entry, this branch's TestWaitTimeout (13) and main's TestResumedStep (7), match what pytest collects, Sphinx -W builds clean, and the map counts show only main's known mismatches.

Merging with the other open PRs, checked with git merge-tree at 89d601c8: #787 (c9833a33), #789 (db64875f) and #709 (991b0b6a) merge cleanly, each with a valid codebase-map.json and only main's known count mismatches. #648 (dce0ff8e) conflicts with main on its own, in a file this branch does not touch. #781 (506fb678) conflicts only on the same count line, as it does with main; resolve it to the sum of the merged class list (397 at that head: 374 + 13 + 7 + 3). #776 (d4e569bf) conflicts with main on its own, and with this branch in two more places: the _agree_to_write docstring in kempnerforge/checkpoint/manager.py, where each PR adds a sentence about the failure it handles (keep both), and the tests/unit/test_checkpoint.py entry of codebase-map.json (keep both classes' new counts and sum the list).

Contribution terms

Closes #556

@Naeemkh Naeemkh added the core Affecting core label Dec 5, 2026
@Naeemkh
Naeemkh requested a review from amazloumi December 5, 2026 22:52
@codecov

codecov Bot commented Dec 5, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.

Files with missing lines Coverage Δ
kempnerforge/checkpoint/__init__.py 100.00% <100.00%> (ø)
kempnerforge/checkpoint/async_save.py 98.92% <100.00%> (+0.14%) ⬆️
kempnerforge/checkpoint/manager.py 99.17% <100.00%> (ø)
kempnerforge/config/checkpoint.py 100.00% <100.00%> (ø)
🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

amazloumi
amazloumi previously approved these changes Dec 6, 2026

@amazloumi amazloumi left a comment •

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Approve. With checkpoint.wait_timeout_sec set, a hung async write now fails every rank together within the timeout, with an error naming the checkpoint and no new collective, and latest never names an unfinished step; left unset, every wait behaves as on main. This held with FSDP and with two pipeline stages on four GPUs, on the save path, the final wait and the shutdown path, and the new tests fail when any line they cover is changed.

Three points that should not hold up the merge:

  1. After CheckpointWriteTimeout the process still does not exit, since Python joins the writer thread at exit, so outside a shutdown a write that never ends holds every rank until the job's time limit (in a 4 GPU run with a 60 s hung write, every rank raised after 5 s but exited only when the write ended). The body already names this; could the follow-up get its own issue?
  2. The rule that wait_timeout_sec stays below distributed.nccl_timeout_sec is only documented. A config that breaks it loads and then fails with gloo timeout errors instead of CheckpointWriteTimeout; JobConfig.post_init sees both values and could refuse it at load time.
  3. Without PP, when rank 0's wait ends well but another rank's timed out, rank 0 commits latest to that (complete) step while every rank reports "Checkpoint save failed on ranks [...]", which could mislead someone reading the logs.

The branch now conflicts with main in codebase-map.json (the test count), so it needs a main merge before it can go in.

@amazloumi amazloumi left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Approve. The main merge resolves its one conflict, the test count in codebase-map.json, to the sum of both sides' classes (394), and nothing else differs from a clean merge. With main's resumed-step and gradient-clearing changes in, a hung write still fails every rank together within the timeout with FSDP and with two pipeline stages, and latest never names an unfinished step. The three not-blocking points of the earlier approval still apply as posted.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

core Affecting core

Projects

None yet

Development

Successfully merging this pull request may close these issues.

shutdown_timeout_sec cannot fire before SLURM's SIGKILL, so nothing bounds a hung emergency flush

2 participants