Skip to content

[Data] Fix unify_tensor_arrays - #60389

Closed
srinathk10 wants to merge 6 commits into
masterfrom
srinathk10/concat_fixes
Closed

srinathk10 wants to merge 6 commits into
masterfrom
srinathk10/concat_fixes

Conversation

@srinathk10

@srinathk10 srinathk10 commented Jan 21, 2026 •

Copy link
Copy Markdown
Contributor

Thank you for contributing to Ray! 🚀
Please review the Ray Contribution Guide before opening a pull request.

⚠️ Remove these instructions before submitting your PR.

💡 Tip: Mark as draft if you want early feedback, or ready for review when it's complete.

Description

Briefly describe what this PR accomplishes and why it's needed.

[Data] Fix unify_tensor_arrays

Problem

When concatenating PyArrow tables containing tensor extension types with varying dimensions (e.g., mixing 2D grayscale and 3D RGB image tensors), PyArrow would fail with:
ArrowTypeError: Array chunks must all be same type

Discovered this issue with #59560

Root Cause

  • Incorrect type deduplication: Using set() to collect distinct types relied on eq, but ArrowVariableShapedTensorType.eq ignores ndim. This incorrectly merged types with different dimensions.
  • Type identity mismatch: PyArrow's C++ validation compares extension types by object identity, not Python's eq. Each converted array created its own type instance, failing validation.

Related issues

Link related issues: "Fixes #1234", "Closes #1234", or "Related to #1234".

Additional information

Optional: Add implementation details, API changes, usage examples, screenshots, etc.

Signed-off-by: Srinath Krishnamachari <[email protected]>
@srinathk10
srinathk10 requested a review from a team as a code owner January 21, 2026 22:26
@srinathk10

Copy link
Copy Markdown
Contributor Author

/gemini summary

@srinathk10

Copy link
Copy Markdown
Contributor Author

/gemini review

@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 provides a critical fix for unify_tensor_arrays to correctly handle concatenation of tensor arrays with different types or shapes. The main issue was that PyArrow's chunked_array validation requires type identity, which was not guaranteed by the previous implementation.

The changes correctly address this by:

  1. Tracking distinct tensor types by their object identity (id()) instead of relying on __eq__.
  2. Ensuring all arrays are re-wrapped with the same unified type instance after unification.
  3. Adding a fix to _pad_shape_with_singleton_axes to handle list-like shape inputs correctly.

New tests have been added that specifically verify that all chunks in a concatenated tensor array share the same type instance, confirming the fix. The changes are well-implemented and the tests are thorough. This is a solid improvement.

@gemini-code-assist

Copy link
Copy Markdown
Contributor

Summary of Changes

This pull request resolves a critical issue in Ray Data's tensor array unification logic, specifically when dealing with PyArrow extension types. The changes ensure that when multiple tensor arrays are combined, the resulting unified arrays consistently share the same underlying PyArrow type instance. This prevents validation errors that could occur during operations like concatenation, especially when handling tensors with varying shapes or dimensions, thereby improving the robustness and reliability of tensor processing within Ray Data.

Highlights

  • PyArrow Type Unification Fix: The core issue addressed is ensuring that when unify_tensor_arrays processes different tensor arrays, the resulting variable-shaped tensor arrays share the exact same type instance (object identity). This is critical because PyArrow's chunked_array validation compares extension types by identity, not just by value equality, preventing ArrowTypeError during concatenation.
  • Improved Type Tracking: The unify_tensor_arrays function now tracks distinct tensor types using a dictionary keyed by object id() instead of a set(). This change correctly accounts for ArrowVariableShapedTensorType instances where __eq__ might ignore ndim, but PyArrow's internal validation requires an exact type match.
  • Consistent Type Wrapping: After converting arrays to variable-shaped tensors, the code now explicitly re-wraps their storage with a single, shared unified_tensor_type instance. This guarantees that all chunks within a chunked_array are perceived by PyArrow as having the identical type instance.
  • Robust Shape Padding: The _pad_shape_with_singleton_axes helper function was updated to explicitly cast the shape argument to a tuple before concatenation, ensuring type consistency and preventing potential issues with non-tuple inputs.
  • New Test Cases: Two new test cases, test_concat_tensor_arrays_share_same_type_instance and test_concat_many_tensor_blocks_with_varying_ndim, have been added to validate the fix. These tests specifically verify that concat operations on varying tensor shapes and dimensions correctly unify types and maintain type instance identity across chunks.

🧠 New Feature in Public Preview: You can now enable Memory to help Gemini Code Assist learn from your team's feedback. This makes future code reviews more consistent and personalized to your project's style. Click here to enable Memory in your admin console.

Changelog
  • python/ray/data/_internal/tensor_extensions/arrow.py
    • Modified to_var_shaped_tensor_array to explicitly name the fields ('data', 'shape') when creating a pa.StructArray for clarity and potential compatibility.
    • Updated _pad_shape_with_singleton_axes to ensure the shape argument is always treated as a tuple, preventing type-related errors during shape padding.
    • Refactored unify_tensor_arrays to track distinct tensor types by object identity (id()) instead of __eq__ to align with PyArrow's strict type validation requirements for chunked_array.
    • Introduced a step in unify_tensor_arrays to re-wrap converted variable-shaped tensor array storage with a single, shared unified_tensor_type instance, ensuring all chunks have identical type instances for PyArrow validation.
  • python/ray/data/tests/test_transform_pyarrow.py
    • Added test_concat_tensor_arrays_share_same_type_instance to verify that concat operations correctly unify tensor arrays and ensure all resulting chunks share the same type instance.
    • Added test_concat_many_tensor_blocks_with_varying_ndim to test the concatenation of blocks containing tensors with alternating dimensions (e.g., 2D and 3D), confirming the robustness of the unification logic.
Activity
  • srinathk10 requested a Gemini summary.
  • srinathk10 requested a Gemini review.

@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 addresses a bug in unify_tensor_arrays concerning the unification of different tensor array types, which previously caused errors in PyArrow. The solution involves correctly identifying distinct type instances by their object ID and ensuring that all unified arrays share a single type instance, a requirement for PyArrow's chunked array validation. The changes are well-reasoned and clearly commented. Furthermore, the new tests effectively target the resolved bug, which is a significant enhancement. My review offers suggestions for improving type safety and making the new tests more robust.

srinathk10 and others added 2 commits January 21, 2026 14:33
Co-authored-by: gemini-code-assist[bot] <176961590+gemini-code-assist[bot]@users.noreply.github.com>
Signed-off-by: Srinath Krishnamachari <[email protected]>
Signed-off-by: Srinath Krishnamachari <[email protected]>
cursor[bot]

This comment was marked as outdated.

Signed-off-by: Srinath Krishnamachari <[email protected]>
@ray-gardener ray-gardener Bot added the data Ray Data-related issues label Jan 22, 2026
@srinathk10 srinathk10 added the go add ONLY when ready to merge, run all tests label Jan 22, 2026
Signed-off-by: Srinath Krishnamachari <[email protected]>
@srinathk10

Copy link
Copy Markdown
Contributor Author

/gemini review

@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 addresses a critical issue in unify_tensor_arrays where PyArrow's C++ validation failed due to type identity mismatches and incorrect deduplication of tensor types with varying dimensions. The changes correctly handle type identity for PyArrow's strict validation, perform logical deduplication, and ensure all arrays are re-wrapped with a single, shared type instance after unification. The logic also correctly pads shapes for variable-shaped tensors with different numbers of dimensions. The addition of comprehensive tests significantly improves confidence in the correctness of the fix.

)
converted = arr.to_var_shaped_tensor_array(ndim=unified_tensor_type.ndim)
# Re-wrap storage with the shared unified type instance
unified_arrs.append(unified_tensor_type.wrap_array(converted.storage))

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.

Which test would fail w/o this?

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.

test_different_ndims_unify_with_padding will fail without this

Signed-off-by: Srinath Krishnamachari <[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 and found 1 potential issue.

unified_arrs.append(arr)
else:
unified_arrs.append(unified_tensor_type.wrap_array(arr.storage))
return unified_arrs

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Mixed v1 and v2 tensor types cause failure

Medium Severity

When unifying arrays with mixed ArrowTensorType (v1) and ArrowTensorTypeV2 (v2) that have identical shapes, the code attempts to wrap one storage format with the other's type at line 1494. Since v1 uses pa.list_ storage while v2 uses pa.large_list storage, calling wrap_array with incompatible storage types fails. The code treats them as logically distinct types but assumes wrap_array can handle the storage, which it cannot when the storage formats differ.

Fix in Cursor Fix in Web

@github-actions

github-actions Bot commented Feb 6, 2026

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 Feb 6, 2026
@github-actions

Copy link
Copy Markdown

This pull request has been automatically closed because there has been no more activity in the 14 days
since being marked stale.

Please feel free to reopen or open a new pull request if you'd still like this to be addressed.

Again, you can always ask for help on our discussion forum or Ray's public slack channel.

Thanks again for your contribution!

@github-actions github-actions Bot closed this Feb 20, 2026
goutamvenkat-anyscale pushed a commit that referenced this pull request Nov 18, 2026
…able-shaped one (#67266)

## Description

`ArrowVariableShapedTensorArray.to_var_shaped_tensor_array()` fails
whenever the target `ndim` is larger than the array's own, so a tensor
column that is fixed-shape in one block and variable-shaped with fewer
dimensions in another can't be concatenated. Two lines were wrong, and
null rows weren't handled:

- `shapes_array.to_pylist()` returns lists, and
`_pad_shape_with_singleton_axes()` does `(1,) * k + shape`, so it raised
`TypeError: can only concatenate tuple (not "list") to tuple`. The
shapes are now converted with `tuple(s)`.
- `pa.StructArray.from_arrays()` was called without field names and
raised `ValueError: Must pass either names or fields`. It now passes
`["data", "shape"]`, the same as the other two places in the file that
build this storage.
- Null rows have a `None` shape, so they are skipped when padding, and
the source null mask is passed to `StructArray.from_arrays()` so they
stay null.
- When every row is null or there are no rows, `pa.array()` infers a
null type for the padded shapes and wrapping the storage fails with
`Incompatible storage type`. The shape type is now passed explicitly
(raised in review).

Added `test_unify_fixed_shaped_with_lower_ndim_variable_shaped`, which
unifies and concatenates a fixed-shape 2D array with a variable-shaped
1D one in both orders, `..._null_rows`, which does the same with a
sliced array that has a null row, and `..._no_valid_rows`, which uses an
all-null and an empty variable-shaped array in both orders. Existing
tests only unified arrays with the same `ndim`, so this branch wasn't
covered. The null-row tests read rows one at a time because `to_numpy()`
on null variable-shaped rows fails on master regardless of this change
(#67236 addresses that).

The 1D tensors come back as `(1, n)` because of the existing
singleton-axis padding. This PR doesn't change that.

## Related issues

Closes #67265

## Additional information

- Not a duplicate: #60389 had the same two changes as part of a larger
rework of `unify_tensor_arrays`, but it was closed as stale in February.
This PR only takes those two lines, handles null rows, and adds tests. I
searched open PRs for `to_var_shaped_tensor_array`,
`_pad_shape_with_singleton_axes`, `unify_tensor_arrays` and
tensor-related keywords; #66997 and #67236 touch other functions.
- Tests, run locally on master `7da1b4c` (`python/ray/data` from source
on a nightly wheel), Python 3.12.3, pyarrow 26.0.0, numpy 2.5.4:
- `pytest python/ray/data/tests/test_tensor_extension.py -k
unify_fixed_shaped_with_lower_ndim`: 21 passed. Without the fix, the
first 9 fail with `TypeError`. With the `None` guard but no mask, the
null-row test fails because the null row becomes valid. Without the
explicit shape type, the 12 `no_valid_rows` cases fail with
`Incompatible storage type`.
- The repro in #67265 and its `repartition(1).take_all()` variants in
both union orders now succeed.
- `pytest python/ray/data/tests/test_tensor_extension.py
python/ray/data/tests/test_transform_pyarrow.py
python/ray/data/tests/test_tensor.py
python/ray/data/tests/test_arrow_block.py
python/ray/data/tests/test_union.py`: 356 passed, 3 skipped, 5 failed.
The 5 fail the same way on unmodified master in my environment:
`test_tensor_array_scalar_cast` (3 formats),
`test_variable_shaped_null_rows_to_pandas_unchanged`, and
`test_tensors_sort[ARROW_NATIVE]`.
  - `pre-commit run --files <changed files>`: passed.
- AI assistance was used to prepare this PR.

---------

Signed-off-by: rayo5o <[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 go add ONLY when ready to merge, run all tests stale The issue is stale. It will be closed within 7 days unless there are further conversation

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Ray fails to serialize self-reference objects

2 participants