Repository navigation
[Train] Relax Ray Train collectives on preemption - #66225
Conversation
…n commit a just-in-time checkpoint Signed-off-by: Lehui Liu <[email protected]>
There was a problem hiding this comment.
Code Review
This pull request introduces a mechanism to relax synchronization barriers and report consolidation gates during node preemption in Ray Train v2. By allowing collectives and checkpoint reports to complete with only the surviving ranks, healthy workers can successfully commit just-in-time checkpoints instead of being stranded. This is supported by tracking collective sequence numbers to prevent stragglers from receiving incorrect payloads, and introducing new configuration options (relax_collectives_on_preemption and preemption_grace_s) in FailureConfig. Feedback-wise, a potential bug was identified in ReportCallbackHandler where an empty list of expected indices could bypass the queue validation and subsequently cause an out-of-bounds IndexError when processing worker metrics. A defensive check is recommended to handle this scenario safely.
| expected_indices = self._get_expected_indices() | ||
| if not all(self._training_report_queues[i] for i in expected_indices): | ||
| return |
There was a problem hiding this comment.
If expected_indices is empty, all(...) evaluates to True, which means the condition not all(...) will be False and the execution will proceed. This leads to an empty metrics_per_worker list, causing an IndexError: list index out of range at line 126 when accessing metrics_per_worker[0].\n\nWe should defensively guard against an empty expected_indices list by returning early.
expected_indices = self._get_expected_indices()\n if not expected_indices or not all(self._training_report_queues[i] for i in expected_indices):\n returnThere was a problem hiding this comment.
Cursor Bugbot has reviewed your changes using default effort and found 2 potential issues.
Reviewed by Cursor Bugbot for commit c5ca9d6. Configure here.
pseudo-rnd-thoughts
left a comment
There was a problem hiding this comment.
To confirm that I understand the PR. Currently on a node preemption, when the deadline hits, then all workers are torn down. This PR expands this capability to allow non-preempted nodes to "survive" beyond the deadline which are responsible for saving a checkpoint which should allow users to save a checkpoint that takes longer than the preemption warning window. This feature is enabled by relax_collectives_on_preemption=True and preemption_grace_s=10.0. The edge case we don't support is worker 0 being preempted and surviving.
Overall, I can't see any significant issues within the PR, I more have suggestions on variables / comments / docstrings for future readers to improve.
Signed-off-by: Lehui Liu <[email protected]>
## Description `//python/ray/train/v2:test_sync_actor` is timing out in CI on every run. It is not a flake: all 17 tests pass, but the target goes over Bazel's 60s limit for `size = "small"`. From the failing build, both attempts showed: - `17 passed in 56.93s` and `17 passed in 57.81s` - `TIMEOUT in 2 out of 2 in 60.0s` That leaves about 2–3s for Python startup, test collection and the module fixture's `ray.shutdown()`, which isn't enough on a loaded CI machine. The slowdown comes from #66225, which added 10 tests to this file. Most of them check that a barrier stays blocked by calling `ray.wait(..., timeout=N)` and asserting nothing finished. Those waits always run for their full timeout, so together they add about 28s of fixed wall time to the module. This PR changes the target from `size = "small"` to `size = "medium"` (300s limit). No test logic changes. Signed-off-by: Lehui Liu <[email protected]>
## Description When a node is drained, Ray Train enabled each worker to react to preemption signal with [ray.train.get_preemption_info()](https://docs.ray.io/en/latest/train/api/doc/ray.train.get_preemption_info.html) so that user can save a just-in-time checkpoint. However, if the affected rank got reclaimed before jit checkpoint fully committed, even if the survivor ranks has full model replica, they will not be able to committed by Ray Train because of the following reasons: 1. 3 collectives need every rank to be alive: `ray.train.report()` broadcasts a checkpoint directory name on the `SynchronizationActor`, `ray.train.get_preemption_info()` uses the same actor, and `ReportCallbackHandler` gates consolidation on one report per rank. A worker reclaimed before it reaches `report()` strands its peers until the deadline. 2. The controller tears the survivors down the moment the deadline passes. A checkpoint that takes longer than the drain window is killed mid-write, so the report will not be reachable, even though the survivor ranks contains the full model replica. This PR addresses both, behind two opt-in `FailureConfig` knobs: - **`relax_collectives_on_preemption`** — allow user to config the above barrier behavior during preemption so that the barrier releases without the reclaimed workers. - **`preemption_grace_s`** — how long the survivors may keep running past the drain deadline, so a slow checkpoint can finish before the restart. ### Usage The training function does not change. User should keep your existing save-and-report helper and call it once more when a preemption is announced, then keep training: ```python def save_checkpoint(metrics, model): with tempfile.TemporaryDirectory() as temp_checkpoint_dir: checkpoint = None if train.get_context().get_world_rank() == 0: ... # Save checkpoint to temp_checkpoint_dir checkpoint = Checkpoint.from_directory(temp_checkpoint_dir) train.report(metrics, checkpoint=checkpoint) def train_fn(config): saved_on_preemption = False for step in range(config["total_steps"]): ... # Training step metrics = {"step": step} preemption_info = train.get_preemption_info() if preemption_info is not None and not saved_on_preemption: # A node is being reclaimed. Save one extra checkpoint now, then # keep training until the node actually goes away. save_checkpoint(metrics, model) saved_on_preemption = True ``` ```python failure_config = ray.train.FailureConfig( max_preemption_failures=3, relax_collectives_on_preemption=True, preemption_grace_s=60.0, ) ``` ### limitation: 1. rank 0 cannot be relaxed at this moment, we keep this behavior same as other checkpoint library. For DDP only, we can have a TODO to enable rank 0 to be relaxed as well. ## Additional information testing script: https://gist.github.com/liulehui/8a38d63956e93ee385a041a3acba1464 corresponding log output: ``` (RayTrainWorker pid=82348) Reporting training result 1: TrainingReport(checkpoint=None, metrics={'step': 0}, validation=False) from rank 0 [22:10:32.505 PDT] [drain] rank 1 is on node 79e9dd4b...; placement={0: 'ae06fed2', 1: '79e9dd4b'} [22:10:32.512 PDT] [drain] node=79e9dd4b... drained via GCS, deadline=+12s (22:10:44.507 PDT) (RayTrainWorker pid=82348) Rank 0 received preemption signal (this_worker_preempted=False, preempted_ranks=[1], deadline_ms=1789621844507). (RayTrainWorker pid=82347) Rank 1 received preemption signal (this_worker_preempted=True, preempted_ranks=[1], deadline_ms=1789621844507). (PreemptionWatcher pid=82395) PreemptionWatcher: preemption detected — preempted_node_ids=['79e9dd4b4465cf9b494a6a1b4e829b8fe83e37e2906ce7be965679f2'], preempted_ranks=[1], deadline_ms=1789621844507 (TrainController pid=82321) Preemption detected on ranks [1]. Relaxed the report barrier to ranks [0] so they can commit a just-in-time checkpoint without them. (SynchronizationActor pid=82345) Synchronization barrier relaxed to expect ranks [0]. (RayTrainWorker pid=82348) [rank 0] PREEMPT signal: this=False preempted_ranks=[1] sec_left=10.4 (RayTrainWorker pid=82348) [rank 0] writing a 20s checkpoint at step 3 (RayTrainWorker pid=82347) [rank 1] PREEMPT signal: this=True preempted_ranks=[1] sec_left=10.4 (RayTrainWorker pid=82347) [rank 1] STALLING at step 3, waiting to be reclaimed WITHOUT calling report() (RayTrainWorker pid=82347) [rank 1] PREEMPT signal: this=True preempted_ranks=[1] sec_left=10.4 (RayTrainWorker pid=82347) [rank 1] STALLING at step 3, waiting to be reclaimed WITHOUT calling report() (RayTrainWorker pid=82348) [rank 0] PREEMPT signal: this=False preempted_ranks=[1] sec_left=10.4 (RayTrainWorker pid=82348) [rank 0] writing a 20s checkpoint at step 3 [22:10:46.511 PDT] [evict] +2s past the drain deadline -> removing node 79e9dd4b... (reclaim) (RayTrainWorker pid=82348) [rank 0] EMERGENCY checkpoint at step 3 (RayTrainWorker pid=82348) Checkpoint successfully created at: Checkpoint(filesystem=local, path=/var/folders/xv/0ps50qx155xd08dr1kk37t7m0000gp/T/relax_barrier_slow_ckpt_grace_35rcx2js/relax_barrier_slow_ckpt_grace/checkpoint_2026-09-16_22-10-54.162754) (RayTrainWorker pid=82348) Reporting training result 4: TrainingReport(checkpoint=Checkpoint(filesystem=local, path=/var/folders/xv/0ps50qx155xd08dr1kk37t7m0000gp/T/relax_barrier_slow_ckpt_grace_35rcx2js/relax_barrier_slow_ckpt_grace/checkpoint_2026-09-16_22-10-54.162754), metrics={'step': 3}, validation=False) from rank 0 (RayTrainWorker pid=82348) [rank 0] EMERGENCY report() RETURNED at step 3 (raylet) /opt/homebrew/Caskroom/miniconda/base/envs/raytrain/lib/python3.12/site-packages/requests/__init__.py:86: RequestsDependencyWarning: Unable to find acceptable character detection dependency (chardet or charset_normalizer). [repeated 2x across cluster] (raylet) warnings.warn( [repeated 2x across cluster] (RayTrainWorker pid=82347) [W916 22:10:29.337089000 ProcessGroupGloo.cpp:547] Warning: Unable to resolve hostname to a (local) address. Using the loopback address as fallback. Manually set the network interface to bind to with GLOO_SOCKET_IFNAME. (function operator()) (RayTrainWorker pid=82347) [rank 1] STARTED FRESH (RayTrainWorker pid=82347) Reporting training result 3: TrainingReport(checkpoint=None, metrics={'step': 2}, validation=False) from rank 1 [repeated 5x across cluster] (RayTrainWorker pid=82348) [rank 0] EMERGENCY checkpoint at step 3 (RayTrainWorker pid=82348) [rank 0] EMERGENCY report() RETURNED at step 3 (RayTrainWorker pid=82348) [rank 0] STARTED FRESH (RayTrainWorker pid=82348) Reporting training result 7: TrainingReport(checkpoint=None, metrics={'step': 6}, validation=False) from rank 0 [repeated 3x across cluster] (RayTrainWorker pid=82348) Reporting training result 10: TrainingReport(checkpoint=None, metrics={'step': 9}, validation=False) from rank 0 [repeated 3x across cluster] (RayTrainWorker pid=82348) Reporting training result 13: TrainingReport(checkpoint=None, metrics={'step': 12}, validation=False) from rank 0 [repeated 3x across cluster] (RayTrainWorker pid=82348) Reporting training result 16: TrainingReport(checkpoint=None, metrics={'step': 15}, validation=False) from rank 0 [repeated 3x across cluster] (RayTrainWorker pid=82348) Reporting training result 19: TrainingReport(checkpoint=None, metrics={'step': 18}, validation=False) from rank 0 [repeated 3x across cluster] (TrainController pid=82321) [FailurePolicy] RETRY (TrainController pid=82321) Source: preemption (TrainController pid=82321) Error count: 1 (max allowed: 3) (TrainController pid=82321) Error: Training was interrupted by node preemption (preempted_ranks=[1], drain_timed_out=True). (TrainController pid=82321) ray.train.PreemptionError: Training was interrupted by node preemption (preempted_ranks=[1], drain_timed_out=True). (TrainController pid=82321) Graceful shutdown of backend failed. This is expected if one of the workers has crashed. (TrainController pid=82321) Traceback (most recent call last): (TrainController pid=82321) File "/Users/lehui/Desktop/ray/python/ray/train/v2/_internal/callbacks/backend_setup.py", line 27, in before_execution_group_shutdown (TrainController pid=82321) self._backend.on_shutdown(execution_group, self._backend_config) (TrainController pid=82321) File "/Users/lehui/Desktop/ray/python/ray/train/torch/config.py", line 280, in on_shutdown (TrainController pid=82321) ray.get(futures, timeout=timeout_s) (TrainController pid=82321) File "/Users/lehui/Desktop/ray/python/ray/_private/auto_init_hook.py", line 22, in auto_init_wrapper (TrainController pid=82321) return fn(*args, **kwargs) (TrainController pid=82321) ^^^^^^^^^^^^^^^^^^^ (TrainController pid=82321) File "/Users/lehui/Desktop/ray/python/ray/_private/client_mode_hook.py", line 134, in wrapper (TrainController pid=82321) return func(*args, **kwargs) (TrainController pid=82321) ^^^^^^^^^^^^^^^^^^^^^ (TrainController pid=82321) File "/Users/lehui/Desktop/ray/python/ray/_private/worker.py", line 2996, in get (TrainController pid=82321) values, debugger_breakpoint = worker.get_objects( (TrainController pid=82321) ^^^^^^^^^^^^^^^^^^^ (TrainController pid=82321) File "/Users/lehui/Desktop/ray/python/ray/_private/worker.py", line 1053, in get_objects (TrainController pid=82321) raise value (TrainController pid=82321) ray.exceptions.ActorDiedError: The actor died unexpectedly before finishing this task. (TrainController pid=82321) class_name: RayTrainWorker (TrainController pid=82321) actor_id: ed9d29087337315cbccf66dd01000000 (TrainController pid=82321) pid: 82347 (TrainController pid=82321) namespace: a61647dc-023c-4cdf-8201-b34fb5b743fa (TrainController pid=82321) ip: 127.0.0.1 (TrainController pid=82321) The actor died because its node has died. Node Id: 79e9dd4b4465cf9b494a6a1b4e829b8fe83e37e2906ce7be965679f2 (TrainController pid=82321) the actor's node was preempted: relax_barrier_demo: simulating node drain (TrainController pid=82321) Attempting to start training worker group of size 2 with the following resources: [{'worker_node': 1}] * 2 (raylet) /opt/homebrew/Caskroom/miniconda/base/envs/raytrain/lib/python3.12/site-packages/requests/__init__.py:86: RequestsDependencyWarning: Unable to find acceptable character detection dependency (chardet or charset_normalizer). (raylet) warnings.warn( (RayTrainWorker pid=82348) Reporting training result 20: TrainingReport(checkpoint=None, metrics={'step': 19}, validation=False) from rank 0 (RayTrainWorker pid=82556) Setting up process group for: env:// [rank=0, world_size=2] (TrainController pid=82321) Started training worker group of size 2: (TrainController pid=82321) - (ip=127.0.0.1, pid=82556) world_rank=0, local_rank=0, node_rank=0 (TrainController pid=82321) - (ip=127.0.0.1, pid=82555) world_rank=1, local_rank=1, node_rank=0 (raylet) /opt/homebrew/Caskroom/miniconda/base/envs/raytrain/lib/python3.12/site-packages/requests/__init__.py:86: RequestsDependencyWarning: Unable to find acceptable character detection dependency (chardet or charset_normalizer). [repeated 7x across cluster] (raylet) warnings.warn( [repeated 7x across cluster] (RayTrainWorker pid=82555) [rank 1] RESUMED from step 3 (checkpoint contains: ['shard_rank0.json']) ``` --------- Signed-off-by: Lehui Liu <[email protected]>
…oject#66752) ## Description `//python/ray/train/v2:test_sync_actor` is timing out in CI on every run. It is not a flake: all 17 tests pass, but the target goes over Bazel's 60s limit for `size = "small"`. From the failing build, both attempts showed: - `17 passed in 56.93s` and `17 passed in 57.81s` - `TIMEOUT in 2 out of 2 in 60.0s` That leaves about 2–3s for Python startup, test collection and the module fixture's `ray.shutdown()`, which isn't enough on a loaded CI machine. The slowdown comes from ray-project#66225, which added 10 tests to this file. Most of them check that a barrier stays blocked by calling `ray.wait(..., timeout=N)` and asserting nothing finished. Those waits always run for their full timeout, so together they add about 28s of fixed wall time to the module. This PR changes the target from `size = "small"` to `size = "medium"` (300s limit). No test logic changes. Signed-off-by: Lehui Liu <[email protected]>
## Description Ray Train added a preemption-handling API (`ray.train.get_preemption_info()`, `PreemptionInfo`, `PreemptionError`, and the `FailureConfig` options `max_preemption_failures`, `relax_collectives_on_preemption`, and `preemption_grace_s`). None of it has a user guide. This PR adds a "Just-in-time checkpointing on node preemption" section to the Train fault tolerance guide (`train/user-guides/fault-tolerance.rst`). The section covers: - **How Ray Train handles a preemption**: detection through Ray Core draining nodes (including TPU slice fate-sharing), the `PreemptionInfo` every rank receives, the drain window (120s fallback when there's no deadline), and the restart. The restart counts against `max_preemption_failures`, which is separate from `max_failures`. - **Save a just-in-time checkpoint**: a runnable `TorchTrainer` example with the preemption-specific lines highlighted. It comes with the usage rules: call `get_preemption_info()` the same number of times on every rank because it's a barrier, save once, fit the upload in the drain window, and don't `return` after saving, because a clean return finishes the run. - **Finish slow checkpoints without the preempted workers**: when to use `relax_collectives_on_preemption` and `preemption_grace_s`. A warning lists the limits: rank 0 must survive, sharded checkpoints (FSDP or ZeRO) can be committed without the preempted ranks' shards, and collectives in user code aren't relaxed. - **Make preemptions visible to Ray**: Briefly introduce how to integrates with Ray core draining code api ## Related issues 1. #63807, #64099, #64360, #66225 2. #63968 ## Additional information Test locally with `make local`, see screenshot below: <img width="2704" height="1588" alt="image" src="https://github.com/user-attachments/assets/e541aa79-5ec1-44d7-a44b-26f9f44f48b3" /> <img width="2682" height="842" alt="image" src="https://github.com/user-attachments/assets/8d32a6c6-06f6-425c-9dbc-b490a225bfee" /> <img width="2674" height="1754" alt="image" src="https://github.com/user-attachments/assets/637d3eff-2980-4bf6-b0f1-4179a756c8ec" /> <img width="2654" height="1586" alt="image" src="https://github.com/user-attachments/assets/18e40213-6c28-41de-b989-5a725c0cc01a" /> <img width="2632" height="1780" alt="image" src="https://github.com/user-attachments/assets/03663ff9-ed65-411e-82a4-54fba7985aa0" /> --------- Signed-off-by: Lehui Liu <[email protected]>
Reverts #66002 on `releases/2.60.0`. This is the release-branch counterpart of #67337, which reverts #66646 and then #66002 on master. This branch never had #66646, so only #66002 is reverted here. ## Why #66002 pins every Train V2 worker to a node from the AutoscalingCoordinator's reservation. #67337 explains why that reservation isn't accurate enough to pin to: - It counts draining nodes and capacity held by work that never went through the coordinator. - It moves when nodes join. When a pin is wrong, the pinned placement group never gets placed, and the controller retries the same pins indefinitely. On this branch, the `train_elastic_e2e_with_node_killing.aws` release test failed in 3 of its 5 weekly release-pipeline runs. In builds 109533 and 111090 it looped on `WorkerGroupStartupTimeoutError` until the job timed out. #66766, where STRICT_SPREAD runs can wait forever, also bisects to #66002. After this revert, Train V2 schedules workers the way it did in 2.59. #66001 and #66370 stay, as in #67337, so Train still uses the coordinator's reservation to count how many workers fit. This is the alternative to #67327, which cherry-picks #66646 onto this branch instead. If this PR merges, #67327 should be closed. ## Revert details `git revert e39557f` applied with no conflicts, and git merged #66225's later change to `controller.py` automatically. The revert touches 11 files, with 70 insertions and 759 deletions. - The diff is byte-identical to #67337's revert of #66002 (deb5235), index lines included. - Before the revert, the 11 files on this branch were identical to master right after #67337 reverts #66646. After the revert, they match #67337's head. - No code on this branch references the functions or classes the revert removes. The few names that still have references are definitions that existed before #66002, such as the Ray Data coordinator's `get_reserved_resources`. Not a duplicate: no PR against `releases/2.60.0` reverts #66002. #67337 targets `master`. ## Testing | Command | Result | |---|---| | pre-commit, run as the commit hook on the 11 changed files | Passed (ruff, black, pydoclint, Ray Train circular imports, and the other applicable hooks) | I didn't run the unit tests locally. CI runs them on this PR: - `:bullettrain_front: ml: train v2 tests` runs the `train_v2`-tagged tests, including `test_controller.py`, `test_elastic_scaling_policy.py`, `test_autoscaling_coordinator_client.py` and `test_failure_policy.py`. - `:train: ml: train v1 tests` runs `python/ray/train/tests/test_autoscaling_coordinator_client.py`. - `:train: ml: data integration tests` runs `test_data_integration.py`. #67337 ran the same test files against the same resulting code on master, and they passed. AI assistance was used to prepare this revert. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Signed-off-by: Sai Miduthuri <[email protected]> Co-authored-by: Claude Opus 5.5 (1M context) <[email protected]>
**Problem**
- Ray Train V2 has been the default since Ray 2.51: `is_v2_enabled()`
defaults to `True`.
- A few Train docs on master still tell readers to set
`RAY_TRAIN_V2_ENABLED=1`.
- The rendered report-callback snippet on the monitoring page asserts
that the variable equals `"1"`. If you copy it as-is, it raises
`KeyError`.
**Change**
- `local-mode.md`: drop `RAY_TRAIN_V2_ENABLED=1` from the two multi-node
`torchrun` commands. The single-node command on the same page already
has none.
- `deprecated.rst`: say that V2 is the default since 2.51, and point to
`RAY_TRAIN_V2_ENABLED=0` for the deprecated V1 API.
- `doc_code/{fault_tolerance,metric_logging,train_tune_interop}.py`:
remove the lines that set or assert the variable.
```
RAY_TRAIN_V2_ENABLED=1 torchrun ... -> torchrun ...
"can be enabled by setting =1" -> "the default starting in Ray 2.51;
for V1, set =0"
os.environ[...] = "1" / assert == "1" -> removed
```
**Decisions to confirm**
- This keeps the "Ray 2.43 through 2.50" notes added in #66895.
- This leaves the intentional `=0` V1 opt-outs alone (`dl_guide.py`,
`tuner.py`, `hvd_trainer.py`, `horovod.md`, the V1 doctests in
`doc/BUILD.bazel`).
**Related:** follows #66895. The FSDP2 example page and several other
templates come from `anyscale/templates` and still set the flag. They
are not part of this PR.
**Tested:** `metric_logging.py` and `train_tune_interop.py` run cleanly
with the variable unset. In `fault_tolerance.py` every section runs up
to the `relax_collectives_on_preemption` block, which needs master
(#66225); the test venv had Ray 2.59.
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Signed-off-by: Marwan Sarieddine <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>

Description
When a node is drained, Ray Train enabled each worker to react to preemption signal with ray.train.get_preemption_info() so that user can save a just-in-time checkpoint. However, if the affected rank got reclaimed before jit checkpoint fully committed, even if the survivor ranks has full model replica, they will not be able to committed by Ray Train because of the following reasons:
ray.train.report()broadcasts a checkpoint directory name on theSynchronizationActor,ray.train.get_preemption_info()uses the same actor, andReportCallbackHandlergates consolidation on one report per rank. A worker reclaimed before it reachesreport()strands its peers until the deadline.A checkpoint that takes longer than the drain window is killed mid-write, so the report will not be reachable, even though the survivor ranks contains the full model replica.
This PR addresses both, behind two opt-in
FailureConfigknobs:relax_collectives_on_preemption— allow user to config the above barrier behavior during preemption so that the barrier releases without the reclaimed workers.preemption_grace_s— how long the survivors may keep running past the drain deadline, so a slow checkpoint can finish before the restart.Usage
The training function does not change. User should keep your existing save-and-report helper and call it once more when a preemption is announced, then keep training:
limitation:
Additional information
testing script: https://gist.github.com/liulehui/8a38d63956e93ee385a041a3acba1464
corresponding log output: