Skip to content

[data] Converge torch preprocessor and TorchInference docstring examples to stock doctests - #67070

Merged
dstrodtman merged 1 commit into
masterfrom
doc-1636-data-torch-doctests
Oct 15, 2026
Merged

dstrodtman merged 1 commit into
masterfrom
doc-1636-data-torch-doctests

Conversation

@dstrodtman

Copy link
Copy Markdown
Contributor

What

Convert the remaining .. testcode:: examples in two ray.data torch docstrings to stock >>> doctests:

Why

This continues the convergence in #66746 and #66812, with the same conversion rules: same code, same order, same docstring, blank lines inside a block dropped, and each example under a plural Examples: header with no blank line after it. Lead-in sentences stay inside the section.

It's also the first Data PR opened after #66814 merged, and it carries the docstring-only label, so its premerge build exercises the new data: docstring examples step and the lint: validate docstring-only scope guard on a real build. #66812 deferred preprocessors/torch.py because it needs torchvision. That's true locally only: torchvision is in python/requirements/ml/data-test-requirements.txt, which the datalbuild image the new step uses installs.

TorchInference changes test reporting as well as markup. Ray's pytest-sphinx fork drops :skipif: True blocks before collection, so the example wasn't reported at all. Under +SKIP_EXAMPLE, the Data doctest plugin and the new runner both report it as skipped.

Not in this PR

SerializablePreprocessorBase._set_serializable_fields stays as is, for the reason in #66812: it shows a method pattern in prose, not under an Examples: section. dataset.py, read_api.py, and llm.py go in their own PRs.

Duplicate check

I searched open PRs for TorchVisionPreprocessor, torch_inference, and testcode doctest data. The only related open PRs are my own #66746, #66812, and #66809, which touch other files.

Tests run

Locally, against a Ray nightly (43b706d) on Python 3.12 with the edited modules overlaid and torchvision 0.29.1 installed. The pytest runs use pytest 7.4.4 and the same flags as the doctest Bazel macro, --doctest-modules -c NO_PYTEST_CONFIG -p <Ray Data doctest plugin>, with both collectors installed.

Run Before After
pytest, both collectors 1 passed 1 passed, 1 skipped (+SKIP_EXAMPLE)
pytest, -p no:sphinx n/a 1 passed, 1 skipped
ci/ray_ci/doc/run_docstring_examples.py on both files n/a 1 docstring run, 0 failed, 1 skipped
ci/ray_ci/doc/check_docstring_only.py --base upstream/master n/a passes: 2 files, docstrings only

The TorchVisionPreprocessor example reads s3://anonymous@air-example-data-2/imagenet-sample-images, as it did before, so it needs network access. pre-commit passes on the changed files.

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

🤖 Generated with Claude Code

…les to stock doctests

Convert the two runnable `.. testcode::` blocks in TorchVisionPreprocessor
and the `:skipif: True` block in TorchInference to `>>>` doctests. The
TorchInference example needs a GPU, so it carries the docstring-level
`+SKIP_EXAMPLE` flag instead of a skipped testcode block.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Douglas Strodtman <[email protected]>
@dstrodtman dstrodtman added docs An issue or change related to documentation data Ray Data-related issues go add ONLY when ready to merge, run all tests labels Oct 15, 2026
@dstrodtman
dstrodtman requested a review from a team as a code owner October 15, 2026 13:15
@dstrodtman dstrodtman added the docstring-only Skip heavy library tests for Ray API docstring edits. label Oct 15, 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 torch.py and torch_inference.py by converting Sphinx .. testcode:: blocks into standard Python doctest format, including the use of the # doctest: +SKIP_EXAMPLE directive for skipped tests. No review comments were provided, and the changes are straightforward, so there is no additional feedback.

@dstrodtman
dstrodtman merged commit 1768cd1 into master Oct 15, 2026
5 checks passed
@dstrodtman
dstrodtman deleted the doc-1636-data-torch-doctests branch October 15, 2026 17:43
dstrodtman added a commit that referenced this pull request Oct 15, 2026
#67080)

## What

Convert the 10 `.. testcode::` blocks in `python/ray/data/read_api.py`
to stock `>>>` doctests:

- `read_parquet`: the projection and filter pushdown example joins the
docstring's existing `>>>` session, and its `testoutput` becomes the
expected output, so the `show(2)` result is still checked.
- `read_sql`: the SQLite example, which now creates its database in a
temporary directory and checks one read with `ds.count()`. See below.
- `read_bigquery`, `read_snowflake`, `read_databricks_tables` (2
blocks), `read_delta_sharing_tables`, and `read_kafka` (2 blocks):
`:skipif: True` examples that need an external service or credentials.
Each docstring carries the docstring-level `# doctest: +SKIP_EXAMPLE`
flag from #66753 once. None of these five docstrings has another `>>>`
example for the flag to skip by accident.

## Why

This continues the convergence in #66746, #66812, and #67070, with the
same conversion rules: same code, same order, same docstring, blank
lines inside a block dropped, bare expressions with an incidental repr
bound to `_`, and each example under a plural `Examples:` header with no
blank line after it. `read_snowflake`'s singular `Example:` header
becomes `Examples:`.

For the label from #66814, this is a larger case than #67070. The runner
runs every docstring in a changed file, so it runs all 35 runnable
docstrings in `read_api.py`, not only the 10 converted blocks. It also
checks output on `read_parquet` and runs five `+SKIP_EXAMPLE`
docstrings.

### Design choices for review

- **`read_sql` creates its database in a temporary directory.** The
original wrote `example.db` to the working directory and removed it in a
hidden `.. testcode:: :hide:` block, because a second run in the same
directory fails on `CREATE TABLE movie` ("table movie already exists").
Stock doctest has no run-but-hide form. The example now opens
`os.path.join(db_dir.name, "example.db")` under a
`tempfile.TemporaryDirectory()` and ends with `db_dir.cleanup()`, so it
can be rerun by readers as well as in CI, with no test-harness change.
An in-memory SQLite database wouldn't work: `read_sql` calls
`connection_factory` inside each read task, in a worker process, so each
worker would open a new empty database. The same `TemporaryDirectory`
pattern is in #66812's `list_stats_summaries`.
- **`read_sql` now checks a read.** The example never consumed the
datasets it built, so it didn't show that a read works. It now calls
`ds.count()` on the all-movies query and expects `4`. With no
`shard_keys`, `read_sql` falls back to a single read task whose metadata
has no row count, so `count()` runs that task in a worker and opens the
database through `create_connection`. On a warm local cluster the count
takes about 1 second.
- **Two `connection.execute(...)` calls are bound to `_`.** As a
statement in `testcode` they printed nothing, but as `>>>` they'd echo a
`sqlite3.Cursor` repr with a memory address.

## Duplicate check

I searched open PRs for `read_api`, `read_sql`, `read_kafka`, and
`testcode doctest data`. #66604 touched `read_api.py` but is merged and
changed different text. The only related open PRs are my own #66746,
#66812, and #67070, which touch other files.

## Tests run

Locally against a Ray nightly (`43b706d`) on Python 3.12, using pytest
7.4.4 and the same flags as the `doctest` Bazel macro,
`--doctest-modules -c NO_PYTEST_CONFIG -p <Ray Data doctest plugin>`,
with both collectors installed. `master`'s `read_api.py` imports
`ray.data.checkpoint.generated_id`, which that nightly predates, so I
applied this PR's diff to the nightly's own `read_api.py` rather than
overlaying `master`'s copy.

| Run | Before | After |
|---|---|---|
| pytest, both collectors | 31 passed, 5 failed | 30 passed, 5 skipped,
5 failed |
| pytest, `-p no:sphinx` | n/a | 30 passed, 5 skipped, 5 failed |
| `read_parquet` and `read_sql` alone, each collector setup | 1 passed
each | 1 passed each |
| `read_sql` run twice in the same directory, `-W
error::ResourceWarning` | n/a | passed both times, about 4 seconds each,
no `example.db` left in the working directory |
| `ci/ray_ci/doc/check_docstring_only.py --base upstream/master` | n/a |
passes: 1 file, docstrings only |

The pass count drops by one because `pytest-sphinx` collected the
`read_parquet` and `read_sql` `testcode` blocks as two extra items.
They're now part of the stock doctest items, one per docstring, and
`read_sql` gains a stock item it didn't have. The five `:skipif: True`
blocks were dropped before collection and never reported. They now
report as skipped.

The same five docstrings fail before and after, all in docstrings this
PR doesn't touch, because of my local environment: `from_tf`
(`tensorflow_datasets`), `read_audio` (`soundfile`), `read_avro`
(`fastavro`), `read_videos` (`decord`), and `read_json`, whose
`ds.schema()` prints `string` where the docstring expects `object`
because of a newer local pandas. The `run_docstring_examples.py` runner
on the file reports 35 docstrings run, with the same five failures and
five skips. `pre-commit` passes on the changed file.

**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]>
Co-authored-by: gemini-code-assist[bot] <176961590+gemini-code-assist[bot]@users.noreply.github.com>
dstrodtman added a commit that referenced this pull request Oct 21, 2026
…examples to stock doctests (#67207)

## Description

Converts the remaining runnable `.. testcode::` examples in nine
`Dataset` methods to stock `>>>` doctests: `streaming_split`, `split`,
`iter_batches`, `iter_jax_batches`, `iter_tf_batches`, `stats`,
`explain`, `serialize_lineage`, and `deserialize_lineage`. It also
converts the one example each in
`SerializablePreprocessorBase._set_serializable_fields`
(`preprocessor.py`) and `MemoryProfiler` (`_internal/util.py`). Stock
doctests render without Sphinx-only directives, and the `docstring-only`
label's examples step runs them. The change touches only docstrings.

Three examples used `:options: +MOCK`, which hid their output from
comparison. Comparing it surfaced the following fixes:

- **`iter_batches`** read `example://image-datasets/simple`, which
resolves inside the installed package, and wheels don't ship
`ray/data/examples/data/`. It now reads the same images from
`s3://anonymous@ray-example-data/image-datasets/simple`, as
`Dataset.map` does. The three images make exactly two batches, so the
expected output drops the `...` line between them, which wouldn't have
matched.
- **`stats`** shows the current output format, with ellipses for counts,
timings, and the read operator's name, which becomes
`ReadRange->SplitBlocks(N)` depending on the CPU count. The `assert
ds.stats() == ""` is now `>>> ds.stats()` with `''` as the output.
- **`MemoryProfiler`** replaces the `...` placeholder statement with
`pass`. In a doctest, a bare `...` expression echoes `Ellipsis` on every
loop iteration. The USS values use an ellipsis.

**`iter_tf_batches`** called `Dataset.to_tf`, which has its own
examples. It now calls `iter_tf_batches` and prints the first batch,
matching the `iter_jax_batches` example.

The fourth `streaming_split` example deliberately blocks, so it stays
render-only, now with `# doctest: +SKIP` on that one line in place of
`:skipif: True`. The rest of the docstring runs. `explain`, `split`, and
the lineage examples matched as written.

**`iter_jax_batches` and `iter_tf_batches` run only in postmerge under
the label.** The docstring examples image omits JAX and TensorFlow, so
the step skips both docstrings by name. They still run in
`//python/ray/data:doctest`.

## Related issues

Related to #66814, #67083, and #67202.

## Additional information

**Not a duplicate.** I searched open PRs that touch
`python/ray/data/dataset.py`, `streaming_split`, `serialize_lineage`, or
`MemoryProfiler`. #67202 converts the `Dataset` transform methods
(`map`, `map_batches`, `flat_map`, `groupby`, `aggregate`, `join`) in
the same file, and the two PRs edit different methods. #64869 and #66340
don't touch these examples. #66746, #66812, #67070, and #67080 converted
other Data modules and have merged.

**Tests run**

- `ci/ray_ci/doc/check_docstring_only.py --base upstream/master`: "3
file(s), docstrings only."
- `ci/ray_ci/doc/run_docstring_examples.py` on the three files in an
aarch64 image built from
`python/deplocks/docs/docstring_examples_depset_py3.10.lock`, with the
Ray nightly at `093faf5583e` and the changed files mounted over the
installed ones. The three files are unchanged between that commit and
this PR's base. Result: 61 docstrings run and 0 failed.
`iter_jax_batches`, `iter_tf_batches`, `to_tf`, `write_tfrecords`, and
`iter_torch_batches` are skipped for libraries the image omits.
- The two JAX and TensorFlow docstrings, run with `doctest` in the same
image after installing `jax` 0.6.2 and `tensorflow` 2.21.0: 0 failures
each. Those aren't CI's pinned versions, so I'll check the postmerge
`data: docs example tests` result after merge.
- `pre-commit run --files` on the three files: all hooks pass, including
ruff, black, pydoclint, and the Ray docstyle check.

The PR carries the `docstring-only` label, and 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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

data Ray Data-related issues docs An issue or change related to documentation docstring-only Skip heavy library tests for Ray API docstring edits. 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