Repository navigation
[rllib] Add type hints and docstrings to the env wrappers - #67628
Merged
Merged
Conversation
Document the public Atari, DeepMind Control Suite, dm_env, and PettingZoo env wrappers in ray.rllib.env.wrappers, which had no class docstrings and few method docstrings. Add parameter type hints so pydoclint can check the new Args sections; Ray runs pydoclint with --arg-type-hints-in-signature. No runtime behavior changes. 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! |
_convert_spec_to_space called np.asscalar, which NumPy removed in 1.23, so converting any BoundedArray spec raised AttributeError. Broadcast the spec's minimum and maximum to its shape instead, which also handles array-valued bounds that np.asscalar rejected. Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: Douglas Strodtman <[email protected]>
pseudo-rnd-thoughts
approved these changes
Nov 3, 2026
pseudo-rnd-thoughts
enabled auto-merge (squash)
November 3, 2026 14:58
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]>
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?
The public env wrappers in
ray.rllib.env.wrappers(atari_wrappers,dm_control_wrapper,dm_env_wrapper, andpettingzoo_env) mostly have no class docstrings and few method docstrings, sohelp()and IDE tooltips show little for them. This PR documents their existing behavior, and fixes one crash indm_env_wrapper.pythat's described below.It also adds parameter type hints. Ray runs pydoclint with
--arg-type-hints-in-signature, so a docstring with anArgs:section fails the check unless every parameter has a hint. Because of that this can't be adocstring-onlyPR. Apart from the fix below, it doesn't change runtime behavior. Stripping docstrings, annotations, and imports, the AST of every changed file matchesmaster, except for that fix indm_env_wrapper.py.Fix:
DMEnvspace conversiondm_env_wrapper._convert_spec_to_spacecallednp.asscalar, which NumPy removed in 1.23, so converting anyBoundedArrayspec raisedAttributeError. That included aDictspec that contains one. The fix passesnp.broadcast_to(spec.minimum, spec.shape)and the same formaximumas theBoxbounds. Broadcasting is needed becausedm_envstores scalar bounds as 0-d arrays, whichBoxrejects against a non-empty shape. It also handles array-valued bounds, whichnp.asscalarrejected even before its removal.What changed:
atari_wrappers.py: Class docstrings withArgs:for every wrapper, folding in the text that sat in__init__docstrings. Docstrings,Args:, andReturns:on eachstep,reset,observation, andrewardoverride, onMonitorEnv's stats getters, and onget_wrapper_by_cls. Type hints use gymnasium'sActTypeandObsType.dm_control_wrapper.py: A class docstring forDMCEnvcovering all 12 constructor arguments, plus docstrings for its spaces,step,reset, andrender.dm_env_wrapper.py:Args:on theDMEnvclass docstring, plus docstrings forstep,reset, and its spaces andreward_range.pettingzoo_env.py:Args:onPettingZooEnv, a class docstring forParallelPettingZooEnv, and docstrings forPettingZooEnv.step,close, andget_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 raisesValueError("Environment not started..."), because nothing ever setsself._prev_obs. I didn't add a docstring that describes a return value it can't produce.DMEnv.reset()andDMCEnv.reset()ignoreseedandoptions. The new docstrings say so.For
render(), adm_envobservation 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 fixesMultiAgentEpisode.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.upstream/masterwith docstrings, annotations, and imports stripped: identical for all four files.pytest python/ray/rllib/env/tests/test_pettingzoo_env.pyagainst this branch'srllibon the current nightly wheel, with the test requirements'pettingzoo==1.24.3andsupersuit==3.9.3: 2 passed._convert_spec_to_spacewithdm-envinstalled, on aBoundedArraywith scalar bounds, one with array bounds, aDiscreteArray, an unboundedArray, and aDictof specs: all five convert. The original code raisesAttributeErroron three of them.FrameStack,GrayScaleAndResize,NormalizedImageEnv,ClipRewardEnv,MaxAndSkipEnv,MonitorEnv, andget_wrapper_by_clsagainst 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