Repository navigation
[Data] Optimize chunked takes for variable-shaped tensors - #66197
richardliaw merged 18 commits into
Conversation
Signed-off-by: OneSizeFitsQuorum <[email protected]>
Signed-off-by: OneSizeFitsQuorum <[email protected]>
There was a problem hiding this comment.
Code Review
This pull request introduces support for variable-shaped tensors in the chunked tensor take fast path. It adds the PreparedVariableShapedTensorTake class and helper functions to validate and prepare variable-shaped tensor chunks, avoiding unnecessary copies or concatenations. Type annotations and imports are updated across transform_pyarrow.py and batcher.py to use the unified PreparedTensorTake type. Additionally, comprehensive unit tests and benchmark workloads are added to verify correctness and measure performance. There are no review comments, so I have no feedback to provide.
Signed-off-by: OneSizeFitsQuorum <[email protected]>
Signed-off-by: OneSizeFitsQuorum <[email protected]>
Signed-off-by: OneSizeFitsQuorum <[email protected]>
Signed-off-by: OneSizeFitsQuorum <[email protected]>
Signed-off-by: OneSizeFitsQuorum <[email protected]>
Signed-off-by: OneSizeFitsQuorum <[email protected]>
Signed-off-by: OneSizeFitsQuorum <[email protected]>
Signed-off-by: OneSizeFitsQuorum <[email protected]>
| source_offsets = np.empty(len(indices), dtype=np.int64) | ||
| shapes = np.empty((len(indices), self.tensor_type.ndim), dtype=np.int64) | ||
| # Sort once to avoid scanning every requested row for every source chunk. | ||
| order = np.argsort(chunk_ids) |
There was a problem hiding this comment.
This chunk-grouping loop (argsort → split at boundaries → handle each group) duplicates _gather_by_sorted_chunk_ids, and the variable path always sorts even when chunk_ids is already in order, e.g. for sorted takes or carry-over. Could we move the grouping into one helper that both paths use? Roughly:
def _iter_chunk_groups(
chunk_ids: np.ndarray,
) -> Iterator[Tuple[int, Union[slice, np.ndarray]]]:
"""Yield ``(chunk_id, positions)`` once per group of rows from the same chunk.
Already-ordered IDs yield contiguous slices without sorting; otherwise
positions come from one argsort. Callers index or scatter by ``positions``
themselves, so requested row order is preserved.
"""
if np.all(chunk_ids[1:] >= chunk_ids[:-1]):
order, sorted_ids = None, chunk_ids
else:
order = np.argsort(chunk_ids)
sorted_ids = chunk_ids[order]
boundaries = np.flatnonzero(sorted_ids[1:] != sorted_ids[:-1]) + 1
start = 0
for stop in chain(boundaries, (len(sorted_ids),)):
if start == stop:
continue
positions = slice(start, stop) if order is None else order[start:stop]
yield int(sorted_ids[start]), positions
start = stop
Then the variable metadata gather becomes:
for chunk_id, positions in _iter_chunk_groups(chunk_ids):
chunk = self.chunks[chunk_id]
rows = local[positions]
source_offsets[positions] = chunk.offsets[rows]
lengths[positions] = chunk.offsets[rows + 1] - chunk.offsets[rows]
shapes[positions] = chunk.shapes[rows]
The fixed path could replace _gather_monotonic_chunk_ids / _gather_by_sorted_chunk_ids with the same loop, and keep its consecutive-rows slice shortcut inside the loop body when positions is a slice.
There was a problem hiding this comment.
Thanks for the suggestion! I've extracted a shared chunk-grouping helper in 3d3565a while preserving the existing sorting strategies: fixed-shaped takes still check for ordered chunk IDs, and variable-shaped takes still sort.
This is primarily a maintainability improvement. Local benchmarks showed about 5–9 μs overhead for small fixed-shaped batches (~5–8%), while end-to-end median differences were within ~2%. Tail latency remains noisy, so I wouldn't claim this is performance-neutral.
I think removing the duplicated grouping logic is a reasonable tradeoff. The relevant unit and batcher tests pass (179 unit tests and 6 batcher tests).
| @@ -1,8 +1,9 @@ | |||
| """Measure local-shuffle tensor ingestion through complete Ray Data pipelines. | |||
There was a problem hiding this comment.
can we use more rows and blocks, and more iterations so the job time is longer so it is more robust to the noise?
There was a problem hiding this comment.
Revised in dd572fd: enabled and disabled now run identical fixed iteration counts per case, with no time-based stopping. The counts are chosen so disabled takes roughly one minute on the local reference machine; enabled finishes after the same work. The doubled rows and 64 source blocks are retained.
I reran all six cases with both flags and verified identical iteration counts and workload settings. For example, variable wide runs 3 iterations in each mode: 56.97 s disabled → 10.66 s enabled (5.34×). Variable image runs 10 in each mode: 59.21 s → 17.24 s (3.43×). All correctness checks passed with no spilling.
The equal-work performance table is now at the top of the PR description. Whole-process time, including startup and warmups, was 441.2 s disabled / 153.1 s enabled.
Signed-off-by: OneSizeFitsQuorum <[email protected]>
Signed-off-by: OneSizeFitsQuorum <[email protected]>
Signed-off-by: OneSizeFitsQuorum <[email protected]>
…conciliation and struct alignment (#66521) (#67995) ## Description Cherry-pick of #66521 (master commit 6fa1a28) onto `releases/2.60.1`. This is a prerequisite for the #67579 pick, #67999. The two sit in a 3-PR stack on `releases/2.60.1` under #68019 (the #67806 pick); merge it with `gh stack merge 68019`. #66521 fixes null-type handling when Ray Data reconciles Arrow schemas across blocks: - A nested field that is all-null in one block and a struct in another crashes `_backfill_missing_fields` with `TypeError: 'pyarrow.lib.DataType' object is not iterable`. - `_reconcile_field` reconciles `[null, list<null>, list<int64>]` to `null` instead of `list<int64>`. Without it, two of the tests #67579 adds fail on this branch. Both are the case where one block's tensor column is fixed-shape, another's is null, and a third's has a different shape. They fail with `ArrowTypeError: Casting from 'extension<ray.data.arrow_variable_shaped_tensor<...>>' to different extension type 'extension<ray.data.arrow_tensor_v2<...>>' not permitted`. ## Related issues Related to #66521. Needed by the #67579 pick. ## Additional information ### Cherry-pick details Applied cleanly with `git cherry-pick -x`. It has the same 2 files, +233/-30, and the same `git patch-id --stable` as the master commit. After the pick, `unit/test_transform_pyarrow.py` is identical to master at 6fa1a28. `transform_pyarrow.py` differs only by #66197's rename of `PreparedChunkedTensorTake` to `PreparedTensorTake`. #66197 is the only master commit that touched these files between the branch cut and #66521, and this change doesn't depend on it. To find what #67579 needed, I applied each master-only commit that touched `transform_pyarrow.py` or the tensor extensions on top of the #67579 pick: #66521, #65961, #66508, #66197, #66703 and #66522. #66521 alone makes the two failing tests pass, and none of the others changes the result. Not a duplicate: this branch doesn't contain #66521, and no PR on any branch references it. ### Testing | Command | Result | |---|---| | `pre-commit run --files <the 2 changed files>` | Passed | | `pytest python/ray/data/tests/unit/test_transform_pyarrow.py python/ray/data/tests/test_transform_pyarrow.py python/ray/data/tests/test_arrow_block.py` | 145 passed, 3 skipped | The #67579 pick's description has the results with both picks applied. I ran these against the Ray 2.60.0 release wheel, with this branch's `python/ray/data` and `python/ray/tests` copied over it. The wheel was built from `releases/2.60.0` at b7f4259, and its Python sources match `releases/2.60.1` except for `_version.py`. The environment was Python 3.12 with pandas 2.3.3 and pyarrow 23.0.1, the versions CI pins. Building Ray from source for `bazel test` wasn't practical on my machine. AI assistance was used to prepare this cherry-pick. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Signed-off-by: dragongu <[email protected]> Signed-off-by: Sai Miduthuri <[email protected]> Co-authored-by: dragongu <[email protected]>
…conciliation and struct alignment (#66521) (#68024) ## Description Cherry-pick of #66521 (master commit 6fa1a28) onto `releases/2.59.2`. **Bottom of a 3-PR stack on `releases/2.59.2`:** this PR, then #68025 (the #67579 pick), then #68026 (the #67806 pick). Merge the stack with `gh stack merge 68026`, which lands all three in order. This is a prerequisite for the #67579 pick. #66521 fixes null-type handling when Ray Data reconciles Arrow schemas across blocks: - A nested field that is all-null in one block and a struct in another crashes `_backfill_missing_fields` with `TypeError: 'pyarrow.lib.DataType' object is not iterable`. - `_reconcile_field` reconciles `[null, list<null>, list<int64>]` to `null` instead of `list<int64>`. Without it, two of the tests #67579 adds fail on this branch. Both are the case where one block's tensor column is fixed-shape, another's is null, and a third's has a different shape. They fail with `ArrowTypeError: Casting from 'extension<ray.data.arrow_variable_shaped_tensor<...>>' to different extension type 'extension<ray.data.arrow_tensor_v2<...>>' not permitted`. ## Related issues Related to #66521. Needed by the #67579 pick. The same pick for 2.60.1 is #67995. ## Additional information ### Cherry-pick details Applied cleanly with `git cherry-pick -x`. It has the same 2 files, +233/-30, and the same `git patch-id --stable` as the master commit. The two files differ from master at 6fa1a28 only by master commits this change doesn't use: #66197, #66269 and #64961 in `transform_pyarrow.py`, and #66269 in `unit/test_transform_pyarrow.py`. Not a duplicate: this branch doesn't contain #66521, and no PR against `releases/2.59.2` references it. #67995 picks the same commit onto `releases/2.60.1`. ### Testing | Command | Result | |---|---| | `pre-commit run --files <the 2 changed files>` | Passed | | `pytest python/ray/data/tests/unit/test_transform_pyarrow.py python/ray/data/tests/test_transform_pyarrow.py python/ray/data/tests/test_arrow_block.py` | 123 passed | The #67579 pick's description, #68025, has the results with the stack applied. I ran these against the Ray 2.59.1 release wheel, with this branch's `python/ray/data` and `python/ray/tests` copied over it. The wheel was built from `releases/2.59.1` at 7bdaad7, and its Python sources match `releases/2.59.2` except for `_version.py`. The environment was Python 3.12 with pandas 2.3.3, pyarrow 23.0.1 and numpy 2.1.3, the versions CI pins on this branch. Building Ray from source for `bazel test` wasn't practical on my machine. AI assistance was used to prepare this cherry-pick. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Signed-off-by: dragongu <[email protected]> Signed-off-by: Sai Miduthuri <[email protected]> Co-authored-by: dragongu <[email protected]>
Performance
Local complete generation/local-shuffle pipeline on
dd572fdb31. Enabled and disabled run the same fixed iterations and rows per iteration. The table compares cumulative timed seconds (correctness warmup excluded); speedup is disabled total / enabled total.(4/8/16, 8)(112/336, 224, 3)(1000/3000, 1697)(500/500/1000/6000, 1697)Fixed counts target roughly one minute per disabled case on this machine; enabled runs finish after the same work. Counts are never adjusted using elapsed time or the feature flag. All samples were retained. The short-row control stays on the standard path.
Environment: float32, NumPy 2.4.6 / PyArrow 19.0.1, 2 Ray CPUs, 3 GiB object store, 64 source blocks. Batch/buffer sizes: 32/256 for image, 8/64 for wide, 64/256 for short. Disabled and enabled ran sequentially in separate processes. These are local results, not cloud release regression evidence.
Summary
Extends the fixed-shaped tensor optimization from #64961 to
ArrowVariableShapedTensorTypein the existing take and local-shuffle paths.The new variable-shaped plan handles each row's independent shape and payload length:
Adds variable-specific regression coverage for sliced storage, empty rows/buffers, malformed shapes/offsets, output bounds, repeated indices, and production local shuffle. The existing release benchmark gains full per-row shape configuration and four variable workloads: short, image, wide, and skewed-wide.
Variable-shaped eligibility
These higher gates account for per-row shape validation and Python slice copies. They are empirical and do not guarantee gains, especially for repeated tiny rows in highly skewed sources.
Validation
Checks on
5f1eb71422(NumPy 2.4 / PyArrow 19):Full local release checks on
dd572fdb31: all six cases (four variable workloads and two fixed controls) passed correctness warmup and their fixed timed iterations under both flags, with identical workload settings and no spilling. Including startup and warmups, whole-process elapsed time was disabled 441.2 s / enabled 153.1 s. Run below, then repeat with flag1:Fixed-count checks confirmed identical defaults/overrides under both flags regardless of iteration speed. All applicable hooks passed.
Related to #64960; extends #64961 to variable shapes. The September 16 open-PR search found no duplicate implementation. AI assistance was used in implementation and validation.