Skip to content

[RLlib] Convert rllib.evaluation and rllib.policy docstring examples to stock doctests - #67767

Merged
pseudo-rnd-thoughts merged 1 commit into
masterfrom
doc-1926-rllib-evaluation-policy-doctests
Nov 4, 2026
Merged

pseudo-rnd-thoughts merged 1 commit into
masterfrom
doc-1926-rllib-evaluation-policy-doctests

Conversation

@dstrodtman

Copy link
Copy Markdown
Contributor

Description

Converts the .. testcode:: examples in the python/ray/rllib/evaluation and python/ray/rllib/policy 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 rllib.utils conversion in #67753.

This PR covers all 30 testcode blocks in these two subpackages, in 10 files:

  • 28 never-run blocks stay never-run. Every block was :skipif: True. Each now sits in a docstring that carries the # doctest: +SKIP_EXAMPLE flag ([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 two ObservationFunction.__call__ blocks share one.
  • 2 blocks that don't parse as Python become .. code-block:: python. These are RolloutWorker.set_global_vars, which has a stray ... continuation, and SampleCollector.get_inference_input_dict, which has "truncated", truncated inside 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:

  • Output moves under the print that produces it. In six docstrings, one testcode block printed several times, and a single testoutput held all the results. They're the RolloutWorker and TFPolicy classes, chop_into_sequences, SampleBatch.split_by_episode, SampleBatch.right_zero_pad, and concat_samples. A doctest checks output right after each statement, so each result now sits under its own print. The output text is unchanged.
  • get_learner_stats gains Args and Returns entries. An Examples: 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" when grad_info has 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_stats calls get_stats, which doesn't exist.
  • RolloutWorker.sample_with_count uses PPOTFPolicy, which doesn't exist.
  • split_by_episode sets "dones" columns, which SampleBatch rejects.
  • concat_samples passes plain dicts to MultiAgentBatch, which needs SampleBatch values.

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.py on all 10 files, in a Python 3.12 virtualenv with ray[rllib]==2.59.0, torch, and tensorflow 2.21: "0 docstring(s) run, 0 failed, 27 skipped, in 10 file(s)." All 27 skips are +SKIP_EXAMPLE.
  • A strict stdlib doctest pass over the same docstrings, which fails on unexpected output the way the RLlib doctest() 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 --files on all 10 files: all hooks pass, including pydoclint.

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

…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]>
@dstrodtman dstrodtman added rllib RLlib related issues docstring-only Skip heavy library tests for Ray API docstring edits. labels Nov 3, 2026
@dstrodtman
dstrodtman marked this pull request as ready for review November 3, 2026 21:00
@dstrodtman
dstrodtman requested a review from a team as a code owner November 3, 2026 21:00
@dstrodtman dstrodtman added the go add ONLY when ready to merge, run all tests label Nov 3, 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 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))

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.

medium

The function being documented is get_learner_stats, but the example calls get_stats(grad_info). It should be updated to call get_learner_stats(grad_info).

Suggested change
>>> print(get_stats(grad_info))
>>> print(get_learner_stats(grad_info))

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.

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)

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.

medium

The example imports PPOTF1Policy but mistakenly passes PPOTFPolicy (which is not imported and does not exist) to default_policy_class. It should be updated to use PPOTF1Policy.

Suggested change
... default_policy_class=PPOTFPolicy)
... default_policy_class=PPOTF1Policy)

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.

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]))

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.

medium

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.

Suggested change
>>> print(concat_samples([b1, b2]))
>>> print(concat_samples([c1, c2]))

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.

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]))

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.

medium

Since this docstring is for the concat_samples_into_ma_batch function, the example should demonstrate calling concat_samples_into_ma_batch([b1, b2]) directly instead of concat_samples([b1, b2]).

Suggested change
>>> print(concat_samples([b1, b2]))
>>> print(concat_samples_into_ma_batch([b1, b2]))

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.

Thanks, that's right. This PR is syntax-only on purpose, so it leaves example code unchanged. #67768, stacked on this PR, fixes this.

@pseudo-rnd-thoughts
pseudo-rnd-thoughts merged commit 1ab41c9 into master Nov 4, 2026
7 checks passed
@pseudo-rnd-thoughts
pseudo-rnd-thoughts deleted the doc-1926-rllib-evaluation-policy-doctests branch November 4, 2026 15:20
pseudo-rnd-thoughts pushed a commit that referenced this pull request Nov 4, 2026
…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]>
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 rllib RLlib related issues

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants