Skip to content

[Data] Add DataIterator.count() to get dataset/shard size - #64869

Draft
HirokiNariyoshi wants to merge 14 commits into
ray-project:masterfrom
HirokiNariyoshi:data/add-dataiterator-count
Draft

HirokiNariyoshi wants to merge 14 commits into
ray-project:masterfrom
HirokiNariyoshi:data/add-dataiterator-count

Conversation

@HirokiNariyoshi

@HirokiNariyoshi HirokiNariyoshi commented Jul 19, 2026 •

Copy link
Copy Markdown
Contributor

Description

Add a public DataIterator.count() that returns the number of rows the iterator
will yield, so users (notably Ray Train workers that receive a shard via
ray.train.get_dataset_shard()) can size LR schedulers, progress bars, or max
training steps without consuming the iterator.

Previously the only options were exhausting the iterator or calling
it._base_dataset.count().

  • DataIteratorImpl (from Dataset.iterator()) delegates to Dataset.count(),
    reading Parquet file metadata where possible (no data scan).

  • StreamSplitDataIterator (from Dataset.streaming_split()) returns the
    per-shard count for equal=True splits (total_rows // num_splits, exact
    since the output splitter drops the remainder). For equal=False the
    per-split count is only known at runtime, so it raises NotImplementedError
    pointing users to count() on the source Dataset. It also raises if called
    while the split is being actively iterated.

  • The base DataIterator.count() is a @PublicAPI method that raises
    NotImplementedError by default, so existing third-party subclasses are
    unaffected.

Related issues

Closes #37634

Test plan

  • pytest python/ray/data/tests/test_iterator.py::test_iterator_count -v
  • pytest python/ray/data/tests/test_iterator.py::test_iterator_count_after_transform -v
  • pytest python/ray/data/tests/test_streaming_integration.py::test_streaming_split_count_equal -v
  • pytest python/ray/data/tests/test_streaming_integration.py::test_streaming_split_count_not_equal_raises -v
  • pytest python/ray/data/tests/test_streaming_integration.py::test_streaming_split_count_during_execution_raises -v

@HirokiNariyoshi
HirokiNariyoshi requested a review from a team as a code owner July 19, 2026 05:05
Copilot AI review requested due to automatic review settings July 19, 2026 05:05

@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 implements the count() method for DataIterator and its subclasses, allowing users to query the number of rows an iterator will yield without consuming it. It supports standard iterators as well as equal-split streaming iterators, while raising appropriate errors for non-equal splits or during active execution. The review feedback suggests optimizing StreamSplitIterator.count() by checking the _equal attribute locally before making a remote call to the coordinator actor, which avoids a blocking ray.get call and prevents wrapping NotImplementedError in a RayTaskError.

Copilot AI 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.

Pull request overview

Adds a public DataIterator.count() API to let users query how many rows an iterator will yield (notably for Ray Train dataset shards) without consuming the iterator or relying on private state.

Changes:

  • Introduce DataIterator.count() as a @PublicAPI method with documented semantics.
  • Implement count() for Dataset.iterator() via DataIteratorImpl delegating to Dataset.count().
  • Implement count() for Dataset.streaming_split() shards via StreamSplitDataIterator/SplitCoordinator, with tests covering equal splits and error cases.

Reviewed changes

Copilot reviewed 5 out of 5 changed files in this pull request and generated 2 comments.

Show a summary per file
File Description
python/ray/data/iterator.py Adds the new public DataIterator.count() API and documents expected behavior.
python/ray/data/_internal/iterator/iterator_impl.py Implements count() for standard dataset iterators by delegating to the underlying dataset.
python/ray/data/_internal/iterator/stream_split_iterator.py Implements count() for streaming split iterators via the coordinator actor.
python/ray/data/tests/test_iterator.py Adds unit tests validating iterator counts and that count() doesn’t consume iteration.
python/ray/data/tests/test_streaming_integration.py Adds integration tests for streaming split count behavior and error cases.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

@ray-gardener ray-gardener Bot added data Ray Data-related issues community-contribution Contributed by the community labels Jul 19, 2026
Restore the equal-split check inside SplitCoordinator.count() so a direct
actor call fails loudly instead of returning a bogus total_rows // n, and
make the during-execution test deterministic with a slow transform.

Signed-off-by: Hiroki Nariyoshi <[email protected]>

@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 using default effort and found 1 potential issue.

Fix All in Cursor

Reviewed by Cursor Bugbot for commit 43be3c7. Configure here.

Guard SplitCoordinator.count() with self._lock instead of
_dataset_state_lock. self._lock is the lock that actually owns the
executor lifecycle (_try_start_new_epoch), so holding it across the
liveness check and the memoized source count prevents an epoch from
starting mid-count and defeating the "no count during execution" guard.

Signed-off-by: Hiroki Nariyoshi <[email protected]>
@HirokiNariyoshi HirokiNariyoshi changed the title Data/add dataiterator count [Data] Add DataIterator.count() to get dataset/shard size Jul 19, 2026
@HirokiNariyoshi

HirokiNariyoshi commented Jul 30, 2026 •

Copy link
Copy Markdown
Contributor Author

Hi, would appreciate a look when someone has a moment, thanks!

@HirokiNariyoshi

Copy link
Copy Markdown
Contributor Author

Hi, would appreciate a look when someone has a moment, thanks!

@owenowenisme , tagging you since you reviewed my last PR, would appreciate a look when you have a moment, thanks!

Comment on lines +347 to +356
from ray.data.dataset import Dataset

# ``_base_dataset`` has a terminal ``StreamingSplit`` operator; its
# single input dependency is the source to count.
split_op = self._base_dataset._logical_plan.dag
source_dag = split_op.input_dependencies[0]
source_plan = LogicalPlan(source_dag, self._data_context)
source_ds = Dataset._from_parent(self._base_dataset, source_plan)
self._source_row_count = source_ds.count()
return self._source_row_count

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.

why can't you just call self._base_dataset.count()

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.

_base_dataset's plan ends in StreamingSplit, which doesn't propagate num_rows. Calling .count() on it would execute the n-way OutputSplitter and hang or return one split's rows. We count the pre-split source instead and return total // n.

@justinvyu justinvyu 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.

Instead of adding this DataIterator.count() API, can you just call Dataset.count() outside of the training loop?

Example:

ds = ray.data.read_parquet(...)

rows_per_worker = ds.count() // num_workers

trainer = TorchTrainer(..., scaling_policy=ray.train.ScalingPolicy(num_workers=num_workers), datasets={"train": ds})
trainer.fit()

I'd prefer not adding this to the data iterator API if possible, since count() will trigger the full dataset execution if you have any 1:many operators (such as map_batches) in your pipeline, since it's impossible to know the number of rows added/removed from your custom UDFs. Then, you need to coordinate a single execution to calculate count() across the N training workers.

@HirokiNariyoshi

Copy link
Copy Markdown
Contributor Author

Instead of adding this DataIterator.count() API, can you just call Dataset.count() outside of the training loop?

Example:

ds = ray.data.read_parquet(...)

rows_per_worker = ds.count() // num_workers

trainer = TorchTrainer(..., scaling_policy=ray.train.ScalingPolicy(num_workers=num_workers), datasets={"train": ds})
trainer.fit()

I'd prefer not adding this to the data iterator API if possible, since count() will trigger the full dataset execution if you have any 1:many operators (such as map_batches) in your pipeline, since it's impossible to know the number of rows added/removed from your custom UDFs. Then, you need to coordinate a single execution to calculate count() across the N training workers.

Yes, this doesn't avoid the underlying Dataset.count() execution cost. On the "coordinate a single execution across N workers" point, for streaming_split(..., equal=True) shards, count() routes to the shared SplitCoordinator, which computes the source count once, memoizes it, and returns total_rows // num_splits, so N workers calling it don't trigger N executions.

This formalizes what users are already doing via the private workaround in issue #37634
( train_ds._base_dataset.count() // session.get_world_size() )

Counting on the driver works when you still have the Dataset, but inside train_loop_per_worker you only get the shard via ray.train.get_dataset_shard(), so at the moment the only public option is to pass a precomputed size through train_loop_config. This puts count() on the shard itself.

@richardliaw

Copy link
Copy Markdown
Contributor

hm the linked issue doesnt seem to have much traction, why don't we wait for more signal before implementing this?

@HirokiNariyoshi
HirokiNariyoshi marked this pull request as draft August 14, 2026 21:27
@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 Aug 29, 2026
@github-actions github-actions Bot added unstale A PR that has been marked unstale. It will not get marked stale again if this label is on it. and removed stale The issue is stale. It will be closed within 7 days unless there are further conversation labels Aug 29, 2026
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]>

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

community-contribution Contributed by the community data Ray Data-related issues unstale A PR that has been marked unstale. It will not get marked stale again if this label is on it.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Data] Get Dataset size from DataIterator

4 participants