Skip to content

[train][2/n] Add ray.train.health.report() - #67520

Merged
pseudo-rnd-thoughts merged 1 commit into
ray-train-health/worker-probesfrom
ray-train-health/health-report
Nov 5, 2026
Merged

pseudo-rnd-thoughts merged 1 commit into
ray-train-health/worker-probesfrom
ray-train-health/health-report

Conversation

@liulehui

@liulehui liulehui commented Oct 28, 2026 •

Copy link
Copy Markdown
Contributor

Description

2nd PR of the new Ray Train Monitoring and Diagnostics REP stack, on top of #67521 (1/n). This PR adds ray.train.health.report(), the way a training function reports health metrics it computes itself.

import ray.train.health as health

def train_func(config):
    for step, batch in enumerate(loader):
        ...
        health.report({"grad_norm": grad_norm}, step=step)

ray.train.health.report(metrics, step=None):

  • Is not a barrier: each worker can call it any number of times.
  • Goes through TrainFnUtils.report_health into the worker's TrainContext, under the same health_lock the WorkerProbe samplers use. poll_status() returns it as WorkerStatus.health_report, alongside probe_results.

Feeding these reports into the HealthManager comes in a later PR.

Test

unit tests

@liulehui liulehui changed the title [train][6/n] Add ray.train.health.report() [train][2/n] Add ray.train.health.report() Oct 28, 2026
@liulehui
liulehui added this pull request to stack #67522 October 28, 2026 23:11
@liulehui
liulehui force-pushed the ray-train-health/health-report branch from 8bc9d16 to 9d32fe5 Compare October 28, 2026 23:34
@liulehui
liulehui force-pushed the ray-train-health/health-report branch from 9d32fe5 to f7c0e7d Compare October 29, 2026 16:27
@liulehui
liulehui marked this pull request as ready for review October 29, 2026 17:54
@liulehui
liulehui requested review from a team as code owners October 29, 2026 17:54
@liulehui liulehui added the go add ONLY when ready to merge, run all tests label Oct 29, 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 a new asynchronous health reporting API (ray.train.health.report) that allows training workers to report health metrics and steps to the controller without encountering barrier synchronization. The implementation includes the HealthReport dataclass, thread-safe merging of metrics in TrainContext, and integration into the worker status polling mechanism, accompanied by unit tests. The review feedback suggests enhancing the defensive type checking in the report function to explicitly reject boolean values (which are technically subclasses of int in Python) and validate the step parameter, along with adding corresponding test cases to verify these validations.

Comment thread python/ray/train/v2/api/health.py Resolved
@liulehui
liulehui force-pushed the ray-train-health/health-report branch from f7c0e7d to 664b528 Compare October 29, 2026 17:56
@ray-gardener ray-gardener Bot added the train Ray Train Related Issue label Oct 29, 2026
)
)

def report_health(self, metrics: Dict[str, float], step: Optional[int]) -> None:

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.

Is Dict[str, float] too restrictive?

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.

It matches ProbeResult.metrics, let's start with restrictive and since There’s no validation buy only the type hint, so we can widen both together once a probe or report needs non-float values.

Comment thread python/ray/train/v2/api/health.py Resolved
@liulehui
liulehui force-pushed the ray-train-health/health-report branch from 664b528 to cac05be Compare November 3, 2026 18:59
@liulehui
liulehui force-pushed the ray-train-health/health-report branch from cac05be to a8a1a16 Compare November 3, 2026 19:47
@liulehui
liulehui force-pushed the ray-train-health/health-report branch 2 times, most recently from e8e9d51 to c095c77 Compare November 3, 2026 22:37

@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 and found 1 potential issue.

Fix All in Cursor

❌ Bugbot Autofix is OFF. To automatically fix reported issues with cloud agents, have a team admin enable autofix in the Cursor dashboard.

Reviewed by Cursor Bugbot for commit c095c77. Configure here.

@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.

LGTM

ray.train.health.report(metrics, step=None) reports numeric health metrics
from the training function. It is not a barrier. Each call merges the metrics
into the worker's TrainContext, and poll_status returns them as
WorkerStatus.health_report.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Lehui Liu <[email protected]>
@liulehui
liulehui force-pushed the ray-train-health/health-report branch from c095c77 to 64af0d6 Compare November 4, 2026 17:57
@pseudo-rnd-thoughts
pseudo-rnd-thoughts enabled stacked auto-merge (squash) November 4, 2026 22:37
pseudo-rnd-thoughts pushed a commit that referenced this pull request Nov 4, 2026
## Description

Converts the `.. testcode::` examples in Ray Train API docstrings to
`>>>` examples under a plural `Examples:` header. Sphinx renders `..
testcode::`, but griffe and MkDocs don't, and stock `>>>` examples
render in both. This follows the Core conversion in #67760 and the Tune
conversion in #67619.

This PR covers 23 files under `python/ray/train/`:

- **Runnable examples stay runnable.** Pytest doctest collects only
`>>>`, so nothing ran these `testcode` blocks before. Fifteen docstrings
now have examples that run: the v2 `TorchTrainer` and `XGBoostTrainer`,
the five `TrainContext` getters, `get_all_reported_checkpoints`,
`get_dataset_shard`, `DataParallelTrainer`, `BaseTrainer.training_loop`,
`LightGBMCheckpoint.from_model`, the Keras `ReportCheckpointCallback`,
and the v1 `report` and `get_checkpoint` in `_internal/session.py`.
- **`:skipif: True` examples become render-only.** They carry the
docstring-level `# doctest: +SKIP_EXAMPLE` flag (#66753).
`DataParallelTrainer` mixes runnable examples with one `:skipif:`
example, so that example's statements carry a per-line `# doctest:
+SKIP` instead, and the rest of the docstring still runs.
- **Examples in modules no doctest target covers are render-only too.**
That's `horovod/horovod_trainer.py`, `v2/jax/jax_trainer.py`, and
`xgboost/xgboost_checkpoint.py`. Whether to add any of them to a target
is a separate question.

This is a syntax-only change. The example code and the claims in each
docstring are unchanged, with these exceptions that the format forces:

- **Interleaved examples move into `Examples:`.** In
`DataParallelTrainer`, `HorovodTrainer`, `BaseTrainer`,
`BaseTrainer.restore`, `JaxTrainer`, `get_dataset_shard`, and three
`TrainContext` getters, example paragraphs and code sat in the
description. They now sit in an `Examples:` section before `Args:`. The
paragraphs that aren't about an example stay in the description. Prose
text is unchanged.
- **`Example:` and numpy-style `Examples` headers become `Examples:`.**
In the LightGBM and XGBoost callbacks and checkpoints, the section moves
ahead of `Args:` and `Returns:`.
- **`Checkpoint.as_directory` drops a hidden setup block and becomes
render-only.** Its `:hide:` block created the `checkpoint` the example
uses. Doctests have no hidden form, and showing the setup would change
what the example shows.
- **`get_trial_dir` in `_internal/session.py`** had `+MOCK` output. It's
render-only, and the output moved under the `tuner.fit()` call that
prints it.
- **Two examples now render that didn't.** `prepare_data_loader` in both
`train_loop_utils.py` copies was written `.. testcode:` with one colon,
and `XGBoostCheckpoint.from_model` was written `... testcode::`. Sphinx
read both as comments, so docs.ray.io never showed them.

### Left out of this PR

These blocks pair with a `:hide:` `testoutput`, or share a docstring
with one. Converting them changes what the example shows, so they'll
follow in a separate PR for Train review:

- `TensorflowTrainer`, both v1 and v2, the whole docstring.
- `TensorflowCheckpoint.from_model`, which is also `+MOCK`.
- `WandbLoggerCallback` in `air/integrations/wandb.py`.
- Six v1 functions in `_internal/session.py`: `get_world_size`,
`get_world_rank`, `get_local_rank`, `get_local_world_size`,
`get_node_rank`, and `get_dataset_shard`.

### Questions for Train

- **No doctest target collects the examples of APIs whose `__module__`
is rewritten.** `ray/train/__init__.py` imports the public API and then
sets `__module__ = "ray.train"` on it: `Checkpoint`, `TrainContext`,
`report`, `get_checkpoint`, `get_dataset_shard`,
`get_all_reported_checkpoints`, `get_preemption_info`, and others. Both
places that could collect these examples miss them:
- **The defining module rejects them.** `doctest.DocTestFinder` keeps an
object only if `inspect.getmodule(obj)` is the module being scanned, and
`getmodule` reads `__module__`. So scanning
`ray.train.v2.api.train_fn_utils` skips `report`. For a renamed class
such as `TrainContext` or `Checkpoint`, the finder never descends into
its methods.
- **The package `__init__.py` is never scanned.** Scanning `ray.train`
itself would find the renamed functions and class docstrings, though
still not the methods. But the `doctest()` macro in `bazel/python.bzl`
excludes the package-root `__init__.py`.
    
`RAY_TRAIN_V2_ENABLED` decides which implementation gets renamed.
`py_doctest[train]` runs with it on and `py_doctest[train-gpu]` with it
off, so each implementation is renamed in exactly the target that would
run it. With this PR and #67821, that leaves 12 runnable docstrings
uncollected: `Checkpoint`, `Checkpoint.as_directory`, the five
`TrainContext` getters, the V2 `get_dataset_shard` and
`get_all_reported_checkpoints`, and the V1 `report`, `get_checkpoint`,
and `get_dataset_shard` in `_internal/session.py`. The `Checkpoint`
class's existing `>>>` examples predate this PR and have never run in a
doctest target. I checked this with `DocTestFinder` against
`ray==2.59.0` under each flag value. Tune rewrites `__module__` the same
way. Its only renamed object with examples, `TuneContext`, copies them
from `_internal/session.py`, and `py_doctest[tune]` excludes its file.

CI's `run_docstring_examples.py` step reads source files directly, so it
still runs these examples, but only on PRs that change those files. Two
ways to fix collection:
- **Keep the rewriting, and have the shared doctest plugin match objects
by their defining file.** Docs can do this, and it doesn't change
runtime behavior.
- **Stop rewriting `__module__` at runtime.** Either present the public
path only in the docs build, or define public APIs in public modules.
Both change what users see in `repr()`, tracebacks, or import paths.
    
Train chose the first for now: #67831 changes the plugin, stacked on
#67821.
- **Bare `trainer.fit()` lines.** Seven runnable examples end in `>>>
trainer.fit()` with no expected output: the five `TrainContext` getters,
`get_all_reported_checkpoints`, and `get_dataset_shard`.
`run_docstring_examples.py` only requires an example with no shown
output to run. A strict doctest would also compare the echoed `Result`
repr and any worker log lines, so these lines need the
`print("[ignore]"); ... # doctest: +ELLIPSIS` form that Tune uses and
that #67821 adopts. #67831 makes that change along with the collection
fix.

## Related issues

Related to #67760, #67619, and #66753.

## Additional information

**Not a duplicate.** I searched open PRs for Train `testcode`, doctest,
and docstring-example changes. None touches these docstrings. #67520 is
the only open Train PR the search returned, and it shares no files with
this one.

**Tests run**

These ran in a Python 3.12 virtualenv with `ray==2.59.0`, `torch`,
`tensorflow` 2.21 with `tf_keras`, `lightgbm`, `xgboost`, and
`scikit-learn`:

- `ci/ray_ci/doc/run_docstring_examples.py` on the 19 files
`py_doctest[train]` covers, with `RAY_TRAIN_V2_ENABLED=1
TF_USE_LEGACY_KERAS=1`: "15 docstring(s) run, 0 failed, 20 skipped, in
19 file(s)."
- The same runner on `_internal/session.py` with
`RAY_TRAIN_V2_ENABLED=0`, matching `py_doctest[train-gpu]`: "2
docstring(s) run, 0 failed, 1 skipped." Neither runnable example needs a
GPU.
- The same runner on `v2/jax/jax_trainer.py` and
`xgboost/xgboost_checkpoint.py`: both skip, as render-only.
`horovod_trainer.py` can't import without Horovod, and no CPU target
covers it.
- `ci/ray_ci/doc/check_docstring_only.py --base upstream/master`: "23
file(s), docstrings only."
- `pre-commit run --files` on all 23 files: all hooks pass, including
pydoclint and the Train circular-import check.

On macOS, the `TorchTrainer` examples needed `GLOO_SOCKET_IFNAME=lo0`.
Without it, gloo aborted the workers, and the controller retried worker
startup without limit instead of failing. That's a local transport
issue, but an unbounded retry would turn any CI worker-start failure
into a hang until the test timeout.

The PR carries the `docstring-only` label. Its commit carries an
`@rtd-build` line for the Read the Docs preview.

AI assistance (Claude Code) was used for this PR.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Signed-off-by: Douglas Strodtman <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
@pseudo-rnd-thoughts
pseudo-rnd-thoughts merged commit ae6993f into master Nov 5, 2026
7 checks passed
@pseudo-rnd-thoughts
pseudo-rnd-thoughts deleted the ray-train-health/health-report branch November 5, 2026 18:37
pseudo-rnd-thoughts pushed a commit that referenced this pull request Nov 12, 2026
…State (#67879)

## Description

WorkerProbe 3/n of the [Ray Train Monitoring and Diagnostics
REP](https://github.com/ray-project/enhancements/tree/main/reps/2026-08-11-ray-train-monitoring-and-diagnostics)
stack, stacked on #67671 (5/n). WorkerProbe 1/n #67521 and 2/n #67520
are merged.

Since 1/n and 2/n, each worker returns its `WorkerProbe` results in
`WorkerStatus.probe_results` and its latest `ray.train.health.report()`
in `WorkerStatus.health_report`. Nothing passes them to the
`HealthManager` yet, so no evaluator sees them. This PR is the
`HealthManager` side:

- **`HealthState.health_reports`**: `{world rank: ProbeResult}`, the
latest `ray.train.health.report()` of each worker that reported.
- **`HealthManager.worker_probes`**: the in-flight checks' `WorkerProbe`
`ScheduledProbe`s, for each worker to sample. `NodeMonitorGroup` still
ignores them.
- **`HealthManager.evaluate_inflight_checks(worker_statuses=None,
timeout=...)`** takes `{world rank: WorkerStatus}` from the worker
group's latest poll. `_to_health_state()` adds each worker's
`WorkerProbe` results to `HealthState.probe_results`, keyed by world
rank, next to the `NodeProbe` results keyed by node ID, and each
`health_report` to `health_reports`.

Nothing calls these yet. WorkerProbe 4/n, after 6/n #67856, wires them
up: `HealthCallback` gives the workers their `WorkerProbe`s, the
controller passes `worker_group_status.worker_statuses`, a `Diagnose`
runs its on-demand `WorkerProbe`s, and an e2e test covers it.

### Not a duplicate

`gh pr list --repo ray-project/ray --state open --search` for
`WorkerProbe`, `health_reports` and `HealthState worker` finds only 5/n
#67671 and 6/n #67856 of this stack, and neither passes worker results
to the `HealthManager`. This PR leaves `evaluate_on_demand_checks()`,
which 6/n changes, alone, and merges cleanly with 6/n.

## Test

```bash
python python/ray/train/v2/tests/test_health_manager.py       # 24 passed
python python/ray/train/v2/tests/test_health_contracts.py     # 17 passed
python python/ray/train/v2/tests/test_health_node_monitor.py  # 13 passed
pre-commit run --files python/ray/train/health/state.py python/ray/train/health/_internal/manager.py python/ray/train/v2/tests/test_health_manager.py  # passed
```

New tests: `test_worker_probes_are_the_inflight_worker_probes` and
`test_worker_results_and_health_reports_reach_the_evaluators`.

AI assistance (Claude Code) was used for this change.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Signed-off-by: Lehui Liu <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
pseudo-rnd-thoughts pushed a commit that referenced this pull request Nov 12, 2026
## Description

4th PR of the WorkerProbe stack (#67521, #67520, #67879), and part of
the [Ray Train Monitoring and Diagnostics
REP](https://github.com/ray-project/enhancements/tree/main/reps/2026-08-11-ray-train-monitoring-and-diagnostics)
stack #67671 → #67856 → #67879.

Workers sample their `WorkerProbe`s (1/n) and the `HealthManager` can
put their results in the `HealthState` (3/n), but nothing gave the
workers their probes or passed the worker poll in, and on-demand
`WorkerProbe`s were dropped. This PR wires them in:

- **`HealthCallback.before_init_train_context`** gives each worker the
in-flight `WorkerProbe`s, `HealthManager.worker_probes`.
- **The controller** passes its worker poll to
`evaluate_inflight_checks(worker_statuses)`, so `WorkerProbe` results
and `ray.train.health.report()` reach the evaluators.
- **`HealthManager.reset()`** takes the attempt's worker group. The
on-demand checks, pre-flight checks and the checks of a `Diagnose`, send
their `WorkerProbe`s to `WorkerGroup.poll_probes_async()`.
`evaluate_on_demand_checks()` waits for the workers as well as the node
monitors, then evaluates one `HealthState` with `WorkerProbe`,
`NodeProbe` and `ControllerProbe` results. On-demand checks without
evaluators start nothing.

## Related

1. REP:
https://github.com/ray-project/enhancements/tree/main/reps/2026-08-11-ray-train-monitoring-and-diagnostics
2. #67521, #67520, #67879, #67856, #67671

Not a duplicate: no open PR passes `WorkerProbe`s or their results
between the Ray Train controller and the `HealthManager`.

## Test

```
python python/ray/train/v2/tests/test_health_manager.py                 # 26 passed
python python/ray/train/v2/tests/test_health_controller.py              # 9 passed
python python/ray/train/v2/tests/test_health_e2e.py                     # 2 passed
python python/ray/train/v2/tests/test_controller.py                     # 25 passed
python python/ray/train/v2/tests/test_controller_callback_behaviour.py  # 10 passed
python python/ray/train/v2/tests/test_worker.py                         # 5 passed
python python/ray/train/v2/tests/test_worker_group.py                   # 46 passed
```

`test_health_e2e` runs the Diagnose scenario with a training step report
(`ray.train.health.report()`) as one of the signals, and an on-demand
`WorkerProbe` in each diagnosis.

This PR was written with AI assistance (Claude Code). I reviewed every
changed line and ran the tests above.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Signed-off-by: Lehui Liu <[email protected]>
Co-authored-by: Claude Opus 5.5 <[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