Repository navigation
[Data] Join dense chunks once when converting multi-chunk tensor columns to pandas - #67283
Conversation
There was a problem hiding this comment.
Code Review
This pull request improves the conversion of multi-chunk Arrow variable-shaped tensor arrays to Pandas. It filters out empty chunks, avoids per-row views when chunks are uniform, and handles mixed chunks (such as dense and ragged chunks, or dense chunks with different shapes) by falling back to one ndarray per row. Additionally, several unit tests are added to verify these behaviors. No review comments were provided, so there is no feedback to address.
There was a problem hiding this comment.
Cursor Bugbot has reviewed your changes and found 1 potential issue.
Reviewed by Cursor Bugbot for commit a99e1d0. Configure here.
Jadiouo
left a comment
There was a problem hiding this comment.
Thanks @rayo5o. Verified base f4f37d3 vs 4abafed (Python 3.13, pyarrow 25.0.1, pandas 3.0.6).
- Correctness: I built multi-block datasets with
from_arrowand read them throughiter_batches,to_pandasandmap_batchesunder V1 and V2: 40 cases covering fixed and variable shapes, mixed ndim, 0-d rows and empty chunks. Values, dtypes and shapes matched base in every case. Cases with null rows raise the same error on both, which I take to be #67236's scope. - Speed: with 128-dim float32 batches crossing blocks,
__from_arrow__went from 273 ms to 60 ms and the whole loop from 707 ms to 484 ms (median of 5 on a shared, noisy machine). Single-chunk batches are unchanged. - Tests: on base, the PR's test file has 6 failures. On this PR, 4 remain, and those also fail on base. With only the first commit applied, the new 0-d test fails, so the second commit is covered.
…mns to pandas A uniformly shaped variable-shaped tensor column converts to pandas as one dense view since ray-project#66122, but only when it has a single chunk. With more chunks, as when a batch spans two blocks, every chunk still went through to_numpy() and the rows were stacked one by one. Convert each chunk with tensor_array_to_numpy() and join them with one np.concatenate. When the chunks can't share one dense array (a ragged chunk, or dense chunks of different row shapes), convert the dense ones back to one ndarray per row, which is what the old path produced. Empty chunks are skipped, so a column with one non-empty chunk stays a view. Closes ray-project#67282 Signed-off-by: rayo5o <[email protected]>
A dense chunk of 0-d rows is 1-d, like a chunk of per-row ndarrays, so comparing row shapes alone let the two be concatenated into an object array of floats and arrays, and TensorArray raised. Fall back whenever any chunk came back as per-row ndarrays. Signed-off-by: rayo5o <[email protected]>
4abafed to
2d4645e
Compare
|
@marwan116 could you take a look when you have a chance? This extends your #66122 dense path to multi-chunk columns, so a pandas batch that spans two blocks is joined with one concatenate instead of row by row (346 → 179 ms for the whole loop in the 65,536 × (128,) case). I rebased it on master today to resolve the conflict with #67579: chunks that can't be joined densely, including ones with null rows, are now joined row by row the same way #67579 does it. Results match master on 33 cases, including null rows in all three fixed-shape formats; the description has the updated test results. |
|
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. |
|
Re-checked on current master (1cee821) with the CI lock versions (pyarrow 25.0.1, pandas 2.3.3): the diff still applies cleanly, and |

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 throughto_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 onenp.concatenate:iter_batches(batch_format="pandas")over uniformly shapedArrowVariableShapedTensorArrayrows, where each block is half a batch so every batch column has 2 chunks. Median of 5 runs, each in a fresh process:__from_arrow____from_arrow__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 callingto_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.
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.stackmakes 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
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
__from_arrow__, but only adds null-row checks around this branch, so whichever lands second needs a small rebase.TensorArrayhas the same dtype, shape and values in all of them.e65c2e2d(python/ray/datafrom 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_rowand..._with_empty_chunks_to_pandas_is_zero_copyfail, 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 onlytest_tensors_sort[ARROW_NATIVE].pre-commit run --files <changed files>: passed.