Skip to content

[ci] Skip RLlib docstring examples that reach torch or TensorFlow stand-ins, and move the docstring image to Python 3.11 - #67822

Open
dstrodtman wants to merge 4 commits into
djs-261109-regen-ray-llm-locksfrom
doc-1926-runner-rllib-stubs
Open

dstrodtman wants to merge 4 commits into
djs-261109-regen-ray-llm-locksfrom
doc-1926-runner-rllib-stubs

Conversation

@dstrodtman

@dstrodtman dstrodtman commented Nov 4, 2026 •

Copy link
Copy Markdown
Contributor

Note

Stacked on #67979, which regenerates two ray-llm locks that went stale on master after #67789. Without it, this PR's raydepsets: compile all dependencies job fails on files it doesn't touch. Merge #67979 first.

Why are these changes needed?

The docstring-only label runs the changed modules' >>> examples in the docstringbuild image, which leaves out torch and TensorFlow. The runner reports an example that fails only because one of those is missing as skipped. It recognizes that case from an ImportError.

RLlib doesn't raise one. try_import_torch and try_import_tf in ray/rllib/utils/framework.py return None for the module and stand-in objects such as _TFStub and _NNStub for its submodules. An RLlib example that needs torch then fails later with an AttributeError, and the runner counts it as failed. #67765 and #67766, which convert and fix rllib.core docstring examples, both fail this way (build 76124, build 76135), with errors such as:

AttributeError: 'NoneType' object has no attribute 'device'   # torch.device("cpu") in get_device
AttributeError: '_TFStub' object has no attribute 'nn'        # tf.nn in get_activation_fn
AttributeError: '_NNStub' object has no attribute 'ReLU'      # nn.ReLU in get_activation_fn

The same examples pass with torch and TensorFlow installed.

This PR makes two changes. The image move is one commit, and the runner change is the other three.

The runner treats RLlib's stand-ins as a missing library. missing_library now also follows an AttributeError in the exception chain. It maps the error to the missing library in these cases, and only when that library isn't installed:

  • The lookup failed on an instance or class of one of RLlib's stand-ins. The runner finds the stand-in classes by walking the objects try_import_torch and try_import_tf return, so it doesn't hard-code RLlib's private class names, and a renamed or new stand-in needs no change here.
  • The lookup failed on None, in a frame from an RLlib module or an RLlib docstring example, and a dotted name on the line that raised resolves to that None in the frame. Either the name is one RLlib binds a missing library to (torch, tf, tf1, tfv, tfp, jax, flax, their underscore aliases, and F for nn.functional), or it's an attribute of a stand-in that's None, such as nn.functional.

The line check tokenizes the line, so comments, strings, and chains such as self.torch.device don't match, and an unrelated bug on None still fails, even in a function that also mentions torch. tensorflow_probability, which try_import_tfp imports, joins the libraries the image omits. To read an example's lines, run_docstring now registers each example's source with linecache. That also fixes the tracebacks the step prints, which showed the module file's lines, such as import abc, instead of the example's.

The docstringbuild image moves to Python 3.11. Python 3.10 reached end of life in October 2026. The image, its two lockfiles, and the doc: docstring examples step now use 3.11, as the docs build already does. Regenerating the locks for 3.11 drops three backports that only 3.10 needs (async-timeout, exceptiongroup, and tomli) and moves scipy from 1.15.3 to 1.17.1. Every other pin is unchanged. The docstring_examples_*.lock rule in .buildkite/test.rules.txt already matches the new lockfile names, and test.rules.test.txt now names them.

Testing

The docstringbuild image builds only on a PR with the docstring-only label, and this PR can't carry it because it changes code. So this PR's premerge doesn't build the 3.11 image or run the new runner. #67976, stacked on this PR, carries the label and exercises both.

Duplicate check

No open PR changes run_docstring_examples.py, the docstringbuild image, or its locks. #67722 stops publishing Python 3.10 wheels and images, and leaves CI images alone.

AI assistance

I wrote this change with Claude Code (Opus 5.5). I reviewed every changed line, and I ran the tests and checks listed above.

🤖 Generated with Claude Code

