Repository navigation
[Data] Skip the redundant block copy for NumPy batches with zero_copy_batch=False - #67192
Conversation
There was a problem hiding this comment.
Code Review
This pull request introduces an optimization to skip copying Arrow batches during batching when a subsequent NumPy conversion will already copy all of the data (i.e., when all columns convert to non-object NumPy arrays). It adds a helper function converts_to_non_object_numpy to identify such schemas, updates the Batcher and batching utilities to support and propagate a numpy_copy_follows flag, and includes comprehensive unit tests to verify the optimization and ensure that in-place mutations do not affect the source data. There are no review comments, so I have no feedback to provide.
hikaru-212
left a comment
There was a problem hiding this comment.
I independently verified the copy-isolation behavior against parent 05d07da and PR HEAD ba3c7a61.
The additional tests passed on both revisions under PyArrow 23 and 26. They cover numeric and tensor batches, nullable types, ragged-tensor fallback, mixed schemas, multiple chunks, and non-NumPy formats. No source-mutation regression was observed within the tested scope.
A focused benchmark also confirmed reduced peak memory for single-chunk numeric batches, while multi-chunk batches showed no comparable improvement.
One minor observation: nullable boolean columns are still classified as safe even though they produce object-dtype NumPy arrays. This remains safe because the elements are immutable (bool/None), but the helper's name and docstring do not fully reflect that behavior.
No implementation correctness issue was found within the tested scope.
Thanks for testing this on two PyArrow versions. Nullable bool: you're right, Multi-chunk: I can reproduce it. With a 256 MiB float64 column, extra peak memory is 513 MiB on both |
Jadiouo
left a comment
There was a problem hiding this comment.
Verified against base 05d07da and PR head 0ec49f3 (Python 3.13, pyarrow 25.0.1, numpy 2.5.3) by calling batch_blocks(..., batch_format="numpy", ensure_copy=True) on single- and multi-chunk blocks. I covered int, float, bool, nullable int, timestamp, fixed-shape tensor, string, list, variable-shaped tensor and mixed schemas, with batch_size None and 4.
No output shared memory with the source, and in-place writes never changed the source. The results matched base in every case. Forcing converts_to_non_object_numpy to return True makes the variable-shaped tensor case mutate the source, so the check is needed.
Peak extra RSS for 8 int64 columns x 4M rows dropped from 501 MB to 244 MB. The 2-chunk and 8-chunk cases stay at 491 MB, matching what hikaru-212 noted. Timings were too noisy in my environment to quote.
The added tests pass (25), and test_batcher, test_transform_pyarrow and block_batching show no regressions (210 passed).
map_groups and the shallow copy of list elements are out of scope here; I filed #67367 for those.
LGTM.
0ec49f3 to
04df9f1
Compare
|
@goutamvenkat-anyscale could you take a look when you have a chance? It drops one full copy of the block for NumPy batches with |
04df9f1 to
f0d7fd0
Compare
There was a problem hiding this comment.
Cursor Bugbot has reviewed your changes using default effort and found 1 potential issue.
Reviewed by Cursor Bugbot for commit f0d7fd0. Configure here.
…_batch=False With zero_copy_batch=False, Batcher copied the Arrow block and _format_batch copied the NumPy arrays again. Skip the block copy when every column converts to a non-object NumPy array, since the NumPy copy already copies all of the data. Object columns (lists, structs, strings, variable-shaped tensors) still copy the block, because _copy_batch only copies the outer array. Closes ray-project#67185 Signed-off-by: ray941005 <[email protected]>
Nullable boolean columns convert to object arrays of bool/None. Copying them is still a full copy because the elements are immutable, but the docstring said every accepted column converts to a non-object array. Signed-off-by: rayo5o <[email protected]>
A fixed-shape tensor column with null rows converts to an object array of views into the block, so copying the NumPy batch does not isolate it. Only skip the block copy for tensor columns without nulls. Signed-off-by: rayo5o <[email protected]>
With ray-project#67154, zero_copy_batch=False also copies when batch_size is None, so map_batches now reaches the batch_size=None branch of the Batcher that skips the block copy for NumPy batches. Add None to the test. Signed-off-by: rayo5o <[email protected]>
8b63ad6 to
1c0a213
Compare
| ) | ||
|
|
||
|
|
||
| def converts_to_non_object_numpy(table: "pyarrow.Table") -> bool: |
There was a problem hiding this comment.
Let's rename this function to something like numpy_on_copy_will_not_cast_to_object
There was a problem hiding this comment.
Renamed to numpy_copy_is_deep in 316dc19. I didn't use "will not cast to object" because nullable bool columns do become object arrays ([True, None] comes out as dtype=object). They're still fully copied since bool and None are immutable, so the function returns True for them.
| numpy_copy_follows: Whether the caller converts each batch to NumPy and | ||
| copies it afterwards. If so, ``ensure_copy`` skips the block copy | ||
| for Arrow batches whose columns all convert to non-object NumPy | ||
| arrays, since the later copy already copies all of their data. |
There was a problem hiding this comment.
Not sure I follow what this param is accomplishing. It's also a leaky abstraction to have the generic Batcher handle the logic for when to copy the underlying numpy buffers
There was a problem hiding this comment.
With zero_copy_batch=False and NumPy batches, Batcher copies the Arrow block and then _format_batch copies every NumPy array again. For fixed-width columns the second copy already gives the UDF its own memory, so the first one only doubles the peak (501 → 245 MiB on a 244 MiB block). It can't be skipped for every NumPy batch: variable-shaped tensors become object arrays of views into the block, and copying those only copies the references.
Agreed that Batcher shouldn't know about NumPy. In 316dc19 it takes a generic skip_copy callable instead, and batch_blocks passes the NumPy check only for batch_format="numpy", right where it sets up the NumPy copy. If you'd rather leave Batcher untouched, the other option is to not ask it to copy NumPy batches and copy the Arrow block in _format_batch when it has object columns. Happy to switch.
…y_is_deep Batcher no longer knows about NumPy. batch_blocks passes the NumPy check as skip_copy for batch_format="numpy", next to the NumPy copy it relies on. Rename converts_to_non_object_numpy to numpy_copy_is_deep: nullable bool columns do convert to object arrays but are still copied in full. Signed-off-by: rayo5o <[email protected]>

Description
With
zero_copy_batch=False, a NumPy batch is copied twice:Batcher.next_batch()copies the Arrow block, and_format_batch()copies the NumPy arrays again with_copy_batch(). For columns that convert to regular NumPy arrays, the second copy already copies all of the data, so the first one only doubles peak memory.The block copy can't be dropped for every column. Lists, structs, strings and variable-shaped tensors convert to object arrays, and
_copy_batch()only copies the outer array. Without the block copy, a variable-shaped tensor's elements would point into the source block and stay writable, so a UDF mutating them would change the source. Fixed-shape tensor columns with null rows convert the same way, so they keep the copy too.Changes
numpy_copy_is_deep(table)intransform_pyarrow.py. It returnsTrueonly for integer, floating, boolean, null, timestamp, date, duration and fixed-shape tensor columns, and tensor columns only when they have no null rows.Batchertakes an optionalskip_copycallable. Whenensure_copyis set andskip_copy(batch)returnsTrue, the block copy is skipped.Batcheritself doesn't know about NumPy.batch_blocks()passes the check above asskip_copywhenbatch_format == "numpy", next to the NumPy copy it relies on. Non-Arrow batches are copied as before.Batchercopy decision, and in-place mutation inmap_batcheswith fixed-shape and variable-shaped tensors.Benchmark
One Arrow block,
batch_blocks(..., batch_size=None, batch_format="numpy", ensure_copy=True)called directly, each run in a fresh process, median of 3 runs (7 interleaved runs for the last three rows). Memory is extra peak RSS.list<int64>, 1M rowsBatches with an object column still copy the block, so their memory is unchanged and the time differences are within noise. One string column is enough to keep the whole batch on the old path. Deciding per column would be a bigger change, so I left it out.
The numbers above are for single-chunk blocks. With several chunks, the NumPy conversion concatenates them, which is already a full copy, and
_copy_batch()copies that again, so peak memory stays the same as master (256 MiB float64 column: 513 MiB with 2, 8 or 64 chunks on both). Skipping_copy_batch()when the conversion already returns a fresh array would cover that case; I left it for a separate change.Related issues
Closes #67185
Additional information
batch_size=None: since [Data] Makezero_copy_batch=Falsecopy default batches #67154,map_transformer.pyalso passesensure_copy=Truefor it, somap_batchesreaches thebatch_size=Nonebranch ofBatchertoo.test_map_batches_numpy_batch_mutationnow coversbatch_size=None; if that branch skips the block copy for every NumPy batch, the variable-shaped tensor case fails.zero_copy_batch=False#67185, which came out of the [Data] Makezero_copy_batch=Falsecopy default batches #67154 review. I searched open PRs forensure_copy,zero_copy_batch,_copy_batchandBatcherand found none changing this copy.05d07da, Python 3.12, pyarrow 26.0.0:pytest python/ray/data/tests/test_transform_pyarrow.py::test_numpy_copy_is_deep python/ray/data/tests/test_batcher.py::test_batcher_skip_copy python/ray/data/tests/test_map_batches.py::test_map_batches_numpy_batch_mutation: 25 passed. With the NumPy check forced to returnTrue, the variable-shaped tensor cases fail withoutput array is read-only.pytest python/ray/data/tests/test_map_batches.py python/ray/data/tests/test_transform_pyarrow.py python/ray/data/tests/test_batcher.py python/ray/data/tests/block_batching/: 935 passed, 4 failed. The 4 also fail on unmodified master:test_map_batches_timestamp_nanosecs(the worker can't import the test module in my setup) and two timing-basedtest_make_async_gen_*tests that fail intermittently.74b21dc8and adding the null-row fix (Python 3.12, pyarrow 26.0.1):test_transform_pyarrow.pyandtest_batcher.py79 passed;test_map_batches.py729 passed, 2 failed (test_map_batches_timestamp_nanosecs, which also fails on master). The two null-row tensor cases in the type check test fail without the fix.14909af5(includes [Data] Makezero_copy_batch=Falsecopy default batches #67154) and addingbatch_size=Noneto the test (pyarrow 26.0.1):test_transform_pyarrow.pyandtest_batcher.py79 passed;test_map_batches.py733 passed, 2 failed (test_map_batches_timestamp_nanosecs, as above).Batcher(316dc199, pyarrow 26.0.1): same results, 79 passed and 733 passed, 2 failed. Ifbatch_blocksskips the copy for every Arrow batch, the variable-shaped tensor mutation tests and theBatchertest fail. Null-row tensor columns still don't let a UDF modify the source (V1, V2 and native tensors, 1 and 2 chunks,batch_size2 andNone).pre-commit run --files <changed files>: passed.