Skip to content

[train][Preemption handling 2/n] Fan out preemption signal to workers - #64099

Merged
justinvyu merged 8 commits into
ray-project:masterfrom
liulehui:preempt-stage2-worker
Jun 24, 2026
Merged

justinvyu merged 8 commits into
ray-project:masterfrom
liulehui:preempt-stage2-worker

Conversation

@liulehui

@liulehui liulehui commented Jun 15, 2026 •

Copy link
Copy Markdown
Contributor

Description

  1. Builds on top of the Stage 1 preemption watcher ([train][Preemption handling 1/n] Add preemption watcher for node-drain observability #63807): when the watcher detects a preemption, it now fans the signal out to the worker actors and stores in PreemptionContext in the TrainContext
  2. added a rpc for mark_preempt in Train worker
  3. watcher fans out preemptionInfo through every worker handle.
  4. follow up PR will add public apis and controller state.

Related issues

#63968

Additional information

  1. added unit tests
  2. ran this script: https://gist.github.com/liulehui/fc9bd4a6fe58b72a85363c0cda619f7e/edit
    logs to ensure information got fan out to workers:
[14:10:49.909 PDT] [drain] node=62e4d889... drained via GCS, deadline=+15s (14:11:04.905 PDT)
(RayTrainWorker pid=99129) Rank 0 received preemption signal (this_worker_preempted=False, preempted_ranks=[1], deadline_ms=1781557864905).
(RayTrainWorker pid=99128) Rank 1 received preemption signal (this_worker_preempted=True, preempted_ranks=[1], deadline_ms=1781557864905).
(PreemptionWatcher pid=99150) PreemptionWatcher: preemption detected — preempted_node_ids=['62e4d8896da4bad4ce970556147a5a927425ab980253cdcd3af74f6e'], preempted_ranks=[1], deadline_ms=1781557864905
(RayTrainWorker pid=99129) [rank 0] PREEMPT signal: this=False ranks=[1] sec_left=13.7
(RayTrainWorker pid=99128) [rank 1] PREEMPT signal: this=True ranks=[1] sec_left=13.7
(RayTrainWorker pid=99128) [rank 1] PREEMPT signal: this=True ranks=[1] sec_left=13.7

@liulehui
liulehui requested a review from a team as a code owner June 15, 2026 16:56

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Code Review

This pull request implements a mechanism to forward detected preemption signals from the PreemptionWatcher to individual worker actors, allowing the training loop to react to node drains. It introduces a thread-shared PreemptionContext on the worker's TrainContext and adds a mark_preempt RPC method to the worker actor to receive and store these signals. The feedback highlights a potential race condition where mark_preempt could be called before TrainContext is initialized, and suggests catching RuntimeError to queue the signal. Additionally, suggestions are provided to make internal dataclass fields private by setting init=False and to add defensive checks against unpopulated distributed contexts in the preemption callback.

Important

The consumer version of Gemini Code Assist on GitHub is being sunset. Starting June 18, 2026, new organization installations will be blocked, and all code review activity will officially cease on July 17, 2026.
For more details on the timeline and next steps, please review the Help Documentation.

Signed-off-by: Lehui Liu <[email protected]>
@liulehui
liulehui force-pushed the preempt-stage2-worker branch from f27329b to 41588c7 Compare June 15, 2026 18:21
@ray-gardener ray-gardener Bot added the train Ray Train Related Issue label Jun 15, 2026

@pseudo-rnd-thoughts pseudo-rnd-thoughts 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.

Looks good to me. Do we have any end to end tests like release tests to check the spot node preemption works fully?

error=error,
training_report=training_report,
return_value=return_value,
preemption_info=train_context.preemption_context.get(),

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.

With the threading lock, do we know the effect as the number of nodes scale? Does this act like a sync barrier between all nodes or is it async so minimal overhead is expected?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

I think the overhead is minimal, the watcher fan out the preemption info to worker async, this should be independent calls.

@pseudo-rnd-thoughts pseudo-rnd-thoughts added the go add ONLY when ready to merge, run all tests label Jun 16, 2026
@liulehui

liulehui commented Jun 16, 2026 •

Copy link
Copy Markdown
Contributor Author

Looks good to me. Do we have any end to end tests like release tests to check the spot node preemption works fully?

Right now I have this script for mocking the preemption https://gist.github.com/liulehui/fc9bd4a6fe58b72a85363c0cda619f7e

Later when it's working e2e, I will add it the release test.

Signed-off-by: Lehui Liu <[email protected]>

@cursor cursor Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Cursor Bugbot has reviewed your changes using default effort and found 1 potential issue.

Fix All in Cursor

Reviewed by Cursor Bugbot for commit dcbfd9c. Configure here.

@justinvyu justinvyu left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Nice!

Signed-off-by: Lehui Liu <[email protected]>
@justinvyu
justinvyu enabled auto-merge (squash) June 23, 2026 23:47
@justinvyu
justinvyu merged commit 29f5206 into ray-project:master Jun 24, 2026
4 checks passed
limarkdcunha pushed a commit to limarkdcunha/ray that referenced this pull request Jun 30, 2026
…ray-project#64099)

1. Builds on top of the Stage 1 preemption watcher (ray-project#63807): when the
watcher detects a preemption, it now fans the signal out to the worker
actors and stores in `PreemptionContext` in the TrainContext
2. added a rpc for mark_preempt in Train worker
3. watcher fans out preemptionInfo through every worker handle.
4. follow up PR will add public apis and controller state.

---------

Signed-off-by: Lehui Liu <[email protected]>
matthewdeng pushed a commit that referenced this pull request Jul 24, 2026
…ller PreemptingState (#64360)

## Description
This is stage 3 of preemption handling for Ray Train V2, stacked on top
of stage 1 (#63807, watcher + observability) and stage 2 (#64099,
worker-side fan-out). Stage 2 fans the preemption signal out to all
workers; this stage
exposes it to user code and add the controller state to react to it.

1. add the public api: `ray.train.get_preemption_info()`, which returns
the current `PreemptionInfo`
2. add `PreemptingState`, when an worker echoes a preemption signal in
its poll status, controller transitions from `RunningState` ->
`PreemptingState`.
3. in PreemptingState, controller will wait until (a) all workers gone
(b) reclaim deadline elapsed (`drain_timed_out`=True, force restart),
(c) clean finish (run finish before the reclaim -> `Finished`.)
4. add `max_preemption_failures` in FailureConfig and `PreemptionError`.

### User behavior coverage
Note that currently, the deadline for preempting exit is the same as
premption signal deadline or 120s if None.

| # | Situation | UDF behavior | preemption budget >= 0 | preemption
budget < 0 |
|---|---|---|---|---|
| 1a | Ray Core draining signal arrives, then the reclaim kills **all**
training workers (before or at the warned deadline) | Save a JIT
checkpoint on the signal, keep training until killed | Enters
`PreemptingState`; once every worker has exited →
`PreemptionError(drain_timed_out=False)` → **restart + resume** |
transfer into ShuttingDown and `ErroredState`; `fit()` raises
`PreemptionError` |
| 1b | Ray Core draining signal arrives, Save a JIT checkpoint on the
signal, keep training until killed **some** workers — others are still
healthy | Healthy workers keep training and stuck at the next report
barrier, util timeout | **Stays in `PreemptingState`** — the partial
kill does *not* trigger an immediate restart; healthy workers get the
rest of the grace window, until every worker exits (→ 1a) or the
deadline passes (→ 2) | same as 1a / 2 |
| 2 | Draining signal arrives but the reclaim is **late** — workers
still alive at the warned deadline (or after 120s if the cloud gave no
deadline) | Keep training | Enters `PreemptingState`; at the deadline
Ray Train stops waiting → `PreemptionError(drain_timed_out=True)` →
tears down the live workers itself → **restart + resume** | Run shuts
down into `ErroredState`; `fit()` raises `PreemptionError` |
| 3 | Worker killed by a reclaim with **no warning ever observed** (no
signal from Ray Core) | Nothing — there was no window to react | Skips
`PreemptingState`; Ray Core tags the death (`RayActorError.preempted`),
so the failure policy still charges it to the **preemption** budget →
**restart + resume** | Run shuts down into `ErroredState`; raises
`WorkerGroupError` carrying the preemption-tagged death |
| 4 | Training **finishes** | Just `return`, as normal | The run
**finishes** (`FinishedState`); **no budget consumed** (works even with
`max_preemption_failures=0`);| — |
| 5 | A **bug in the training code** (e.g. the JIT-checkpoint part
raises) while a warning is active or during the drain | e.g. user write
a bug in jit checkpoint function | Fails fast: no `preempted` tag on the
error → `WorkerGroupError` → charged to **`max_failures`**; the drain is
not prolonged and the preemption budget never hides real bugs |
retried/raised per `max_failures` |
| 6 | A **second node is warned** while the first is still draining
(staggered preemption) | Nothing new — keep checkpointing | The signals
are **merged** in `PreemptingState` (union of nodes/ranks, earliest
deadline); exits via 1a/2 with the merged info in the error | same as 1a
/ 2 |


### Controller State transition graph for PreemptingState:
<img width="1340" height="1290" alt="3e915f722c3f4389dfa9e9d28fdcd207"
src="https://github.com/user-attachments/assets/dfa5a19b-770c-42a4-b132-a41a75294781"
/>

## Related issues
part of #63968

## Additional information
tested with this script:
https://gist.github.com/liulehui/2760cf896c4404f63827ba9e2664938b
this is the log:
```
RayTrainWorker pid=84119) [rank 1] PREEMPT signal: this=True preempting_ranks=[1] nodes=['2de6f67435d75ff6eb4045e628cbfd0fb0150ec1470b203d631b26da'] sec_left=14.7
(RayTrainWorker pid=84118) [rank 0] PREEMPT signal: this=False preempting_ranks=[1] nodes=['2de6f67435d75ff6eb4045e628cbfd0fb0150ec1470b203d631b26da'] sec_left=14.7
(RayTrainWorker pid=84119) [rank 1] starting fresh
(RayTrainWorker pid=84119) [rank 1] periodic checkpoint at step 0
(RayTrainWorker pid=84119) [rank 1] PREEMPT signal: this=True preempting_ranks=[1] nodes=['2de6f67435d75ff6eb4045e628cbfd0fb0150ec1470b203d631b26da'] sec_left=14.7
(RayTrainWorker pid=84118) [rank 0] EMERGENCY checkpoint at step 9
(RayTrainWorker pid=84118) [rank 0] EMERGENCY checkpoint at step 9
(RayTrainWorker pid=84119) Reporting training result 10: TrainingReport(checkpoint=None, metrics={'step': 9}, validation=False) from rank 1 [repeated 4x across cluster]
(TrainController pid=84105) [FailurePolicy] RETRY
(TrainController pid=84105)   Source: preemption
(TrainController pid=84105)   Error count: 1 (max allowed: 3)
(TrainController pid=84105) Error: Training was interrupted by node preemption (preempted_ranks=[1], drain_timed_out=False).
(TrainController pid=84105) ray.train.v2.api.exceptions.PreemptionError: Training was interrupted by node preemption (preempted_ranks=[1], drain_timed_out=False).
(TrainController pid=84105) 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=84184) Setting up process group for: env:// [rank=0, world_size=2]
(RayTrainWorker pid=84184) [W625 15:57:53.256638000 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())
(TrainController pid=84105) Started training worker group of size 2: 
(TrainController pid=84105) - (ip=127.0.0.1, pid=84184) world_rank=0, local_rank=0, node_rank=0
(TrainController pid=84105) - (ip=127.0.0.1, pid=84183) world_rank=1, local_rank=1, node_rank=0
(RayTrainWorker pid=84184) [rank 0] RESUMED from step 9
(RayTrainWorker pid=84184) [rank 0] RESUMED from step 9
```

---------

Signed-off-by: Lehui Liu <[email protected]>
400Ping pushed a commit to 400Ping/ray that referenced this pull request Aug 18, 2026
…ray-project#64099)

1. Builds on top of the Stage 1 preemption watcher (ray-project#63807): when the
watcher detects a preemption, it now fans the signal out to the worker
actors and stores in `PreemptionContext` in the TrainContext
2. added a rpc for mark_preempt in Train worker
3. watcher fans out preemptionInfo through every worker handle.
4. follow up PR will add public apis and controller state.

---------

Signed-off-by: Lehui Liu <[email protected]>
Signed-off-by: 400Ping <[email protected]>
400Ping pushed a commit to 400Ping/ray that referenced this pull request Aug 18, 2026
…ller PreemptingState (ray-project#64360)

## Description
This is stage 3 of preemption handling for Ray Train V2, stacked on top
of stage 1 (ray-project#63807, watcher + observability) and stage 2 (ray-project#64099,
worker-side fan-out). Stage 2 fans the preemption signal out to all
workers; this stage
exposes it to user code and add the controller state to react to it.

1. add the public api: `ray.train.get_preemption_info()`, which returns
the current `PreemptionInfo`
2. add `PreemptingState`, when an worker echoes a preemption signal in
its poll status, controller transitions from `RunningState` ->
`PreemptingState`.
3. in PreemptingState, controller will wait until (a) all workers gone
(b) reclaim deadline elapsed (`drain_timed_out`=True, force restart),
(c) clean finish (run finish before the reclaim -> `Finished`.)
4. add `max_preemption_failures` in FailureConfig and `PreemptionError`.

### User behavior coverage
Note that currently, the deadline for preempting exit is the same as
premption signal deadline or 120s if None.

| # | Situation | UDF behavior | preemption budget >= 0 | preemption
budget < 0 |
|---|---|---|---|---|
| 1a | Ray Core draining signal arrives, then the reclaim kills **all**
training workers (before or at the warned deadline) | Save a JIT
checkpoint on the signal, keep training until killed | Enters
`PreemptingState`; once every worker has exited →
`PreemptionError(drain_timed_out=False)` → **restart + resume** |
transfer into ShuttingDown and `ErroredState`; `fit()` raises
`PreemptionError` |
| 1b | Ray Core draining signal arrives, Save a JIT checkpoint on the
signal, keep training until killed **some** workers — others are still
healthy | Healthy workers keep training and stuck at the next report
barrier, util timeout | **Stays in `PreemptingState`** — the partial
kill does *not* trigger an immediate restart; healthy workers get the
rest of the grace window, until every worker exits (→ 1a) or the
deadline passes (→ 2) | same as 1a / 2 |
| 2 | Draining signal arrives but the reclaim is **late** — workers
still alive at the warned deadline (or after 120s if the cloud gave no
deadline) | Keep training | Enters `PreemptingState`; at the deadline
Ray Train stops waiting → `PreemptionError(drain_timed_out=True)` →
tears down the live workers itself → **restart + resume** | Run shuts
down into `ErroredState`; `fit()` raises `PreemptionError` |
| 3 | Worker killed by a reclaim with **no warning ever observed** (no
signal from Ray Core) | Nothing — there was no window to react | Skips
`PreemptingState`; Ray Core tags the death (`RayActorError.preempted`),
so the failure policy still charges it to the **preemption** budget →
**restart + resume** | Run shuts down into `ErroredState`; raises
`WorkerGroupError` carrying the preemption-tagged death |
| 4 | Training **finishes** | Just `return`, as normal | The run
**finishes** (`FinishedState`); **no budget consumed** (works even with
`max_preemption_failures=0`);| — |
| 5 | A **bug in the training code** (e.g. the JIT-checkpoint part
raises) while a warning is active or during the drain | e.g. user write
a bug in jit checkpoint function | Fails fast: no `preempted` tag on the
error → `WorkerGroupError` → charged to **`max_failures`**; the drain is
not prolonged and the preemption budget never hides real bugs |
retried/raised per `max_failures` |
| 6 | A **second node is warned** while the first is still draining
(staggered preemption) | Nothing new — keep checkpointing | The signals
are **merged** in `PreemptingState` (union of nodes/ranks, earliest
deadline); exits via 1a/2 with the merged info in the error | same as 1a
/ 2 |

### Controller State transition graph for PreemptingState:
<img width="1340" height="1290" alt="3e915f722c3f4389dfa9e9d28fdcd207"
src="https://github.com/user-attachments/assets/dfa5a19b-770c-42a4-b132-a41a75294781"
/>

## Related issues
part of ray-project#63968

## Additional information
tested with this script:
https://gist.github.com/liulehui/2760cf896c4404f63827ba9e2664938b
this is the log:
```
RayTrainWorker pid=84119) [rank 1] PREEMPT signal: this=True preempting_ranks=[1] nodes=['2de6f67435d75ff6eb4045e628cbfd0fb0150ec1470b203d631b26da'] sec_left=14.7
(RayTrainWorker pid=84118) [rank 0] PREEMPT signal: this=False preempting_ranks=[1] nodes=['2de6f67435d75ff6eb4045e628cbfd0fb0150ec1470b203d631b26da'] sec_left=14.7
(RayTrainWorker pid=84119) [rank 1] starting fresh
(RayTrainWorker pid=84119) [rank 1] periodic checkpoint at step 0
(RayTrainWorker pid=84119) [rank 1] PREEMPT signal: this=True preempting_ranks=[1] nodes=['2de6f67435d75ff6eb4045e628cbfd0fb0150ec1470b203d631b26da'] sec_left=14.7
(RayTrainWorker pid=84118) [rank 0] EMERGENCY checkpoint at step 9
(RayTrainWorker pid=84118) [rank 0] EMERGENCY checkpoint at step 9
(RayTrainWorker pid=84119) Reporting training result 10: TrainingReport(checkpoint=None, metrics={'step': 9}, validation=False) from rank 1 [repeated 4x across cluster]
(TrainController pid=84105) [FailurePolicy] RETRY
(TrainController pid=84105)   Source: preemption
(TrainController pid=84105)   Error count: 1 (max allowed: 3)
(TrainController pid=84105) Error: Training was interrupted by node preemption (preempted_ranks=[1], drain_timed_out=False).
(TrainController pid=84105) ray.train.v2.api.exceptions.PreemptionError: Training was interrupted by node preemption (preempted_ranks=[1], drain_timed_out=False).
(TrainController pid=84105) 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=84184) Setting up process group for: env:// [rank=0, world_size=2]
(RayTrainWorker pid=84184) [W625 15:57:53.256638000 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())
(TrainController pid=84105) Started training worker group of size 2:
(TrainController pid=84105) - (ip=127.0.0.1, pid=84184) world_rank=0, local_rank=0, node_rank=0
(TrainController pid=84105) - (ip=127.0.0.1, pid=84183) world_rank=1, local_rank=1, node_rank=0
(RayTrainWorker pid=84184) [rank 0] RESUMED from step 9
(RayTrainWorker pid=84184) [rank 0] RESUMED from step 9
```

---------

Signed-off-by: Lehui Liu <[email protected]>
Signed-off-by: 400Ping <[email protected]>
matthewdeng pushed a commit that referenced this pull request Oct 6, 2026
## 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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

go add ONLY when ready to merge, run all tests train Ray Train Related Issue

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants