Skip to content

[train] Converge TorchCheckpoint docstring examples to stock doctests - #66747

Merged
dstrodtman merged 2 commits into
masterfrom
doc-1636-train-testcode-doctests
Oct 7, 2026
Merged

dstrodtman merged 2 commits into
masterfrom
doc-1636-train-testcode-doctests

Conversation

@dstrodtman

@dstrodtman dstrodtman commented Oct 5, 2026 •

Copy link
Copy Markdown
Contributor

What

Convert the .. testcode:: examples in ray.train.torch.TorchCheckpoint (from_state_dict, from_model) to stock >>> doctests.

Why

.. testcode:: / .. testoutput:: is Sphinx-specific RST, run by Ray's fork of pytest-sphinx and not rendered by griffe/mkdocstrings. Stock >>> doctests render under both Sphinx and griffe and run under plain pytest --doctest-modules. This continues the convergence piloted in #65901 (ray.util.actor_pool, ray.util.placement_group), using the same conversion rules.

How the blocks convert

Same code, same order, same docstring. Each docstring stays one doctest item and moves from the pytest-sphinx collector to stock doctest.

  • assert lines stay as plain >>> lines, and existing expected output stays as the doctest's expected output.
  • Bare expressions whose repr is incidental are bound to _.
  • Blank lines inside a block are dropped, since a blank line ends a doctest example.

One behavior difference to know: a testcode block with no testoutput ignores stdout, but stock doctest fails on any unmatched stdout. Every converted block was run to confirm it prints nothing unexpected.

Examples that now check something

Both blocks used .. testoutput:: :hide: with a body of ..., which matches any output, so they validated nothing. Their output is deterministic apart from a temp path, so they now check it:

  • from_state_dict expects worked, after its existing assert.
  • from_model expects Checkpoint(filesystem=local, path=...) under # doctest: +ELLIPSIS.
  • torch.manual_seed(42) returns a Generator, so it's bound to _.

Tests run

Locally, against a Ray nightly (43b706d) with the edited module overlaid, using pytest 7.4.4 and the same flags as the doctest Bazel macro: --doctest-modules -c NO_PYTEST_CONFIG -p <default_doctest_pytest_plugin>, with both collectors installed (stock doctest plus ray-project/pytest-sphinx). RAY_USAGE_STATS_PROMPT_ENABLED=0 suppresses the nightly-wheel-only usage banner, which source-built CI doesn't print. pre-commit passes on the changed files.

RAY_TRAIN_V2_ENABLED=1 and TF_USE_LEGACY_KERAS=1 are set to match //python/ray/train:py_doctest[train].

Module Before After
ray/train/torch/torch_checkpoint.py 2 passed (pytest-sphinx, output unchecked) 2 passed (doctest, output checked)

Related finding, not changed here

ray/train/__init__.py sets __module__ = "ray.train" on Checkpoint, TrainContext, and other re-exported classes. doctest.DocTestFinder skips objects whose __module__ doesn't match the file being collected, so neither collector ever collects those classes' docstring examples. For example, ray/train/v2/api/context.py collects 0 items. Those examples are untested today. Several of them also print from inside Train workers, and Ray forwards that output to the driver's stdout asynchronously, so they would flake under stock doctest if collection were fixed. That needs its own decision, so this PR doesn't touch those files.

Rendering

Each converted example sits under a plural Examples: header, indented, with no blank line after the header. That is the only form that renders as an examples section on both Sphinx (napoleon) and griffe/mkdocstrings. Griffe's Google parser treats singular Example: as an admonition, treats a header followed by a blank line as plain text, and renders >>> in free prose as Markdown blockquotes. On Sphinx this only adds or renames the "Examples" rubric. Every changed docstring was rendered before and after with Sphinx 8.2.3 (autodoc, napoleon, sphinx.ext.doctest) and mkdocstrings-python 2.0.9 / griffelib 2.3.0. Sphinx output has no regressions, and every converted example renders as highlighted doctest code under griffe.

Duplicate check

gh pr list --state open --search for "testcode", "doctest", and the touched module names found no open PR converting these docstrings.

AI assistance

Drafted with AI assistance (Claude Code). The submitter reviews every changed line before marking this ready for review.

🤖 Generated with Claude Code

dstrodtman and others added 2 commits October 5, 2026 16:22
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Douglas Strodtman <[email protected]>
griffe only parses a plural Examples: header with content on the next line as an examples section; Sphinx napoleon renders either way.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Douglas Strodtman <[email protected]>
@dstrodtman
dstrodtman force-pushed the doc-1636-train-testcode-doctests branch from dcba9e5 to ca43975 Compare October 5, 2026 20:22
@dstrodtman
dstrodtman marked this pull request as ready for review October 6, 2026 18:52
@dstrodtman
dstrodtman requested a review from a team as a code owner October 6, 2026 18:52
@dstrodtman dstrodtman added the go add ONLY when ready to merge, run all tests label Oct 6, 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 refactors the docstring examples in python/ray/train/torch/torch_checkpoint.py for from_state_dict and from_model to use standard Python doctest format (>>>) instead of Sphinx .. testcode:: directives. The review feedback suggests two improvements: first, replacing the fragile string comparison of PyTorch state dicts with a robust element-wise tensor equality check using torch.equal; second, renaming the variable input to avoid shadowing the Python built-in input() function, adhering to PEP 8 guidelines.

Comment on lines +83 to +84
>>> # Assert they have the same state dict
>>> assert str(model.state_dict()) == str(model_from_chkpt.state_dict())

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

Comparing the string representation of PyTorch state dicts (str(state_dict)) is fragile and prone to flakiness because tensor string formatting can vary across PyTorch versions, devices, or float precision settings. It is much more robust to iterate over the state dict keys and assert tensor equality using torch.equal.

Suggested change
>>> # Assert they have the same state dict
>>> assert str(model.state_dict()) == str(model_from_chkpt.state_dict())
>>> # Assert they have the same state dict
>>> for k, v in model.state_dict().items():
... assert torch.equal(v, model_from_chkpt.state_dict()[k])

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.

Out of scope for this syntax-only conversion. The str(state_dict) comparison predates this PR, and this PR keeps the example code as it was. Leaving it for the Ray Train owners to decide.

Comment on lines +131 to +132
>>> input = torch.randn(2, 2)
>>> output = model(input)

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

Using input as a variable name shadows the Python built-in input() function. According to PEP 8, it is best practice to avoid shadowing built-in names to prevent confusion and potential bugs. Consider renaming the variable to x or input_tensor.

Suggested change
>>> input = torch.randn(2, 2)
>>> output = model(input)
>>> x = torch.randn(2, 2)
>>> output = model(x)
References
  1. PEP 8 recommends avoiding names that shadow built-in functions or types to prevent confusion and name clashing. (link)

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.

Out of scope for this syntax-only conversion. The input name predates this PR, and this PR keeps the example code as it was. Leaving it for the Ray Train owners to decide.

@dstrodtman
dstrodtman merged commit c6a1494 into master Oct 7, 2026
7 checks passed
@dstrodtman
dstrodtman deleted the doc-1636-train-testcode-doctests branch October 7, 2026 13:03
dstrodtman added a commit that referenced this pull request Oct 14, 2026
…ocstring examples, piloted on Ray Data (#66814)

> [!NOTE]
> **Draft proposal.** This PR is for agreeing on the direction before
the label extends past Ray Data. It's rebased on `master` now that
#66806 has merged.

## Why are these changes needed?

A docstring edit in `python/ray/<lib>/` routes like a code change, so it
runs every test suite that library's tag selects, and the `go` premerge
runs all of them before merge. Converting docstring examples from
Sphinx-only `.. testcode::` to stock `>>>` doctests produces a steady
stream of these PRs. On master, 398 `testcode` blocks in 147 files
remain.

Measured on seven recent docstring-only PRs, one premerge build each:

| PR | Library | Premerge runner-hours |
|---|---|---|
| #65901 | core | 39.6 |
| #66745 | core | 43.7 |
| #66749 | rllib | 15.3 |
| #66747 | train | 10.6 |
| #66746 | data | 10.3 |
| #66748 | tune | 8.6 |
| #66604 | data | 8.2 |

Runner-hours are summed job durations from the Buildkite API, so
queueing doesn't count.

None of those suites can fail on a docstring-only change, except through
a test that asserts on `__doc__` text. What a docstring edit can break
is the example code in the docstrings it touched.

## What this PR does

It adds a `docstring-only` PR label, piloted on Ray Data only. Under the
label, a Data PR runs the `>>>` examples in the docstrings of only the
modules it changed, plus the API checks and lint, instead of every Data
test suite.

- **The guard.** `lint: validate docstring-only scope` runs whenever the
label is present, is tagged `always`, and can't be turned off.
`ci/ray_ci/doc/check_docstring_only.py` parses each changed file at the
merge-base and at `HEAD` with Python's `ast`, removes the docstring from
the module and from every class and function, and compares `ast.dump` of
the two trees. It fails on any difference, on any file that isn't `.py`,
on any added, deleted, renamed, copied, or type-changed file, and on any
parse error. Comments aren't in the AST, so comment edits pass. A string
later in a body and a `__doc__` assignment both count as code.
- **What the label skips.** The 10 Data test steps in `data.rayci.yml`
that run on premerge get `if: '!(build.pull_request.labels includes
"docstring-only")'`, the same pattern `docs-go` used. `pyrefly type
check` isn't gated.
- **What it runs instead.** A new `data: docstring examples` step, gated
on the label, runs `ci/ray_ci/doc/run_docstring_examples.sh`:
1. It lists the `.py` files the PR modified under `python/ray/data/`,
excluding `tests/` and `examples/`, and exits if there are none.
1. It builds the Data CI image with the PR's Ray, using `test_in_docker
--build-only`, the same Ray install every Data test step uses.
1. In that image, it runs `ci/ray_ci/doc/run_docstring_examples.py` on
only those files.

The runner imports each module and extracts the `>>>` examples from
every docstring in the file. It runs each docstring's examples in order,
in a copy of the module's globals, as an interactive session would. An
example that shows output must print it, so those examples are unit
tests rather than smoke tests. Matching follows Ray's doctest targets:
`...` matches any text (pytest's default ELLIPSIS flag), and per-example
directives apply. An example that shows no output only has to run
without raising, and one that shows a traceback must raise a matching
exception. The standard library's doctest module supplies the parser and
the output comparison, with no doctest runner, pytest collection, or
Bazel doctest target. Examples still written as `.. testcode::` aren't
run.
- **Docs.** `doc/source/ray-contribute/ci.md` gets a "Docstring-only
changes" section.

### Design choices for review

- **Changed files only.** The unit is the changed module, not the
library. A PR that edits `aggregate.py` runs only `aggregate.py`'s
examples.
- **Output is checked where it's shown.** A stale result in an example
fails the step, the same as in Ray's doctest targets. Examples that show
nothing are smoke tests.
- **Data only.** Extending the label means an `if:` on most library test
steps in every per-library `*.rayci.yml`, which each library team owns.
This draft shows the shape on one library first. `ml: data integration
tests` also carries the `data` tag but lives in `ml.rayci.yml`, so it
still runs under the label.
- **Some image builds still run.** The label gates test steps, not the
`wanda` image builds they depend on. rayci selects steps by tag and
pulls in every image a selected step depends on, and it doesn't evaluate
`if:`. `wanda` steps can't take an `if:` either. Under the label, a Data
docstring PR still emits 5 image jobs that feed only the gated steps:
`datamongobuild-py3.10`, `datatfdsbuild-py3.12`, `docgpubuild-py3.10`,
`docgpubuild-py3.12`, and `oss-ci-base_gpu-py3.12`. On premerge builds
[74154](https://buildkite.com/ray-project/premerge/builds/74154) and
[74459](https://buildkite.com/ray-project/premerge/builds/74459), those
5 jobs took 4.1 and 10.1 minutes. Each takes about 50 seconds as a cache
hit, and `docgpubuild-py3.10` took 401 seconds on a miss. That's small
next to the 6.9 runner-hours the gated steps took. Dropping them needs a
rayci change that evaluates label gates before it marks dependencies.
The other 20 image jobs in the build feed a step the label keeps, or
rayci selects them on their own.
- **Known residual risk.** A test that asserts on `__doc__` text, or on
line numbers a docstring edit shifts, isn't visible to the guard. The
postmerge build is the backstop.

## Related issue number

None. Duplicate check: I searched open PRs for `docstring-only` and
`docstring only label`, and found no PR that adds a label or guard for
docstring-only changes.

## Tests run

- `pytest ci/ray_ci/doc/test_check_docstring_only.py
ci/ray_ci/doc/test_run_docstring_examples.py`: 29 passed. The runner's
tests cover examples that use module globals, a raising example that
fails with its file, line, and docstring name, wrong output that fails
with a diff, matching output with ELLIPSIS and a directive, expected and
mismatched exceptions, `+SKIP` and `+SKIP_EXAMPLE`, and no names leaking
between docstrings.
- The guard against real branches: it passes the three open docstring
PRs, #66745 (2 files), #66746 (1 file), and #66812 (5 files). It fails
#66806's branch and names the two `.py` files with code changes and the
three Markdown files.
- The runner against a Ray nightly (`43b706d`) on real branches. On
#66812's five files, 7 docstrings ran and passed in 24 seconds. On
#66746's `aggregate.py`, 18 docstrings ran and passed in 12 seconds.
With output checking, on six `master` Data modules that already use
`>>>` (`dataset.py`, `expressions.py`, `iterator.py`, `datatype.py`, and
two preprocessors), 113 of 118 docstrings passed in 36 seconds. The 5
failures are packages missing from the local environment (`torch`,
`tensorflow`, `crc32c`), not output mismatches.
- `--list-changed` in a scratch clone whose only change is a docstring
edit to `python/ray/data/aggregate.py` lists exactly that file.
- Pipeline generation with `rayci` built at `.rayciversion` (0.48.0),
for that simulated PR, on the premerge and microcheck pipeline IDs. Both
generate, with selected tags `always data lint`. Evaluating the
generated `if:` conditions shows the following:
- **Without the label:** the Data test steps match the real premerge
build of #66746
([74459](https://buildkite.com/ray-project/premerge/builds/74459)).
- **With `docstring-only`:** the 10 gated steps drop out, and `data:
docstring examples` and `lint: validate docstring-only scope` are added.
The API checks, `pyrefly`, `test-rules`, and `ml: data integration
tests` still run.
- The image jobs the label leaves running: I reran the same simulation
with the 10 gated steps removed from the YAML, which is what a rayci
change that evaluates label gates before marking dependencies would
emit. The build goes from 25 image jobs to 20. The 5 removed are listed
under "Some image builds still run." If the two `continuous-build` Data
steps are also dropped, `datalbuild-py3.12` goes too, for 6.
- Estimated saving on build 74459: the 10 gated steps took 6.9 of its
10.3 runner-hours. The new step adds one Data image build and a run of
seconds per changed file.
- `pre-commit` passes on the changed files.

Not yet run: the label on a real Buildkite build, including the
`--build-only` and `docker run` part of the new step. Nothing in the
repo evaluates Buildkite `if:` conditions, so the first labeled Data
docstring PR is the confirming check.

**AI assistance.** This change was drafted with Claude Code. I reviewed
every line and ran the tests above.

🤖 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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

go add ONLY when ready to merge, run all tests

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants