Skip to content

[Data] Correct the prefetch_batches and local_shuffle_buffer_size docstrings on iteration APIs - #67486

Merged
dstrodtman merged 4 commits into
masterfrom
djs-261027-data-prefetch-docstrings
Oct 30, 2026
Merged

dstrodtman merged 4 commits into
masterfrom
djs-261027-data-prefetch-docstrings

Conversation

@dstrodtman

@dstrodtman dstrodtman commented Oct 27, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Corrects the prefetch_batches and local_shuffle_buffer_size argument docstrings that are copied across the Dataset and DataIterator iteration APIs, so they describe what BatchIterator and ShufflingBatcher actually do. This is a docstring-only change. Behavior is unchanged.

This came up while reviewing #67454, which documents the iteration pipeline on the Ray Data internals page. The API reference pages that section links to contradicted its diagram.

Before

prefetch_batches

The shared text said:

The number of batches to fetch ahead of the current batch to fetch. If set to greater than 0, a separate threadpool will be used to fetch the objects to the local node, format the batches, and apply the collate_fn. Defaults to 1.

That doesn't match python/ray/data/_internal/block_batching/iter_batches.py:

  • Iteration always runs in a background thread. _iter_batches wraps the pipeline in iter_threaded(...) whatever the value of prefetch_batches.
  • The format and collate pool has min(RAY_DATA_MAX_FORMAT_THREADPOOL_NUM_WORKERS, prefetch_batches) workers, and that environment variable defaults to 4. Setting prefetch_batches above 4 fetches further ahead but adds no threads, and the docstring didn't say so.
  • With prefetch_batches=0, there's no pool. prefetch_batches_locally yields block refs without prefetching, and format and collate run inline.
  • iter_batches, iter_tf_batches, to_tf, and to_torch don't accept a collate_fn, but their docstrings mentioned applying one.
  • The first sentence repeated "to fetch". iter_jax_batches had a different one-line version.

local_shuffle_buffer_size

The docstrings disagreed with each other and with ShufflingBatcher in python/ray/data/_internal/batcher.py:

  • The iter_torch_batches, iter_tf_batches, to_torch, and to_tf docstrings said the buffer size "must be greater than or equal to batch_size." The code doesn't reject a smaller value. It rounds it up to batch_size.
  • ShufflingBatcher raises ValueError when batch_size is None. Only some docstrings said batch_size is required, and iter_batches, which accepts batch_size=None, didn't.
  • DataIterator.iter_jax_batches had a one-line version, "Minimum rows for local in-memory shuffle."
  • None of them stated the trade-off that ShufflingBatcher's own docstring gives: a larger buffer is more random but adds latency to the first batch.

After

prefetch_batches

Every prefetch_batches docstring now uses the same text. Methods that accept collate_fn (iter_torch_batches, iter_jax_batches) mention collation, and the others don't:

The number of batches to fetch ahead of the current batch. Ray Data prepares batches in background threads while your code consumes the current one. If greater than 0, a thread pool formats the batches. The pool has prefetch_batches threads, up to a limit of 4. To change the limit, set the RAY_DATA_MAX_FORMAT_THREADPOOL_NUM_WORKERS environment variable. If 0, Ray Data doesn't prefetch blocks and formats each batch without the thread pool. Defaults to 1.

local_shuffle_buffer_size

Every docstring now uses the same text:

If not None, Ray Data randomly shuffles the data using a local in-memory shuffle buffer, and this value serves as the minimum number of rows that must be in the buffer to yield a batch. When there are no more rows to add to the buffer, Ray Data drains the remaining rows. A larger buffer makes the shuffle more random but might increase the latency to the first batch. If this value is smaller than batch_size, Ray Data rounds it up to batch_size. Local shuffling raises a ValueError if batch_size is None.

I kept the "minimum number of rows" sentence's meaning as it was. It's an approximation of the compaction watermarks in ShufflingBatcher.has_batch(), and I've asked in a comment below whether you want it more precise.

Updated methods, for both arguments:

  • DataIterator: iter_batches, iter_torch_batches, iter_tf_batches, iter_jax_batches, to_torch, and to_tf.
  • Dataset: iter_batches, iter_torch_batches, iter_tf_batches, iter_jax_batches, and to_tf.

Subsystems

API (docstrings only)

Not a duplicate

I searched open PRs for prefetch_batches and iterator docstring changes. #67355 touches iter_batches.py and util.py to stop the block prefetcher early, but it doesn't change these docstrings, the thread-pool sizing, or ShufflingBatcher.

Testing

  • pre-commit run --files python/ray/data/iterator.py python/ray/data/dataset.py passes, including ruff, black, pydoclint, and the Ray docstyle check.
  • I checked each claim against iter_batches.py (_format_batches, _iter_batches, prefetch_batches_locally), util.py (iter_threaded), and batcher.py (ShufflingBatcher.__init__ and has_batch) on master.
  • I didn't run a local Sphinx build. The change is plain prose plus inline literals.

The docstring-only label is applied to skip the heavy Ray Data test suites.

I wrote this with AI assistance (Claude Code). I reviewed every changed line and can defend the change.

🤖 Generated with Claude Code

The shared prefetch_batches description said a separate threadpool
fetches objects, formats batches, and applies collate_fn whenever
prefetch_batches > 0. That doesn't match BatchIterator: iteration always
runs in a background thread, the format/collate pool is capped at
RAY_DATA_MAX_FORMAT_THREADPOOL_NUM_WORKERS (default 4), and with 0 there
is no pool and no block prefetching. Several methods without a
collate_fn parameter also mentioned collate_fn.

Docstring-only change across DataIterator and Dataset.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Douglas Strodtman <[email protected]>
@dstrodtman dstrodtman added the docstring-only Skip heavy library tests for Ray API docstring edits. label Oct 27, 2026
@dstrodtman
dstrodtman requested a review from a team as a code owner October 27, 2026 17:25

@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 updates the docstrings for the prefetch_batches parameter across several batch iteration and conversion methods in dataset.py and iterator.py to clarify how Ray Data prepares batches in background threads. The review feedback correctly identifies that the iter_jax_batches methods in both files do not accept a collate_fn parameter, and suggests removing misleading references to collation from their docstrings.

Comment on lines +7094 to +7101
prefetch_batches: The number of batches to fetch ahead of the current batch.
Ray Data prepares batches in background threads while your code consumes
the current one. If greater than 0, a thread pool formats the batches
and applies ``collate_fn``. The pool has ``prefetch_batches`` threads,
up to a limit of 4. To change the limit, set the
``RAY_DATA_MAX_FORMAT_THREADPOOL_NUM_WORKERS`` environment variable. If
0, Ray Data doesn't prefetch blocks and formats and collates each batch
without the thread pool. Defaults to 1.

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

The iter_jax_batches method does not accept a collate_fn parameter. Mentioning collate_fn and collation in this docstring is misleading. Please update the docstring to remove references to collate_fn and collation, matching the docstring used for iter_batches or iter_tf_batches.

Suggested change
prefetch_batches: The number of batches to fetch ahead of the current batch.
Ray Data prepares batches in background threads while your code consumes
the current one. If greater than 0, a thread pool formats the batches
and applies ``collate_fn``. The pool has ``prefetch_batches`` threads,
up to a limit of 4. To change the limit, set the
``RAY_DATA_MAX_FORMAT_THREADPOOL_NUM_WORKERS`` environment variable. If
0, Ray Data doesn't prefetch blocks and formats and collates each batch
without the thread pool. Defaults to 1.
prefetch_batches: The number of batches to fetch ahead of the current batch.
Ray Data prepares batches in background threads while your code consumes
the current one. If greater than 0, a thread pool formats the batches.
The pool has ``prefetch_batches`` threads, up to a limit of 4. To change
the limit, set the ``RAY_DATA_MAX_FORMAT_THREADPOOL_NUM_WORKERS``
environment variable. If 0, Ray Data doesn't prefetch blocks and formats
each batch without the thread pool. Defaults to 1.

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.

iter_jax_batches does accept collate_fn. It's in the signature in both dataset.py and iterator.py, and DataIterator.iter_jax_batches passes it to _iter_batches(_collate_fn=collate_fn). So the collation wording is correct here, and I'm leaving it as is.

Comment on lines +770 to +777
prefetch_batches: The number of batches to fetch ahead of the current batch.
Ray Data prepares batches in background threads while your code consumes
the current one. If greater than 0, a thread pool formats the batches
and applies ``collate_fn``. The pool has ``prefetch_batches`` threads,
up to a limit of 4. To change the limit, set the
``RAY_DATA_MAX_FORMAT_THREADPOOL_NUM_WORKERS`` environment variable. If
0, Ray Data doesn't prefetch blocks and formats and collates each batch
without the thread pool. Defaults to 1.

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

The iter_jax_batches method does not accept a collate_fn parameter. Mentioning collate_fn and collation in this docstring is misleading. Please update the docstring to remove references to collate_fn and collation, matching the docstring used for iter_batches or iter_tf_batches.

Suggested change
prefetch_batches: The number of batches to fetch ahead of the current batch.
Ray Data prepares batches in background threads while your code consumes
the current one. If greater than 0, a thread pool formats the batches
and applies ``collate_fn``. The pool has ``prefetch_batches`` threads,
up to a limit of 4. To change the limit, set the
``RAY_DATA_MAX_FORMAT_THREADPOOL_NUM_WORKERS`` environment variable. If
0, Ray Data doesn't prefetch blocks and formats and collates each batch
without the thread pool. Defaults to 1.
prefetch_batches: The number of batches to fetch ahead of the current batch.
Ray Data prepares batches in background threads while your code consumes
the current one. If greater than 0, a thread pool formats the batches.
The pool has ``prefetch_batches`` threads, up to a limit of 4. To change
the limit, set the ``RAY_DATA_MAX_FORMAT_THREADPOOL_NUM_WORKERS``
environment variable. If 0, Ray Data doesn't prefetch blocks and formats
each batch without the thread pool. Defaults to 1.

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.

iter_jax_batches does accept collate_fn. It's in the signature in both dataset.py and iterator.py, and DataIterator.iter_jax_batches passes it to _iter_batches(_collate_fn=collate_fn). So the collation wording is correct here, and I'm leaving it as is.

The iter_torch_batches family said the buffer size must be at least
batch_size. ShufflingBatcher doesn't reject a smaller value: it rounds
it up to batch_size. It does raise ValueError when batch_size is None,
which only some docstrings mentioned. State both consistently across
DataIterator and Dataset, add the randomness-versus-first-batch-latency
trade-off from ShufflingBatcher's own docstring, and move the text to
active voice and present tense.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Douglas Strodtman <[email protected]>
@dstrodtman dstrodtman changed the title [Data] Correct the prefetch_batches docstring on iteration APIs [Data] Correct the prefetch_batches and local_shuffle_buffer_size docstrings on iteration APIs Oct 27, 2026
@dstrodtman

Copy link
Copy Markdown
Contributor Author

Question for the Ray Data maintainers about local_shuffle_buffer_size, which I didn't want to settle on my own.

Every docstring describes the value as "the minimum number of rows that must be in the buffer to yield a batch." In ShufflingBatcher.has_batch(), though, once a batch is available the batcher yields when either of these holds:

  • The compacted rows reach max(batch_size, 0.5 * shuffle_buffer_min_size), set by SHUFFLE_BUFFER_COMPACTION_THRESHOLD.
  • The rows beyond one batch reach 1.5 * shuffle_buffer_min_size, set by SHUFFLE_BUFFER_COMPACTION_RATIO.

So the configured value works more like a target buffer size than a strict per-yield minimum. This PR keeps the existing sentence's meaning and only fixes voice, tense, and the two verified errors described in the PR description. Do you want the docstring to describe the watermark behavior more precisely, or is the "minimum rows" approximation the right level of detail for users?

@dstrodtman dstrodtman added the go add ONLY when ready to merge, run all tests label Oct 27, 2026
@ray-gardener ray-gardener Bot added docs An issue or change related to documentation data Ray Data-related issues labels Oct 27, 2026
@rtd-build

Signed-off-by: Douglas Strodtman <[email protected]>
@dstrodtman
dstrodtman merged commit 2599949 into master Oct 30, 2026
6 checks passed
@dstrodtman
dstrodtman deleted the djs-261027-data-prefetch-docstrings branch October 30, 2026 12:16
dstrodtman added a commit that referenced this pull request Oct 30, 2026
…ing_id bit-split docstrings (#67532)

## Summary

Corrects two Ray Data docstrings that disagree with the code.
`Dataset.union` described the wrong output order and its skipped example
showed it. `monotonically_increasing_id` gave the wrong bit width for
the task ID. This is a docstring-only change. Behavior is unchanged.

This is separate from #67486, which corrects the `prefetch_batches` and
`local_shuffle_buffer_size` docstrings.

## Before

**`Dataset.union`.** The docstring said the order of the blocks in the
datasets is preserved, "as is the relative ordering between the datasets
passed in the argument list." Its example, marked `+SKIP`, showed
`range(2).union(range(3))` returning `[0, 1, 0, 1, 2]`, all of the first
dataset before the second. The code does neither:

- Without `preserve_order`, `UnionOperator._add_input_inner` adds each
input bundle straight to the output buffer as it arrives, so the order
depends on scheduling.
- With `preserve_order`, `UnionOperator._try_round_robin` takes one
block from each input in argument order, then the next block from each,
until every input runs out. `range(2).union(range(3))` returns `[0, 0,
1, 1, 2]`.

**`monotonically_increasing_id`.** The docstring said the task ID takes
"the upper 31 bits." `expression_evaluator.py` sets `TASK_BITS = 30` and
`ROW_BITS = 33`, so the task ID takes the 30 bits above the record
number, and the sign bit of the int64 is unused. The record-number half
and the example output were already correct.

## After

- `Dataset.union` states both behaviors and names
`DataContext.execution_options.preserve_order` as the switch. The
example sets `preserve_order`, uses two-block inputs so the interleaving
reads as block-level rather than row-level, and runs as a doctest:

  ```python
  >>> ds1 = ray.data.range(4, override_num_blocks=2)
  >>> ds2 = ray.data.range(4, override_num_blocks=2)
  >>> [row["id"] for row in ds1.union(ds2).take_all()]
  [0, 1, 0, 1, 2, 3, 2, 3]
  >>> ctx.execution_options.preserve_order = False
  ```

The example sets `preserve_order` itself rather than relying on
`doctest_pytest_plugin.py`, so it's deterministic in any runner,
including the `data: docstring examples` step, and resets the flag
afterward, as `streaming_train_test_split`'s example does.
- `monotonically_increasing_id` says 30 bits for the task ID and notes
the unused sign bit.

## Subsystems

API (docstrings only).

## Testing

- **Probe on Ray 2.59.0** (whose `UnionOperator` matches master's):
`range(2).union(range(3)).take_all()` returned `[0, 0, 1, 1, 2]` in 5 of
5 runs with `preserve_order=True`. `range(4,
override_num_blocks=2).with_column("uid",
monotonically_increasing_id())` returned `uid` values `0, 1, 8589934592,
8589934593`, so the second task starts at `2**33`.
- **New `union` example** run through `doctest` against Ray 2.59.0 with
`ray.init(num_cpus=N)` for N = 1, 4, and 16: 5 of 5 passes at each.
- `python ci/ray_ci/doc/check_docstring_only.py --base "$(git merge-base
upstream/master HEAD)"`: `2 file(s), docstrings only.`
- `python ci/ray_ci/doc/run_docstring_examples.py
python/ray/data/dataset.py python/ray/data/expressions.py`: `PASS
Dataset.union` and `PASS monotonically_increasing_id`. The run had 84
PASS, 15 SKIP, and 7 FAIL. All 7 failures came from the local
environment, not this change: Ray 2.59.0 lacks APIs that master has
(`unnest`, `write_orc`), and the venv lacks Pillow and crc32c. CI runs
these with this PR's Ray build in the Data image.
- `pre-commit run` on both files: passes.

I didn't run `//python/ray/data:doctest` under Bazel locally.

## Additional information

**Not a duplicate.** I searched open PRs for `union preserve_order` and
`monotonically_increasing_id` and found nothing. #67486 touches
different docstrings.

The commit carries an `@rtd-build` line so the preview renders the
changed API pages. The PR carries the `docstring-only` label.

AI assistance (Claude Code) was used for this PR. I reviewed every
changed 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

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