Repository navigation
[train] Convert Ray Train docstring examples to stock doctests - #67786
Merged
Merged
Conversation
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]>
Contributor
|
Warning You have reached your daily quota limit. Please wait up to 24 hours and I will start processing your requests again! |
This was referenced Nov 4, 2026
Merged
pseudo-rnd-thoughts
approved these changes
Nov 4, 2026
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]>
5 of 7 tasks
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]>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Description
Converts the
.. testcode::examples in Ray Train API docstrings to>>>examples under a pluralExamples: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/:>>>, so nothing ran thesetestcodeblocks before. Fifteen docstrings now have examples that run: the v2TorchTrainerandXGBoostTrainer, the fiveTrainContextgetters,get_all_reported_checkpoints,get_dataset_shard,DataParallelTrainer,BaseTrainer.training_loop,LightGBMCheckpoint.from_model, the KerasReportCheckpointCallback, and the v1reportandget_checkpointin_internal/session.py.:skipif: Trueexamples become render-only. They carry the docstring-level# doctest: +SKIP_EXAMPLEflag ([core] Add a docstring-level +SKIP_EXAMPLE doctest flag for render-only examples #66753).DataParallelTrainermixes runnable examples with one:skipif:example, so that example's statements carry a per-line# doctest: +SKIPinstead, and the rest of the docstring still runs.horovod/horovod_trainer.py,v2/jax/jax_trainer.py, andxgboost/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:
Examples:. InDataParallelTrainer,HorovodTrainer,BaseTrainer,BaseTrainer.restore,JaxTrainer,get_dataset_shard, and threeTrainContextgetters, example paragraphs and code sat in the description. They now sit in anExamples:section beforeArgs:. The paragraphs that aren't about an example stay in the description. Prose text is unchanged.Example:and numpy-styleExamplesheaders becomeExamples:. In the LightGBM and XGBoost callbacks and checkpoints, the section moves ahead ofArgs:andReturns:.Checkpoint.as_directorydrops a hidden setup block and becomes render-only. Its:hide:block created thecheckpointthe example uses. Doctests have no hidden form, and showing the setup would change what the example shows.get_trial_dirin_internal/session.pyhad+MOCKoutput. It's render-only, and the output moved under thetuner.fit()call that prints it.prepare_data_loaderin bothtrain_loop_utils.pycopies was written.. testcode:with one colon, andXGBoostCheckpoint.from_modelwas 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.WandbLoggerCallbackinair/integrations/wandb.py._internal/session.py:get_world_size,get_world_rank,get_local_rank,get_local_world_size,get_node_rank, andget_dataset_shard.Questions for Train
No doctest target collects the examples of APIs whose
__module__is rewritten.ray/train/__init__.pyimports 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:doctest.DocTestFinderkeeps an object only ifinspect.getmodule(obj)is the module being scanned, andgetmodulereads__module__. So scanningray.train.v2.api.train_fn_utilsskipsreport. For a renamed class such asTrainContextorCheckpoint, the finder never descends into its methods.__init__.pyis never scanned. Scanningray.trainitself would find the renamed functions and class docstrings, though still not the methods. But thedoctest()macro inbazel/python.bzlexcludes the package-root__init__.py.RAY_TRAIN_V2_ENABLEDdecides which implementation gets renamed.py_doctest[train]runs with it on andpy_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 fiveTrainContextgetters, the V2get_dataset_shardandget_all_reported_checkpoints, and the V1report,get_checkpoint, andget_dataset_shardin_internal/session.py. TheCheckpointclass's existing>>>examples predate this PR and have never run in a doctest target. I checked this withDocTestFinderagainstray==2.59.0under each flag value. Tune rewrites__module__the same way. Its only renamed object with examples,TuneContext, copies them from_internal/session.py, andpy_doctest[tune]excludes its file.CI's
run_docstring_examples.pystep reads source files directly, so it still runs these examples, but only on PRs that change those files. Two ways to fix collection:__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 inrepr(), 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 fiveTrainContextgetters,get_all_reported_checkpoints, andget_dataset_shard.run_docstring_examples.pyonly requires an example with no shown output to run. A strict doctest would also compare the echoedResultrepr and any worker log lines, so these lines need theprint("[ignore]"); ... # doctest: +ELLIPSISform 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,tensorflow2.21 withtf_keras,lightgbm,xgboost, andscikit-learn:ci/ray_ci/doc/run_docstring_examples.pyon the 19 filespy_doctest[train]covers, withRAY_TRAIN_V2_ENABLED=1 TF_USE_LEGACY_KERAS=1: "15 docstring(s) run, 0 failed, 20 skipped, in 19 file(s)."_internal/session.pywithRAY_TRAIN_V2_ENABLED=0, matchingpy_doctest[train-gpu]: "2 docstring(s) run, 0 failed, 1 skipped." Neither runnable example needs a GPU.v2/jax/jax_trainer.pyandxgboost/xgboost_checkpoint.py: both skip, as render-only.horovod_trainer.pycan'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 --fileson all 23 files: all hooks pass, including pydoclint and the Train circular-import check.On macOS, the
TorchTrainerexamples neededGLOO_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-onlylabel. Its commit carries an@rtd-buildline for the Read the Docs preview.AI assistance (Claude Code) was used for this PR.
🤖 Generated with Claude Code