Skip to content

[train][Preemption handling 3/n] Add public preemption API and controller PreemptingState - #64360

Merged
matthewdeng merged 16 commits into
ray-project:masterfrom
liulehui:preempt-stage3-controller
Jul 24, 2026
Merged

matthewdeng merged 16 commits into
ray-project:masterfrom
liulehui:preempt-stage3-controller

Conversation

@liulehui

@liulehui liulehui commented Jun 25, 2026 •

Copy link
Copy Markdown
Contributor

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:

3e915f722c3f4389dfa9e9d28fdcd207

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

@liulehui
liulehui requested a review from a team as a code owner June 25, 2026 23:06
@liulehui liulehui added the go add ONLY when ready to merge, run all tests label Jun 25, 2026

@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 introduces node preemption handling in Ray Train v2, adding a new PreemptingState to the controller state machine, a PreemptionError exception, and a separate max_preemption_failures retry budget in FailureConfig. It also exposes preemption_info to the public API so training loops can gracefully handle imminent node reclamation. The review feedback highlights a critical issue in staggered preemption scenarios where sequential preemption signals can overwrite and erase previous preemption history, and provides a code suggestion to merge the preemption information instead.

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.

@ray-gardener ray-gardener Bot added the train Ray Train Related Issue label Jun 26, 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.

Overall, looks really good. I couldn't see anything in particular wrong with the implementation.

I was imagining different edge cases and I'm not sure we have tests for all of them

  • What happens if there are two overlapping preemptions (i.e., half way through one preemption, another starts for a different node), I think you cover this in the tests already
  • What happens if all the nodes are spot nodes, and they are all preempted, how is this handled? Does this raise a different error or do you always need an on-demand node?
  • What happens if another node is preempted in between shutdown and startup? Is this just picked up due after the startup?

Do we have tests for all of these cases? Why isn't this an Anyscale Runtime exclusive?
Currently, all the tests are mock / state machine testing. Would it be possible to have some end to end implementation version as well, to check that the machinery works in practice as well? The preemption part should be mocked still, just the DataParallelTrainer should be real if that makes sense.

Another note, in a preemption state, if the train_fn is returned then we assume that the user is just ending the train_fn cleanly for the preemption to restart it. However, is there a way of preventing this if you actually want to end training? Would we want to change it that you need to return a PreemptionInfo object to make it clear, otherwise, we assume you do want to do end? I know this isn't super elegant but the case seems like one we need to consider. Or are we accepting that when the train_fn is ready to actually end, and it actually restarted then that will be handled fine? If so, could we have a test for this.
I hope this ramble makes sense

@liulehui

Copy link
Copy Markdown
Contributor Author

Overall, looks really good. I couldn't see anything in particular wrong with the implementation.

I was imagining different edge cases and I'm not sure we have tests for all of them

  • What happens if there are two overlapping preemptions (i.e., half way through one preemption, another starts for a different node), I think you cover this in the tests already
  • What happens if all the nodes are spot nodes, and they are all preempted, how is this handled? Does this raise a different error or do you always need an on-demand node?
  • What happens if another node is preempted in between shutdown and startup? Is this just picked up due after the startup?

Do we have tests for all of these cases? Why isn't this an Anyscale Runtime exclusive? Currently, all the tests are mock / state machine testing. Would it be possible to have some end to end implementation version as well, to check that the machinery works in practice as well? The preemption part should be mocked still, just the DataParallelTrainer should be real if that makes sense.

Another note, in a preemption state, if the train_fn is returned then we assume that the user is just ending the train_fn cleanly for the preemption to restart it. However, is there a way of preventing this if you actually want to end training? Would we want to change it that you need to return a PreemptionInfo object to make it clear, otherwise, we assume you do want to do end? I know this isn't super elegant but the case seems like one we need to consider. Or are we accepting that when the train_fn is ready to actually end, and it actually restarted then that will be handled fine? If so, could we have a test for this. I hope this ramble makes sense

  1. two overlapping preemption
    Yes, this is covered. let's consider preemption A and preemption B.
    a. Preemption A arrived, controller transition into PreemptingState, preemption B arrives, this two gets merged as one, see merge_preemption_info in this PR.
    b. preempting A arrivess, controller transition into PreemptingState, restart, scheduling, preemption B arrives, Ray core guaranteed that placement groups won't schedule on draning nodes.
    c. Preempting A arrives, controller in PreemptingState, Restart, Running, preemption B arrives, this is essentially another preemption event.

  2. I don't think in Ray train we should care about spot and on demand nodes, if there are no nodes left to be schedule, then controller should be in scheduling -> rescheduling loop.

  3. Re: What happens if another node is preempted in between shutdown and startup? Ray Core guaranteed that placement groups won't schedule on draining nodes.

  4. yes we do have unit test cover them, see test_preemption_drain_then_restart and test_merge_preemption_info_dedupes_overlapping_ranks

  5. We don't have a strong motivation to put it proprietary I think, most primitive are OSS'ed already.

  6. I did put a DataParallelTrainer test, see this https://gist.github.com/liulehui/2760cf896c4404f63827ba9e2664938b and corresponding logs in the PR description, once implementation done, we can add release test later.

  7. Re: Another note, in a preemption state, if the train_fn is returned then we assume that the user is just ending the train_fn cleanly for the preemption to restart it. However, is there a way of preventing this if you actually want to end training? , user can simply set the max_preemption_failure in FailureConfig, to control the number of retry, just set to 0 can stop it after preempting.

@pseudo-rnd-thoughts

pseudo-rnd-thoughts commented Jun 30, 2026 •

Copy link
Copy Markdown
Member
  1. To confirm, we have tests to check all of these cases?
  2. Agreed about this, but it should be a very simple test. Could we add it just in case there is something weird that happens?
  3. Perfect, good to hear
  4. Nice job
  5. For testing, proper real release test with actual spot nodes and preemption will be great (in a future PR) but a couple basic tests (and one edge case) that are end to end just with mocked preemption would be very helpful such that its not only the release tests that test this and that it might be testable locally is very helpful.
  6. Won't this lead to the run "failing" due to an error being raised (by default with a try/except which makes the code all uglier). Also, on a preemption, I didn't think there was any way to modify the DataParallelTrainer between shutdown and restart. I'm not sure I understand how your solution is possible. I still think that returning the PreemptionInfo is the best solution to this. Given the 120 seconds by AWS I think this is a more common problem than we might expect, particularly with a large number of spot nodes for users

@liulehui
liulehui force-pushed the preempt-stage3-controller branch from 36bf78c to 50e4fd4 Compare July 2, 2026 23:00
@liulehui
liulehui requested a review from a team as a code owner July 2, 2026 23:00
@liulehui

liulehui commented Jul 6, 2026 •

Copy link
Copy Markdown
Contributor Author
  1. To confirm, we have tests to check all of these cases?
  2. Agreed about this, but it should be a very simple test. Could we add it just in case there is something weird that happens?
  3. Perfect, good to hear
  4. Nice job
  5. For testing, proper real release test with actual spot nodes and preemption will be great (in a future PR) but a couple basic tests (and one edge case) that are end to end just with mocked preemption would be very helpful such that its not only the release tests that test this and that it might be testable locally is very helpful.
  6. Won't this lead to the run "failing" due to an error being raised (by default with a try/except which makes the code all uglier). Also, on a preemption, I didn't think there was any way to modify the DataParallelTrainer between shutdown and restart. I'm not sure I understand how your solution is possible. I still think that returning the PreemptionInfo is the best solution to this. Given the 120 seconds by AWS I think this is a more common problem than we might expect, particularly with a large number of spot nodes for users
  1. for testing, e2e, I added a file test_preemption_fault_tolerance.py
    Note that mocking draining nodes like we did in the testing script: https://gist.github.com/liulehui/2760cf896c4404f63827ba9e2664938b, because mocking is in pytest while the watcher is in its own process.
  2. I am not entirely get the point I think, but I attached one table below for the current expect user behavior, put in the PR description as well. I think initially the confusion is from whether we allow early return from user after ack the preemption signal, the return can also from genuine finished UDF. I did some homework and checked that other framework like Orbax for emergent checkpoint all do continue to actual reclaim instead of early return. I personally don't want to overloading the return value, especially I think this should be related with results instead of making it interact with control flow. So, the expected user behavior would be:
def train_func():
      for step in steps:
        if ray.train.get_preemption_info():
          jit_checkpoint()
          # no return here. 
      
        train_step()

      return       

if user do return, we log a warning and shut down.

Please see below table:
note that currently, the deadline for preempting exit is the same as premption signal deadline or 120s if None.

# Scenario Timing vs. reclaim deadline UDF behavior Controller flow Budget remaining Budget exhausted
1a Signal; all ranks killed by reclaim kills observed before/at deadline JIT-checkpoint, keep training Running → Preempting → all exited → PreemptionError(drain_timed_out=False, worker_failures=kills) RESTART SD → E, fit() raises PreemptionError
1b Signal; subset of ranks killed kills before deadline, others alive Healthy ranks keep training/checkpointing Running → Preempting → stays in Preempting (healthy ranks continue) → exits via 1a (rest exit) or 4 (deadline) RESTART same as 1a/4
2 Signal; UDF ignores it any Nothing (signal is optional) Identical to 1a/1b — flow never depends on reading the signal RESTART same
3 No advance signal from ray core, only dies with RayActorError(preempted=True) Nothing Skips P: R → error → failure policy classifies via RayActorError.preempted RESTART SD → E, raises WorkerGroupError carrying the preempted RayActorError
4 Signal; ranks still running at deadline (late/no reclaim; 120s fallback) deadline fires first Keep training R → P → deadline → PreemptionError(drain_timed_out=True); live ranks torn down in Restarting RESTART ShuttingDown → Errored, raises PreemptionError
5 Training finishes during signal before deadline & before any kill Plain return R [→ P] → SD → F + warning; no budget consumed, works even with max_preemption_failures=0 — —
6 Staggered: 2nd node drains mid-drain during drain Keep checkpointing Echoes merged in P (union of ranks, earliest deadline); exits via 1a/4 with merged info in the error RESTART same
7 User bug during signal/drain any (before ranks die) Fix the bug In R or P: no preempted flag → fail fast → WorkerGroupError → charged to max_failures (drain not prolonged for a real bug) retry iff max_failures remains raises WorkerGroupError
8 User bug and reclaim kill in same poll during drain — Drain continues (preempted death present); final PreemptionError.worker_failures carries both RESTART (preemption budget) raises PreemptionError

@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 great @liulehui, thanks for the changes and adding the e2e tests.

On 2., I think I misunderstood the implementation. My expectation / understanding was that if there was a preemption then the user would be recommended to call return from the train_fn which would cleanly deal with the train state and signal when a rank had saved its checkpoint etc. I'm now doubting that this is the recommended strategy with your example code. If this isn't the recommended solution then I agree that we shouldn't overload the return control flow. (if we were recommending to call return when the train_fn is ready for preemption then I'm more worried about conflicting when train_fn is ready for preemption and when the train_fn is finished).

Does this make more sense? Am I correct in all my understanding?

@liulehui

liulehui commented Jul 7, 2026

Copy link
Copy Markdown
Contributor Author

Looks great @liulehui, thanks for the changes and adding the e2e tests.

On 2., I think I misunderstood the implementation. My expectation / understanding was that if there was a preemption then the user would be recommended to call return from the train_fn which would cleanly deal with the train state and signal when a rank had saved its checkpoint etc. I'm now doubting that this is the recommended strategy with your example code. If this isn't the recommended solution then I agree that we shouldn't overload the return control flow. (if we were recommending to call return when the train_fn is ready for preemption then I'm more worried about conflicting when train_fn is ready for preemption and when the train_fn is finished).

Does this make more sense? Am I correct in all my understanding?

Yes, the early return after jit checkpoint was my original proposal and your concern with the return value is valid.
I also thought about add a ack flag for the preemption signal, i.e. if user ack the signal, we treat the return as after jit, otherwise, the return is a genuine return of UDF.
But that introduce a issue with:

def train_func():
    for step in steps:
         if preemption_info:
            jit_checkpoint()
         train_step()
    return

if this UDF happens to finish genuinely, say for training for 1000 steps, at 999 we got the signal, but training finished cleanly with 120s with 1000, this means we will force the worker to restart just to drain.
I agree that return preemption info would be a way to tell the difference, but I don't want the return value of UDF can interact with our control flow.

and after looking into other library for jit checkpoint feature, most recommend way is:

def train_func():
     model = Model()
     for step in steps:
          train_step()
          if preemption_info:
              jit_checkpoint()
              continue # instead of return    

thus, I decided to change to this for now. But happen to adjust if we think the early return with info is better!

@pseudo-rnd-thoughts

Copy link
Copy Markdown
Member

Yes, the early return after jit checkpoint was my original proposal and your concern with the return value is valid.
I also thought about add a ack flag for the preemption signal, i.e. if user ack the signal, we treat the return as after jit, otherwise, the return is a genuine return of UDF.

Ahh that makes sense. Yes, I agree that using an ack signal with return would be a nice solution, however, your right that the chance of a mistake accidentally ending a training run early is too high. I'm sure we'll have some fun bugs where training is killed part way through from the spot node but it should be worth it.

The new code looks good, lets just make sure all the code examples match the new expected implementation.

Comment thread python/ray/train/v2/api/exceptions.py Outdated
Comment on lines +67 to +72
worker_failures: A mapping from worker rank to the exception observed on
that worker at teardown, if any.
drain_timed_out: True if the worker group was torn down because the
preemption deadline elapsed before all ranks had exited (i.e. the
drain did not complete in time), rather than all workers exiting
cleanly first.

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.

What are these fields for?

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.

added some more description:

  1. worker_failures if for possible error that occurs during preempting, say user wrote a issue in the jit_checkpoint logic.
  2. drain_timed_out, this is a time window that preemptingState will leave, we let health ranks to survive longer than preempted ones, but we can not keep them indefinitely.

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.

Does worker_failures ever get consumed/displayed anywhere?

Comment thread python/ray/train/__init__.py Resolved
@liulehui
liulehui force-pushed the preempt-stage3-controller branch from 38ae610 to 7fd91d9 Compare July 10, 2026 21:31
liulehui added 4 commits July 21, 2026 11:12
Signed-off-by: Lehui Liu <[email protected]>
Signed-off-by: Lehui Liu <[email protected]>
Signed-off-by: Lehui Liu <[email protected]>
@liulehui
liulehui force-pushed the preempt-stage3-controller branch from 7fd91d9 to 1fc3fd5 Compare July 21, 2026 18:12
liulehui added 2 commits July 21, 2026 13:18
Signed-off-by: Lehui Liu <[email protected]>
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 30dbee2. Configure here.

@matthewdeng matthewdeng 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!

@matthewdeng
matthewdeng merged commit 27b0e6a into ray-project:master Jul 24, 2026
3 checks passed
matthewdeng pushed a commit that referenced this pull request Aug 4, 2026
#65183)

## Description
`ray.train.get_preemption_info()` (added in #64360) was a local,
per-worker read. The preemption notice is fanned out to workers as
independent, un-awaited RPCs, so different workers might observe it on
different steps, which will cause an issue in the below example.

```python
for step in range(total_steps):
    train_step()                                    # DDP gradient all-reduce: a barrier
    if ray.train.get_preemption_info() is not None:
        ray.train.report(metrics, checkpoint=ckpt)  # report(): another barrier
```

Let's assume that the preemption signal lands on rank 1 first

| | rank 0 | rank 1 |
|---|---|---|
| step N, after `train_step()` | local read → `None` → **skips** the
branch | local read → `Info` → **enters** `report()` |
| step N | proceeds to `train_step()` → blocks in the DDP all-reduce |
blocked in the `report()` barrier |

Deadlock. Rank 0 waits for rank 1's gradients; rank 1 waits for rank 0
to reach `report()`.

This PR makes `ray.train.get_preemption_info()` a collective with
broadcast_from_rank_zero, so all ranks reads the same preemption info as
rank0 sees.. The value is now safe to use as the condition for another
collective, e.g. ray.train.report().

After this change, both ranks receive `Info` on the same step and enter
`report()` together.

Other considerations I have and rejected by myself:
1. add another `ray.train.reach_preemption_sync_point()`. this way we
have `ray.train.get_preemption_info()` as non consistent read while
`ray.train.reach_preemption_sync_point()` do a collective, but the non
consistent read api does not add a lot value and eventually need to
preemption info, and two user api will introduce disagreement and hurt
usability.
2. in the follow up PR, we will address relaxing the barrier among
health ranks

## Related issues
#63968

## Additional information
unit tests

---------

Signed-off-by: Lehui Liu <[email protected]>
Artimislyy pushed a commit to Artimislyy/ray that referenced this pull request Aug 11, 2026
ray-project#65183)

## Description
`ray.train.get_preemption_info()` (added in ray-project#64360) was a local,
per-worker read. The preemption notice is fanned out to workers as
independent, un-awaited RPCs, so different workers might observe it on
different steps, which will cause an issue in the below example.

```python
for step in range(total_steps):
    train_step()                                    # DDP gradient all-reduce: a barrier
    if ray.train.get_preemption_info() is not None:
        ray.train.report(metrics, checkpoint=ckpt)  # report(): another barrier
```

Let's assume that the preemption signal lands on rank 1 first

| | rank 0 | rank 1 |
|---|---|---|
| step N, after `train_step()` | local read → `None` → **skips** the
branch | local read → `Info` → **enters** `report()` |
| step N | proceeds to `train_step()` → blocks in the DDP all-reduce |
blocked in the `report()` barrier |

Deadlock. Rank 0 waits for rank 1's gradients; rank 1 waits for rank 0
to reach `report()`.

This PR makes `ray.train.get_preemption_info()` a collective with
broadcast_from_rank_zero, so all ranks reads the same preemption info as
rank0 sees.. The value is now safe to use as the condition for another
collective, e.g. ray.train.report().

After this change, both ranks receive `Info` on the same step and enter
`report()` together.

Other considerations I have and rejected by myself:
1. add another `ray.train.reach_preemption_sync_point()`. this way we
have `ray.train.get_preemption_info()` as non consistent read while
`ray.train.reach_preemption_sync_point()` do a collective, but the non
consistent read api does not add a lot value and eventually need to
preemption info, and two user api will introduce disagreement and hurt
usability.
2. in the follow up PR, we will address relaxing the barrier among
health ranks

## Related issues
ray-project#63968

## Additional information
unit tests

---------

Signed-off-by: Lehui Liu <[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]>
400Ping pushed a commit to 400Ping/ray that referenced this pull request Aug 18, 2026
ray-project#65183)

## Description
`ray.train.get_preemption_info()` (added in ray-project#64360) was a local,
per-worker read. The preemption notice is fanned out to workers as
independent, un-awaited RPCs, so different workers might observe it on
different steps, which will cause an issue in the below example.

```python
for step in range(total_steps):
    train_step()                                    # DDP gradient all-reduce: a barrier
    if ray.train.get_preemption_info() is not None:
        ray.train.report(metrics, checkpoint=ckpt)  # report(): another barrier
```

Let's assume that the preemption signal lands on rank 1 first

| | rank 0 | rank 1 |
|---|---|---|
| step N, after `train_step()` | local read → `None` → **skips** the
branch | local read → `Info` → **enters** `report()` |
| step N | proceeds to `train_step()` → blocks in the DDP all-reduce |
blocked in the `report()` barrier |

Deadlock. Rank 0 waits for rank 1's gradients; rank 1 waits for rank 0
to reach `report()`.

This PR makes `ray.train.get_preemption_info()` a collective with
broadcast_from_rank_zero, so all ranks reads the same preemption info as
rank0 sees.. The value is now safe to use as the condition for another
collective, e.g. ray.train.report().

After this change, both ranks receive `Info` on the same step and enter
`report()` together.

Other considerations I have and rejected by myself:
1. add another `ray.train.reach_preemption_sync_point()`. this way we
have `ray.train.get_preemption_info()` as non consistent read while
`ray.train.reach_preemption_sync_point()` do a collective, but the non
consistent read api does not add a lot value and eventually need to
preemption info, and two user api will introduce disagreement and hurt
usability.
2. in the follow up PR, we will address relaxing the barrier among
health ranks

## Related issues
ray-project#63968

## Additional information
unit tests

---------

Signed-off-by: Lehui Liu <[email protected]>
Signed-off-by: 400Ping <[email protected]>
nadongjun pushed a commit to nadongjun/ray that referenced this pull request Oct 6, 2026
ray-project#65183)

## Description
`ray.train.get_preemption_info()` (added in ray-project#64360) was a local,
per-worker read. The preemption notice is fanned out to workers as
independent, un-awaited RPCs, so different workers might observe it on
different steps, which will cause an issue in the below example.

```python
for step in range(total_steps):
    train_step()                                    # DDP gradient all-reduce: a barrier
    if ray.train.get_preemption_info() is not None:
        ray.train.report(metrics, checkpoint=ckpt)  # report(): another barrier
```

Let's assume that the preemption signal lands on rank 1 first

| | rank 0 | rank 1 |
|---|---|---|
| step N, after `train_step()` | local read → `None` → **skips** the
branch | local read → `Info` → **enters** `report()` |
| step N | proceeds to `train_step()` → blocks in the DDP all-reduce |
blocked in the `report()` barrier |

Deadlock. Rank 0 waits for rank 1's gradients; rank 1 waits for rank 0
to reach `report()`.

This PR makes `ray.train.get_preemption_info()` a collective with
broadcast_from_rank_zero, so all ranks reads the same preemption info as
rank0 sees.. The value is now safe to use as the condition for another
collective, e.g. ray.train.report().

After this change, both ranks receive `Info` on the same step and enter
`report()` together.

Other considerations I have and rejected by myself:
1. add another `ray.train.reach_preemption_sync_point()`. this way we
have `ray.train.get_preemption_info()` as non consistent read while
`ray.train.reach_preemption_sync_point()` do a collective, but the non
consistent read api does not add a lot value and eventually need to
preemption info, and two user api will introduce disagreement and hurt
usability.
2. in the follow up PR, we will address relaxing the barrier among
health ranks

## Related issues
ray-project#63968

## Additional information
unit tests

---------

Signed-off-by: Lehui Liu <[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]>
dstrodtman added a commit that referenced this pull request Oct 13, 2026
…s, and preemption budget

- asynchronous-validation.md: cover both ways the validation run can pass
  metrics back, note return values need Ray 2.56, and recommend
  return_value over a placeholder NO_UPLOAD checkpoint.
- checkpoints.md: contrast ASYNC with SYNC, where a TemporaryDirectory
  works because report waits for the upload.
- elastic-training.md: scope max_preemption_failures to Ray 2.58 (#64360).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Douglas Strodtman <[email protected]>
dstrodtman added a commit that referenced this pull request Oct 13, 2026
…s, and preemption budget

- asynchronous-validation.md: cover both ways the validation run can pass
  metrics back, note return values need Ray 2.56, and recommend
  return_value over a placeholder NO_UPLOAD checkpoint.
- checkpoints.md: contrast ASYNC with SYNC, where a TemporaryDirectory
  works because report waits for the upload.
- elastic-training.md: scope max_preemption_failures to Ray 2.58 (#64360).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Douglas Strodtman <[email protected]>
dstrodtman added a commit that referenced this pull request Oct 13, 2026
…s, and preemption budget

- asynchronous-validation.md: cover both ways the validation run can pass
  metrics back, note return values need Ray 2.56, and recommend
  return_value over a placeholder NO_UPLOAD checkpoint.
- checkpoints.md: contrast ASYNC with SYNC, where a TemporaryDirectory
  works because report waits for the upload.
- elastic-training.md: scope max_preemption_failures to Ray 2.58 (#64360).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Douglas Strodtman <[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