Repository navigation
[Data] Add DataIterator.count() to get dataset/shard size - #64869
HirokiNariyoshi wants to merge 14 commits into
Conversation
Closes ray-project#37634 Signed-off-by: Hiroki Nariyoshi <[email protected]>
Signed-off-by: Hiroki Nariyoshi <[email protected]>
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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@PublicAPImethod with documented semantics. - Implement
count()forDataset.iterator()viaDataIteratorImpldelegating toDataset.count(). - Implement
count()forDataset.streaming_split()shards viaStreamSplitDataIterator/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.
Signed-off-by: Hiroki Nariyoshi <[email protected]>
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]>
There was a problem hiding this comment.
Cursor Bugbot has reviewed your changes using default effort and found 1 potential issue.
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]>
|
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! |
| 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 |
There was a problem hiding this comment.
why can't you just call self._base_dataset.count()
There was a problem hiding this comment.
_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
left a comment
There was a problem hiding this comment.
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.
Signed-off-by: Hiroki Nariyoshi <[email protected]>
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 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. |
|
hm the linked issue doesnt seem to have much traction, why don't we wait for more signal before implementing this? |
|
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. |
…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]>

Description
Add a public
DataIterator.count()that returns the number of rows the iteratorwill yield, so users (notably Ray Train workers that receive a shard via
ray.train.get_dataset_shard()) can size LR schedulers, progress bars, or maxtraining steps without consuming the iterator.
Previously the only options were exhausting the iterator or calling
it._base_dataset.count().DataIteratorImpl(fromDataset.iterator()) delegates toDataset.count(),reading Parquet file metadata where possible (no data scan).
StreamSplitDataIterator(fromDataset.streaming_split()) returns theper-shard count for
equal=Truesplits (total_rows // num_splits, exactsince the output splitter drops the remainder). For
equal=Falsetheper-split count is only known at runtime, so it raises
NotImplementedErrorpointing users to
count()on the sourceDataset. It also raises if calledwhile the split is being actively iterated.
The base
DataIterator.count()is a@PublicAPImethod that raisesNotImplementedErrorby default, so existing third-party subclasses areunaffected.
Related issues
Closes #37634
Test plan
pytest python/ray/data/tests/test_iterator.py::test_iterator_count -vpytest python/ray/data/tests/test_iterator.py::test_iterator_count_after_transform -vpytest python/ray/data/tests/test_streaming_integration.py::test_streaming_split_count_equal -vpytest python/ray/data/tests/test_streaming_integration.py::test_streaming_split_count_not_equal_raises -vpytest python/ray/data/tests/test_streaming_integration.py::test_streaming_split_count_during_execution_raises -v