This is an automated email from the ASF dual-hosted git repository.
gaogaotiantian pushed a commit to branch branch-4.x
in repository https://gitbox.apache.org/repos/asf/spark.git
The following commit(s) were added to refs/heads/branch-4.x by this push:
new aba27a9bc015 [SPARK-60599][PYTHON] Avoid materializing per-row
argument tuples when evaluating Arrow-optimized Python UDFs
aba27a9bc015 is described below
commit aba27a9bc0156d58cb4c4cb277ecd0b84311c3a8
Author: Tian Gao <[email protected]>
AuthorDate: Mon Nov 9 14:32:49 2026 -0800
[SPARK-60599][PYTHON] Avoid materializing per-row argument tuples when
evaluating Arrow-optimized Python UDFs
### What changes were proposed in this pull request?
`ArrowBatchedUDFArrowHandler` (Arrow-optimized `udf`,
`SQL_ARROW_BATCHED_UDF`) used to evaluate each UDF by zipping its argument
columns into a materialized list of row tuples and then calling
`udf_func(*row)` for each row:
```python
rows = list(zip(*[columns[o] for o in offsets]))
...
return [udf_func(*row) for row in rows]
```
This PR passes the argument columns to `_evaluate_batch_udf` and iterates
over them directly:
```python
args = [columns[o] for o in offsets]
...
if len(args) == 1:
return [udf_func(v) for v in args[0]]
return [udf_func(*row) for row in zip(*args)]
```
A single-argument UDF builds no per-row tuple at all. A multi-argument UDF
still gets one tuple per row from `zip()`, but each tuple is freed right after
the call instead of being held in a list for the whole batch.
The UDF is deliberately called in the comprehension body rather than
through `list(map(udf_func, *args))`: `map()` calls the UDF inside its
`__next__`, so a `StopIteration` raised by the UDF would be taken as the end of
input and the batch would come back short (`RESULT_ROWS_MISMATCH`) instead of
failing with `STOP_ITERATION_OCCURRED`. A code comment records this.
Other changes:
- The `arrow.concurrency.level` thread-pool path passes the columns to
`pool.map(udf_func, *args)` instead of mapping over row tuples.
- Zero-arg UDFs keep a dedicated branch (`[udf_func() for _ in
range(num_rows)]`), which replaces the `zero_arg` flag and the `_NoValue`
placeholder column.
- `bench_eval_type.ArrowBatchedUDFTimeBench` gets a 3-arg `concat3_udf`
case; all existing cases there were single-arg.
### Why are the changes needed?
Performance. The old code allocated one tuple per row, per UDF, per batch,
and kept them all alive in a list until the batch was done. Since tuples are
tracked by the cyclic GC, a batch's worth of live tuples triggers extra GC
collections, which scan the live Python column lists. Not materializing the
list avoids most of that.
Results from `ArrowBatchedUDFTimeBench` (in-process `worker.main`, no JVM).
These are min wall times over 5 rounds of 7 runs each, with the baseline and
this PR alternated between rounds. Apple Silicon, CPython 3.12.12, PyArrow
23.0.1:
| Scenario | `identity_udf` (1 arg) | `concat3_udf` (3 args) |
|---|---|---|
| `sm_batch_few_col` | 17.18 -> 16.95 ms (-1.3%) | 19.72 -> 19.57 ms
(-0.8%) |
| `lg_batch_few_col` | 42.53 -> 40.61 ms (-4.5%) | 48.93 -> 47.07 ms
(-3.8%) |
| `pure_ints` | 61.95 -> 59.66 ms (-3.7%) | 69.39 -> 66.87 ms (-3.6%) |
| `pure_floats` | 60.79 -> 58.42 ms (-3.9%) | 103.80 -> 101.55 ms (-2.2%) |
| `pure_strings` | 112.97 -> 111.35 ms (-1.4%) | 115.13 -> 113.15 ms
(-1.7%) |
| `mixed_types` | 86.96 -> 85.00 ms (-2.3%) | 93.41 -> 91.11 ms (-2.5%) |
| `sm_batch_many_col` | 43.11 -> 43.33 ms (+0.5%) | 43.76 -> 43.59 ms
(-0.4%) |
| `lg_batch_many_col` | 169.69 -> 168.39 ms (-0.8%) | 173.32 -> 171.51 ms
(-1.0%) |
Run-to-run spread is a few percent, so the individual percentages are
approximate. For comparison, the `list(map(...))` variant measured in the same
run was within about 1% of these numbers in most scenarios (about 2.5% in
`pure_strings`), but it breaks `StopIteration` handling as described above.
The `*_many_col` scenarios send 50 columns to a UDF that reads at most 3,
so their time is dominated by converting input columns that the UDF never
reads. In real queries, `EvalPythonEvaluatorFactory` projects only the UDF
argument expressions, so the few-column numbers are closer to what real
workloads get.
### Does this PR introduce _any_ user-facing change?
No. Results, their order, and exception / `StopIteration` handling are
unchanged. The decoded output of every `ArrowBatchedUDFTimeBench` scenario is
byte-identical before and after this change.
### How was this patch tested?
- Existing tests in
`pyspark.eval_handlers.tests.test_arrow_eval_type_handlers`, including the
zero-arg, keyword-arg, multi-arg, and concurrency cases.
- `test_stop_iteration_raises_runtime_error` now asserts the
`STOP_ITERATION_OCCURRED` error condition (previously it only checked for
`PySparkRuntimeError`, which `RESULT_ROWS_MISMATCH` also satisfies), with one
subtest per evaluation branch: zero-arg, single-arg, multi-arg, and keyword-arg.
- New `test_concurrency_level_multi_and_zero_arg`, which covers the
thread-pool path with multi-arg, keyword-arg, and zero-arg UDFs.
- The end-to-end `test_raise_stop_iteration` tests (classic and Connect,
Arrow UDF suites) cover the user-visible error; they failed in CI on the
earlier `list(map(...))` version of this PR.
- Benchmarked with `ArrowBatchedUDFTimeBench` as described above.
### Was this patch authored or co-authored using generative AI tooling?
Generated-by: Claude Code (Claude Opus 5.5)
This pull request and its description were written by Isaac.
Closes #59845 from gaogaotiantian/SPARK-60599-arrow-batched-udf-map.
Authored-by: Tian Gao <[email protected]>
Signed-off-by: Tian Gao <[email protected]>
(cherry picked from commit 0ec7b70fe10390ff62ab0a74c55014c1ecef29d4)
Signed-off-by: Tian Gao <[email protected]>
skip-checks: true
---
python/benchmarks/bench_eval_type.py | 3 +-
python/pyspark/eval_handlers/_arrow.py | 31 +++++++++--------
.../tests/test_arrow_eval_type_handlers.py | 39 +++++++++++++++++++---
3 files changed, 52 insertions(+), 21 deletions(-)
diff --git a/python/benchmarks/bench_eval_type.py
b/python/benchmarks/bench_eval_type.py
index 592654c43eb9..dc2ad6220620 100644
--- a/python/benchmarks/bench_eval_type.py
+++ b/python/benchmarks/bench_eval_type.py
@@ -535,11 +535,12 @@ class _ArrowBatchedBenchMixin:
)
# UDFs for SQL_ARROW_BATCHED_UDF operate on individual Python values.
- # arg_offsets=[0] means the UDF receives column 0 value per row.
+ # arg_offsets lists the input columns whose values are passed to the UDF
per row.
_udfs = {
"identity_udf": (lambda x: x, None, [0]),
"stringify_udf": (lambda x: str(x), StringType(), [0]),
"nullcheck_udf": (lambda x: x is not None, BooleanType(), [0]),
+ "concat3_udf": (lambda a, b, c: f"{a}{b}{c}", StringType(), [0, 1, 2]),
}
params = [list(_scenario_configs), list(_udfs)]
param_names = ["scenario", "udf"]
diff --git a/python/pyspark/eval_handlers/_arrow.py
b/python/pyspark/eval_handlers/_arrow.py
index fb635c6b1fca..2480e5a21e67 100644
--- a/python/pyspark/eval_handlers/_arrow.py
+++ b/python/pyspark/eval_handlers/_arrow.py
@@ -33,7 +33,6 @@ import time
from collections.abc import Iterator
from typing import TYPE_CHECKING, Any
-from pyspark import _NoValue
from pyspark.errors import PySparkRuntimeError
from pyspark.eval_handlers._base import (
BatchEvalTypeHandler,
@@ -840,12 +839,10 @@ class
ArrowBatchedUDFArrowHandler(BatchEvalTypeHandler["pa.RecordBatch"]):
wrapped_func, args_kwargs_offsets = wrap_kwargs_support(
func, udf.args_offsets, udf.kwargs_offsets
)
- zero_arg = len(args_kwargs_offsets) == 0
self._udf_infos.append(
(
wrapped_func,
- args_kwargs_offsets or (0,),
- zero_arg,
+ args_kwargs_offsets,
to_arrow_type(
udf.return_type,
timezone="UTC",
@@ -893,13 +890,21 @@ class
ArrowBatchedUDFArrowHandler(BatchEvalTypeHandler["pa.RecordBatch"]):
phase_timers = None
@fail_on_stopiteration
- def _evaluate_batch_udf(udf_func: Any, rows: list[tuple]) -> list[Any]:
+ def _evaluate_batch_udf(udf_func: Any, args: list[list[Any]],
num_rows: int) -> list[Any]:
if runner_conf.arrow_concurrency_level <= 0:
- return [udf_func(*row) for row in rows]
+ if not args:
+ return [udf_func() for _ in range(num_rows)]
+ # Call the UDF in the comprehension body, not via
list(map(...)): map()
+ # would swallow a StopIteration raised by the UDF as end of
input.
+ if len(args) == 1:
+ return [udf_func(v) for v in args[0]]
+ return [udf_func(*row) for row in zip(*args)]
from concurrent.futures import ThreadPoolExecutor
with
ThreadPoolExecutor(max_workers=runner_conf.arrow_concurrency_level) as pool:
- return list(pool.map(lambda row: udf_func(*row), rows))
+ if not args:
+ return list(pool.map(lambda _: udf_func(),
range(num_rows)))
+ return list(pool.map(udf_func, *args))
# Keep phase totals and the batch count local, then publish them once
per task.
input_duration_ns = 0
@@ -924,25 +929,19 @@ class
ArrowBatchedUDFArrowHandler(BatchEvalTypeHandler["pa.RecordBatch"]):
)
for col, conv in zip(input_batch.itercolumns(),
self._arrow_to_py_converters)
]
- if not columns:
- columns = [[_NoValue] * num_rows]
# --- Process: evaluate each UDF row-by-row ---
output_arrays: list[pa.Array] = []
- for udf_func, offsets, zero_arg, arrow_return_type,
result_conv in self._udf_infos:
+ for udf_func, offsets, arrow_return_type, result_conv in
self._udf_infos:
if phase_timers is not None and output_arrays:
# Reuse the batch start for the first UDF, avoiding
another clock read.
# Later UDFs start input after the loop transition.
input_start_ns = clock()
- rows = (
- [() for _ in range(num_rows)]
- if zero_arg
- else list(zip(*[columns[o] for o in offsets]))
- )
+ args = [columns[o] for o in offsets]
if phase_timers is not None:
udf_start_ns = clock()
input_duration_ns += udf_start_ns - input_start_ns
- results = _evaluate_batch_udf(udf_func, rows)
+ results = _evaluate_batch_udf(udf_func, args, num_rows)
if phase_timers is not None:
output_start_ns = clock()
udf_duration_ns += output_start_ns - udf_start_ns
diff --git
a/python/pyspark/eval_handlers/tests/test_arrow_eval_type_handlers.py
b/python/pyspark/eval_handlers/tests/test_arrow_eval_type_handlers.py
index 834fa7599874..7022daaadb01 100644
--- a/python/pyspark/eval_handlers/tests/test_arrow_eval_type_handlers.py
+++ b/python/pyspark/eval_handlers/tests/test_arrow_eval_type_handlers.py
@@ -366,13 +366,44 @@ class
ArrowBatchedUDFArrowHandlerTests(ArrowEvalTypeHandlerTestCase):
out = list(handler.run(0, iter([self._batch(a=list(range(10)), b=[0] *
10)])))
self.assertEqual(out[0].column(0).to_pylist(), [v * 2 for v in
range(10)])
+ def test_concurrency_level_multi_and_zero_arg(self):
+ conf =
RunnerConf({"spark.sql.execution.pythonUDF.arrow.concurrency.level": "4"})
+ handler = self._handler((lambda a, b: a - b, [0, 1], {}, LongType()),
runner_conf=conf)
+ out = list(handler.run(0, iter([self._batch(a=list(range(10)), b=[1] *
10)])))
+ self.assertEqual(out[0].column(0).to_pylist(), [v - 1 for v in
range(10)])
+
+ handler = self._handler((lambda x, y: x - y, [0], {"y": 1},
LongType()), runner_conf=conf)
+ out = list(handler.run(0, iter([self._batch(a=list(range(10)), b=[1] *
10)])))
+ self.assertEqual(out[0].column(0).to_pylist(), [v - 1 for v in
range(10)])
+
+ handler = self._handler(
+ (lambda: 7, [], {}, LongType()), runner_conf=conf,
input_type=StructType()
+ )
+ empty = pa.RecordBatch.from_pydict({"a": [1, 2, 3]}).select([])
+ out = list(handler.run(0, iter([empty])))
+ self.assertEqual(out[0].column(0).to_pylist(), [7, 7, 7])
+
def test_stop_iteration_raises_runtime_error(self):
- def stop(a):
+ def stop(*args, **kwargs):
raise StopIteration()
- handler = self._handler((stop, [0], {}, LongType()))
- with self.assertRaises(PySparkRuntimeError):
- list(handler.run(0, iter([self._batch(a=[1], b=[0])])))
+ batch = self._batch(a=[1, 2], b=[0, 0])
+ empty = batch.select([])
+ # (args_offsets, kwargs_offsets, input_type, batch): one case per
evaluation branch.
+ cases = {
+ "zero_arg": ([], {}, StructType(), empty),
+ "single_arg": ([0], {}, None, batch),
+ "multi_arg": ([0, 1], {}, None, batch),
+ "keyword_arg": ([0], {"y": 1}, None, batch),
+ }
+ for name, (args_offsets, kwargs_offsets, input_type, data) in
cases.items():
+ with self.subTest(case=name):
+ handler = self._handler(
+ (stop, args_offsets, kwargs_offsets, LongType()),
input_type=input_type
+ )
+ with self.assertRaises(PySparkRuntimeError) as ctx:
+ list(handler.run(0, iter([data])))
+ self.assertEqual(ctx.exception.getCondition(),
"STOP_ITERATION_OCCURRED")
@unittest.skipIf(not have_pyarrow, pyarrow_requirement_message)
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]