Skip to content

[Data] Skip the redundant block copy for NumPy batches with zero_copy_batch=False - #67192

Merged
goutamvenkat-anyscale merged 5 commits into
ray-project:masterfrom
rayo5o:data-skip-redundant-batch-copy
Nov 24, 2026
Merged

goutamvenkat-anyscale merged 5 commits into
ray-project:masterfrom
rayo5o:data-skip-redundant-batch-copy

Conversation

@rayo5o

@rayo5o rayo5o commented Oct 20, 2026 •

Copy link
Copy Markdown
Contributor

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

  • Add numpy_copy_is_deep(table) in transform_pyarrow.py. It returns True only for integer, floating, boolean, null, timestamp, date, duration and fixed-shape tensor columns, and tensor columns only when they have no null rows.
  • Batcher takes an optional skip_copy callable. When ensure_copy is set and skip_copy(batch) returns True, the block copy is skipped. Batcher itself doesn't know about NumPy.
  • batch_blocks() passes the check above as skip_copy when batch_format == "numpy", next to the NumPy copy it relies on. Non-Arrow batches are copied as before.
  • Add tests for the type check, the Batcher copy decision, and in-place mutation in map_batches with 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.

data master this PR
8 int64 columns × 4M rows (244 MiB) 76 ms / 501 MiB 39 ms / 245 MiB
fixed-shape tensor, 50k × (32, 32) float32 52 ms / 392 MiB 47 ms / 196 MiB
variable-shaped tensor, 1M rows 1583 ms / 480 MiB 1527 ms / 480 MiB
list<int64>, 1M rows 191 ms / 205 MiB 196 ms / 205 MiB
8 int64 columns + 1 string column 145 ms / 583 MiB 151 ms / 583 MiB

Batches 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] Make zero_copy_batch=False copy default batches #67154, map_transformer.py also passes ensure_copy=True for it, so map_batches reaches the batch_size=None branch of Batcher too. test_map_batches_numpy_batch_mutation now covers batch_size=None; if that branch skips the block copy for every NumPy batch, the variable-shaped tensor case fails.
  • Not a duplicate: this is the implementation for [Data] Avoid copying NumPy batches twice when zero_copy_batch=False #67185, which came out of the [Data] Make zero_copy_batch=False copy default batches #67154 review. I searched open PRs for ensure_copy, zero_copy_batch, _copy_batch and Batcher and found none changing this copy.
  • Tests, run locally with Ray nightly 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 return True, the variable-shaped tensor cases fail with output 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-based test_make_async_gen_* tests that fail intermittently.
    • After rebasing onto 74b21dc8 and adding the null-row fix (Python 3.12, pyarrow 26.0.1): test_transform_pyarrow.py and test_batcher.py 79 passed; test_map_batches.py 729 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.
    • After rebasing onto 14909af5 (includes [Data] Make zero_copy_batch=False copy default batches #67154) and adding batch_size=None to the test (pyarrow 26.0.1): test_transform_pyarrow.py and test_batcher.py 79 passed; test_map_batches.py 733 passed, 2 failed (test_map_batches_timestamp_nanosecs, as above).
    • After moving the NumPy check out of Batcher (316dc199, pyarrow 26.0.1): same results, 79 passed and 733 passed, 2 failed. If batch_blocks skips the copy for every Arrow batch, the variable-shaped tensor mutation tests and the Batcher test fail. Null-row tensor columns still don't let a UDF modify the source (V1, V2 and native tensors, 1 and 2 chunks, batch_size 2 and None).
    • 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 20, 2026 14:04

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

@ray-gardener ray-gardener Bot added data Ray Data-related issues community-contribution Contributed by the community labels Oct 20, 2026

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

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.

@rayo5o

rayo5o commented Oct 23, 2026

Copy link
Copy Markdown
Contributor Author

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, [True, None] comes out as an object array of bool/None. I checked the other whitelisted types with nulls (ints, dates, timestamps, durations, null) and they all come out non-object, so bool is the only exception. Copying it is still a full copy since the elements are immutable. I'll fix the docstring to say that.

Multi-chunk: I can reproduce it. With a 256 MiB float64 column, extra peak memory is 513 MiB on both 05d07da and this PR for 2, 8 and 64 chunks, and drops to 257 MiB only with 1 chunk. With several chunks the NumPy conversion has to concatenate them, which is already a full copy, and _copy_batch then copies that again. My benchmark called combine_chunks() first, so it missed this. Skipping _copy_batch when the conversion already made a fresh array would be a separate change, so I'd keep it out of this PR. I'll note the limitation in the description.

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

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.

@rayo5o

rayo5o commented Nov 2, 2026

Copy link
Copy Markdown
Contributor Author

@goutamvenkat-anyscale could you take a look when you have a chance? It drops one full copy of the block for NumPy batches with zero_copy_batch=False (peak 501 → 245 MiB for a 244 MiB block). Rebased on master on Nov 2 after a docstring conflict with #67539, and CI is green. Multi-chunk blocks aren't covered here; that's step 2 in #67459.

@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 using default effort and found 1 potential issue.

Fix All in Cursor

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]>
@rayo5o
rayo5o force-pushed the data-skip-redundant-batch-copy branch from 8b63ad6 to 1c0a213 Compare November 16, 2026 10:41
)


def converts_to_non_object_numpy(table: "pyarrow.Table") -> bool:

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.

Let's rename this function to something like numpy_on_copy_will_not_cast_to_object

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.

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.

Comment thread python/ray/data/_internal/batcher.py Outdated
Comment on lines +222 to +225
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.

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.

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

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.

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]>
@goutamvenkat-anyscale goutamvenkat-anyscale added the go add ONLY when ready to merge, run all tests label Nov 24, 2026
@goutamvenkat-anyscale
goutamvenkat-anyscale enabled auto-merge (squash) November 24, 2026 18:24
@goutamvenkat-anyscale
goutamvenkat-anyscale merged commit ac15152 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] Avoid copying NumPy batches twice when zero_copy_batch=False

4 participants