@dstrodtman
dstrodtman requested review from a team as code owners November 4, 2026 16:49
@dstrodtman dstrodtman added the go add ONLY when ready to merge, run all tests label Nov 4, 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 upgrades the docstring build and testing environment from Python 3.10 to Python 3.11, updating Buildkite configurations, Dockerfiles, and dependency lock files (including upgrading scipy to 1.17.1). It also enhances the docstring example runner to correctly identify missing libraries (such as PyTorch or TensorFlow) when RLlib's stubbed imports raise an AttributeError instead of an ImportError. The review feedback suggests a simplification to the namespace lookup logic when detecting these stubbed libraries.

Comment thread ci/ray_ci/doc/run_docstring_examples.py Outdated
Comment on lines +171 to +174
if name in code.co_varnames:
value = frame.f_locals.get(name, ...)
else:
value = frame.f_globals.get(name, ...)

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

We can simplify the lookup of name in the frame's namespaces. Checking code.co_varnames is unnecessary because if name is a local variable that shadows a global, it must already be bound for an AttributeError to have been raised (otherwise an UnboundLocalError would have occurred). Furthermore, using frame.f_locals.get(name, frame.f_globals.get(name, ...)) correctly handles free and cell variables (which are present in f_locals but not in co_varnames).

        value = frame.f_locals.get(name, frame.f_globals.get(name, ...))

@ray-gardener ray-gardener Bot added docs An issue or change related to documentation devprod labels Nov 4, 2026
pseudo-rnd-thoughts pushed a commit that referenced this pull request Nov 4, 2026
> [!NOTE]
> Stacked on #67822, which fixes the `docstring-only` runner failures
this PR hit on `rllib.core` examples that need torch. Merge #67822
first. GitHub then retargets this PR to `master`.

## Description

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

This PR covers all 29 `testcode` blocks in `rllib/core`, in 10 files:

- **20 runnable blocks become runnable doctests, in 13 docstrings.**
They're in `distribution.py` (2), `models/base.py` (2),
`models/catalog.py`, `models/torch/base.py`, `models/configs.py` (7),
`default_model_config.py` (2), `rl_module.py` (3), and `learner.py` (2).
None of these ran before, because the RLlib `doctest()` target doesn't
execute `testcode`. All of them pass now.
- **6 never-run blocks stay never-run.** These were `:skipif: True`.
Each now sits in a docstring that carries the `# doctest: +SKIP_EXAMPLE`
flag (#66753). They're in `TorchCategorical`, `TorchDiagGaussian` (2),
`TorchDeterministic`, and `FreeLogStdMLPHeadConfig` (2).
- **3 blocks that don't parse as Python become `.. code-block::
python`.** The two `CNNTransposeHeadConfig` examples have an
unterminated string, `framework="torch)`. The
`InferenceOnlyAPI.get_non_inference_attributes` example is pseudocode
(`[some NN component]`).

This is a syntax-only change. The example code and the claims in each
docstring are unchanged, apart from these format-forced edits:

- **Two calls discard their result.** In `Learner`,
`learner.add_module(...)` and `learner.remove_module(...)` return a
`MultiRLModuleSpec`, which a doctest would echo. They're now assigned to
`_`.
- **Section headers change.** The `Example:` headers in
`models/configs.py` merge into one `Examples:` section per docstring. In
`Catalog`, `Usage example:` becomes `Examples:`, and the stray line `#
Define a custom catalog` becomes a code comment in the example. As plain
docstring text, that line would render as a Markdown heading.
- **Intro prose moves into the `Examples:` section.** Lines such as
"Example for training:" in `RLModule`, the "Note: We use PPO..."
paragraph in `Learner`, and the second paragraph of `DefaultModelConfig`
are unchanged, but they're now indented under `Examples:`.
- **`Model` gains an `Args` entry.** An `Examples:` section makes
pydoclint check the class docstring against `__init__`, and the RLlib
baseline is empty. The entry says `config` is the model config, which
the model stores as `self.config`. That's what `Model.__init__` does.

### Left for a separate correctness PR

Some converted examples run but are wrong, and some never-run examples
fail when run. They'll go to RLlib review as a correctness change. For
example, `MLPHeadConfig` and `MLPEncoderConfig` build with
`framework="tf2"`, which returns `None`. The `RLModule` inference loop
never runs. The `Learner` example's `model` settings are ignored.
`TorchDiagGaussian` is called without its required `scale` argument.

## Related issues

Related to #66749, #66753, and #67753.

## Additional information

**Not a duplicate.** I searched open PRs for RLlib `testcode` and
doctest conversions, 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: "13 docstring(s) run, 0 failed, 4 skipped, in 10 file(s)." All
four skips are `+SKIP_EXAMPLE`.
- 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 13 runnable docstrings pass.
- `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](https://claude.com/claude-code)

Signed-off-by: Douglas Strodtman <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
@pseudo-rnd-thoughts
pseudo-rnd-thoughts requested a review from a team as a code owner November 4, 2026 22:49

@cursor cursor Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Cursor Bugbot has reviewed your changes and found 2 potential issues.

Fix All in Cursor

❌ Bugbot Autofix is OFF. To automatically fix reported issues with cloud agents, have a team admin enable autofix in the Cursor dashboard.

Reviewed by Cursor Bugbot for commit 5a1dfb3. Configure here.

Comment thread python/ray/rllib/core/models/catalog.py Resolved
@pseudo-rnd-thoughts

Copy link
Copy Markdown
Member

Why are we updating to Python 3.11 here and nowhere else?

@dstrodtman

Copy link
Copy Markdown
Contributor Author

Per Claude review, @elliot-barn has a PR open to change the default/base Python for testing from 3.10 to 3.11 (3.10 is EOS), but some of the doc images don't pick up that default because they're built through a different stack.

@pseudo-rnd-thoughts

Copy link
Copy Markdown
Member

You'll need to compile the requirements on a linux machine rather than our macs

@dstrodtman

Copy link
Copy Markdown
Contributor Author

The docstring locks are built with --python-platform=linux, so the host doesn't change the result. Premerge's raydepsets job rebuilt them on Linux and they matched (build 76288). That job failed on the two ray-llm-base_extra_testdeps locks, which went stale on master after #67789 and which #67846 regenerates. I'll rebase once that lands.

@elliot-barn elliot-barn left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for this! The stub detection approach makes sense. A couple of things below, plus one scope question:

#67765 targeted this PR's branch (doc-1926-runner-rllib-stubs) and was merged into it on 11-04, so this [ci] PR now also carries its rllib.core docstring rewrite (10 RLlib files, roughly 900 lines). The description still says #67765 "exercises both once it's rebased onto this branch". Could you either update the title/description so RLlib owners know they're approving those changes too, or drop them from this branch and land #67765 separately against master after this one? Otherwise reverting this PR would also revert #67765.

Comment thread ci/ray_ci/doc/run_docstring_examples.py Outdated
code = frame.f_code
line = linecache.getline(code.co_filename, tb.tb_lineno)
for name, library in _RLLIB_NONE_NAMES.items():
if not re.search(rf"\b{name}\.{re.escape(error.name)}\b", line):

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nn.functional.<fn> slips through here. _NNStub.__init__ sets self.functional = None, so nn.functional.softplus(...) raises AttributeError: 'NoneType' object has no attribute 'softplus':

  • error.obj is None, so the stub branch above doesn't fire.
  • The regex looks for torch.softplus / tf.softplus / tf1.softplus, which isn't on a line that says nn.functional.softplus (or F.softplus after F = nn.functional).

So an RLlib example that reaches e.g. TorchSquashedGaussian.logp without torch is reported as FAILED rather than skipped. There are ~33 nn.functional. uses in rllib.

Separately, \b{name}\.{attr}\b also matches attribute chains like self.torch.device and text in comments/strings on the same line, so a genuine None bug on such a line could be reported as "skipped for torch".

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.

Fixed in e05edba. The runner now tokenizes the failing line and resolves each dotted name that ends in the failing attribute in the frame. A chain rooted at a stand-in whose attribute is None, such as nn.functional.softplus, maps to the stand-in's library, and F (RLlib's alias for nn.functional) is a known None name. Because it's token-based now, comments and strings don't count, and self.torch.device or f().torch.device don't match, since the chain has to start at a bare name. Tests cover each of these.

Comment thread ci/ray_ci/doc/run_docstring_examples.py Outdated
_RLLIB_FRAMEWORK = "ray.rllib.utils.framework"
# The names RLlib's examples and modules bind the missing library's module to,
# which try_import_torch and try_import_tf set to None.
_RLLIB_NONE_NAMES = {"torch": "torch", "tf": "tensorflow", "tf1": "tensorflow"}

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

A couple of gaps in this map:

  • try_import_tfp returns None (bound as tfp), and try_import_jax returns None, None (jax, flax). Both tensorflow and jax are in OMITTED_LIBRARIES, so an example touching tfp.distributions or jax.numpy would fail instead of skip.
  • The tf entry can't match: try_import_tf returns (None, _TFStub(), None), so tf is the stub, not None, and the obj branch already covers it. tfv is the third value that's None.

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.

Added in e05edba: tfp maps to tensorflow_probability, which joins OMITTED_LIBRARIES, and jax and flax map to jax, since try_import_jax returns None, None unless both import. tfv and the _torch, _tf1, and _tfv aliases are in too. I kept tf, because tf, _, _ = try_import_tf() in one RLlib module binds tf to the first value, which is None. A comment on the map says so.

Comment thread ci/ray_ci/doc/run_docstring_examples.py Outdated
# ray/rllib/utils/framework.py for its submodules, so an example fails later
# with an AttributeError instead of an ImportError. These are the stand-ins'
# class names, mapped to the library each one replaces.
_RLLIB_STUBS = {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Optional, more of a design thought: hard-coding RLlib's private stub class names here means a new or renamed stub in framework.py (or another None attribute like _NNStub.functional) silently breaks skip detection, with nothing keeping the two lists in sync.

An alternative would be to have the stubs themselves raise ModuleNotFoundError(name="torch") / name="tensorflow" from a __getattr__, so the existing ImportError path in missing_library handles them, with no traceback/regex inspection needed. It would be a small RLlib-side change, but it would make the runner logic much simpler. Happy either way if you'd rather keep RLlib untouched.

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.

Took the spirit of this without touching RLlib. The runner no longer hard-codes the stand-in class names. It finds them by walking what try_import_torch() and try_import_tf() return, plus their attributes, keeping the classes ray.rllib.utils.framework defines. A renamed or new stand-in is picked up automatically, and a test covers a renamed one. Against the real framework.py, the walk finds all six current classes.

I didn't go the __getattr__ route, because it only covers the stand-in objects. torch, tfp, jax, and flax come back as plain None, and RLlib checks those with is None and truthiness, so the runner would still need the None path either way.

@elliot-barn elliot-barn left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

#67765 targeted this PR's branch (doc-1926-runner-rllib-stubs) and was merged into it on 11-04, so this [ci] PR now also carries its rllib.core docstring rewrite (10 RLlib files, roughly 900 lines). The description still says #67765 "exercises both once it's rebased onto this branch". Could you either call this out in the title/description so RLlib owners know they're approving it, or drop those commits here and land #67765 separately against master afterwards? Otherwise reverting this PR would also revert #67765.

Comment thread ci/ray_ci/doc/run_docstring_examples.py Outdated
code = frame.f_code
line = linecache.getline(code.co_filename, tb.tb_lineno)
for name, library in _RLLIB_NONE_NAMES.items():
if not re.search(rf"\b{name}\.{re.escape(error.name)}\b", line):

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This misses nn.functional.<fn>, which is common in RLlib (~33 uses). _NNStub.__init__ sets self.functional = None, so nn.functional.softplus(...) raises AttributeError: 'NoneType' object has no attribute 'softplus'. error.obj is None, so the stub branch doesn't fire, and the regex only looks for torch. / tf. / tf1.. An example that reaches e.g. TorchSquashedGaussian.logp without torch is reported as FAILED instead of skipped.

Same for the other names RLlib binds to None: tfp (try_import_tfp), jax/flax (try_import_jax) and tfv. These aren't in _RLLIB_NONE_NAMES, and tensorflow and jax are both in OMITTED_LIBRARIES.

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.

Same fix as the thread above, in e05edba: nn.functional and F now map to torch, and tfp, jax, flax, and tfv are covered.

@dstrodtman

Copy link
Copy Markdown
Contributor Author

@elliot-barn On scope: I dropped #67765's commit from this branch and rebased onto master, so this PR is back to the runner and image changes only (8 files). The rllib.core rewrite is now #67976, the same commit unchanged, stacked on this PR, and #67766 is restacked on top of it. Reverting this PR no longer touches RLlib. The two Bugbot findings on catalog.py and distribution.py moved with it and are noted in #67976.

@dstrodtman
dstrodtman removed this pull request from stack #67977 November 9, 2026 16:53
@dstrodtman
dstrodtman changed the base branch from master to djs-261109-regen-ray-llm-locks November 9, 2026 16:53
@dstrodtman
dstrodtman force-pushed the doc-1926-runner-rllib-stubs branch from e05edba to f0985ab Compare November 9, 2026 16:54
@dstrodtman
dstrodtman added this pull request to stack #67980 November 9, 2026 16:54
dstrodtman and others added 4 commits November 9, 2026 16:16
…nd-ins

RLlib's try_import_torch and try_import_tf don't raise when the library
is missing. They return None for the module and stand-in objects for its
submodules, so in the docstring-examples image an RLlib example that
needs torch fails with an AttributeError instead of an ImportError, and
the runner reports it as failed rather than skipped.

missing_library now also follows AttributeErrors. It maps one raised on
a stand-in class from ray/rllib/utils/framework.py to the library it
replaces, and one raised on a `torch`, `tf`, or `tf1` that's None, in
RLlib code or an RLlib example, to torch or TensorFlow. The None case
matches the source line that raised, so a different bug on None still
fails. To read an example's lines, run_docstring registers each
example's source with linecache, which also gives tracebacks the
example's own lines instead of the module file's.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Douglas Strodtman <[email protected]>
Python 3.10 reached end of life in October 2026. The docstringbuild
image, its two lockfiles, and the "doc: docstring examples" step now use
Python 3.11, matching the docs build, which already builds with 3.11.

Regenerating the locks for 3.11 drops three backports that only 3.10
needs (async-timeout, exceptiongroup, tomli) and moves scipy from 1.15.3
to 1.17.1. Every other pin is unchanged.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Douglas Strodtman <[email protected]>
Look up the name in f_locals before f_globals instead of branching on
co_varnames. f_locals also holds closure variables, which co_varnames
doesn't list, so a torch or tf bound in an enclosing function and set to
None was missed. Add a test for that case.

Signed-off-by: Douglas Strodtman <[email protected]>
…functional, tfp, and jax

Derive RLlib's stand-in classes by walking the objects try_import_torch and
try_import_tf return, instead of hard-coding their class names, so a renamed
or new stand-in in framework.py needs no change to the runner.

Resolve each dotted name ending in the failing attribute on the line that
raised, using tokenize instead of a regex, so comments, strings, and chains
such as self.torch.device no longer match. A chain rooted at a stand-in whose
attribute is None, such as nn.functional, now counts as the stand-in's
library, as does a None bound to F.

Add the other names RLlib binds a missing library to: tfp from
try_import_tfp, jax and flax from try_import_jax, tfv, and the underscore
aliases. Add tensorflow_probability to OMITTED_LIBRARIES.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Douglas Strodtman <[email protected]>
@dstrodtman
dstrodtman force-pushed the doc-1926-runner-rllib-stubs branch from f0985ab to 10d5de7 Compare November 9, 2026 21:17
@github-actions

Copy link
Copy Markdown

This pull request has been automatically marked as stale because it has not had
any activity for 14 days. It will be closed in another 14 days if no further activity occurs.
Thank you for your contributions.

You can always ask for help on our discussion forum or Ray's public slack channel.

If you'd like to keep this open, just leave any comment, and the stale label will be removed.

@github-actions github-actions Bot added the stale The issue is stale. It will be closed within 7 days unless there are further conversation label Nov 24, 2026

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

devprod docs An issue or change related to documentation go add ONLY when ready to merge, run all tests stale The issue is stale. It will be closed within 7 days unless there are further conversation

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants