Skip to content

[Data] Optimize chunked takes for variable-shaped tensors - #66197

Merged
richardliaw merged 18 commits into
ray-project:masterfrom
OneSizeFitsQuorum:OneSizeFitsQuorum/variable-tensor-take
Sep 30, 2026
Merged

richardliaw merged 18 commits into
ray-project:masterfrom
OneSizeFitsQuorum:OneSizeFitsQuorum/variable-tensor-take

Conversation

@OneSizeFitsQuorum

@OneSizeFitsQuorum OneSizeFitsQuorum commented Sep 16, 2026 •

Copy link
Copy Markdown
Contributor

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.

Variable shape cycle Rows/iteration Iterations (both) Disabled total Enabled total Speedup
Short-row control: (4/8/16, 8) 8,192 50 58.02 s 56.81 s 1.02×
Image: (112/336, 224, 3) 2,048 10 59.21 s 17.24 s 3.43×
Wide: (1000/3000, 1697) 256 3 56.97 s 10.66 s 5.34×
Wide, 12:1 spread: (500/500/1000/6000, 1697) 256 4 67.21 s 13.55 s 4.96×

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 ArrowVariableShapedTensorType in the existing take and local-shuffle paths.

The new variable-shaped plan handles each row's independent shape and payload length:

  1. Prepare: validate per-row shapes, data/shape offsets, buffer bounds, and output capacity; retain source NumPy views and row metadata.
  2. Take: compute offsets and shapes for the selected rows, then copy each row's payload directly into the final output buffer. Variable-shaped gathering needs no intermediate tensor payload array.

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

  • Non-null integer or floating-point tensors with consistent rank and at least two nonempty chunks.
  • Average source row ≥8 KiB and total source payload ≥8 MiB; either source payload averages ≥2 MiB or estimated output averages ≥512 KiB per physical chunk, counting empty chunks.
  • For repeated-row requests, source payload must cover 8 KiB per requested row, or every source row must be ≥8 KiB. Ordinary shuffle permutations satisfy this additional guard.

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):

python -m pytest -q python/ray/data/tests/unit/test_chunked_tensor_take.py python/ray/data/tests/unit/test_chunked_variable_tensor_take.py  # 179 passed
python -m pytest -q python/ray/data/tests/test_batcher.py -k shuffling_batcher_production_tensors  # 6 passed
pyrefly check python/ray/data/_internal/tensor_extensions/chunked_tensor_take.py python/ray/data/tests/unit/test_chunked_variable_tensor_take.py  # 0 errors

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 flag 1:

RAY_DATA_ENABLE_CHUNKED_TENSOR_TAKE=0 python release/nightly_tests/dataset/chunked_tensor_take_benchmark.py --num-cpus 2 --object-store-memory 3221225472

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.

@OneSizeFitsQuorum
OneSizeFitsQuorum marked this pull request as ready for review September 16, 2026 04:03
@OneSizeFitsQuorum
OneSizeFitsQuorum requested a review from a team as a code owner September 16, 2026 04:03

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

@ray-gardener ray-gardener Bot added data Ray Data-related issues community-contribution Contributed by the community labels Sep 16, 2026
@xinyuangui2 xinyuangui2 added the go add ONLY when ready to merge, run all tests label Sep 16, 2026
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)

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.

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.

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.

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.

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.

can we use more rows and blocks, and more iterations so the job time is longer so it is more robust to the noise?

@OneSizeFitsQuorum OneSizeFitsQuorum Sep 30, 2026 •

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.

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.

@richardliaw
richardliaw merged commit 47cd63a into ray-project:master Sep 30, 2026
6 checks passed
@OneSizeFitsQuorum
OneSizeFitsQuorum deleted the OneSizeFitsQuorum/variable-tensor-take branch October 1, 2026 10:27
nadongjun pushed a commit to nadongjun/ray that referenced this pull request Oct 6, 2026
sai-miduthuri added a commit that referenced this pull request Nov 13, 2026
…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]>
sai-miduthuri added a commit that referenced this pull request Nov 13, 2026
…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]>
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 go add ONLY when ready to merge, run all tests

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants