Repository navigation
[Data] Keep tensor columns with null rows mergeable across blocks - #67579
Conversation
…here Problem: - Since pandas UDF batches became Arrow blocks (#61733), a column whose value is a stacked array in one row, a ragged list in another and None in a third gets three storage types across one-row blocks: tensor, pickled object and null. - Building a batch across those blocks failed: schema reconciliation refused "columns with both objects and tensors", and a tensor column with a null arm reached the tensor unifier, which rejects null. Change: - An object arm wins the reconciliation. Tensor rows join as one ndarray each; the object concat path already does that. - A tensor column with a null arm becomes an object column too, because a tensor array cannot hold null rows: to_numpy() fails on them. PyArrow unifies null with a tensor type on its own, so unify_schemas demotes those fields after either unification path. - The refusal is gone. Unit tests cover both unifications and the concat, and an end-to-end test runs the one-row-block scenario. Co-Authored-By: Claude Fable 5.1 <[email protected]> Signed-off-by: Marwan Sarieddine <[email protected]>
|
Warning You have reached your daily quota limit. Please wait up to 24 hours and I will start processing your requests again! |
Problem: - When PyArrow's first unification fails, for example because two tensor blocks have different shapes, unify_schemas rewrites the null arms with the reconciled tensor type before the final unification. - The demotion to objects then saw no null arm, so concat handed the null chunk to the tensor unifier, which rejects it. Change: - Demote against the schemas as they were before the overrides. - Both null-arm tests now also cover tensor blocks of differing shape. Co-Authored-By: Claude Fable 5.1 <[email protected]> Signed-off-by: Marwan Sarieddine <[email protected]>
rayo5o
left a comment
There was a problem hiding this comment.
Some numbers for the decisions section, in case they help pick between objects and tensors with null rows.
The cost of the demotion is per batch, not per null row. 8 blocks of 64 × 224×224×3 float32 (294 MiB), with and without one extra 1-row null block, through concat and then to_batch_format("numpy"). GPU4 (shared Linux node, 8 CPUs), PR head 908b003, 7 runs each, median:
| no null block | + one null block | |
|---|---|---|
concat |
~0 s | 0.26 s |
| to numpy | 0.025 s | 0.23 s |
| numpy column | float32 (512, 224, 224, 3) |
object (513,) |
On the merge base 1629bfb the null case raises Trying to unify unsupported tensor type: null, so this is what not erroring costs, not a slowdown against master.
iter_torch_batches still fails on any batch that has a None:
RuntimeError: Numpy array of object dtype cannot be converted to a Torch Tensor. This may because the numpy array is a ragged tensor--it contains items of different sizes. ...
The rows aren't ragged, one is missing, so the hint points the user at the wrong fix (a collate_fn for ragged shapes). If objects stay the choice, could this error mention None when the object column holds one? I didn't touch that path or measure the tensor-with-null-rows alternative.
Tests on 908b003 (WSL, no polars or Pillow installed): the first group in the description gives 162 passed, 3 skipped (polars). test_tensor_extension.py, unit/test_object_extension.py, unit/test_arrow_type_conversion.py, test_batcher.py and test_strict_mode.py give 331 passed, 5 failed. Four are tensor tests I've seen fail on master before (test_tensor_array_scalar_cast ×3, test_variable_shaped_null_rows_to_pandas_unchanged); test_strict_read_schemas needs Pillow and fails the same way on 1629bfb.
Problem: - A tensor column with a null arm was demoted to pickled objects for the whole batch. One None row made every row next to it pay for pickling, and the column type depended on which rows shared a batch. - Tensor arrays could already carry null rows, but to_numpy() failed on them with "buffer is too small", so nothing could read them. Change: - unify_tensor_arrays turns a null-typed chunk into null rows of the unified tensor type, so unify_schemas no longer demotes the field. - Both tensor array classes convert null rows to numpy as one ndarray per row with None for the null row, and build from numpy input that holds None. - TensorArray accepts None rows, so a tensor column with null rows converts to pandas and back. - The torch conversion error names None rows instead of blaming ragged shapes. Co-Authored-By: Claude Fable 5.1 <[email protected]> Signed-off-by: Marwan Sarieddine <[email protected]>
|
Thanks for the numbers, they changed the decision: the column now stays a tensor column with null rows (6cd32ed), and the torch error names the None rows. Your four tensor failures and the Pillow one are environment-only here too. |
Problem: - to_var_shaped_tensor_array rebuilt the struct storage without a mask, so a null row of the list storage read as a valid row over a neighbour's data after shape promotion. Change: - Pass the array's null mask to the struct storage. Co-Authored-By: Claude Fable 5.1 <[email protected]> Signed-off-by: Marwan Sarieddine <[email protected]>
rayo5o
left a comment
There was a problem hiding this comment.
Re-ran on 8a7f862 and the null block no longer costs anything. Same setup as before (8 blocks of 64 × 224×224×3 float32 plus one 1-row null block), GPU4, 7 runs each, median: concat ~0 s, to numpy 0.026 s against 0.025 s without the null block, down from 0.26 s + 0.23 s on 908b003. The column stays ArrowTensorTypeV2, and the torch error now names the null row.
I also pushed one-row None blocks through other paths with V1 and V2 tensors: iter_batches (numpy and pandas batches), a pandas UDF, to_pandas, take_all, repartition, a ragged column, and a parquet write and read. Row values and None positions come back right in all eight; on 1629bfb seven of them raised.
Not blocking: with arrow_fixed_shape_tensor_format = ARROW_NATIVE, to_pandas, the pandas UDF case and the parquet round trip still fail, as they do on 1629bfb (the pandas UDF one now says Array contains nulls, explicitly pass allow_nulls=true). Fine as a follow-up if native tensors aren't meant to be covered here.
Tests on 8a7f862 (WSL): the files from the description plus test_torch_tensor_utils.py and test_pandas_block.py give 584 passed, 7 failed. The 7 are ones I've seen fail on master before, or need Pillow or scipy, which aren't installed here.
|
Ran the repro from #67200 on 8a7f862 and it passes: with a null row in a fixed-shape or ragged tensor column, So this likely fixes #67200, and overlaps #67236, which makes the same two |
Problem: - A variable-shaped row can be null in its data or shape child rather than in the struct slot. to_numpy() only checked the struct slot, so such a row read a neighbour's bytes or raised. Change: - A row is null when the struct slot, the data child or the shape child is null. Same rule as PR #67236. Co-Authored-By: Claude Fable 5.1 <[email protected]> Signed-off-by: Marwan Sarieddine <[email protected]>
|
Thanks for connecting the issues. The body now says this fixes #67200 and how it relates to #67236 and #67293. #67236 covers the read side and makes |
|
Thanks for running the eight paths. On the native format: for me |
There was a problem hiding this comment.
Based on discussion with @marwan116:
Silently merging object and tensor type batches can lead to subtle divergences in dtypes from the schema and this can be a footgun.
Instead we discussed two options:
- Keep the merge, but make it loud - basically loudly log that we are merging types, log which columns, their original types
- Raise a clear error about why schema unification failed, allowing users to know exactly which combination of columns and specific types failed unification, rather than the entire schemas. This should be more informative than the current behaviour which can be ambiguous:
ValueError: Found columns with both objects and tensors
----------------
Schemas:
----------------
[id: int64
pts: extension<ray.data.arrow_pickled_object<ArrowPythonObjectType>>, id...
Problem: - Merging a column that is a tensor in one block and pickled objects in another silently turned the whole column into pickled objects, with no sign to the user that the type was lost. Change: - Restore the error for that case. A follow-up PR extends its message with the columns and the types found. - Keep the null-row support: a tensor column next to a null block stays a tensor column, with None for the missing rows. Co-Authored-By: Claude Fable 5.1 <[email protected]> Signed-off-by: Marwan Sarieddine <[email protected]>
|
Scope change after discussion with the Data team: 90ee5fd restores the error for a column that is a tensor in one block and pickled objects in another. Merging those silently turned every row into a pickled object and lost the type, so users should make every row the same kind instead, for example by returning ragged arrays as nested lists. A follow-up PR by ayushk7102 extends that error with the columns and types found. The null-row support stays: a tensor column next to a null block remains a tensor column, with None for the missing rows. The body and title now describe only that. |
…tensor-object-null
There was a problem hiding this comment.
Thanks for working on this! It seems like there are only a few edge cases that can still cause issues:
- A null-free slice after a null row reads shifted rows in
to_numpy, silently with default settings
Repro:
import numpy as np
from ray.data.extensions import ArrowTensorArray
tensors = ArrowTensorArray.from_numpy([np.array([0]), None, np.array([2]), np.array([3])])
tensors[2:3].to_numpy() # [[3]], expected [[2]]
It seems like this is because when merging nulls into a tensor block, the nulls do not contribute to the offset calculation, and all succeeding elements in the array find themselves shifted ahead.
- Under
ARROW_NATIVE, a UDF's None rows now become native null rows that read back as zeros. Master kept them as None.
Repro:
import numpy as np, ray
from ray.data import DataContext
from ray.data._internal.tensor_extensions.arrow import FixedShapeTensorFormat
DataContext.get_current().arrow_fixed_shape_tensor_format = FixedShapeTensorFormat.ARROW_NATIVE
ds = ray.data.from_items([{"x": 0}]).map_batches(lambda b: {"x": [np.array([1, 1]), None]})
ds.take_batch()["x"]
# PR: [[1 1], [0 0]] the None row comes back as zeros
# master: [array([1, 1]), None] correct
When you read batches in numpy format (either by iter_batches(batch_format="numpy") or take_batch` which uses numpy format by default, the conversion is handled using pyarrow's native tensor class. This turns the whole column into one dense numpy array and ignores which rows are null.
| # Handle special cases in priority order | ||
|
|
||
| # 1. Tensor fields | ||
| # 1. Tensor fields. A null arm becomes null rows of the tensor type. |
There was a problem hiding this comment.
Nit: Can we clarify what we mean by "null arm"?
There was a problem hiding this comment.
Fair, "arm" was my shorthand. Reworded in 4576963.
The case:
block 1: {"img": [t0, t1]} # type: tensor
block 2: {"img": [None, None]} # type: nullThese now unify to the tensor type. Block 2 becomes two null rows. The comment says that in plain words now.
| """One ndarray view per row and ``None`` for each null row. A dense | ||
| array has no slot for a missing row, so this is the only shape the | ||
| column can take once it holds one.""" |
There was a problem hiding this comment.
Nit: I am a little unclear on what it means that a "dense array has no slot for a missing row." Can we re-word this to specifiy what we mean here, e.g. what is a slot etc?
There was a problem hiding this comment.
Agreed, "slot" was vague. Reworded in 4576963.
The idea:
from_numpy([t0, t1, t2]).to_numpy() # shape (3, 2, 2), one dense array
from_numpy([t0, None, t2]).to_numpy() # ?A dense array has no way to say "row 1 is missing". Every row must be a tensor. So we return an object array instead: [t0, None, t2], one view per row.
| # here, so build the correctly typed empty buffer directly. | ||
| values = np.empty((0,) + self.element_shape, dtype=self._dtype) | ||
| else: | ||
| elif values.dtype != object or all(v is not None for v in values): |
There was a problem hiding this comment.
| elif values.dtype != object or all(v is not None for v in values): | |
| elif values.dtype != object or array.null_count == 0 : |
Nit: could we do this to avoid iterating all of the elements in the array? Since values is built from array this should be valid.
There was a problem hiding this comment.
Took it as is, thanks. In 4576963.
values comes straight from array. A None in values can only come from a null row in array. So:
all(v is not None for v in values) # walks every row
array.null_count == 0 # same answer, Arrow already knows it…rmat Problem: - A null-free slice taken after a null row read shifted rows in the dense to_numpy path, and a longer slice ran off the buffer. The path computed its start as slice position times tensor size, but a null row holds no values, so later offsets are not evenly spaced. - Under ARROW_NATIVE a None row became a native null row that read back as zeros, because pyarrow's to_numpy_ndarray() ignores the validity bitmap. Change: - The dense path starts from the slice's first list offset, which is absolute into the values buffer. - native_tensor_array_to_numpy() blanks null rows with None and replaces to_numpy_ndarray() at every native read site. The chunked reader joins row by row when the column has a null. - Reword the "null arm" and "slot" comments and use the Arrow null count in the pandas conversion. - Tests for the slice, the native helper, and the end-to-end case in all three tensor formats. Co-Authored-By: Claude Fable 5.1 <[email protected]> Signed-off-by: Marwan Sarieddine <[email protected]>
|
Good catches, thanks. Both were real. Both sat on the fast path, where every row used to have values. Fixed in 4576963. The slice bug. Take Row i starts at Now slice The old code didn't look at the offsets. It assumed row 2 starts at 2 × 1 = 2, which is The native bug. pyarrow's |
Problem: the check that turns a column of ndarrays into a tensor column only looked at element 0. A batch whose first row was None became a list<double> column, and concatenating it with the tensor blocks next to it raised "Trying to unify unsupported tensor type". Two more places assumed a tensor in a null row's place: the pandas TensorArray dtype read element 0, and unifying a chunk of only null rows into a ragged column tried to build tensors from None. Change: - The tensor checks in tensor_extensions/utils.py look at the first element that is not None, and skip None rows when comparing shapes. - TensorArray.dtype takes dtype and shape from the first tensor when the storage is an object array with null rows. - unify_tensor_arrays turns a chunk of only null rows into nulls of the unified type, and the V1 to_var_shaped_tensor_array does the same. - Tests cover a None at the start, end and whole of a batch, fixed and ragged, one and two blocks, in every tensor format, read back as numpy, pandas and through a second pandas UDF. Co-Authored-By: Claude Fable 5.1 <[email protected]> Signed-off-by: Marwan Sarieddine <[email protected]>
ayushk7102
left a comment
There was a problem hiding this comment.
Thanks for working on this @marwan116 , LGTM!
…or (#67647) ## Summary When blocks can't be merged because a column has different types in different blocks, the error now names every conflicting column and the types it had, with block counts. Before, the message was cut off at 200 characters, which usually hid the type causing the conflict. ## Before ``` ArrowConversionError: Error converting data to Arrow: Failed to unify schemas: Found columns with both objects and tensors: pts ---------------- Schemas: ---------------- [id: int64 pts: extension<ray.data.arrow_pickled_object<ArrowPythonObjectType>>, id... ``` - `ArrowConversionError` truncates its message to 200 characters, so the raw schema dump stops after the first schema and the conflicting tensor type never appears. - The object/tensor check in `_reconcile_diverging_fields` raises on the first conflicting column, so other conflicting columns go unreported. - A printed `pa.Schema` shows extension types as `extension<ray.data.arrow_tensor_v2<...>>`, without shape or dtype. ## After ``` ArrowSchemaUnificationError: Failed to unify schemas across 3 blocks. Columns with incompatible types: - 'pts': extension<ray.data.arrow_pickled_object<ArrowPythonObjectType>> (1 block), ArrowTensorTypeV2(shape=(2, 4, 3), dtype=double) (1 block), null (1 block) Cause: Found columns with both objects and tensors: pts ``` - `concat` raises the new `ArrowSchemaUnificationError`, a subclass of `ArrowConversionError` that skips the truncation. Existing `except ArrowConversionError` handlers (e.g. the pandas fallback in `block.py`) still catch it. - The message lists each column whose type differs across blocks (up to 20), with each type's `str()` (tensor shape and dtype included) and how many blocks had it. - The object/tensor `ValueError` now names all conflicting columns, not just the first. - The new code only runs after unification has already failed, so the success path is unchanged. ## Subsystems Block / data format ## Related work Not a duplicate. #67579 makes tensor columns with null rows mergeable and notes that "a follow-up PR extends that error with the columns and types found". This is that follow-up. No other open PR changes this error message. ## Testing ``` pytest python/ray/data/tests/unit/test_transform_pyarrow.py 118 passed ``` - Added `test_concat_objects_and_tensors_error_lists_columns_and_types`: two conflicting columns, checks the header, that both columns are named, and the full type list for each. - Existing tests matching `Failed to unify schemas` and `Found columns with both objects and tensors` still pass. - Manual repro (pandas UDF returning a ragged list, a stacked array, and `None` across three blocks) produces the "After" message above. AI assistance ([Claude Code](https://claude.com/claude-code)) was used to write this change. I reviewed every line and ran the tests above. --------- Signed-off-by: Ayush Kumar <[email protected]>
| in the fixed-size storage and reads back as whatever that slot holds, | ||
| usually zeros. | ||
| """ | ||
| dense = array.to_numpy_ndarray() |
There was a problem hiding this comment.
On pyarrow 26 this line raises before the null handling below runs: ArrowInvalid: Array contains nulls, explicitly pass allow_nulls=true to leave them undefined. to_numpy_ndarray() takes no such argument. In a clean venv with the same two-row array ([[1, 1], None], fixed_shape_tensor(int64, [2])), 23.0.1, 24.0.0 and 25.0.0 return [[1, 1], [0, 0]], and 26.0.0 raises. CI pins 23.0.1, so it doesn't show there.
On 1651891 with pyarrow 26, test_batches_keep_tensor_column_with_missing_rows[ARROW_NATIVE] fails, and the repro from the review ([np.array([1, 1]), None] from a UDF) raises in take_batch() and batch_format="numpy". Master gives [array([1, 1]), None] in the same environment. Checking null_count first and not going through to_numpy_ndarray() when there are nulls would avoid it.
Signed-off-by: Elliot Barnwell <[email protected]>
There was a problem hiding this comment.
Cursor Bugbot has reviewed your changes and found 1 potential issue.
❌ Bugbot Autofix is OFF. To automatically fix reported issues with cloud agents, have a team admin enable autofix in the Cursor dashboard.
Reviewed by Cursor Bugbot for commit bdc6f1e. Configure here.
| is_valid = np.asarray(array.is_valid()) | ||
| return create_ragged_ndarray( | ||
| [dense[i] if is_valid[i] else None for i in range(len(array))] | ||
| ) |
There was a problem hiding this comment.
Native null conversion fails on PyArrow 26
High Severity
native_tensor_array_to_numpy calls to_numpy_ndarray() before applying the validity bitmap. On PyArrow 26 that API raises ArrowInvalid when the array contains nulls, so the None-row path never runs and native tensor batches, row iteration, and unification crash instead of returning None for missing rows.
Additional Locations (2)
Reviewed by Cursor Bugbot for commit bdc6f1e. Configure here.
## Description #67579 made `native_tensor_array_to_numpy` return `None` for the null rows of a pyarrow-native tensor column. It calls `to_numpy_ndarray()` first, which reads null rows as zeros on pyarrow 23–25 but raises `ArrowInvalid: Array contains nulls` on pyarrow 26. So with `ARROW_NATIVE` and pyarrow 26, any batch with a null tensor row now fails, where it returned `None` before #67579. This converts the same storage without its validity bitmap, which gives the dense array 23–25 returned on every version, and then fills in `None` as before. ## Related issues Follow-up to #67579 ([review comment](#67579 (comment))). ## Additional information - Not a duplicate: no open PR or issue changes this function. #67293 handles native null rows elsewhere. - Tests: Ray CI runs Data tests on pyarrow 17 and 23 (the nightly pyarrow job is disabled), so the failure doesn't show there. Locally on pyarrow 26, master fails 19 `ARROW_NATIVE` null-row tests in `test_tensor_extension.py` and `test_arrow_block.py`; they pass with this change. Eight related test files on pyarrow 17, 23 and 26 show no other change. <details> <summary>Tests that also fail on unmodified master</summary> - `test_tensor_array_scalar_cast` x3 (all versions) - `test_tensors_sort[ARROW_NATIVE]` (pyarrow 26) - `test_tensor_array_boolean_slice_pandas_roundtrip` x6 (pyarrow 17) </details> - AI assistance was used to prepare this PR. Signed-off-by: rayo5o <[email protected]>
… in Arrow-backed to_pandas (#67566) (#67994) ## Description Cherry-pick of #67566 (master commit af8f74e) onto `releases/2.60.1`. Since 2.56, `ArrowBlockAccessor.to_pandas()` maps each column to `pd.ArrowDtype`. Before pandas 3.1, `pd.ArrowDtype.__from_arrow__` casts every column, even to its own type. Arrow's cast of a nested null child resizes that child to the number of rows, so elements disappear. For example, a `list<null>` column `[[None, None], [None]]` comes back as `[[None, None], []]`. When the batch goes back to Arrow untouched, it fails instead with `ArrowInvalid: Length spanned by list offsets (3) larger than values array (length 2)`. Users hit this with sparse list columns. #67566 maps types that nest a null type to a `pd.ArrowDtype` subclass that skips the identity cast. ## Related issues Related to #67566. ## Additional information ### Cherry-pick details Applied cleanly with `git cherry-pick -x`. It has the same 2 files, +89/-2, and the same `git patch-id --stable` as the master commit. No prerequisite commits are missing. The new code hooks into `_arrow_backed_pandas_dtype`, which this branch already has from the #66578 pick (#66644). The two files differ from master at af8f74e only by master commits this change doesn't use. This PR and the #67579 pick both edit `arrow_block.py` and `test_arrow_block.py`. I applied this commit on top of the #66521 and #67579 picks, and it merges cleanly and passes the tests below. Not a duplicate: this branch doesn't contain #67566, and no PR against `releases/2.60.1` references it. ### Testing | Command | Result | |---|---| | `pre-commit run --files <the 2 changed files>` | Passed | | `pytest python/ray/data/tests/test_arrow_block.py python/ray/data/tests/test_pandas_block.py` | 106 passed | | `pytest python/ray/data/tests/test_arrow_block.py`, run with this PR's tests against the branch code without the fix | 3 failed (the 3 new nested-null cases of `test_arrow_block_to_pandas_preserves_arrow_types_through_roundtrip`), 31 passed | | `pytest test_arrow_block.py test_pandas_block.py test_tensor_extension.py`, with the #66521 and #67579 picks also applied | 397 passed | 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: Marwan Sarieddine <[email protected]> Signed-off-by: Sai Miduthuri <[email protected]> Co-authored-by: Marwan Sarieddine <[email protected]> Co-authored-by: Claude Opus 5.5 <[email protected]>
… in Arrow-backed to_pandas (#67566) (#68022) ## Description Cherry-pick of #67566 (master commit af8f74e) onto `releases/2.59.2`. Since 2.56, `ArrowBlockAccessor.to_pandas()` maps each column to `pd.ArrowDtype`. Before pandas 3.1, `pd.ArrowDtype.__from_arrow__` casts every column, even to its own type. Arrow's cast of a nested null child resizes that child to the number of rows, so elements disappear. For example, a `list<null>` column `[[None, None], [None]]` comes back as `[[None, None], []]`. When the batch goes back to Arrow untouched, it fails instead with `ArrowInvalid: Length spanned by list offsets (3) larger than values array (length 2)`. Users hit this with sparse list columns. #67566 maps types that nest a null type to a `pd.ArrowDtype` subclass that skips the identity cast. ## Related issues Related to #67566. The same pick for 2.60.1 is #67994. ## Additional information ### Cherry-pick details Applied with `git cherry-pick -x`. `arrow_block.py` merged cleanly. `test_arrow_block.py` conflicted only on its import list: master also imports `ArrowRow` there, from a master-only change that this branch's tests don't use. I added only #67566's `_arrow_backed_pandas_dtype` import. The added and removed lines are identical to the master commit, and `git patch-id` differs only because of that context line. No prerequisite commits are missing. The new code hooks into `_arrow_backed_pandas_dtype`, which this branch already has from the #66578 pick (#66617). The two files differ from master at af8f74e only by master commits this change doesn't use. This PR and the #67579 pick (#68025) both edit `arrow_block.py` and `test_arrow_block.py`. This commit merges cleanly with the #66521, #67579 and #67806 stack and passes the tests below. Not a duplicate: this branch doesn't contain #67566, and no PR against `releases/2.59.2` references it. #67994 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/test_arrow_block.py python/ray/data/tests/test_pandas_block.py` | 87 passed | | `pytest python/ray/data/tests/test_arrow_block.py`, run with this PR's tests against the branch code without the fix | 3 failed (the 3 new nested-null cases of `test_arrow_block_to_pandas_preserves_arrow_types_through_roundtrip`), 24 passed | | `pytest test_arrow_block.py test_pandas_block.py test_tensor_extension.py`, with the #66521, #67579 and #67806 stack also applied | 365 passed | 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: Marwan Sarieddine <[email protected]> Signed-off-by: Sai Miduthuri <[email protected]> Co-authored-by: Marwan Sarieddine <[email protected]> Co-authored-by: Claude Opus 5.5 <[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]>
…ble across blocks (#67579) (#67999) ## Description Cherry-pick of #67579 (master commit 1acc2c3) onto `releases/2.60.1`. **Middle of a 3-PR stack on `releases/2.60.1`:** #67995 (the #66521 pick), then this PR, then #68019 (the #67806 pick, which fixes this change on pyarrow 26). Merge the stack with `gh stack merge 68019`, which lands all three in order. Since #61733 (2.56), a batch that spans blocks whose tensor column is null in one of them fails with `ValueError: Trying to unify unsupported tensor type: null`. A pandas UDF that returns `None` for some rows and an ndarray for others is enough to hit it. It worked in 2.55. #67579 lets tensor arrays carry null rows, so these blocks merge, the column stays a tensor column, and missing rows read back as `None`. ## Related issues Related to #67579. Depends on #67995, the #66521 pick. ## Additional information ### Cherry-pick details Applied with `git cherry-pick -x`. 9 of the 10 files merged cleanly. `tensor_extensions/pandas.py` conflicted only on the `TensorArray.dtype` docstring. Master had reformatted it in #67539 (ruff D212/D200), which isn't on this branch. I kept this branch's docstring and added the PR's one new line, `first = _first_non_null(self._tensor)`. The added and removed lines are identical to the master commit. `git patch-id` differs only because of that docstring context line. Prerequisite: #66521. Without it, `test_arrow_concat_tensor_with_null_keeps_tensor_type[last_shape1]` and `test_unify_schemas_tensor_with_null_keeps_tensor_type[other_shape1]` fail on this branch. These are the cases where the tensor blocks have different shapes. I applied each master-only commit that touched `transform_pyarrow.py` or the tensor extensions between the branch cut and #67579 on top of this pick. #66521 alone fixes both tests. The other files differ from master only by master commits this change doesn't use. Not a duplicate: this branch doesn't contain #67579, and no PR against `releases/2.60.1` references it. ### Testing All of these ran with the #66521 pick applied underneath. | Command | Result | |---|---| | `pre-commit run --files <the 10 changed files>` | Passed | | `pytest test_arrow_block.py test_tensor_extension.py test_torch_tensor_utils.py unit/test_transform_pyarrow.py test_transform_pyarrow.py test_pandas_block.py` (under `python/ray/data/tests/`) | 526 passed, 3 skipped | | The same test files from this PR, against the code with only #66521 (no #67579) | 60 failed, 155 passed, and `test_tensor_extension.py` fails to collect, because it imports a helper this PR adds | | This pick directly on `releases/2.60.1`, without #66521 | The 2 tests above fail | | `test_arrow_block.py test_pandas_block.py test_tensor_extension.py` with the #67566 pick (#67994) also applied | 397 passed | `test_tensor_column_no_memory_leak` needs `scipy`, which my environment didn't have at first. The 526 passed is from a run with scipy installed. 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, plus numpy 2.2.6 and torch 2.9.0+cpu. 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: Marwan Sarieddine <[email protected]> Signed-off-by: Elliot Barnwell <[email protected]> Signed-off-by: Sai Miduthuri <[email protected]> Co-authored-by: Marwan Sarieddine <[email protected]> Co-authored-by: Claude Fable 5.1 <[email protected]> Co-authored-by: Elliot Barnwell <[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]>
…ble across blocks (#67579) (#68025) ## Description Cherry-pick of #67579 (master commit 1acc2c3) onto `releases/2.59.2`. **Middle of a 3-PR stack on `releases/2.59.2`:** #68024 (the #66521 pick), then this PR, then #68026 (the #67806 pick, which fixes this change on pyarrow 26). Merge the stack with `gh stack merge 68026`, which lands all three in order. Since #61733 (2.56), a batch that spans blocks whose tensor column is null in one of them fails with `ValueError: Trying to unify unsupported tensor type: null`. A pandas UDF that returns `None` for some rows and an ndarray for others is enough to hit it. It worked in 2.55. #67579 lets tensor arrays carry null rows, so these blocks merge, the column stays a tensor column, and missing rows read back as `None`. ## Related issues Related to #67579. Depends on #68024, the #66521 pick. The same pick for 2.60.1 is #67999. ## Additional information ### Cherry-pick details Applied with `git cherry-pick -x`. 5 of the 10 files merged cleanly. In the other 5, each conflict was master-only code that sits next to #67579's additions: | File | Master-only context | Kept from #67579 | |---|---|---| | `arrow_ops/transform_pyarrow.py` | the `chunked_tensor_take` imports (#64961) | the `create_ragged_ndarray` import | | `tensor_extensions/arrow.py` | `tensor_array_to_numpy` and `_to_dense_ndarray_or_none` (#66122) | `native_tensor_array_to_numpy` | | `tensor_extensions/pandas.py` | the `TensorArray.dtype` docstring reformat (#67539) | `first = _first_non_null(self._tensor)`, under this branch's docstring | | `tests/test_arrow_block.py` | earlier tests, such as #65539's | the 68 lines of new tests | | `tests/test_tensor_extension.py` | #66122's tests | the 280 lines of new tests | I resolved each conflict by applying only #67579's change relative to its parent, which was a pure insertion every time, and dropping the master-only lines. Across all 10 files, the added and removed lines are identical to the master commit. `git patch-id` differs only because of the context lines. Prerequisite: #66521. Without it, `test_arrow_concat_tensor_with_null_keeps_tensor_type[last_shape1]` and `test_unify_schemas_tensor_with_null_keeps_tensor_type[other_shape1]` fail on this branch, as they do on 2.60.1. Not a duplicate: this branch doesn't contain #67579, and no PR against `releases/2.59.2` references it. #67999 picks the same commit onto `releases/2.60.1`. ### Testing The six test files, under `python/ray/data/tests/`, are `test_arrow_block.py test_tensor_extension.py test_torch_tensor_utils.py unit/test_transform_pyarrow.py test_transform_pyarrow.py test_pandas_block.py`. | Command | Result | |---|---| | `pre-commit run --files <the 10 changed files>` | Passed | | `pytest <the six files>`, with the whole stack (#66521, this PR, #67806) | 478 passed | | `pytest --continue-on-collection-errors <the six files>`, with this PR's tests against the code with only #66521 | 60 failed, 203 passed, and `test_tensor_extension.py` fails to collect, because it imports a helper this PR adds | | `pytest <the six files>`, with this pick directly on `releases/2.59.2`, without #66521 | The 2 tests above fail, 465 passed | | `pytest test_arrow_block.py test_pandas_block.py test_tensor_extension.py`, with the stack and the #67566 pick (#68022) applied together | 365 passed | 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, numpy 2.1.3, scipy 1.17.1 and torch 2.9.0+cpu, 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: Marwan Sarieddine <[email protected]> Signed-off-by: Elliot Barnwell <[email protected]> Signed-off-by: Sai Miduthuri <[email protected]> Co-authored-by: Marwan Sarieddine <[email protected]> Co-authored-by: Claude Fable 5.1 <[email protected]> Co-authored-by: Elliot Barnwell <[email protected]>
…#67806) (#68019) ## Description Cherry-pick of #67806 (master commit d0d059f) onto `releases/2.60.1`. **Top of a 3-PR stack on `releases/2.60.1`:** #67995 (the #66521 pick), then #67999 (the #67579 pick), then this PR. Merging this PR with `gh stack merge` lands all three in order. #67579 makes `native_tensor_array_to_numpy` return `None` for the null rows of a pyarrow-native tensor column. It calls `to_numpy_ndarray()` first. That reads null rows as zeros on pyarrow 23–25, but pyarrow 26 raises `ArrowInvalid: Array contains nulls`. Ray requires only `pyarrow >= 17.0.0`. So with `FixedShapeTensorFormat.ARROW_NATIVE` on pyarrow 26, #67999 alone breaks batches with a null tensor row that work in 2.60.0. #67806 converts the same storage without its validity bitmap, which gives the dense array on every pyarrow version, and then fills in `None` as before. ## Related issues Related to #67806, the follow-up to #67579. Requested in [this review on #67999](#67999 (review)). ## Additional information ### Cherry-pick details Applied cleanly with `git cherry-pick -x` on top of the #67579 pick. It has the same 2 files, +21/-5, and the same `git patch-id --stable` as the master commit. It changes only `native_tensor_array_to_numpy`, which #67579 adds, and the test #67579 adds for it, so it needs nothing else from master. Not a duplicate: neither this branch nor the stack below it contains #67806, and no open PR picks it. The only open PR that mentions it is #67999, through the review that asks for this pick. ### Testing The six test files are the ones from #67999: `test_arrow_block.py test_tensor_extension.py test_torch_tensor_utils.py unit/test_transform_pyarrow.py test_transform_pyarrow.py test_pandas_block.py`, under `python/ray/data/tests/`. | Command | Result | |---|---| | `pre-commit run --files <the 2 changed files>` | Passed | | `pytest <the six files>`, pyarrow 23.0.1, with this PR | 526 passed, 3 skipped, the same as #67999 alone | | `pytest <the six files>`, pyarrow 26.0.1, #67999 without this PR | 19 failed, 507 passed, 3 skipped. All 19 are `ARROW_NATIVE` null-row tests that #67579 adds (`test_batches_keep_tensor_column_*` and `test_native_tensor_array_to_numpy_with_null_rows`), and all fail with `ArrowInvalid: Array contains nulls` | | `pytest <the six files>`, pyarrow 26.0.1, with this PR | 526 passed, 3 skipped | I also ran an end-to-end check on pyarrow 26.0.1. A pandas UDF returns an ndarray for some rows and `None` for others, followed by `take_all()` with `ARROW_NATIVE`: | Case | `releases/2.60.1` (fa795b8) | #67999 (715ce08) | #67999 + this PR | |---|---|---|---| | `None` rows inside one block | works | `ArrowInvalid` | works | | same, after slicing off the first row | works | `ArrowInvalid` | works | With the default V2 format, both cases work on all three. CI on this branch runs the Data tests on pyarrow 23.0.1 and 17.0.0, so it doesn't exercise this failure. 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, numpy 2.2.6 and torch 2.9.0+cpu, with pyarrow 23.0.1 or 26.0.1. 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: rayo5o <[email protected]> Signed-off-by: Sai Miduthuri <[email protected]> Co-authored-by: ray05 <[email protected]>
…#67806) (#68026) ## Description Cherry-pick of #67806 (master commit d0d059f) onto `releases/2.59.2`. **Top of a 3-PR stack on `releases/2.59.2`:** #68024 (the #66521 pick), then #68025 (the #67579 pick), then this PR. Merging this PR with `gh stack merge` lands all three in order. #67579 makes `native_tensor_array_to_numpy` return `None` for the null rows of a pyarrow-native tensor column. It calls `to_numpy_ndarray()` first. That reads null rows as zeros on pyarrow 23–25, but pyarrow 26 raises `ArrowInvalid: Array contains nulls`. Ray requires only `pyarrow >= 17.0.0`. So with `FixedShapeTensorFormat.ARROW_NATIVE` on pyarrow 26, the #67579 pick alone breaks batches with a null tensor row. #67806 converts the same storage without its validity bitmap, which gives the dense array on every pyarrow version, and then fills in `None` as before. ## Related issues Related to #67806, the follow-up to #67579. The same pick for 2.60.1 is #68019, requested in [this review on #67999](#67999 (review)). ## Additional information ### Cherry-pick details Applied cleanly with `git cherry-pick -x` on top of the #67579 pick. It has the same 2 files, +21/-5, and the same `git patch-id --stable` as the master commit. It changes only `native_tensor_array_to_numpy`, which #67579 adds, and the test #67579 adds for it, so it needs nothing else from master. Not a duplicate: neither this branch nor the stack below it contains #67806, and no PR against `releases/2.59.2` references it. #68019 picks the same commit onto `releases/2.60.1`. ### Testing The six test files, under `python/ray/data/tests/`, are `test_arrow_block.py test_tensor_extension.py test_torch_tensor_utils.py unit/test_transform_pyarrow.py test_transform_pyarrow.py test_pandas_block.py`. | Command | Result | |---|---| | `pre-commit run --files <the 2 changed files>` | Passed | | `pytest <the six files>`, pyarrow 23.0.1, with this PR | 478 passed | | `pytest <the six files>`, pyarrow 26.0.1, the #67579 pick without this PR | 19 failed, 459 passed. All 19 are `ARROW_NATIVE` null-row tests that #67579 adds (`test_batches_keep_tensor_column_*` and `test_native_tensor_array_to_numpy_with_null_rows`) | | `pytest <the six files>`, pyarrow 26.0.1, with this PR | 478 passed | CI on this branch runs the Data tests on pyarrow 23.0.1 and 17.0.0, so it doesn't exercise this failure. 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, numpy 2.1.3 and torch 2.9.0+cpu, with pyarrow 23.0.1 or 26.0.1. 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: rayo5o <[email protected]> Signed-off-by: Sai Miduthuri <[email protected]> Co-authored-by: ray05 <[email protected]>
…mns to pandas (#67283) ## Description Since #66122, a variable-shaped tensor column whose rows all have the same shape converts to pandas as one dense view, but only when the column has a single chunk. A batch that spans two blocks reaches `TensorDtype.__from_arrow__` with two chunks, and each chunk still went through `to_numpy()`, which returns one ndarray per row for the result to be stacked from. The multi-chunk branch now converts each chunk with `tensor_array_to_numpy()` and joins them with one `np.concatenate`: - If the chunks can't share one dense array (a ragged or null-bearing chunk next to a dense one, which #66122 noted can't be concatenated, or dense chunks of different row shapes), the dense chunks are converted back to one ndarray per row and all rows are joined one by one, which is what master does for null rows since #67579. - Empty chunks are skipped, so a column with only one non-empty chunk is still a view, like the single-chunk path. - The chunks sit in separate buffers, so the joined array is still a copy, as before. It just isn't built row by row. `iter_batches(batch_format="pandas")` over uniformly shaped `ArrowVariableShapedTensorArray` rows, where each block is half a batch so every batch column has 2 chunks. Median of 5 runs, each in a fresh process: | rows | batch size | | master | this PR | |---|---:|---|---:|---:| | 65,536 × (128,) float32 | 1024 | whole loop | 346 ms | 179 ms | | | | inside `__from_arrow__` | 156 ms | 30 ms | | 2,048 × (224, 224, 3) uint8 | 64 | whole loop | 172 ms | 147 ms | | | | inside `__from_arrow__` | 82 ms | 54 ms | When each block is exactly one batch (1 chunk per batch), nothing changes. The benchmark script is in #67282. New tests in `test_tensor_extension.py`: - `test_variable_shaped_uniform_rows_multi_chunk_to_pandas_skips_per_row`: uniform rows in two chunks convert without calling `to_numpy()`. - `test_variable_shaped_mixed_chunks_to_pandas`: dense then ragged, ragged then dense, and dense chunks of different row shapes still convert row by row. - `test_variable_shaped_zero_dim_mixed_chunks_to_pandas`: with 0-d rows, a dense chunk next to a chunk with a null row still falls back. A dense chunk of 0-d rows is 1-d like a per-row chunk, so row shapes alone can't tell them apart (found by Cursor Bugbot). - `test_variable_shaped_multi_chunk_with_empty_chunks_to_pandas_is_zero_copy`: empty chunks around one non-empty chunk give a view of it. ## Why this matters A variable-shaped tensor column whose rows all share one shape reaches `TensorDtype.__from_arrow__` as several chunks whenever a batch spans more than one block. Before this PR only the single-chunk case took the dense path from #66122; with two or more chunks, every row became its own NumPy view and the rows were stacked one by one. A NumPy view holds no data, but it is still a Python object: ~112 bytes of metadata (refcount, type, data pointer, shape/strides, base, dtype, flags, ...) no matter how small the row is. So the old path's memory and time overhead grew with the number of **rows**; the new path's grows with the number of **chunks**. ``` Arrow buffers: 2 chunks, 6 rows of 4 x float32 chunk A: [r0][r1] chunk B: [r2][r3][r4][r5] BEFORE: one view per row, then np.stack [r0] [r1] [r2] [r3] [r4] [r5] <- 6 ndarray objects (~112 B of metadata each) | | | | | | +----+----+--+-+----+----+ | np.stack: makes another view per row, then copies row by row v [ 6x4 float32 ] AFTER: one view per chunk, then one np.concatenate [r0 r1] [r2 r3 r4 r5] <- 2 ndarray objects shape (2, 4) shape (4, 4) same buffers; a leading row dim with a 16 B stride | | +-------+-------+ | np.concatenate: one block copy per chunk, in C v [ 6x4 float32 ] ``` Both paths copy the payload once into the output. The difference is the per-object metadata around it, roughly (number of NumPy objects) x ~112 B, so it matters for many small tensors and fades for a few large ones. That's why the benchmark above gains most on the `(128,)` float32 rows (156 ms -> 30 ms inside `__from_arrow__`) and less on the images. Peak memory follows the same pattern. In a standalone NumPy reproduction of the two paths with 1M rows of `(4,)` float32 (16 MB of data), the old path peaked at ~313 MB, about 240 MB of it per-row view objects (`np.stack` makes a second set). The new path peaked at 16 MB. If only one non-empty chunk is left, the result is a view of the Arrow buffer with no copy at all. ### How chunks are joined now ```mermaid flowchart TD A["Drop empty chunks"] --> B["tensor_array_to_numpy() per chunk"] B --> C{"All dense, same row shape?<br/>no object dtype, one shape[1:]"} C -- yes --> D["One np.concatenate<br/>(single chunk: stays a view)"] C -- no --> E["Fall back to one ndarray per row<br/>(ragged chunk, null row, or mixed row shapes)"] ``` The dtype check is needed for 0-d rows: a dense chunk of scalars and a per-row chunk with a null row are both 1-D, so `shape[1:]` alone can't tell them apart. ## Related issues Closes #67282 ## Additional information - Not a duplicate: #66122 left multi-chunk columns out of scope, and no open issue or PR covers them. #67236 also edits `__from_arrow__`, but only adds null-row checks around this branch, so whichever lands second needs a small rebase. - I also compared this branch with master on 33 cases: uniform, multi-dimensional rows, mixed dense/ragged in both orders, different row shapes, ragged only, a null row, empty chunks in different positions, bool, 0-d rows with and without a null row, fixed-shape, and fixed-shape columns with null rows (before or after a dense chunk, an all-null chunk, next to an empty chunk, a slice after a null row) in the V1, V2 and native formats. The resulting `TensorArray` has the same dtype, shape and values in all of them. - Tests, run locally after rebasing on master `e65c2e2d` (`python/ray/data` from source on a nightly wheel), Python 3.12.3, numpy 2.5.4, pandas 3.0.6, with pyarrow 26.0.0 and 23.0.1: - `pytest python/ray/data/tests/test_tensor_extension.py -k "multi_chunk or mixed_chunks"`: 6 passed. On master, `..._skips_per_row` and `..._with_empty_chunks_to_pandas_is_zero_copy` fail, and the 0-d test fails without the second commit. The other mixed-chunk cases pass either way and guard the fallback. - `pytest python/ray/data/tests/test_tensor_extension.py python/ray/data/tests/test_pandas_block.py python/ray/data/tests/test_arrow_serialization.py python/ray/data/tests/unit/test_transform_pyarrow.py python/ray/data/tests/unit/test_data_batch_conversion.py python/ray/data/tests/test_batcher.py python/ray/data/tests/test_tensor.py`: 616 passed, 6 skipped, 8 failed on pyarrow 26, and 617 passed, 6 skipped, 7 failed on pyarrow 23. The same tests fail on unmodified master in my environment: `test_tensor_array_scalar_cast` (3 formats), `TestSizeBytes::test_small`, `TestSizeBytes::test_large_str`, `test_numpy_to_tensor_warning` (2 params), and on pyarrow 26 only `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]>


Summary
A batch that spans blocks whose tensor column is null in one of them fails with "Trying to unify unsupported tensor type: null". This PR lets tensor arrays carry null rows, so such blocks merge and the column stays a tensor column, with
Nonefor the missing rows. A column that is a tensor in one block and pickled objects in another keeps raising; a follow-up PR extends that error with the columns and types found.Problem
Nonebecomes null.to_numpy()on them failed with "buffer is too small", so nothing could read them ([Data]to_pandas()returns another row's value or raises for null rows in tensor columns #67200).ValueError: Trying to unify unsupported tensor type: nullimgis a tensor column withNonein row 5Change
unify_tensor_arraysturns a null-typed chunk into null rows of the unified tensor type, soconcatkeeps the column a tensor column.to_numpy()returns one ndarray view per row withNonefor each null row, andfrom_numpy()acceptsNoneamong the tensors. A variable-shaped row is null when its struct slot or either child is null. Null rows survive promotion to the variable-shaped type.TensorArrayacceptsNonerows, so such a column converts to pandas and back.Nonerows instead of blaming ragged shapes.What a batch looks like, for a tensor column where one row is missing:
float32 (8, 2, 2)object (8,), views andNone, nothing pickledDecisions to confirm
None, since a dense array has no slot for a missing row. Filling the row with zeros or NaN would invent data and has no form for integer or ragged tensors.from_numpy()withNoneamong the tensors now builds a tensor array with null rows. Before, such a column fell back to pickled objects with a warning.Subsystems
Block / data format (
arrow_ops/transform_pyarrow.py,tensor_extensions/arrow.py,tensor_extensions/pandas.py).Related
to_pandas()returns another row's value or raises for null rows in tensor columns #67200:to_pandas()and numpy batches now returnNonefor a null tensor row instead of another row's value or an error.to_numpypaths null-aware and makesto_pandasraise on null rows. This PR also builds tensor arrays from input holdingNone, converts null rows to pandas and back, keeps them through shape promotion, and merges null chunks. The rule that a null child marks a null row is taken from fix:null rows in tensor columns #67236.fixed_shape_tensortype alone; [Data] Return None for null rows in Arrow-native tensor columns instead of zeros #67293 covers its null rows.Testing
AI assistance (Claude Code) was used to find the root cause and write this change.
🤖 Generated with Claude Code