Skip to content

[train] Convert Ray Train docstring examples to stock doctests - #67786

Merged
pseudo-rnd-thoughts merged 1 commit into
masterfrom
doc-1927-train-air-doctests
Nov 4, 2026
Merged

pseudo-rnd-thoughts merged 1 commit into
masterfrom
doc-1927-train-air-doctests

Conversation

@dstrodtman

@dstrodtman dstrodtman commented Nov 3, 2026 •

Copy link
Copy Markdown
Contributor

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 ([core] Add a docstring-level +SKIP_EXAMPLE doctest flag for render-only examples #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 [train] Fix broken Ray Train docstring examples and convert the rest to stock doctests #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: [ci][train] Collect doctests for APIs whose __module__ is rewritten #67831 changes the plugin, stacked on [train] Fix broken Ray Train docstring examples and convert the rest to stock doctests #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 [train] Fix broken Ray Train docstring examples and convert the rest to stock doctests #67821 adopts. [ci][train] Collect doctests for APIs whose __module__ is rewritten #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

Converts the `.. testcode::` examples in Ray Train API docstrings to
`>>>` doctests under an `Examples:` header. Runnable examples stay
runnable. `:skipif: True` examples carry the docstring-level
`# doctest: +SKIP_EXAMPLE` flag, or a per-line `# doctest: +SKIP` in a
docstring that also has runnable examples. Example code is unchanged.

Blocks paired with a hidden `testoutput` stay as `testcode` for a
follow-up.

@rtd-build

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Douglas Strodtman <[email protected]>
@dstrodtman
dstrodtman requested a review from a team as a code owner November 3, 2026 21:48
@dstrodtman dstrodtman added train Ray Train Related Issue go add ONLY when ready to merge, run all tests docstring-only Skip heavy library tests for Ray API docstring edits. labels Nov 3, 2026
@gemini-code-assist

Copy link
Copy Markdown
Contributor

Warning

You have reached your daily quota limit. Please wait up to 24 hours and I will start processing your requests again!

@pseudo-rnd-thoughts
pseudo-rnd-thoughts merged commit 1cd6568 into master Nov 4, 2026
6 checks passed
@pseudo-rnd-thoughts
pseudo-rnd-thoughts deleted the doc-1927-train-air-doctests branch November 4, 2026 22:48
pseudo-rnd-thoughts pushed a commit that referenced this pull request Nov 5, 2026
Resolve conflicts with #67786 (stock doctest conversion) by keeping this
branch's fixed docstring examples.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Mark Towers <[email protected]>
pseudo-rnd-thoughts pushed a commit that referenced this pull request Nov 5, 2026
…to stock doctests (#67821)

## Description

This is a correctness change for Train review. It fixes Train and AIR
docstring examples that were wrong, and it converts the examples #67786
left out because converting them changes what they show. After this PR,
no `testcode` or `testoutput` remains in `python/ray/train` or
`python/ray/air`.

Stacked on #67786. Review that PR first. This diff is against its
branch.

### Examples that were wrong

- **`prepare_data_loader`**, in both `train_loop_utils.py` copies: the
example built `train_dataloader`, then passed and looped over
`train_loader`, which it never defined. Both now use `train_dataloader`.
This example never rendered before #67786, because its directive had one
colon.
- **`get_devices`**, in both copies: each example's first line compared
`CUDA_VISIBLE_DEVICES` with `==` where `get_device` assigns it with `=`.
It now assigns.
- **`JaxTrainer`**: `train_loop_config={"argv": absolute_argv}` used an
undefined name. It now passes `main`'s `argv` parameter.
- **`WandbLoggerCallback`**: `train_func` called `train.report` without
importing `train`. A function passed to `tune.Tuner` reports with
`tune.report`, which the example already imports through `from ray
import tune`.
- **`report`** in `_internal/session.py`: the example called
`ray.train.get_context()` but imported only `from ray import train`. It
now calls `train.get_context()`.

### Descriptions that were wrong

- **`get_checkpoint()` doesn't return a dict.** The train-loop examples
in `DataParallelTrainer`, `HorovodTrainer`, and both `TensorflowTrainer`
docstrings said "Returns dict of last saved checkpoint." Both
`get_checkpoint` implementations are typed `Optional[Checkpoint]`, so
the comment now reads "Returns the last saved checkpoint, or None."
- **`LightGBMTrainer`'s default backend isn't "rabit".** Rabit is
XGBoost's communicator. With no `lightgbm_config`, the trainer uses
`LightGBMConfig()` (`lightgbm/v2.py`), and the description now says so.
The same sentence on the XGBoost trainers is correct:
`XGBoostConfig.xgboost_communicator` defaults to `"rabit"`.
- **`BaseTrainer.fit()` returns `ray.train.Result`.** There's no
`ray.result` module.

### Examples that change what they show

These pair with a hidden `testoutput`, which has no doctest form.

- **`Checkpoint.as_directory` is runnable.** Its hidden block created
the checkpoint the example uses. The setup is now visible, including the
`23` that `write_text` returns.
- **Training runs that printed hidden output** use the idiom Tune
already uses for this: `print("[ignore]"); ... # doctest: +ELLIPSIS`,
with `[ignore]...` as the output. That covers the v2 `TensorflowTrainer`
and 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`.
- **`TensorflowTrainer`** (v1 and v2) gets the same `Examples:` layout
as `DataParallelTrainer` in #67786. The signature stubs and the
train-loop methods block run.
- **Render-only, with `+SKIP_EXAMPLE` or per-line `+SKIP`:**
  - `get_local_rank` uses `use_gpu=True` with two workers.
- The v1 `TensorflowTrainer` training example uses three GPU workers. It
sits in a docstring with runnable examples, so its statements carry a
per-line `+SKIP`.
- `TensorflowCheckpoint.from_model` downloads ResNet-101 weights, and
its output was `+MOCK`.
- `WandbLoggerCallback` needs a WandB API key, and no doctest target
covers `air/integrations/wandb.py`.

### Question for Train: the GPU examples

`tensorflow/tensorflow_trainer.py` and `_internal/session.py` are in
`py_doctest[train-gpu]`, so the `get_local_rank` and v1
`TensorflowTrainer` examples could run there. I made them render-only
because I couldn't run them without GPUs. If you'd rather they run in
that target, I'll drop the skips. One thing to check first is that the
v1 example asks for three GPU workers.

## Related issues

Stacked on #67786. Related to #66753.

## Additional information

**Not a duplicate.** I searched open PRs for Train `testcode`, doctest,
and docstring-example changes. Only #67786, which this PR stacks on,
touches these docstrings.

**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 8 changed files that
`py_doctest[train]` covers, with `RAY_TRAIN_V2_ENABLED=1
TF_USE_LEGACY_KERAS=1`: "6 docstring(s) run, 0 failed, 10 skipped, in 8
file(s)." `Checkpoint.as_directory` and the v2 `TensorflowTrainer` pass.
- The same runner on `_internal/session.py` and
`tensorflow/tensorflow_trainer.py` with `RAY_TRAIN_V2_ENABLED=0`,
matching `py_doctest[train-gpu]`: "8 docstring(s) run, 0 failed, 2
skipped." All six session functions above pass, except `get_local_rank`,
which skips.
- The same runner on `v2/jax/jax_trainer.py` and
`air/integrations/wandb.py`: both skip, as render-only.
- `ci/ray_ci/doc/check_docstring_only.py --base
doc-1927-train-air-doctests`: "13 file(s), docstrings only."
- `pre-commit run --files` on all 13 files: all hooks pass.

I checked the fixes in render-only examples (`prepare_data_loader`,
`get_devices`, `JaxTrainer`, `WandbLoggerCallback`) by reading them
against the source, not by running them.

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]>
Signed-off-by: Mark Towers <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
Co-authored-by: Mark Towers <[email protected]>
dstrodtman added a commit that referenced this pull request Nov 9, 2026
…67831)

## Description

> Stacked on #67821, which is stacked on #67786. Review only the top
commit until those merge.

Ray Train and Tune overwrite `__module__` on their public re-exports, so
`ray.train.report` presents as `ray.train` instead of
`ray.train.v2.api.train_fn_utils`. Doctest collects an object only from
the module that `__module__` names. The `doctest()` macro in
`bazel/python.bzl` excludes the package `__init__.py` from every target.
Between the two, no doctest target collected these docstrings.

This PR changes the two doctest plugins so that collection also accepts
a function or class whose code is defined in the module being scanned.
Runtime `__module__` rewriting is unchanged.

### How it works

`DocTestFinder._from_module` checks `inspect.getmodule(obj)` first,
which reads `__module__`, so a renamed object fails before the
`__globals__` check that would accept it. The plugin wraps that method.
When the stock check says no, it also accepts the following:

- **A function** whose unwrapped `__globals__` is the scanned module's
namespace.
- **A class** that has a method, static method, class method, or
property getter meeting the same test.

Pytest's `MockAwareDocTestFinder` calls `super()._from_module` on Python
3.12 and earlier, and doesn't override it on 3.13, so the patch covers
both. An object imported from another module still fails, because its
functions' globals are the other module's. That means nothing is
collected twice.

Both `bazel/default_doctest_pytest_plugin.py` and
`python/ray/data/tests/doctest_pytest_plugin.py` change, since each asks
to be kept in sync with the other. Ray Data rewrites no `__module__`, so
its targets collect nothing new.

### What starts running

| Target | Newly collected | Result |
|---|---|---|
| `py_doctest[train]` (V2 on) | `Checkpoint`, `Checkpoint.as_directory`,
the five V2 `TrainContext` getters, `get_dataset_shard`,
`get_all_reported_checkpoints` | 9 pass |
| `py_doctest[train]` (V2 on) | V2 `report`, `get_checkpoint`,
`get_preemption_info` | 3 skip, render-only (`+SKIP_EXAMPLE`) |
| `py_doctest[train-gpu]` (V2 off) | V1 `report`, `get_checkpoint`,
`get_dataset_shard` | 3 pass |
| `py_doctest[train-gpu]` (V2 off) | Six V1 `TrainContext` methods | 4
pass, 2 skip |

`py_doctest[train_v2]` also globs `v2/**`, so the V2 examples run there
too, the same as every other V2 docstring already does.

The six V1 `TrainContext` methods copy their docstrings from
`_internal/session.py` with `_copy_doc`. Those session functions were
already collected, so these examples now run twice in the GPU target.
`TuneContext` copies the same docstrings, but `py_doctest[tune]`
excludes `tune/context.py`.

### Examples changed so they pass

The five V2 `TrainContext` getters, `get_dataset_shard`, and
`get_all_reported_checkpoints` from #67786 ended in a bare `>>>
trainer.fit()`. Under strict doctest that line echoes a `Result` and
fails. They now use `print("[ignore]"); trainer.fit() # doctest:
+ELLIPSIS` with `[ignore]...` output, the form the V1 session examples
in #67821 use.

The comment in `ci/ray_ci/doc/run_docstring_examples.py` that said
Train's LightGBM and XGBoost examples "are still testcode blocks" now
says they skip there and run in `py_doctest[train]`.

## Related issues

Follows up the collection question raised in #67786. The longer-term
direction is for Train to define public APIs in public modules once
Train V1 is removed. At that point the rewriting and this plugin path
can both go.

## Additional information

**Not a duplicate.** I searched open PRs for doctest plugin and
`__module__` changes. Only #67786, this PR's base, came up.

**Tests run**

These ran with Python 3.12 against the `ray==2.59.0` wheel. I applied
this stack's Train diff to a copy of the installed package. Two files
didn't patch cleanly against 2.59, so I moved this branch's docstrings
onto the 2.59 code instead.

- **Collection, before and after:** pytest `--collect-only
--doctest-modules` with the old and new plugin on the
`py_doctest[train]` file list (`RAY_TRAIN_V2_ENABLED=1`) and the
`py_doctest[train-gpu]` list (`=0`). The only additions are the items in
the table above. Collection errors from libraries missing locally are
identical before and after.
- **Every loaded module:** imported every `ray.*` subpackage that
imports locally (about 1,258 modules) and compared `DocTestFinder`
output under each plugin, with `RAY_TRAIN_V2_ENABLED` at 0 and at 1.
Only `ray.train` modules and `ray.tune.context` gain tests. No
`doctest()` target covers `ray.tune.context`.
- **Running the new items:** `py_doctest[train]` items: 9 passed, 3
skipped. `py_doctest[train-gpu]` items: 7 passed, 2 skipped. None of the
GPU-target examples needs a GPU. On macOS, these needed
`GLOO_SOCKET_IFNAME=lo0`.
- **pre-commit:** all hooks pass on the changed files, including black,
ruff, pydoclint, and `pyrefly (ray data)`. Pyrefly skips any file under
a hidden directory, and my worktree path has one, so I ran that hook
from a checkout without one.

Changing a file under `bazel/` selects most premerge tags, so this PR
runs the full suite. That's the end-to-end check that no other library's
doctest target breaks.

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 pushed a commit that referenced this pull request Nov 16, 2026
…n legacy LightGBM/XGBoost trainers (#68145)

## Why are these changes needed?

In `_get_legacy_train_fn_per_worker` for both `LightGBMTrainer`
(`python/ray/train/lightgbm/lightgbm_trainer.py`) and `XGBoostTrainer`
(`python/ray/train/xgboost/xgboost_trainer.py`):

1. `num_boost_round = num_boost_round or DEFAULT_NUM_BOOST_ROUND` used
truthiness instead of an explicit `is None` check. When a caller
explicitly passed `num_boost_round=0` (for example in dry-run
initialization or checkpoint evaluation without additional boosting
rounds), `0 or 10` silently evaluated to `10`.
2. `callbacks = trainer_kwargs.get("callbacks", [])` retrieved the
caller's list reference directly and appended `default_callback_cls()`
in-place (`callbacks.append(...)`). Reusing the same configuration
dictionary across multiple `Trainer` instantiations mutated the caller's
`callbacks` list on each run, and passing `callbacks=None` or a tuple
raised an `AttributeError`.

This PR:
- Checks `if num_boost_round is None: num_boost_round =
DEFAULT_NUM_BOOST_ROUND` so explicit `0` is preserved.
- Copies `callbacks = list(trainer_kwargs.get("callbacks") or [])`
before appending the default `RayTrainReportCallback`.

## Related issue number

N/A

## Checks

- [x] I've signed off every commit(by using the -s flag, i.e., `git
commit -s`) in this PR.
- [x] I've run `scripts/format.sh` to lint the changes in this PR.
- [x] I've included any doc changes needed for
https://docs.ray.io/en/master/.
- [x] I've made sure the tests are passing. Note that there might be a
few flaky tests, see the recent failures at https://flakey-tests.ray.io/
- Testing Strategy
- [x] Unit tests (`python/ray/train/tests/test_lightgbm_trainer.py` and
`python/ray/train/tests/test_xgboost_trainer.py`)
   - [ ] Release tests
   - [ ] This PR is not tested :(

## Acknowledgements

Thanks to @dstrodtman (#67821, #67786, #67620), @pseudo-rnd-thoughts
(#63988, #63427, #63365), and @justinvyu (#57256, #50042) for their work
maintaining `LightGBMTrainer` and `XGBoostTrainer`.

---------

Signed-off-by: Parth Vadera <[email protected]>
Co-authored-by: Copilot <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

docstring-only Skip heavy library tests for Ray API docstring edits. 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.

2 participants