Skip to content

[Data] Join dense chunks once when converting multi-chunk tensor columns to pandas - #67283

Merged
goutamvenkat-anyscale merged 2 commits into
ray-project:masterfrom
rayo5o:data-multichunk-tensor-pandas
Nov 24, 2026
Merged

goutamvenkat-anyscale merged 2 commits into
ray-project:masterfrom
rayo5o:data-multichunk-tensor-pandas

Conversation

@rayo5o

@rayo5o rayo5o commented Oct 22, 2026 •

Copy link
Copy Markdown
Contributor

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:

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

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)"]
Loading

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: [Data] Avoid copying the payload converting uniform tensor columns to pandas #66122 left multi-chunk columns out of scope, and no open issue or PR covers them. fix:null rows in tensor columns #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.

@rayo5o
rayo5o requested a review from a team as a code owner October 22, 2026 15:53

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

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

Fix All in Cursor

Reviewed by Cursor Bugbot for commit a99e1d0. Configure here.

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

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_arrow and read them through iter_batches, to_pandas and map_batches under 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]>
@rayo5o
rayo5o force-pushed the data-multichunk-tensor-pandas branch from 4abafed to 2d4645e Compare November 5, 2026 01:56
@rayo5o

rayo5o commented Nov 5, 2026

Copy link
Copy Markdown
Contributor Author

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

@github-actions

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 Nov 19, 2026
@rayo5o

rayo5o commented Nov 23, 2026

Copy link
Copy Markdown
Contributor Author

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 test_tensor_extension.py gives 253 passed and 3 failed with it. The 3 are test_tensor_array_scalar_cast, which fail the same way on master without this PR. Without the change, the two new multi-chunk tests fail. Still ready for review.

@github-actions github-actions Bot added unstale A PR that has been marked unstale. It will not get marked stale again if this label is on it. and removed stale The issue is stale. It will be closed within 7 days unless there are further conversation labels Nov 23, 2026
@goutamvenkat-anyscale goutamvenkat-anyscale added go add ONLY when ready to merge, run all tests and removed unstale A PR that has been marked unstale. It will not get marked stale again if this label is on it. labels Nov 24, 2026
@goutamvenkat-anyscale
goutamvenkat-anyscale enabled auto-merge (squash) November 24, 2026 18:52
@goutamvenkat-anyscale
goutamvenkat-anyscale merged commit 228a0b8 into ray-project:master Nov 24, 2026
8 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

community-contribution Contributed by the community data Ray Data-related issues go add ONLY when ready to merge, run all tests

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Data] Converting multi-chunk variable-shaped tensor columns to pandas skips the dense fast path

3 participants