Repository navigation
[RLlib] Convert rllib.env docstring examples to stock doctests - #67763
Conversation
Convert the `.. testcode::` examples in `rllib/env` docstrings to `>>>` examples under an `Examples:` header, so they render in griffe and MkDocs as well as Sphinx. Runnable blocks become runnable doctests, `:skipif: True` blocks carry `+SKIP_EXAMPLE`, and blocks that don't parse as Python become `code-block` directives. Example code and docstring claims are 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 converts Sphinx-style testcode and testoutput blocks into doctest-compatible Examples blocks across several RLlib environment and episode files. The review feedback identifies several issues and inaccuracies in the updated example code blocks, such as incorrect argument passing in with_agent_groups, outdated reset() return values, incorrect environment references, and multiple slicing or indexing errors in the expected outputs of get_actions, get_rewards, and get_extra_model_outputs.
| >>> grouped_env = env.with_agent_groups(env, { | ||
| ... "group1": ["agent1", "agent2", "agent3"], | ||
| ... "group2": ["agent4", "agent5"], | ||
| ... }) |
There was a problem hiding this comment.
In with_agent_groups, self is passed implicitly when called on an instance of MultiAgentEnv. Passing env as the first argument explicitly will result in a TypeError or incorrect behavior as it binds env to the groups parameter.
| >>> grouped_env = env.with_agent_groups(env, { | |
| ... "group1": ["agent1", "agent2", "agent3"], | |
| ... "group2": ["agent4", "agent5"], | |
| ... }) | |
| >>> grouped_env = env.with_agent_groups({ | |
| ... "group1": ["agent1", "agent2", "agent3"], | |
| ... "group2": ["agent4", "agent5"], | |
| ... }) |
There was a problem hiding this comment.
Thanks, that's right. This PR is syntax-only on purpose, so it leaves example code unchanged. #67764, stacked on this PR, fixes this.
| >>> obs = ma_cartpole.reset() | ||
| >>> print(obs) |
There was a problem hiding this comment.
In Gymnasium and modern RLlib, reset() returns a tuple of (obs, infos). Assigning the result directly to obs and printing it will print the tuple instead of just the observations dictionary.
| >>> obs = ma_cartpole.reset() | |
| >>> print(obs) | |
| >>> obs, infos = ma_cartpole.reset() | |
| >>> print(obs) |
There was a problem hiding this comment.
Thanks, that's right. This PR is syntax-only on purpose, so it leaves example code unchanged. #67764, stacked on this PR, fixes this.
| >>> ma_stateless_cartpole = ma_stateless_cartpole_cls( | ||
| ... {"num_agents": 3}) | ||
| >>> print(obs) |
There was a problem hiding this comment.
The second print(obs) statement prints the observations from the first environment (ma_cartpole) instead of the newly created ma_stateless_cartpole environment. We should call reset() on ma_stateless_cartpole first to get and print its observations.
| >>> ma_stateless_cartpole = ma_stateless_cartpole_cls( | |
| ... {"num_agents": 3}) | |
| >>> print(obs) | |
| >>> ma_stateless_cartpole = ma_stateless_cartpole_cls( | |
| ... {"num_agents": 3}) | |
| >>> obs, infos = ma_stateless_cartpole.reset() | |
| >>> print(obs) |
There was a problem hiding this comment.
Thanks, that's right. This PR is syntax-only on purpose, so it leaves example code unchanged. #67764, stacked on this PR, fixes this.
| >>> _ = episode.get_actions(slice(None, 2)) # [1, 2] | ||
| >>> _ = episode.get_actions(slice(-2, None)) # [2, 3] | ||
| >>> # Using `fill=...` (requesting slices beyond the boundaries). | ||
| >>> _ = episode.get_actions(slice(-5, -2), fill=-9) # [-9, -9, 1, 2] |
There was a problem hiding this comment.
The slice slice(-5, -2) on a list of length 3 produces exactly 3 elements (indices -5, -4, -3). The returned list is [-9, -9, 1]. The comment incorrectly shows 4 elements [-9, -9, 1, 2].
| >>> _ = episode.get_actions(slice(-5, -2), fill=-9) # [-9, -9, 1, 2] | |
| >>> _ = episode.get_actions(slice(-5, -2), fill=-9) # [-9, -9, 1] |
There was a problem hiding this comment.
Thanks, that's right. This PR is syntax-only on purpose, so it leaves example code unchanged. #67764, stacked on this PR, fixes this. The getter examples there show their real output, so the doctest checks the values.
| >>> _ = episode.get_actions( | ||
| ... slice(0, 2), | ||
| ... one_hot_discrete=True, | ||
| ... ) # [[0 1 0 0], [0 0 0 1]] (actions=1 and 3) |
There was a problem hiding this comment.
The slice slice(0, 2) selects indices 0 and 1, which correspond to actions 1 and 2. The one-hot representation of 2 is [0, 0, 1, 0]. The comment incorrectly shows [0, 0, 0, 1] (action 3) and states actions=1 and 3.
| >>> _ = episode.get_actions( | |
| ... slice(0, 2), | |
| ... one_hot_discrete=True, | |
| ... ) # [[0 1 0 0], [0 0 0 1]] (actions=1 and 3) | |
| >>> _ = episode.get_actions( | |
| ... slice(0, 2), | |
| ... one_hot_discrete=True, | |
| ... ) # [[0 1 0 0], [0 0 1 0]] (actions=1 and 2) |
There was a problem hiding this comment.
Thanks, that's right. This PR is syntax-only on purpose, so it leaves example code unchanged. #67764, stacked on this PR, fixes this. The getter examples there show their real output, so the doctest checks the values.
| >>> _ = episode.get_rewards(slice(None, 2)) # [1.0, 2.0] | ||
| >>> _ = episode.get_rewards(slice(-2, None)) # [2.0, 3.0] | ||
| >>> # Using `fill=...` (requesting slices beyond the boundaries). | ||
| >>> _ = episode.get_rewards(slice(-5, -2), fill=0.0) # [0.0, 0.0, 1.0, 2.0] |
There was a problem hiding this comment.
The slice slice(-5, -2) on a list of length 3 produces exactly 3 elements (indices -5, -4, -3). The returned list is [0.0, 0.0, 1.0]. The comment incorrectly shows 4 elements [0.0, 0.0, 1.0, 2.0].
| >>> _ = episode.get_rewards(slice(-5, -2), fill=0.0) # [0.0, 0.0, 1.0, 2.0] | |
| >>> _ = episode.get_rewards(slice(-5, -2), fill=0.0) # [0.0, 0.0, 1.0] |
There was a problem hiding this comment.
Thanks, that's right. This PR is syntax-only on purpose, so it leaves example code unchanged. #67764, stacked on this PR, fixes this. The getter examples there show their real output, so the doctest checks the values.
| ... ) | ||
| >>> # Plain usage (`indices` arg only). | ||
| >>> _ = episode.get_extra_model_outputs("mo", -1) # 3 | ||
| >>> _ = episode.get_extra_model_outputs("mo", 1) # 0 |
There was a problem hiding this comment.
Thanks, that's right. This PR is syntax-only on purpose, so it leaves example code unchanged. #67764, stacked on this PR, fixes this. The getter examples there show their real output, so the doctest checks the values.
…7764) ## Description This is a correctness change for RLlib review. It fixes `rllib.env` docstring examples that were wrong or couldn't run. Stacked on #67763. 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. - `EnvContext.set_defaults`: `print(env_ctx)` prints the worker fields too, such as `worker=0/None`, because `EnvContext.__str__` appends them. The example now prints `dict(env_ctx)`, which gives the dict the example showed. - `make_multi_agent`: `reset()` returns `(obs, infos)`, so `print(obs)` printed a tuple. The example also never reset the three-agent env, so its second `print(obs)` reprinted the first env's observations. Both resets now unpack the tuple, and the outputs show each agent's observation array. ### Getter examples now check their values The `SingleAgentEpisode` getter examples called `get_infos`, `get_actions`, `get_rewards`, and `get_extra_model_outputs`, and each one gave its result in a comment. The calls now show their output, so the doctest checks it. Four comments were wrong: - `get_actions(slice(-5, -2), fill=-9)` returns three items, `[array(-9), array(-9), 1]`, not four. - `get_actions(slice(0, 2), one_hot_discrete=True)` returns the one-hot vectors for actions 1 and 2, not 1 and 3. - `get_rewards(slice(-5, -2), fill=0.0)` returns three items, not four. - `get_extra_model_outputs("mo", 1)` returns `2`, not `0`. In the `SingleAgentEpisode` class example, the comment expects `[0.0, 0.0, 0.0, r0]` when looking back four rewards from ts=1. But `slice(-4, 0)` with `neg_index_as_lookback=True` returns four fill values. The example now uses `slice(-3, 1)`, which returns what the comment describes, and it shows that output. In these outputs, fill values come back as 0-d NumPy arrays, such as `array(-9)`, mixed with plain Python values. The examples show what the getters return today. ### Fixed but still render-only - `MultiAgentEnv.with_agent_groups`: the example passed `env` as the first argument, but the method's first parameter is `groups`. It now passes only the groups dict. The example uses a placeholder env, so it stays render-only. `doc/source/rllib/multi-agent-envs.md` includes this method's source, so the fix shows there too. - `PettingZooEnv`: the example used `pettingzoo.butterfly.prison_v3`. That env isn't in PettingZoo 1.24.3, the version `python/requirements/ml/rllib-test-requirements.txt` pins, or in 1.27.0. The example now uses `pistonball_v6`, as the RLlib multi-agent envs page does. The outputs come from running the example with PettingZoo 1.27.0. It stays render-only, because PettingZoo isn't installed in the doctest environment. `ExternalEnv`, `MultiAgentEnv.step`, `MultiAgentEnv.reset`, and `BaseEnv` are unchanged and stay render-only. The `ExternalEnv` example still passes the deprecated `env` argument to `DQN`. ## Related issues Stacked on #67763. 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 4 changed files: "10 docstring(s) run, 0 failed, 3 skipped, in 4 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 10 runnable docstrings pass, and the rest carry `+SKIP_EXAMPLE`. - The `PettingZooEnv` example with `+SKIP_EXAMPLE` removed, in the same environment plus PettingZoo 1.27.0: all 11 examples pass. I didn't verify it end to end against the pinned 1.24.3. - `ci/ray_ci/doc/check_docstring_only.py --base doc-1926-rllib-env-doctests`: "4 file(s), docstrings only." - `pre-commit run --files` on all 4 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 inpython/ray/rllib/envdocstrings 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 23
testcodeblocks inrllib/envoutsidetests/, in 7 files:SingleAgentEpisodeclass example and itsto_numpy,get_observations,get_infos,get_actions,get_rewards,get_extra_model_outputs, andsliceexamples, plusMultiAgentEpisode.to_numpyandMultiAgentEpisode.slice. None of these ran before, because the RLlibdoctest()target doesn't executetestcode. All ten pass now.: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). They're inEnvContext.set_defaults,ExternalEnv,MultiAgentEnv.step,MultiAgentEnv.with_agent_groups,make_multi_agent, andPettingZooEnv(six blocks)... code-block:: python, and their output becomestext. They're inBaseEnvandMultiAgentEnv.reset.This is a syntax-only change. The example code and the claims in each docstring are unchanged, with two exceptions that the format forces:
episode.get_infos(-1)andepisode.to_numpy()now start with_ =. The comments that follow them are unchanged.printthat produces it. InMultiAgentEnv.stepandmake_multi_agent, onetestoutputheld the output of several prints. The output text is unchanged.doc/source/rllib/multi-agent-envs.mdincludes the wholewith_agent_groupsmethod as Python source throughliteralinclude. That page showed the.. testcode::and:skipif: Truelines before, and it shows the>>>lines and the# doctest: +SKIP_EXAMPLEcomment now.Left for a separate correctness PR
Converting the never-run examples surfaced the following errors. This PR leaves them as-is:
EnvContext.set_defaults:print(env_ctx)also prints the worker fields, not only the dict.make_multi_agent:reset()returns(obs, infos), and the secondprint(obs)reprints the first env's observations.with_agent_groups: the example passesenvas thegroupsargument.PettingZooEnv: PettingZoo no longer shipsprison_v3.SingleAgentEpisodegetter comments give the wrong value.Related issues
Related to #66749, #66753, and #67753.
Additional information
Not a duplicate. I searched open PRs for RLlib
testcodeand doctest conversions, and none touches these docstrings.Tests run
These ran in a Python 3.12 virtualenv with
ray[rllib]==2.59.0,torch, andtensorflow2.21. The wheel doesn't includeray/rllib/env/tests, whichMultiAgentEpisode.to_numpyimports, so that module was loaded from the source tree, where the Bazel target finds it.ci/ray_ci/doc/run_docstring_examples.pyon all 7 files: "10 docstring(s) run, 0 failed, 6 skipped, in 7 file(s)." All six skips are+SKIP_EXAMPLE.doctestpass withELLIPSIS. Unlike the runner above, it fails on unexpected output, the way the RLlibdoctest()target does. All 10 runnable docstrings pass.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