Repository navigation
[ci] Skip RLlib docstring examples that reach torch or TensorFlow stand-ins, and move the docstring image to Python 3.11 - #67822
Conversation
There was a problem hiding this comment.
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.
| if name in code.co_varnames: | ||
| value = frame.f_locals.get(name, ...) | ||
| else: | ||
| value = frame.f_globals.get(name, ...) |
There was a problem hiding this comment.
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, ...))> [!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]>
There was a problem hiding this comment.
Cursor Bugbot has reviewed your changes and found 2 potential issues.
❌ 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.
|
Why are we updating to Python 3.11 here and nowhere else? |
|
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. |
|
You'll need to compile the requirements on a linux machine rather than our macs |
|
The docstring locks are built with |
elliot-barn
left a comment
There was a problem hiding this comment.
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.
| 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): |
There was a problem hiding this comment.
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.objisNone, 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 saysnn.functional.softplus(orF.softplusafterF = 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".
There was a problem hiding this comment.
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.
| _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"} |
There was a problem hiding this comment.
A couple of gaps in this map:
try_import_tfpreturnsNone(bound astfp), andtry_import_jaxreturnsNone, None(jax,flax). Both tensorflow and jax are inOMITTED_LIBRARIES, so an example touchingtfp.distributionsorjax.numpywould fail instead of skip.- The
tfentry can't match:try_import_tfreturns(None, _TFStub(), None), sotfis the stub, notNone, and theobjbranch already covers it.tfvis the third value that'sNone.
There was a problem hiding this comment.
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.
| # 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 = { |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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
left a comment
There was a problem hiding this comment.
#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.
| 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): |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
Same fix as the thread above, in e05edba: nn.functional and F now map to torch, and tfp, jax, flax, and tfv are covered.
f9061ae to
e05edba
Compare
|
@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 |
e05edba to
f0985ab
Compare
…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]>
f0985ab to
10d5de7
Compare
|
This pull request has been automatically marked as stale because it has not had 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. |

Note
Stacked on #67979, which regenerates two
ray-llmlocks that went stale on master after #67789. Without it, this PR'sraydepsets: compile all dependenciesjob fails on files it doesn't touch. Merge #67979 first.Why are these changes needed?
The
docstring-onlylabel runs the changed modules'>>>examples in thedocstringbuildimage, 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 anImportError.RLlib doesn't raise one.
try_import_torchandtry_import_tfinray/rllib/utils/framework.pyreturnNonefor the module and stand-in objects such as_TFStuband_NNStubfor its submodules. An RLlib example that needs torch then fails later with anAttributeError, and the runner counts it as failed. #67765 and #67766, which convert and fixrllib.coredocstring examples, both fail this way (build 76124, build 76135), with errors such as: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_librarynow also follows anAttributeErrorin the exception chain. It maps the error to the missing library in these cases, and only when that library isn't installed:try_import_torchandtry_import_tfreturn, so it doesn't hard-code RLlib's private class names, and a renamed or new stand-in needs no change here.None, in a frame from an RLlib module or an RLlib docstring example, and a dotted name on the line that raised resolves to thatNonein the frame. Either the name is one RLlib binds a missing library to (torch,tf,tf1,tfv,tfp,jax,flax, their underscore aliases, andFfornn.functional), or it's an attribute of a stand-in that'sNone, such asnn.functional.The line check tokenizes the line, so comments, strings, and chains such as
self.torch.devicedon't match, and an unrelated bug onNonestill fails, even in a function that also mentionstorch.tensorflow_probability, whichtry_import_tfpimports, joins the libraries the image omits. To read an example's lines,run_docstringnow registers each example's source withlinecache. That also fixes the tracebacks the step prints, which showed the module file's lines, such asimport abc, instead of the example's.The
docstringbuildimage moves to Python 3.11. Python 3.10 reached end of life in October 2026. The image, its two lockfiles, and thedoc: docstring examplesstep 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, andtomli) and movesscipyfrom 1.15.3 to 1.17.1. Every other pin is unchanged. Thedocstring_examples_*.lockrule in.buildkite/test.rules.txtalready matches the new lockfile names, andtest.rules.test.txtnow names them.Testing
pytest ci/ray_ci/doc/test_run_docstring_examples.pypasses all 62 tests. The RLlib tests run against a fakeray.rllib.utils.frameworkshaped like the real one. They cover each kind of stand-in, a renamed stand-in,nn.functionaldirectly and throughF, everyNonename above, aNonelocal as inget_deviceand in a closure, unrelatedAttributeErrors onNone(including a framework name in a comment, in a string, and asholder.torch), code outside RLlib, and an installed library.ray/rllib/utils/framework.pywith its Ray imports shimmed and no torch or TensorFlow. The runner finds all six of its stand-in classes, and mapsnn.functional.softplus(as inTorchSquashedGaussian.logp),F.relu,tfp.distributions,jax.numpy,flax.linen, andtfvto the right library.>>>examples on master, the old and new runners give identical per-docstring results in that environment.raydepsets build --all-configs --checkpasses on this branch, stacked on [deps] Regenerate the ray-llm base_extra_testdeps locks after the brotli bump #67979, and no other lock changes.pre-commit runon the changed files passes.The
docstringbuildimage builds only on a PR with thedocstring-onlylabel, 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, thedocstringbuildimage, 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