Repository navigation
[RLlib] Convert rllib.connectors docstring examples to stock doctests - #67758
Conversation
Convert the `.. testcode::` examples in `rllib/connectors` docstrings to `>>>` examples under an `Examples:` header, so they render in griffe and MkDocs as well as Sphinx, and the RLlib doctest target runs them. The example code and docstring claims are unchanged. A block that doesn't parse becomes a `.. 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 converts Sphinx .. testcode:: blocks into standard Python doctest examples across various RLlib connector files to improve documentation and testability. The review feedback points out critical bugs in the FrameSkippingAgentConnector example class within connector.py, specifically the use of an undefined default_dict name and incorrect attribute access on ac_data instead of the loop variable d.
| >>> class FrameSkippingAgentConnector(AgentConnector): | ||
| ... def __init__(self, n): | ||
| ... self._n = n | ||
| ... self._frame_count = default_dict(str, default_dict(str, int)) | ||
| ... | ||
| ... def reset(self, env_id: str): | ||
| ... del self._frame_count[env_id] | ||
| ... | ||
| ... def __call__( | ||
| ... self, ac_data: List[AgentConnectorDataType] | ||
| ... ) -> List[AgentConnectorDataType]: | ||
| ... ret = [] | ||
| ... for d in ac_data: | ||
| ... assert d.env_id and d.agent_id, "Skipping works per agent!" | ||
| ... | ||
| ... count = self._frame_count[ac_data.env_id][ac_data.agent_id] | ||
| ... self._frame_count[ac_data.env_id][ac_data.agent_id] = ( | ||
| ... count + 1 | ||
| ... ) | ||
| ... | ||
| ... if count % self._n == 0: | ||
| ... ret.append(d) | ||
| ... return ret |
There was a problem hiding this comment.
There are a couple of bugs in this example class definition that will cause it to fail if executed:
default_dictis not a standard Python class and is likely a typo forcollections.defaultdict. Furthermore, the nested initializationdefault_dict(str, default_dict(str, int))is invalid fordefaultdict. It should be initialized using a lambda:defaultdict(lambda: defaultdict(int)).- Inside
__call__,ac_datais a list ofAgentConnectorDataTypeobjects, so it does not haveenv_idoragent_idattributes. The code should reference the loop variabledinstead ofac_data(i.e.,d.env_idandd.agent_id).
Since this example is only defined but never instantiated or called in the doctest, these errors were not caught by the doctest runner.
>>> from collections import defaultdict
>>> class FrameSkippingAgentConnector(AgentConnector):
... def __init__(self, n):
... self._n = n
... self._frame_count = defaultdict(lambda: defaultdict(int))
...
... def reset(self, env_id: str):
... del self._frame_count[env_id]
...
... def __call__(
... self, ac_data: List[AgentConnectorDataType]
... ) -> List[AgentConnectorDataType]:
... ret = []
... for d in ac_data:
... assert d.env_id and d.agent_id, "Skipping works per agent!"
...
... count = self._frame_count[d.env_id][d.agent_id]
... self._frame_count[d.env_id][d.agent_id] = (
... count + 1
... )
...
... if count % self._n == 0:
... ret.append(d)
... return retThere was a problem hiding this comment.
Thanks, that's right. This PR is syntax-only on purpose, so it leaves example code unchanged. #67759, stacked on this PR, fixes this.
…run (#67759) ## Description This is a correctness change for RLlib review. It fixes `rllib.connectors` docstring examples that were wrong, and it converts the last two `testcode` blocks in `rllib/connectors`. Those blocks needed an expected-output change, so they stayed out of the syntax-only conversion in #67758. After this PR, no `testcode` or `testoutput` remains in `rllib/connectors`. Stacked on #67758. Review that PR first. This diff is against its branch. ### `testcode` blocks this PR converts - `AddObservationsFromEpisodesToBatch` and `AddNextObservationsFromEpisodesToTrainBatch`: each example prints observations drawn from `obs_space.sample()` and shows no expected output. Each print now shows its output, with `...` in place of the random values, such as `1st Episode's last obs is [...]`. The next-observations example shows that `get_observations([1, 2])` returns a list of float32 arrays. Both now run. ### Examples that were wrong - `AgentConnector`: the `FrameSkippingAgentConnector` sketch called `default_dict`, which doesn't exist. It also indexed the frame count with `ac_data.env_id`, but `ac_data` is the input list, not an item. It now uses `collections.defaultdict`, and it indexes with `d.env_id` and `d.agent_id`. With the fix, the class emits an item on every `n`th call, and `reset()` clears the count. The doctest defines the class but doesn't call it. This also fixes the "prosessed" typo in the prose that follows. - `ActionConnector`: the example called `np.zeros_like` without importing NumPy. It now imports it. - `AddColumnsFromEpisodesToTrainBatch`: the config snippet ended with a stray backtick. It also called `config.training(learner_connector=...)`, which is deprecated in favor of `config.learners(learner_connector=...)`, so it now calls `learners()`. It stays a render-only `python` code block, because it sits mid-prose and uses the reader's own `config`. - `AddTimeDimToBatchAndZeroPad`: a comment said the learner connector uses a sequence length of 4. The dummy module sets `max_seq_len` to 3, and the checked output is chunked by 3, so the comment now says 3. ### Review fixes - `AgentConnector`: the `FrameSkippingAgentConnector.reset` sketch used `del self._frame_count[env_id]`, which raises `KeyError` for an env that hasn't stepped yet. It now uses `pop(env_id, None)`. From a gemini-code-assist comment. ## Related issues Stacked on #67758. 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 5 changed files: "5 docstring(s) run, 0 failed, 0 skipped, in 5 file(s)." - A strict stdlib `doctest` pass over the same docstrings with `ELLIPSIS`, which fails on unexpected output the way the RLlib `doctest()` target does: all 5 pass. - `ci/ray_ci/doc/check_docstring_only.py --base doc-1926-rllib-connectors-doctests`: "5 file(s), docstrings only." - `pre-commit run --files` on all 5 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/connectorsdocstrings 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 17 of the 19
testcodeblocks inrllib/connectors, in 10 files:connector_v2.py, four are inconnector.py, and seven connector pieces undercommon/,learner/, andenv_to_module/have one each. None of these ran before, because the RLlibdoctest()target doesn't executetestcode. All 16 pass now... code-block:: python. The:skipif: Trueexample inAddColumnsFromEpisodesToTrainBatchends with a stray backtick.This is a syntax-only change. The example code and the claims in each docstring are unchanged, except for one change the format forces. In
AgentConnectorandActionConnector, theExample:header becomesExamples:. InActionConnector, the example now sits indented under that header.Left for a separate correctness PR
AddObservationsFromEpisodesToBatchandAddNextObservationsFromEpisodesToTrainBatchprint observations drawn fromobs_space.sample()and show no expected output. A doctest fails on that output, so these two need an expected-output change. They'll go to RLlib review as a correctness change.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
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: "14 docstring(s) run, 0 failed, 0 skipped, in 10 file(s)." The 16 blocks sit in 14 docstrings.doctestpass over the same docstrings withELLIPSIS. Unlike the runner above, it fails on unexpected output, the way the RLlibdoctest()target does. All 14 docstrings pass.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