Repository navigation
[core] Convert Ray Core docstring examples to stock doctests - #67760
dstrodtman wants to merge 1 commit into
Conversation
Converts the remaining `.. testcode::` examples in Ray Core API docstrings to `>>>` doctests under an `Examples:` header. The `ray.init` and `ray.remote` examples are runnable; `:skipif: True` lines carry `# doctest: +SKIP`. Examples with `+MOCK` output, and examples in modules no doctest target collects, carry the docstring-level `# doctest: +SKIP_EXAMPLE` flag. Example code is unchanged. @rtd-build Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: Douglas Strodtman <[email protected]>
There was a problem hiding this comment.
Code Review
This pull request standardizes the documentation across several Ray modules by converting Sphinx-style test blocks into standard Python doctest examples. While this is a great improvement for documentation consistency, the review identified two issues in the updated examples: the ray.util.as_completed example incorrectly iterates over resolved values instead of tuples of object references, and an assertion in the ray.remote options example compares a returned tuple to a list, which would cause a test failure.
| >>> for x in ray.util.as_completed(refs, chunk_size=2): | ||
| ... print(x) | ||
| 4 | ||
| 2 | ||
| 6 | ||
| 8 | ||
| 10 |
There was a problem hiding this comment.
The ray.util.as_completed function yields tuples of (ready_refs, remaining_refs) where ready_refs is a list of ObjectRefs, rather than yielding the resolved values directly. Printing x directly would print a tuple of lists of ObjectRefs instead of the integer values. To get the resolved values, you need to call ray.get on the ready_refs list.
| >>> for x in ray.util.as_completed(refs, chunk_size=2): | |
| ... print(x) | |
| 4 | |
| 2 | |
| 6 | |
| 8 | |
| 10 | |
| >>> for ready_refs, _ in ray.util.as_completed(refs, chunk_size=2): | |
| ... print(ray.get(ready_refs)) | |
| [4, 2] | |
| [6, 8] | |
| [10] |
There was a problem hiding this comment.
as_completed yields resolved values, not (ready, remaining) tuples: _wait_and_get_single_batch returns ray.get(ready) unless yield_obj_refs=True, and as_completed does yield from results. Running the example prints the integers. The example code is also unchanged from master; this PR only converts its syntax.
| ... return 1, 2 | ||
| >>> f_with_2_gpus = f.options(num_gpus=2) | ||
| >>> object_refs = f_with_2_gpus.remote() # doctest: +SKIP | ||
| >>> assert ray.get(object_refs) == [1, 2] # doctest: +SKIP |
There was a problem hiding this comment.
Since f is defined with num_returns=2, calling f_with_2_gpus.remote() returns a tuple of ObjectRefs. Passing this tuple to ray.get preserves the tuple structure and returns a tuple of values (1, 2). Comparing this tuple to the list [1, 2] will evaluate to False and cause an AssertionError if executed. The assertion should compare against the tuple (1, 2) instead.
| >>> assert ray.get(object_refs) == [1, 2] # doctest: +SKIP | |
| >>> assert ray.get(object_refs) == (1, 2) # doctest: +SKIP |
There was a problem hiding this comment.
With num_returns=2, .remote() returns a list of ObjectRefs, so ray.get(object_refs) returns [1, 2] and the assertion holds. Checked locally. This line is also unchanged from master.
## 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]>
|
This pull request has been automatically marked as stale because it has not had You can always ask for help on our discussion forum or Ray's public slack channel. If you'd like to keep this open, just leave any comment, and the stale label will be removed. |
Description
Converts the remaining
.. testcode::examples in Ray Core 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 earlier Core conversion in #66745.This PR covers 25
testcodeblocks in 7 files:ray.initandray.remotebecome runnable doctests._private/worker.pyis in the_privatedoctest glob, so these run in the Core doctest target for the first time. The two:skipif: Trueblocks inray.init(address="auto"and theray://address) carry a per-line# doctest: +SKIP.+MOCKbecome render-only.+MOCKmarks illustrative output that was never checked. These docstrings carry the docstring-level# doctest: +SKIP_EXAMPLEflag ([core] Add a docstring-level +SKIP_EXAMPLE doctest flag for render-only examples #66753):ray.util.as_completedandray.util.map_unorderedinutil/helpers.py,RuntimeContext.get_task_id,get_task_name, andget_task_function_name, andray.util.state.get_log.+SKIP_EXAMPLE.runtime_context.py,job_config.py,actor.py,_common/deprecation.py, andutil/state/api.pyare outside every Coredoctest()glob, so nothing ran these examples before and nothing runs them now. The flag keeps a>>>from looking tested when it isn't. Whether to add any of these modules to a doctest target is a question for Core, below.This is a syntax-only change. The example code and the claims in each docstring are unchanged, with these exceptions that the format forces:
ray.initandray.remotegain anExamples:section. Their examples were interleaved with description prose. The example paragraphs and code now sit in anExamples:section beforeArgs:, and the paragraphs that aren't about an example stay in the description above it: theRAY_ADDRESSparagraph inray.init, and the actor-termination paragraph, theray.killsentence, and the tip inray.remote. The prose text is unchanged.ray.init()shows its return value. A doctest echoes theRayContextthatray.init()returns, so the example showsRayContext(...)under it.ray.remotedrops a hidden setup block. A:hide:block restarted Ray withnum_cpus=5, num_gpus=5so the.options(num_gpus=2)example could run. Doctests have no hidden form, so instead the two lines that need two GPUs carry# doctest: +SKIP. Everything else in that example runs on a CPU-only cluster.JobConfigandget_loghad:hide:blocks that shut down or started Ray. Their examples don't run, so the scaffolding has nothing to set up.printthat produces it. Inget_task_id,get_task_name, andget_task_function_name, onetestcodeblock printed several times and a singletestoutputheld every result. Each output line now sits under its ownprint. The output text is unchanged.as_completedalso drops the# Output:label line, which a doctest would read as printed output.DeprecatedgainsArgsandReturnsentries. AnExamples:section makes pydoclint check its signature. Each entry describes what the decorator body does.Left out of this PR
ray.LoggingConfig(_private/ray_logging/logging_config.py). Its docstring is assigned throughLoggingConfig.__doc__ = """...""", whichcheck_docstring_only.pyreads as a code change, so including it would void thedocstring-onlylabel for the whole PR. It'll follow in a separate PR.ObjectRefGeneratorandray._private.profiling.profile. Neither appears in an API reference listing, so their examples don't render on docs.ray.io.Question for Core: run the out-of-glob examples?
To help decide whether any of these modules should join a doctest target, I ran their examples locally with the
+SKIP_EXAMPLEflags removed:get_session_name,task_id,get_runtime_context,get_task_name, the threeJobConfigexamples,__ray_call__,Deprecated, andas_completed.get_task_nameandas_completedpassed on this run, but their output depends on scheduling.get_task_id(task IDs differ per run),get_task_function_name(the output uses a[python module name]placeholder),get_log(log lines differ), andmap_unordered(completion order differs).The docstring examples runner accepts an example that prints output it doesn't show. A stock pytest doctest target is stricter, so examples such as
task_idandget_runtime_context, which echo object refs and IDs, would need output or+SKIPlines first. If Core wants any of them collected, that change, plus adding the module to a target, will go in a separate PR for Core review rather than this syntax-only one.Related issues
Related to #66745 and #66753.
Additional information
Not a duplicate. I searched open PRs for Core
testcodeand doctest conversions, and none touches these docstrings. #66745 convertedutil/debug.pyandutil/queue.pyand merged.Tests run
ci/ray_ci/doc/run_docstring_examples.pyon all 7 files, in a Python 3.11 virtualenv withray==2.59.0:ray.initandray.remotepass, and the 14+SKIP_EXAMPLEdocstrings skip. The one failure isActorMethod.optionsinactor.py, an existing>>>example this PR doesn't touch. CI's step doesn't run it, because no doctest target coversactor.py.ci/ray_ci/doc/check_docstring_only.py --base upstream/master: "7 file(s), docstrings only."pre-commit run --fileson all 7 files: all hooks pass, including pydoclint.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