Repository navigation
[RLlib] Convert rllib.evaluation and rllib.policy docstring examples to stock doctests - #67767
Conversation
…to stock doctests Convert the `.. testcode::` examples in the rllib/evaluation and rllib/policy docstrings to `>>>` examples under an `Examples:` header, so they render in griffe and MkDocs as well as Sphinx. All of these examples were `:skipif: True`, so they stay never-run: each docstring now carries `+SKIP_EXAMPLE`, and the two blocks that don't parse as Python become `.. code-block:: python`. @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 refactors docstrings across RLlib to replace .. testcode:: and .. testoutput:: blocks with standard Python Examples: blocks using doctest syntax. The review feedback highlights several minor errors in these newly formatted examples, such as calling incorrect or unimported functions (e.g., calling get_stats instead of get_learner_stats, using PPOTFPolicy instead of PPOTF1Policy, and calling concat_samples instead of concat_samples_into_ma_batch or passing the wrong variables).
| Examples: | ||
| >>> grad_info = worker.learn_on_batch(samples) # doctest: +SKIP_EXAMPLE | ||
| >>> # {"td_error": [...], "learner_stats": {"vf_loss": ..., ...}} | ||
| >>> print(get_stats(grad_info)) |
There was a problem hiding this comment.
Thanks, that's right. This PR is syntax-only on purpose, so it leaves example code unchanged. #67768, stacked on this PR, fixes this.
| >>> from ray.rllib.algorithms.ppo.ppo_tf_policy import PPOTF1Policy | ||
| >>> worker = RolloutWorker( | ||
| ... env_creator=lambda _: gym.make("CartPole-v1"), | ||
| ... default_policy_class=PPOTFPolicy) |
There was a problem hiding this comment.
There was a problem hiding this comment.
Thanks, that's right. This PR is syntax-only on purpose, so it leaves example code unchanged. #67768, stacked on this PR, fixes this.
| ... }}, env_steps=2) | ||
| >>> c2 = SampleBatch({"a": np.array([3]), | ||
| ... "b": np.array([12])}) | ||
| >>> print(concat_samples([b1, b2])) |
There was a problem hiding this comment.
In this example, c1 and c2 are defined but the code mistakenly calls concat_samples([b1, b2]) again (which was already called in the previous example block). It should call concat_samples([c1, c2]) to demonstrate the concatenation of a MultiAgentBatch and a SampleBatch and to match the expected output.
| >>> print(concat_samples([b1, b2])) | |
| >>> print(concat_samples([c1, c2])) |
There was a problem hiding this comment.
Thanks, that's right. This PR is syntax-only on purpose, so it leaves example code unchanged. #67768, stacked on this PR, fixes this.
| ... }}, env_steps=2) | ||
| >>> b2 = SampleBatch({"a": np.array([3]), | ||
| ... "b": np.array([12])}) | ||
| >>> print(concat_samples([b1, b2])) |
There was a problem hiding this comment.
There was a problem hiding this comment.
Thanks, that's right. This PR is syntax-only on purpose, so it leaves example code unchanged. #67768, stacked on this PR, fixes this.
…es and make them run (#67768) ## Description This is a correctness change for RLlib review. It fixes `rllib.evaluation` and `rllib.policy` docstring examples that were wrong or couldn't run. It also turns the two code-block fallbacks from #67767 back into doctests. After this PR, 17 of these docstrings run in the doctest target, and no `testcode` or `testoutput` remains in either subpackage. Stacked on #67767. Review that PR first. This diff is against its branch. ### Examples that were broken and now run Before this PR, each of these was `:skipif: True` and failed when run. Each now runs, and the `+SKIP_EXAMPLE` flag is gone, so the doctest target checks it. - `get_learner_stats`: the example called `get_stats`, which doesn't exist, on the result of `worker.learn_on_batch(samples)`, where `worker` and `samples` were undefined. It now passes literal `grad_info` dicts in the shape the old comment showed, covering both the single-agent and the multi-agent case. - `discount_cumsum`: the output was a symbolic formula. It's now the real `array([4.707, 5.23 , 4.7 , 3. ])`, and the formula is a comment. - `RolloutWorker.sample`, `sample_with_count`, `learn_on_batch`, `compute_gradients`, and `apply_gradients`: - `PPOTF1Policy` fails to build with the default config, so each example now passes a `PPOConfig` with the old API stack enabled and `framework("tf")`. - `sample_with_count` used `PPOTFPolicy` instead of `PPOTF1Policy`. - `sample` used `AlgorithmConfig` without importing it. - `learn_on_batch` and `compute_gradients` passed an undefined `samples` instead of `batch`. - `sample()` returns a `MultiAgentBatch`, not a `SampleBatch`, so the outputs now show that. - `chop_into_sequences`: the outputs now show the list of arrays and the array that the function returns. The values are the same as before. - `ViewRequirement`: `ModelV2(...)` raised `TypeError`. The example now builds a `ModelV2` with real spaces. It shows that the model's only default view requirement is `obs`, with `shift=0`. - `SampleBatch.concat`, `rows`, `columns`, `shuffle`, `split_by_episode`, and `right_zero_pad`: - The outputs were dict literals, but `print(batch)` shows a summary such as `SampleBatch(5: ['a'])`. The examples now print columns, and the outputs are real. - `split_by_episode` set a `"dones"` column, which `SampleBatch` rejects with `KeyError`. It now sets `"terminateds"`, which the splitter reads. - `shuffle` now seeds NumPy, so its output is fixed. - `concat_samples` and `concat_samples_into_ma_batch`: - Both passed plain dicts to `MultiAgentBatch`, which asserts on `SampleBatch` values. - The second `concat_samples` call concatenated `b1` and `b2` instead of `c1` and `c2`. - The `concat_samples_into_ma_batch` example called `concat_samples`. - The outputs now show the real `MultiAgentBatch` repr and the concatenated columns. The five `RolloutWorker` examples build old-API-stack TF1 PPO policies. They take about 9 seconds together on CPU. Their outputs show 2,000 sampled steps, which comes from PPO's default config. I ran them locally, but not under Bazel. If RLlib would rather not run old-API-stack TF code in the doctest target, re-adding `# doctest: +SKIP_EXAMPLE` keeps the corrected examples render-only. ### Fixed but still render-only - `RolloutWorker` class docstring: the single-agent half gets the same config fix and runs. The multi-agent half uses placeholders and `PGTFPolicy`, which RLlib no longer has, so the docstring stays skipped. - `RolloutWorker.set_global_vars`: the stray `...` is gone, and so is the assignment of the method's `None` return value. It's a doctest again. - `SampleCollector.add_init_obs`, `add_action_reward_next_obs`, and `get_inference_input_dict`: - The `add_action_reward_next_obs` calls now pass `env_id`. - `add_init_obs` is called with keywords, since its arguments are keyword-only. - `get_inference_input_dict` gets a policy ID, not `policy.model`, and its dict syntax error is fixed. - The examples still use placeholder `env` and `collector` objects. `ObservationFunction.__call__`, `Policy.learn_on_batch`, `Policy.export_checkpoint`, `TFPolicy`, and `RolloutWorker.get_weights`, `set_weights`, and `get_global_vars` use placeholder objects. They're unchanged and stay render-only. ### Found, not fixed here These need RLlib's call, so this PR leaves them alone: - The abstract `SampleCollector.add_init_obs` has no `env_id` parameter, but `SimpleListCollector.add_init_obs`, its only implementation, requires one. The example follows the abstract signature. - The render-only `get_global_vars` output, `{"timestep": 424242}`, leaves out `num_grad_updates_per_policy`, which the real dict contains. ## Related issues Stacked on #67767. Related to #66753. ## Additional information **Not a duplicate.** I searched open PRs for RLlib `testcode`, doctest, and docstring-example changes, and none touches these docstrings. **Tests run** These ran in a Python 3.12 virtualenv with `ray[rllib]==2.59.0`, `torch`, and `tensorflow` 2.21: - `ci/ray_ci/doc/run_docstring_examples.py` on all 7 changed files: "17 docstring(s) run, 0 failed, 8 skipped, in 7 file(s)." - A strict stdlib `doctest` pass over the same docstrings with `ELLIPSIS`. Unlike the runner above, it fails on unexpected output, the way the RLlib `doctest()` target does. All 17 runnable docstrings pass, and the rest carry `+SKIP_EXAMPLE`. - `ci/ray_ci/doc/check_docstring_only.py --base doc-1926-rllib-evaluation-policy-doctests`: "7 file(s), docstrings only." - `pre-commit run --files` on all 7 files: all hooks pass. 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]>
Description
Converts the
.. testcode::examples in thepython/ray/rllib/evaluationandpython/ray/rllib/policydocstrings to>>>examples under a pluralExamples:header. Sphinx renders.. testcode::, but griffe and MkDocs don't, and stock>>>examples render in both. This follows therllib.utilsconversion in #67753.This PR covers all 30
testcodeblocks in these two subpackages, in 10 files::skipif: True. Each now sits in a docstring that carries the# doctest: +SKIP_EXAMPLEflag ([core] Add a docstring-level +SKIP_EXAMPLE doctest flag for render-only examples #66753), so the doctest target and the docstring examples step skip the whole docstring. There are 27 such docstrings, because the twoObservationFunction.__call__blocks share one... code-block:: python. These areRolloutWorker.set_global_vars, which has a stray...continuation, andSampleCollector.get_inference_input_dict, which has"truncated", truncatedinside a dict literal.This is a syntax-only change. The example code and the claims in each docstring are unchanged, with two exceptions that the format forces:
printthat produces it. In six docstrings, onetestcodeblock printed several times, and a singletestoutputheld all the results. They're theRolloutWorkerandTFPolicyclasses,chop_into_sequences,SampleBatch.split_by_episode,SampleBatch.right_zero_pad, andconcat_samples. A doctest checks output right after each statement, so each result now sits under its ownprint. The output text is unchanged.get_learner_statsgainsArgsandReturnsentries. AnExamples:section makes pydoclint check docstrings it used to skip as short, and the RLlib baseline is empty. The function returns the value under"learner_stats"whengrad_infohas that key. Otherwise, it returns a dict of those values from each nested dict that has the key. The entries describe that.Left for a separate correctness PR
Converting the never-run examples surfaced errors, which this PR leaves as-is:
get_learner_statscallsget_stats, which doesn't exist.RolloutWorker.sample_with_countusesPPOTFPolicy, which doesn't exist.split_by_episodesets"dones"columns, whichSampleBatchrejects.concat_samplespasses plain dicts toMultiAgentBatch, which needsSampleBatchvalues.Related issues
Related to #66749, #66753, and #67753.
Additional information
Not a duplicate. I searched open PRs for RLlib
testcode, doctest, and docstring-example changes, and none touches these docstrings.Tests run
ci/ray_ci/doc/run_docstring_examples.pyon all 10 files, in a Python 3.12 virtualenv withray[rllib]==2.59.0,torch, andtensorflow2.21: "0 docstring(s) run, 0 failed, 27 skipped, in 10 file(s)." All 27 skips are+SKIP_EXAMPLE.doctestpass over the same docstrings, which fails on unexpected output the way the RLlibdoctest()target does: 0 failing, with all 27 skipped.ci/ray_ci/doc/check_docstring_only.py --base upstream/master: "10 file(s), docstrings only."pre-commit run --fileson all 10 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