Skip to content

[Data] Avoid copying the payload converting uniform tensor columns to pandas - #66122

Merged
goutamvenkat-anyscale merged 4 commits into
masterfrom
marwan/data-tensor-pandas-zero-copy
Sep 25, 2026
Merged

goutamvenkat-anyscale merged 4 commits into
masterfrom
marwan/data-tensor-pandas-zero-copy

Conversation

@marwan116

@marwan116 marwan116 commented Sep 12, 2026 •

Copy link
Copy Markdown
Contributor

Closes #66118.

The problem

Converting a variable-shaped tensor column to a pandas batch copies the whole tensor payload, even when nothing needs copying.

ArrowVariableShapedTensorArray.to_numpy returns one ndarray view per row. TensorArray then stacks those views into a dense array, which allocates a new buffer and copies every byte.

When all the rows have the same shape, they already sit back to back in one Arrow buffer. The dense array is already there. Only the stacking makes a copy.

Measured on a single 128 MiB row:

time rate
before 14.27 ms 9.4 GB/s (a memory copy)
after 0.18 ms 750 GB/s (a view)

The fix

ArrowVariableShapedTensorArray._to_dense_numpy_or_none returns a single (num_rows, *shape) view when the rows are uniformly shaped and adjacent in the buffer, and None otherwise. arrow.tensor_array_to_numpy tries it and falls back to the existing path, and the pandas conversion calls that.

to_numpy is unchanged on purpose. It is documented to return one ndarray per row, and a one-row slice of a ragged column is trivially uniform, so putting the fast path there would change what a ragged column returns depending on how it was sliced. Three existing tests rely on that.

Ragged rows, null rows, non-adjacent rows and multi-chunk columns all take the old path.

A chunked column is converted chunk by chunk and joined with np.concatenate, which cannot join a dense (n, k) chunk to a ragged object array:

ValueError: all the input arrays must have same number of dimensions,
but the array at index 0 has 2 dimension(s) and the array at index 1 has 1 dimension(s)

Reaching the fast path there means rewriting the join as well, which is out of scope here. On 2000 rows × 128 float32 the same data converts in 0.024 ms as one chunk and 5.20 ms as two.

What this changes for callers

Both of these are how a fixed-shape tensor column already behaves, so the change brings variable-shaped columns into line rather than introducing something new. Both are the ordinary price of a zero-copy view.

The pandas column now aliases the block. Writes through it reach the Arrow buffer, and on a block that came from the object store — whose buffers are read-only — assignment raises:

ValueError: assignment destination is read-only

Checked both ways, on a locally built block and on one round-tripped through ray.put; fixed-shape columns behave identically in both.

Peak memory improves, but a slice pins its whole source block. The view holds the Arrow buffer it points into, so a 2-row slice of a 64 MiB block keeps all 64 MiB alive after that block is dropped:

slice owner owner size
fast path (view) 0.125 MiB pa.Buffer 64.0 MiB
old path (stack) 0.125 MiB — —

Tests

Eleven tests in test_tensor_extension.py, thirteen cases with parametrization.

Three assert the conversion is actually copy-free — np.shares_memory against the Arrow payload buffer, for uniform rows, a slice of them, and rows of more than one dimension. Those are the three that fail on master as a behavior difference; the rest call the new helper directly, which does not exist there.

Three are regression guards that pass either way and pin that nothing else moved: ragged rows still convert correctly, to_numpy still returns one ndarray per row, and a null-bearing column still converts to exactly what the old path produced.

The rest cover the conditions under which the fast path declines, each pinned separately:

case why it declines
ragged rows shapes differ
rows differing in one extent — (2, 3), (2, 4) offsets are irregular
rows of equal size, different shape — (2, 3), (3, 2) adjacent at a fixed stride, so only the shapes give it away
a column with no rows nothing to view
rows of zero size — (3, 0), (3, 2, 0) nothing to point at
a null row on the storage struct self.null_count
a null row on the data child data_array.null_count
a null row on the shape child the extents no longer fill num_rows * ndim

The three null levels are independent, and the obvious way to make a null row — take with a null index — marks all three at once, so the test builds the storage by hand and marks one at a time. The struct and data levels are the ones that matter: each leaves uniform shapes and adjacent offsets behind it, so every other check passes and a view would hand the null row's untouched buffer contents back as data.

pytest python/ray/data/tests/test_tensor_extension.py            197 passed
pytest python/ray/data/tests/test_tensor.py                       95 passed, 3 skipped
pytest python/ray/data/tests/test_pandas_block.py                 57 passed
pytest python/ray/data/tests/test_arrow_serialization.py          32 passed
pytest python/ray/data/tests/unit/test_transform_pyarrow.py       78 passed
pytest python/ray/data/tests/unit/test_data_batch_conversion.py   28 passed

Notes

Not a duplicate: no open PR touches this conversion, and no PR references #66118. The nearest neighbour, #64961, changes tensor concatenation during row takes, not the pandas conversion.

AI assistance was used for this change.

… pandas

`ArrowVariableShapedTensorArray.to_numpy` returns one ndarray view per
row. `TensorArray` stacks those into a dense array, which allocates a
fresh buffer and copies every byte.

When the rows all have the same shape they already sit back to back in
one Arrow buffer, so the dense array is already there and a single view
describes it. Adds `_to_dense_numpy_or_none`, which returns that view or
`None` when the rows cannot be described by one, and has the pandas
conversion try it before falling back.

`to_numpy` is left alone on purpose: it is documented to return one
ndarray per row, and a one-row slice of a ragged column is trivially
uniform, so folding the fast path in there would change what a ragged
column returns depending on how it was sliced.

Measured on one 128 MiB row: 14.27 ms (9.4 GB/s, a memory copy) before,
0.18 ms (750 GB/s, a view) after.

Signed-off-by: Marwan Sarieddine <[email protected]>
@marwan116
marwan116 requested a review from a team as a code owner September 12, 2026 05:12

@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 introduces a fast path for converting variable-shaped tensor arrays to dense NumPy arrays without copying when the rows are uniformly shaped and adjacent. The reviewer suggests optimizing this implementation by replacing the use of to_pylist() and Python loops with fully vectorized NumPy operations on the PyArrow arrays directly to avoid performance bottlenecks and memory overhead on large datasets.

@marwan116 marwan116 added data Ray Data-related issues go add ONLY when ready to merge, run all tests labels Sep 12, 2026
…on lists

The probe read the shapes and offsets with `to_pylist()`, which allocates
a Python object per row. A ragged column pays that and then falls back,
so the probe cost 58% of the conversion it was trying to avoid, and on a
column of many small rows it swallowed most of the saving it made.

Read the offset and shape buffers as ndarrays instead and compare them
vectorized. Measured on 50k rows: the probe drops from 65.6ms to 0.014ms
on a ragged column, and a uniform column goes from 1.6x faster than the
old path to 2091x. A single 128MiB row is unchanged at ~0.19ms.

Also pins multi-dimensional shapes, which now matter: the check reshapes
the flat shape buffer by `ndim` rather than comparing per-row lists.

Signed-off-by: Marwan Sarieddine <[email protected]>

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

Here are a few comments! Also, three things we might want to add in the PR description:

  1. The pandas column now aliases the block: writes reach it, and assignment raises
    on object-store blocks (which is already how fixed-shape already behaves, but this is still a behavior change);
  2. Peak memory improves, but a 2-row slice of a 64 MiB source block keeps all
    64 MiB alive even after that block is dropped;
  3. Multi-chunk columns still take the old path (0.02 vs 4.95 ms); np.concatenate
    can't join dense and ragged chunks. (This is out of scope but is worth mentioning in "Ragged rows, null rows, and non-adjacent rows all take the old path".)

Comment on lines +1763 to +1764
shape_offsets = np.asarray(shapes_array.offsets)
flat_shapes = np.asarray(shapes_array.values)[shape_offsets[0] : shape_offsets[-1]]

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.

Suggested change
shape_offsets = np.asarray(shapes_array.offsets)
flat_shapes = np.asarray(shapes_array.values)[shape_offsets[0] : shape_offsets[-1]]
flat_shapes = np.asarray(shapes_array.flatten())

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Adopted

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Adopted in a165884.

The manual slice was there because .values ignores slicing — after arr.slice(1, 3) it still returns all five rows' extents — so I had to re-apply the offsets by hand. .flatten() already does that. I checked the two agree on every shape of column the probe can see:

column .values[off0:offN] .flatten()
uniform 1-D, 5 rows [4,4,4,4,4] same
uniform 2-D, 4 rows [2,3,2,3,2,3,2,3] same
ragged [3,5] same
slice(1, 3) [4,4,4] same
slice(3, 2) [4,4] same
empty [] same
one null row [4,4] same

Still zero-copy — flatten().buffers()[1].address == values.buffers()[1].address, sliced or not — and the extra cost is a flat ~0.7 µs, not per-row:

manual slice .flatten()
50k rows, 1-D 0.0027 ms 0.0034 ms
50k rows, 2-D 0.0028 ms 0.0035 ms
single 128 MiB row 0.0026 ms 0.0034 ms

Against a whole-probe budget of ~15 µs that is not measurable.

One consequence worth recording: .flatten() drops the values behind a null slot, where the manual slice kept them. So a null shape row now fails the flat_shapes.size != num_rows * ndim check on its own, and shapes_array.null_count > 0 above it has become redundant — deleting it leaves the suite green. I kept it anyway. Rejecting nulls by way of flatten's null handling is too indirect to leave implicit, and it is one comparison on a scalar.

)

if isinstance(array, ArrowVariableShapedTensorArray):
dense = array._to_dense_numpy_or_none()

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.

_to_dense_numpy_or_none is called outside of its module; should we make it public (Remove the leading underscore)?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Resolved by removing the cross-module call rather than making public

  • _tensor_array_to_numpy moved into arrow.py as tensor_array_to_numpy
  • _to_dense_numpy_or_none is now only ever called from inside arrow.py - so the leading underscore is accurate again.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Resolved in a165884 by removing the cross-module call rather than by renaming — see the reply on moving the isinstance check into arrow.py.

_tensor_array_to_numpy moved into arrow.py as tensor_array_to_numpy, so _to_dense_numpy_or_none is now only ever called from inside arrow.py and the leading underscore is accurate again. pandas.py calls one function and knows nothing about the Arrow class hierarchy.

ArrowVariableShapedTensorArray,
)

if isinstance(array, ArrowVariableShapedTensorArray):

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.

Is it possible to move this check into arrow.py? The type is directly available and we can keep all Arrow checks there.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Done - I moved the whole helper rather than just the check, which also answers the question about _to_dense_numpy_or_none being private.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Done in a165884 — I moved the whole helper rather than just the check, which also answers the question about _to_dense_numpy_or_none being private.

Before:

pandas.py                           arrow.py
_tensor_array_to_numpy()            class ArrowVariableShapedTensorArray
  from arrow import …        ────►    ._to_dense_numpy_or_none()   ← private, but
  if isinstance(arr, …):                                             reached from
      arr._to_dense_numpy_or_none()                                  another module

After:

pandas.py                           arrow.py
__from_arrow__()                    tensor_array_to_numpy()        ← the one entry point
  tensor_array_to_numpy()    ────►    if isinstance(arr, …):
                                          arr._to_dense_numpy_or_none()
                                    class ArrowVariableShapedTensorArray
                                      ._to_dense_numpy_or_none()   ← private, and now
                                                                     only used in-module

Two details:

  • No annotation, and no leading underscore, matching fixed_shape_extension_scalar_to_ndarray a few hundred lines up — the existing precedent in this file for an _internal helper that crosses a module boundary. @DeveloperAPI would overstate it.
  • The import stays function-local. arrow.py and pandas.py both import each other lazily today (arrow.py:619, arrow.py:1175, pandas.py:1305), and I did not want to be the one to find out which module wins at import time.

@marwan116 marwan116 self-assigned this Sep 24, 2026
Moves `_tensor_array_to_numpy` out of `pandas.py` and into `arrow.py` as
`tensor_array_to_numpy`. The `isinstance` check now sits where the Arrow
type is, and `_to_dense_numpy_or_none` is only called from inside its own
module, so its leading underscore is accurate again.

Reads the row extents with `shapes_array.flatten()` rather than slicing
`.values` by the offsets by hand. Equivalent on uniform, ragged, sliced,
empty and null-bearing columns, still zero-copy, and a flat ~0.7us
dearer against a probe that costs ~15us.

Drops `if shape else 1` from `num_items_per_row`: `np.prod(())` is
already 1.

Adds the null tests the reviewer asked for. A null row can be marked on
the storage struct or on either child, independently, and `take` with a
null index marks all three at once, so the test builds the storage by
hand and marks one level at a time. The struct and `data` levels each
leave uniform shapes and adjacent offsets behind them, so without their
checks the probe hands the null row's untouched buffer contents back as
data.

Deleting each remaining guard in turn and re-running the file found three
more that nothing was watching, now covered too: rows of equal size but
different shape ((2,3) vs (3,2), adjacent at a fixed stride so only the
shapes give it away), a column with no rows, and rows of zero size.

Signed-off-by: Marwan Sarieddine <[email protected]>
@marwan116

Copy link
Copy Markdown
Contributor Author

All three are in the description now, each checked rather than restated.

1. Aliasing. Confirmed both ways. On a locally built block the pandas column is a view and a write through it reaches the Arrow buffer; on a block round-tripped through ray.put the buffer is read-only and assignment raises ValueError: assignment destination is read-only. A fixed-shape column does exactly the same thing in both cases, so this is variable-shaped catching up rather than something new — which is how I've worded it.

2. Retention. Confirmed, and your numbers are right. A 2-row slice of a 64 MiB block:

slice owner of the memory owner size
fast path (view) 0.125 MiB pa.Buffer 64.0 MiB
old path (stack) 0.125 MiB — —

RSS is useless for showing this (the allocator does not hand the pages back), so the description quotes the ownership chain instead.

3. Multi-chunk. Confirmed: 2000 × 128 float32 converts in 0.024 ms as one chunk and 5.20 ms as two, and the join fails exactly as you said —

ValueError: all the input arrays must have same number of dimensions,
but the array at index 0 has 2 dimension(s) and the array at index 1 has 1 dimension(s)

Moved out of the "takes the old path" aside and into its own paragraph, with the reason it is not a one-line fix.


One thing your question about nulls turned up that I would not have found otherwise. Having written the null tests, I checked whether the rest of the probe's guards were actually held by anything — delete a guard, run the file, see if it still passes:

guard removed file
self.null_count fails
data_array.null_count fails
num_rows == 0 passes — nothing watching
num_items_per_row == 0 passes — nothing watching
(shapes != shapes[0]).any() passes — nothing watching

Three real gaps, now covered:

  • Rows of equal size but different shape. The existing "rows differing in one extent" test used (2, 3) vs (2, 4), which has irregular offsets, so the adjacency check was rejecting it and the shape comparison never got a turn. (2, 3) vs (3, 2) is six items either way — adjacent at a fixed stride, every other check passes, and without the shape comparison the probe returns a (2, 2, 3) view that relabels row 1's shape.
  • A column with no rows. num_rows == 0 is not defensive: flatten() on an empty column gives size 0, which equals 0 * ndim, so the reshape succeeds and shapes[0] then raises IndexError. An empty block is ordinary.
  • Rows of zero size — (3, 0) and (3, 2, 0), cf. [Data] 2.56 regression: TensorDtype.__from_arrow__ crashes reconstructing an empty tensor column: cannot reshape array of size 0 into shape (0) #64766.

Five guards still survive deletion: shapes_array.null_count, the two data_offsets size checks, the offset-contiguity check, and data_buffer is None. Each can only fire on an array whose shape and data children contradict each other, and a ListArray cannot express a gap between consecutive rows at all — the end of row i is the start of row i+1 by construction. I kept them as cheap consistency checks and would rather say that than write tests against arrays Arrow cannot produce.

Full file is 197 passed.

@marwan116
marwan116 requested a review from rayhhome September 24, 2026 23:14
@goutamvenkat-anyscale
goutamvenkat-anyscale merged commit 9520c9b into master Sep 25, 2026
6 checks passed
@goutamvenkat-anyscale
goutamvenkat-anyscale deleted the marwan/data-tensor-pandas-zero-copy branch September 25, 2026 05:55
nadongjun pushed a commit to nadongjun/ray that referenced this pull request Oct 6, 2026
… pandas (ray-project#66122)

Closes ray-project#66118.

## The problem

Converting a variable-shaped tensor column to a pandas batch copies the
whole tensor payload, even when nothing needs copying.

`ArrowVariableShapedTensorArray.to_numpy` returns one ndarray view per
row. `TensorArray` then stacks those views into a dense array, which
allocates a new buffer and copies every byte.

When all the rows have the same shape, they already sit back to back in
one Arrow buffer. The dense array is already there. Only the stacking
makes a copy.

Measured on a single 128 MiB row:

| | time | rate |
| --- | ---: | ---: |
| before | 14.27 ms | 9.4 GB/s (a memory copy) |
| after | 0.18 ms | 750 GB/s (a view) |

## The fix

`ArrowVariableShapedTensorArray._to_dense_numpy_or_none` returns a
single `(num_rows, *shape)` view when the rows are uniformly shaped and
adjacent in the buffer, and `None` otherwise.
`arrow.tensor_array_to_numpy` tries it and falls back to the existing
path, and the pandas conversion calls that.

`to_numpy` is unchanged on purpose. It is documented to return one
ndarray per row, and a one-row slice of a ragged column is trivially
uniform, so putting the fast path there would change what a ragged
column returns depending on how it was sliced. Three existing tests rely
on that.

Ragged rows, null rows, non-adjacent rows and **multi-chunk columns**
all take the old path.

A chunked column is converted chunk by chunk and joined with
`np.concatenate`, which cannot join a dense `(n, k)` chunk to a ragged
object array:

```
ValueError: all the input arrays must have same number of dimensions,
but the array at index 0 has 2 dimension(s) and the array at index 1 has 1 dimension(s)
```

Reaching the fast path there means rewriting the join as well, which is
out of scope here. On 2000 rows × 128 float32 the same data converts in
0.024 ms as one chunk and 5.20 ms as two.

## What this changes for callers

Both of these are how a **fixed-shape** tensor column already behaves,
so the change brings variable-shaped columns into line rather than
introducing something new. Both are the ordinary price of a zero-copy
view.

**The pandas column now aliases the block.** Writes through it reach the
Arrow buffer, and on a block that came from the object store — whose
buffers are read-only — assignment raises:

```
ValueError: assignment destination is read-only
```

Checked both ways, on a locally built block and on one round-tripped
through `ray.put`; fixed-shape columns behave identically in both.

**Peak memory improves, but a slice pins its whole source block.** The
view holds the Arrow buffer it points into, so a 2-row slice of a 64 MiB
block keeps all 64 MiB alive after that block is dropped:

| | slice | owner | owner size |
| --- | ---: | --- | ---: |
| fast path (view) | 0.125 MiB | `pa.Buffer` | 64.0 MiB |
| old path (stack) | 0.125 MiB | — | — |

## Tests

Eleven tests in `test_tensor_extension.py`, thirteen cases with
parametrization.

Three assert the conversion is actually copy-free — `np.shares_memory`
against the Arrow payload buffer, for uniform rows, a slice of them, and
rows of more than one dimension. Those are the three that fail on master
as a behavior difference; the rest call the new helper directly, which
does not exist there.

Three are regression guards that pass either way and pin that nothing
else moved: ragged rows still convert correctly, `to_numpy` still
returns one ndarray per row, and a null-bearing column still converts to
exactly what the old path produced.

The rest cover the conditions under which the fast path declines, each
pinned separately:

| case | why it declines |
| --- | --- |
| ragged rows | shapes differ |
| rows differing in one extent — `(2, 3)`, `(2, 4)` | offsets are
irregular |
| rows of equal size, different shape — `(2, 3)`, `(3, 2)` | adjacent at
a fixed stride, so only the shapes give it away |
| a column with no rows | nothing to view |
| rows of zero size — `(3, 0)`, `(3, 2, 0)` | nothing to point at |
| a null row on the storage struct | `self.null_count` |
| a null row on the `data` child | `data_array.null_count` |
| a null row on the `shape` child | the extents no longer fill `num_rows
* ndim` |

The three null levels are independent, and the obvious way to make a
null row — `take` with a null index — marks all three at once, so the
test builds the storage by hand and marks one at a time. The struct and
`data` levels are the ones that matter: each leaves uniform shapes and
adjacent offsets behind it, so every other check passes and a view would
hand the null row's untouched buffer contents back as data.

```
pytest python/ray/data/tests/test_tensor_extension.py            197 passed
pytest python/ray/data/tests/test_tensor.py                       95 passed, 3 skipped
pytest python/ray/data/tests/test_pandas_block.py                 57 passed
pytest python/ray/data/tests/test_arrow_serialization.py          32 passed
pytest python/ray/data/tests/unit/test_transform_pyarrow.py       78 passed
pytest python/ray/data/tests/unit/test_data_batch_conversion.py   28 passed
```

## Notes

Not a duplicate: no open PR touches this conversion, and no PR
references ray-project#66118. The nearest neighbour, ray-project#64961, changes tensor
concatenation during row takes, not the pandas conversion.

AI assistance was used for this change.

---------

Signed-off-by: Marwan Sarieddine <[email protected]>
moiz-naeem added a commit to moiz-naeem/ray that referenced this pull request Oct 22, 2026
Addresses review feedback on ray-project#67236.

to_numpy() on a variable-shaped tensor column only consulted the struct's
own validity bitmap. A row that is null in just its data or shape child
passes that check, so the row was rebuilt from offsets that address another
row's bytes and came back as that row's data, with no error. Build the null
mask from the struct and the data child, and keep the existing shape-is-None
test, so a null at any level reads as missing.

TensorArray has no null representation, so a null row forced the backing
ndarray to object dtype. The column then reported TensorDtype(shape=(),
dtype=object) and could not be converted back to Arrow. Refuse the
conversion in TensorDtype.__from_arrow__ with a message pointing at
batch_format="numpy" instead of returning a TensorArray that cannot round
trip. Checked twice: up front on null_count, which also keeps a multi-chunk
column away from a concatenate that cannot mix dense and ragged chunks, and
again on the converted values, which is what catches a child-level null.

test_variable_shaped_null_rows_to_pandas_unchanged pinned the old pandas
output as a regression guard for ray-project#66122. That baseline was the bug: it
compared to_numpy() against to_pandas().to_numpy(), both reading through the
same broken path, so it held while both returned another row's bytes. It now
asserts the column is refused.

Signed-off-by: moiz-naeem <[email protected]>
rayo5o added a commit to rayo5o/ray that referenced this pull request Nov 5, 2026
…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]>
sai-miduthuri added a commit that referenced this pull request Nov 13, 2026
…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]>
goutamvenkat-anyscale pushed a commit that referenced this pull request Nov 24, 2026
…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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

data Ray Data-related issues go add ONLY when ready to merge, run all tests

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Data] Potential unnecessary copy converting flat Arrow tensor columns to pandas with zero_copy_batch=True

3 participants