Repository navigation
[rllib] Add missing docstrings, Args, and Returns to env runner, MultiAgentEnv, and episode APIs - #67626
Merged
Conversation
…iAgentEnv, and episode APIs Document existing behavior on public methods and properties of EnvRunner, MultiAgentEnv, MultiAgentEpisode, and SingleAgentEpisode that render on the RLlib API reference without a description, parameter entry, or Returns section. Also correct MultiAgentEpisode.get_terminateds's summary, which referred to indices the method doesn't take, and fix the malformed Returns section on MultiAgentEpisode.get_state. @rtd-build Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: Douglas Strodtman <[email protected]>
Contributor
|
Warning You have reached your daily quota limit. Please wait up to 24 hours and I will start processing your requests again! |
This was referenced Oct 30, 2026
Merged
Merged
pseudo-rnd-thoughts
approved these changes
Nov 3, 2026
pseudo-rnd-thoughts
pushed a commit
that referenced
this pull request
Nov 3, 2026
…odule, and connector pipeline APIs (#67629) ## Why are these changes needed? Several public methods and classes in `ray.rllib.algorithms`, `ray.rllib.core`, and `ray.rllib.connectors` have no docstring, no parameter entry, or no `Returns:` section. Most of them render on the RLlib API reference. This PR documents their existing behavior and changes only docstrings. What changed: - **`Algorithm`:** A docstring and `Returns:` for `get_default_config`. `Args:` and `Returns:` for `get_default_policy_class`. A docstring, `Args:`, and `Returns:` for `restore_offline_eval_runners`, modeled on `restore_env_runners`. A docstring and `Args:` for `load_checkpoint`. - **`Learner` and `LearnerGroup`:** Docstrings for `Learner.node` and `Learner.device`, and for `LearnerGroup.is_remote` and `is_local`. `Returns:` for `LearnerGroup.get_stats`, naming both keys. - **`RLModule`, `RLModuleSpec`, `MultiRLModule`, and `MultiRLModuleSpec`:** `Returns:` sections for `build`, `as_multi_rl_module_spec`, `as_multi_rl_module`, `is_stateful`, `to_dict`, the three `get_*_action_dist_cls` methods, and `MultiRLModule.items` and `keys`. Also a docstring, `Args:`, and `Returns:` for `RLModuleSpec.from_module`. - **Connector pipelines:** Class docstrings for `EnvToModulePipeline`, `LearnerConnectorPipeline`, and `ModuleToEnvPipeline`. Two of these correct an existing summary, so they need a closer look: - `MultiRLModule.items()` said it iterates "over the module IDs", but it yields (ModuleID, RLModule) pairs. `values()` has the same mistake in its docstring and in its `ValuesView[ModuleID]` return annotation. Fixing an annotation is a code change, so both `values()` fixes are in #67631. - `RLModule.as_multi_rl_module()` now says the returned MultiRLModule holds a newly built module rather than this instance. That's because `MultiRLModule.setup()` calls `RLModuleSpec.build()`. Rows left out on purpose: - Methods whose new `Args:` sections would need parameter type hints first. Ray's pydoclint configuration fails an `Args:` section on an unannotated signature. These are `RLlibCallback.on_workers_recreated`, `AgentToModuleMapping`, `Learner.apply`, both `from_dict` methods, and the two connector `__call__` methods with untyped `**kwargs`. They go in a separate PR without the label. - The `ConnectorV2.input_observation_space` and `input_action_space` setters. Sphinx renders a property from its getter's docstring only. ## Related issue number None. The work comes from the docs team's inventory of `@PublicAPI` symbols with missing docstrings. It follows #67626, which covers `ray.rllib.env`. I searched open PRs for RLlib docstring work and for these files and found no overlap. ## Checks - `pre-commit run --files <changed files>`: all hooks pass, including ruff, black, and pydoclint 0.9.1 with the repo's arguments. - `python ci/ray_ci/doc/check_docstring_only.py --base <merge-base>`, with both the guard from this PR's base and the guard as of #67599: `docstring-only guard: 8 file(s), docstrings only.` - No `>>>` examples were added or changed. The commit carries an `@rtd-build` line so Read the Docs builds a preview. AI assistance (Claude Code) was used to draft these docstrings. I reviewed every changed line against the code. 🤖 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]>
pseudo-rnd-thoughts
pushed a commit
that referenced
this pull request
Nov 3, 2026
…atch, and utils APIs (#67630) ## Why are these changes needed? Several public methods and classes in `ray.rllib.offline`, `ray.rllib.policy.sample_batch`, and `ray.rllib.utils` have no docstring, no parameter entry, or no `Returns:` section. This PR documents their existing behavior and changes only docstrings. What changed: - **Offline:** - A class docstring with `Args:` for `OfflineData`, plus docstrings for `OfflineData.sample` and its two `default_*_batches_kwargs` properties. - `Args:` and `Returns:` for `OfflineSingleAgentEnvRunner.sample`, including when it writes its buffer. - `Args:` on the `OfflinePreLearner` class docstring. - A docstring for `get_offline_io_resource_bundles`. - Docstrings for `IOContext.input_config` and `output_config`. - **`SampleBatch` and `MultiAgentBatch`:** - `Returns:` for `agent_steps` and `env_steps`. - A docstring for `is_training` and `Args:` for `set_training`. - `Args:` and `Returns:` for `MultiAgentBatch.timeslices`. - **Utils:** - `Returns:` for `MetricsLogger.get_state`. - `Args:` and `Returns:` for `huber_loss` and for the torch and TensorFlow versions of `symlog` and `inverse_symlog`. - Docstrings for `sample()` on `FlexDict`, `Repeated`, and `Simplex`. `OfflineData.sample` and `OfflineSingleAgentEnvRunner.sample` have the most new content and need the closest read. `Repeated.sample()` is documented as returning 1 to `max_len` items, which is what it does. The `Repeated` class docstring's example still says "from 0 to 10 boxes", because `contains()` does accept an empty list. Rows left out on purpose: - Methods whose new `Args:` sections would need parameter type hints first. Ray's pydoclint configuration fails an `Args:` section on an unannotated signature. These are `MetricsLogger.log_dict`, `one_hot_multidiscrete`, `FlexDict.assertSpace`, `Repeated.contains`, `Simplex` and its `contains`, `to_jsonable`, and `from_jsonable`, and `SampleBatch.get`. They go in a separate PR without the label. - `SampleBatch.concat_samples` and `MultiAgentBatch.concat_samples`, which are `@Deprecated(error=True)` stubs. ## Related issue number None. The work comes from the docs team's inventory of `@PublicAPI` symbols with missing docstrings. It follows #67626, and its companion for `algorithms`, `core`, and `connectors` is #67629. I searched open PRs for RLlib docstring work and for these files and found no overlap. ## Checks - `pre-commit run --files <changed files>`: all hooks pass, including ruff, black, and pydoclint 0.9.1 with the repo's arguments. - `python ci/ray_ci/doc/check_docstring_only.py --base <merge-base>`, with both the guard from this PR's base and the guard as of #67599: `docstring-only guard: 13 file(s), docstrings only.` - No `>>>` examples were added or changed. The commit carries an `@rtd-build` line so Read the Docs builds a preview. AI assistance (Claude Code) was used to draft these docstrings. I reviewed every changed line against the code. 🤖 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]>
pseudo-rnd-thoughts
pushed a commit
that referenced
this pull request
Nov 3, 2026
## Why are these changes needed?
The public env wrappers in `ray.rllib.env.wrappers` (`atari_wrappers`,
`dm_control_wrapper`, `dm_env_wrapper`, and `pettingzoo_env`) mostly
have no class docstrings and few method docstrings, so `help()` and IDE
tooltips show little for them. This PR documents their existing
behavior, and fixes one crash in `dm_env_wrapper.py` that's described
below.
It also adds parameter type hints. Ray runs pydoclint with
`--arg-type-hints-in-signature`, so a docstring with an `Args:` section
fails the check unless every parameter has a hint. Because of that this
can't be a `docstring-only` PR. Apart from the fix below, it doesn't
change runtime behavior. Stripping docstrings, annotations, and imports,
the AST of every changed file matches `master`, except for that fix in
`dm_env_wrapper.py`.
### Fix: `DMEnv` space conversion
`dm_env_wrapper._convert_spec_to_space` called `np.asscalar`, which
NumPy removed in 1.23, so converting any `BoundedArray` spec raised
`AttributeError`. That included a `Dict` spec that contains one. The fix
passes `np.broadcast_to(spec.minimum, spec.shape)` and the same for
`maximum` as the `Box` bounds. Broadcasting is needed because `dm_env`
stores scalar bounds as 0-d arrays, which `Box` rejects against a
non-empty shape. It also handles array-valued bounds, which
`np.asscalar` rejected even before its removal.
What changed:
- **`atari_wrappers.py`:** Class docstrings with `Args:` for every
wrapper, folding in the text that sat in `__init__` docstrings.
Docstrings, `Args:`, and `Returns:` on each `step`, `reset`,
`observation`, and `reward` override, on `MonitorEnv`'s stats getters,
and on `get_wrapper_by_cls`. Type hints use gymnasium's `ActType` and
`ObsType`.
- **`dm_control_wrapper.py`:** A class docstring for `DMCEnv` covering
all 12 constructor arguments, plus docstrings for its spaces, `step`,
`reset`, and `render`.
- **`dm_env_wrapper.py`:** `Args:` on the `DMEnv` class docstring, plus
docstrings for `step`, `reset`, and its spaces and `reward_range`.
- **`pettingzoo_env.py`:** `Args:` on `PettingZooEnv`, a class docstring
for `ParallelPettingZooEnv`, and docstrings for `PettingZooEnv.step`,
`close`, and `get_sub_environments`.
None of these wrappers has a page on docs.ray.io, so the docstrings show
up in `help()` and in IDEs.
### Issues found, not changed here
These look like bugs too, but the right fix depends on intent, so I left
them alone:
- `DMEnv.render()` always raises `ValueError("Environment not
started...")`, because nothing ever sets `self._prev_obs`. I didn't add
a docstring that describes a return value it can't produce.
- `DMEnv.reset()` and `DMCEnv.reset()` ignore `seed` and `options`. The
new docstrings say so.
For `render()`, a `dm_env` observation is often a dict of state arrays
rather than an RGB frame, so whether it should return the observation,
read from physics, or go away is the owners' call.
## Related issue number
None. This continues #67626, which documents the rest of
`ray.rllib.env`, and is separate from #67627, which fixes
`MultiAgentEpisode.get_truncateds`. I searched open PRs for these files
and for RLlib docstring work and found no overlap.
## Checks
- `pre-commit run --files <changed files>`: all hooks pass, including
pydoclint 0.9.1 with the repo's arguments.
- AST comparison against `upstream/master` with docstrings, annotations,
and imports stripped: identical for all four files.
- `pytest python/ray/rllib/env/tests/test_pettingzoo_env.py` against
this branch's `rllib` on the current nightly wheel, with the test
requirements' `pettingzoo==1.24.3` and `supersuit==3.9.3`: 2 passed.
- `_convert_spec_to_space` with `dm-env` installed, on a `BoundedArray`
with scalar bounds, one with array bounds, a `DiscreteArray`, an
unbounded `Array`, and a `Dict` of specs: all five convert. The original
code raises `AttributeError` on three of them.
- All four modules import cleanly. A smoke test on a fake image env
checked `FrameStack`, `GrayScaleAndResize`, `NormalizedImageEnv`,
`ClipRewardEnv`, `MaxAndSkipEnv`, `MonitorEnv`, and `get_wrapper_by_cls`
against the shapes and values the new docstrings state. The
Atari-specific wrappers need ROMs and weren't run.
AI assistance (Claude Code) was used to draft the docstrings, type
hints, and fix. I reviewed every changed line.
🤖 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]>
dstrodtman
added a commit
that referenced
this pull request
Nov 3, 2026
…#67631) ## Why are these changes needed? These public RLlib methods and classes had no docstring, or no `Args:` or `Returns:` section, and their signatures had no type hints. Ray runs pydoclint with `--arg-type-hints-in-signature`, which fails an `Args:` section on an unannotated signature. So documenting them means adding parameter hints too, and they can't go in a `docstring-only` PR the way #67629 and #67630 do. This PR adds both. It's the companion to those two. What changed: - **`RLlibCallback.on_workers_recreated`:** Type hints and a docstring. It marks the hook as deprecated in favor of `on_env_runners_recreated()`, as the existing source comment says, and notes that `Algorithm` still calls it. - **`AgentToModuleMapping`:** A hint for `agent_to_module_mapping_fn`, using the existing `AgentToModuleMappingFn` alias, and `Args:` for all constructor arguments, including what `as_learner_connector` changes. - **`ConnectorPipelineV2.__call__` and `NormalizeAndClipActions.__call__`:** `**kwargs: Any`, plus `Args:` and `Returns:` sections. - **`Learner.apply`:** Hints and a docstring. - **`RLModuleSpec.from_dict` and `MultiRLModuleSpec.from_dict`:** `d: Dict[str, Any]`, plus `Args:` and `Returns:` sections. - **`MetricsLogger.log_dict`:** `value_dict: Dict[str, Any]` and an `Args:` section. - **`one_hot_multidiscrete`:** Hints and a docstring. - **`FlexDict.assertSpace`, `Repeated.contains`, `Simplex`, and `Simplex.contains`, `to_jsonable`, and `from_jsonable`:** Hints and docstrings. - **`SampleBatch.get`:** Hints and `Args:` and `Returns:` sections. Apart from the `one_hot_multidiscrete` and `AgentToModuleMapping` fixes below, nothing changes at runtime. Stripping docstrings, annotations, and imports, the AST of every changed file except `utils/numpy.py` matches the base commit. ### Three fixes to existing mistakes - `one_hot_multidiscrete(x, depths=List[int])` made the `typing.List[int]` object the *default* value of `depths` instead of its annotation. This PR makes it `depths: List[int]`. A call that left out `depths` already raised `TypeError` when the function iterated the default, so this only changes the error such a call gets. - `MultiRLModule.values()` returns `self._rl_modules.values()`, a view of RLModules, but it was annotated `ValuesView[ModuleID]` and its summary said it iterates over module IDs. This PR corrects both. The docstring fix moved here from #67629, so the two PRs don't edit adjacent lines. - The `AgentToModuleMapping` docstring example returned `{}` instead of the output its `check()` expects. Without `as_learner_connector=True`, the connector keeps only the agents that act next in `episodes`, and the example passes `episodes=[]`. The example now passes `as_learner_connector=True` and runs as written. ## Related issue number None. The work comes from the docs team's inventory of `@PublicAPI` symbols with missing docstrings, and it completes the RLlib list with #67626, #67628, #67629, and #67630. I searched open PRs for these files and for RLlib docstring work and found no overlap. ## Checks - `pre-commit run --files <changed files>`: all hooks pass, including ruff, black, and pydoclint 0.9.1 with the repo's arguments. - `pytest` against this branch's `rllib` on the current nightly wheel, covering `test_metrics_logger.py`, `test_serialization.py`, `test_sample_batch.py`, `test_multi_agent_batch.py`, and `test_multi_agent_env_runner.py`: 63 passed and 2 failed. The failures are `TestSampleBatch::test_count` and `test_interceptors`, and they fail the same way without this PR's changes. They look like a mismatch with the NumPy 2.5 in my local environment. - A smoke test of every changed symbol: `one_hot_multidiscrete` with numpy and torch inputs, `Simplex` sample, contains, and the JSON round trip, `Repeated.contains`, `FlexDict.sample`, `SampleBatch.get`, `MetricsLogger.log_dict` with a key prefix, `Learner.apply`, and `on_workers_recreated`. - The fixed `AgentToModuleMapping` docstring example, run as written: passes. AI assistance (Claude Code) was used to draft the docstrings and type hints. I reviewed every changed line. 🤖 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]>
pseudo-rnd-thoughts
added a commit
that referenced
this pull request
Nov 6, 2026
… flag for "__all__" (#67627) ## Why are these changes needed? `MultiAgentEpisode.get_truncateds()` builds its `"__all__"` entry from `self.is_terminated` instead of `self.is_truncated`: ```python truncateds.update({"__all__": self.is_terminated}) ``` So an episode that's terminated but not truncated reports `get_truncateds()["__all__"] == True`. `get_terminateds()`, two methods up, reads `self.is_terminated` as expected, and this looks like a copy of it that missed one name. This PR: - Reads `self.is_truncated` for `"__all__"` in `get_truncateds()`. - Adds a docstring with a `Returns:` section, matching the one on `get_terminateds()`. The method had none. - Adds `test_get_terminateds_and_truncateds` to `test_multi_agent_episode.py`. The only caller in RLlib is `MultiAgentEpisode.cut()`, which passes `get_truncateds()` to the successor episode's constructor. With the old code, cutting a terminated episode produced a successor with `is_truncated=True`. ### A related question for RLlib, not changed here When every agent is done after an `add_env_step()` call, the "Case 2" block in `add_env_step()` sets `self.is_terminated = True` even if all agents were truncated rather than terminated. A fully truncated episode therefore reports both `is_terminated` and `is_truncated` as `True`. The comment above the block describes a mix of truncated and terminated agents, so this might be intended or might be broader than intended. This PR leaves it alone, and the new test doesn't assert `get_terminateds()` for the truncated case because of it. ## Related issue number None. I found this while adding docstrings to `ray.rllib.env` in #67626, which leaves `get_truncateds` out so that its docstring doesn't describe the bug. I searched open PRs for `get_truncateds` and `multi_agent_episode` and found no overlap. ## Checks - `pytest --noconftest python/ray/rllib/env/tests/test_multi_agent_episode.py` against the branch's `rllib` on top of the current nightly wheel: 19 passed. - The same new test against the original line: fails, as expected. - `pre-commit run --files <changed files>`: all hooks pass. AI assistance (Claude Code) was used to find the bug and draft the fix and test. I reviewed every changed line. 🤖 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]> Co-authored-by: Mark Towers <[email protected]>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Why are these changes needed?
Several public methods and properties of
EnvRunner,MultiAgentEnv,MultiAgentEpisode, andSingleAgentEpisoderender on the RLlib API reference with no description, no parameter entry, or noReturns:section. This PR documents their existing behavior. It changes only docstrings.What changed, all under
python/ray/rllib/env/:EnvRunner.get_spaces: adds aReturns:section, including the"__env__"and"__env_single__"entries that both built-in env runners add.MultiAgentEnv.get_observation_spaceandget_action_space: adds a docstring,Args:, andReturns:, including the old API stack fallback toobservation_spaceandaction_space.MultiAgentEnv.num_agentsandmax_num_agents: adds a docstring.MultiAgentEpisodeandSingleAgentEpisode: adds docstrings tocustom_data,observation_space, andaction_space, and aReturns:section toget_duration_s.MultiAgentEpisode.get_terminateds: replaces a summary that referred to indices the method doesn't take, and addsReturns:.MultiAgentEpisode.get_state: fixes a malformedReturns:section that put its text on the heading line, so the section didn't parse.These are new descriptions of behavior, not formatting fixes, so they need a read from someone who knows the code. Each one comes from the method body and its callers at the current
master.MultiAgentEpisode.get_truncatedsis left out on purpose. It sets"__all__"fromself.is_terminatedrather thanself.is_truncated, which looks like a bug, so it gets its own PR rather than a docstring that describes it.The property setters for
observation_spaceandaction_spacestay undocumented. Sphinx renders a property from its getter's docstring only.Related issue number
None. The work comes from the docs team's inventory of
@PublicAPIsymbols with missing docstrings. I searched open PRs for RLlib docstring work and for these files and found no overlap.Checks
pre-commit run --files <changed files>: all hooks pass, including ruff, black, and pydoclint 0.9.1 with the repo's arguments.python ci/ray_ci/doc/check_docstring_only.py --base upstream/master:docstring-only guard: 4 file(s), docstrings only.>>>examples were added or changed.This PR carries the
docstring-onlylabel, and the commit has an@rtd-buildline so Read the Docs builds a preview.AI assistance (Claude Code) was used to draft these docstrings. I reviewed every changed line against the code.
🤖 Generated with Claude Code