Repository navigation
[Data] Return None for null rows in Arrow-native tensor columns instead of zeros - #67293
ShawnGarello wants to merge 1 commit into
Conversation
…ad of zeros transform_pyarrow.to_numpy() and _iter_rows_from_batch_with_tensors() convert PyArrow's native fixed_shape_tensor columns with to_numpy_ndarray(), which ignores validity. A null row came back as whatever its slot held (zeros after take), so numpy batches, iter_rows(), take() and take_all() returned zeros for it, while pandas batches already returned None. With null rows present, to_numpy() now returns a 1D object ndarray with None for each null row and its tensor for each other row, the same as Ray's own tensor types and plain list columns. A chunked column with a null in any chunk gives one such array over all chunks. Row iteration goes through to_numpy(), so rows get None too. Null-free columns keep the existing dense, zero-copy path. Signed-off-by: Shawn Garello <[email protected]>
There was a problem hiding this comment.
Code Review
This pull request introduces support for handling null rows in native FixedShapeTensorArrays by converting them to a 1D object NumPy array where null rows are represented as None. It updates to_numpy conversion utilities and adds corresponding unit tests. The review feedback suggests optimizing the _native_tensor_rows_to_numpy helper function by vectorizing the array population instead of using a Python for loop, which can be a performance bottleneck for large datasets.
| rows = np.empty(len(array), dtype=object) | ||
| for i in range(len(array)): | ||
| rows[i] = None if is_null[i] else tensors[i] |
There was a problem hiding this comment.
The current implementation uses a Python for loop to populate the object array, which can be a significant performance bottleneck for large datasets. We can vectorize this operation by leveraging NumPy's bulk assignment and boolean indexing, which avoids the Python loop entirely and runs much faster.
| rows = np.empty(len(array), dtype=object) | |
| for i in range(len(array)): | |
| rows[i] = None if is_null[i] else tensors[i] | |
| rows = np.empty(len(array), dtype=object) | |
| rows[:] = list(tensors) | |
| rows[is_null] = None |
Jadiouo
left a comment
There was a problem hiding this comment.
Verified against base e91b1de and head 1373ee9 (Python 3.13, pyarrow 25.0.1, numpy 2.5.3).
- The repro from the description gives zeros for the null row on base and
Noneon head, for the numpy batch,take()andtake_all(). - The new tests: 8 failed / 3 passed on base, 11 passed on head.
unit/test_transform_pyarrow.pyandunit/test_arrow_block.py: 190 passed, 3 skipped. test_tensor.pyhas one failure,test_tensors_sort[ARROW_NATIVE], which fails the same way on base.- Null-free columns stay dense and share memory with the Arrow buffer; chunked, all-null and empty columns also look right.
- I tried gemini's vectorized version: same output, but only about 1.05x–1.2x faster, so I don't think it needs to block this.
One question: a block with nulls gives an object array, and a block without nulls gives a dense float64 array, so one iter_batches run can yield both types. Is that intended? It might matter for code that expects a fixed dtype, such as a torch collate function.
|
Thanks for checking. Yes, that's intended: a dense array can't hold For torch, a batch with a null row now hits Ray's existing "object dtype cannot be converted to a Torch Tensor" error, which points to I'll keep the loop unless a maintainer prefers the vectorized version, given the small speedup. |
Jadiouo
left a comment
There was a problem hiding this comment.
Thanks, that makes sense. An explicit error that points to collate_fn is better than silently training on zeros. LGTM.
…7579) ## 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 `None` for 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 - Since #61733 (2.56), the batch a pandas UDF returns becomes an Arrow block right away. Each one-row block types a column from its own value: a stacked array becomes a tensor, `None` becomes null. - Merging those blocks into a batch reconciles the schemas. A tensor with a null arm passed reconciliation and then failed in the tensor unifier, which rejected null. - Tensor arrays could already hold null rows, but `to_numpy()` on them failed with "buffer is too small", so nothing could read them (#67200). - In 2.55 the batches stayed pandas blocks, so there was no Arrow schema to unify. ```python import numpy as np, ray def decode(batch): row = int(batch["id"][0]) return {"img": [None if row == 5 else np.full((2, 2), row, np.float32)]} ds = ray.data.range(8).map_batches(decode, batch_size=1) next(iter(ds.iter_batches(batch_size=8, batch_format="numpy"))) ``` | | Result | |---|---| | 2.55 | works | | 2.56 to master | `ValueError: Trying to unify unsupported tensor type: null` | | After | works, `img` is a tensor column with `None` in row 5 | ## Change ``` block 1 img = stacked array -> tensor block 2 img = None -> null Before: unify schemas -> tensor -> concat: "unsupported tensor type: null" After: unify schemas -> tensor -> null chunk becomes null rows of the tensor type ``` - `unify_tensor_arrays` turns a null-typed chunk into null rows of the unified tensor type, so `concat` keeps the column a tensor column. - Both tensor array classes read null rows: `to_numpy()` returns one ndarray view per row with `None` for each null row, and `from_numpy()` accepts `None` among 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. - `TensorArray` accepts `None` rows, so such a column converts to pandas and back. - The torch conversion error names `None` rows instead of blaming ragged shapes. - A column that is a tensor in one block and pickled objects in another still raises "Found columns with both objects and tensors". Merging them would silently turn every row into a pickled object and lose the type. What a batch looks like, for a tensor column where one row is missing: | batch | before | after | |---|---|---| | no missing row | error | `float32 (8, 2, 2)` | | one missing row | error | `object (8,)`, views and `None`, nothing pickled | | schema | error | tensor | ## Decisions to confirm - A batch holding a null row comes back as one ndarray per row with `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()` with `None` among the tensors now builds a tensor array with null rows. Before, such a column fell back to pickled objects with a warning. - Tensors next to pickled objects keep raising rather than merging to objects, per review. Users make every row the same kind, for example by returning ragged arrays as nested lists. ## Subsystems Block / data format (`arrow_ops/transform_pyarrow.py`, `tensor_extensions/arrow.py`, `tensor_extensions/pandas.py`). ## Related - Reported by a customer upgrading from 2.55 to 2.59, alongside #67566. - Fixes #67200: `to_pandas()` and numpy batches now return `None` for a null tensor row instead of another row's value or an error. - Overlaps #67236, which makes the same two `to_numpy` paths null-aware and makes `to_pandas` raise on null rows. This PR also builds tensor arrays from input holding `None`, 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 #67236. - Leaves the native `fixed_shape_tensor` type alone; #67293 covers its null rows. - A follow-up PR extends the objects-and-tensors error with the columns and types found. ## Testing ``` 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 \ python/ray/data/tests/test_tensor_extension.py \ python/ray/data/tests/test_torch_tensor_utils.py # 387 passed ``` AI assistance (Claude Code) was used to find the root cause and write this change. 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Signed-off-by: Marwan Sarieddine <[email protected]> Signed-off-by: Elliot Barnwell <[email protected]> Co-authored-by: Claude Fable 5.1 <[email protected]> Co-authored-by: Elliot Barnwell <[email protected]>
## 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]>
|
This pull request has been automatically marked as stale because it has not had You can always ask for help on our discussion forum or Ray's public slack channel. If you'd like to keep this open, just leave any comment, and the stale label will be removed. |
|
This pull request has been automatically closed because there has been no more activity in the 14 days 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! |
Summary
A null row in a PyArrow-native
fixed_shape_tensorcolumn comes back as zeros in numpy batches and initer_rows/take/take_all. It now comes back asNone, as it already does in pandas batches, and intake_all()for Ray's own tensor types.Related: #67200, #67236
Before
transform_pyarrow.to_numpyand_iter_rows_from_batch_with_tensorsuseto_numpy_ndarray(), which ignores validity, so a null row returns whatever is in its slot. pandas batches already giveNone.After
objectarray,Nonefor null rows and the tensor for each other row (the same as plain list columns, and what fix:null rows in tensor columns #67236 does for Ray's tensor types). A chunked column with a null in any chunk gives one such array. Without nulls, nothing changes (same dense, zero-copy array).iter_rows/take/take_all:Nonefor a null row.map_batches(..., batch_format="numpy")returning it) falls back to Ray's pickled-object column with a warning, as for any object array. Values andNoneare kept, instead of zeros being written back.flowchart TD subgraph Before subgraph BS[Subsystem: block / data format] subgraph BC["Component: transform_pyarrow.to_numpy, ArrowBlockAccessor.iter_rows"] B1[native fixed_shape_tensor column] --> B2["to_numpy_ndarray(): null row becomes zeros"] end end end subgraph After subgraph AS[Subsystem: block / data format] subgraph AC["Component: transform_pyarrow.to_numpy, ArrowBlockAccessor.iter_rows"] A1[native fixed_shape_tensor column] -->|no null rows| A2["to_numpy_ndarray(), unchanged"] A1 -->|null rows| A3["1-D object array, None for null rows"] end end end classDef removed fill:#ffcdd2,stroke:#c62828,color:#000 classDef added fill:#c8e6c9,stroke:#2e7d32,color:#000 class B2 removed class A3 addedSubsystems
Block / data format (
arrow_ops/transform_pyarrow.py,arrow_block.py).Testing
tests/unit/test_transform_pyarrow.py(to_numpy, float64/int64, sliced and chunked, plus null-free guards),tests/unit/test_arrow_block.py(iter_rows),tests/test_tensor.py(Dataset). They fail without the fix (8 failed, guards pass) and pass with it (11 passed).pytest python/ray/data/tests/unit/test_transform_pyarrow.py python/ray/data/tests/unit/test_arrow_block.py: 190 passed, 3 skippedpytest python/ray/data/tests/test_tensor.py -k "not test_large_tensor_creation": 93 passed, 3 skipped (the existing ARROW-5890 skip).test_large_tensor_creationneeds more memory than my machine has; it runs out with or without this changepytest python/ray/data/tests/test_tensor_extension.py -k "not test_large_arrow_tensor_array": 195 passed (the deselected test allocates more than my machine allows; it covers V1/V2 large offsets, which this PR doesn't touch)pytest python/ray/data/tests/test_transform_pyarrow.py: 11 passedWhy this is not a duplicate
No open issue or PR covers native tensor null rows (searched open PRs for
fixed_shape_tensor,FixedShapeTensor,native tensor null,"null" "tensor",to_numpy_ndarray, and issues forfixed_shape_tensor null,native tensor null). #67236 fixes the same bug for Ray's V1/V2 tensor types and leavespa.fixed_shape_tensorout of scope on purpose; I said this PR would follow in #67236 (comment). The files don't overlap with #67236.AI use
I used an AI coding assistant (Claude Code) to help write the fix and tests. I reviewed every line and ran the tests above locally.