viirya commented on code in PR #60327:
URL: https://github.com/apache/spark/pull/60327#discussion_r4540998068
##########
sql/core/src/main/scala/org/apache/spark/sql/execution/python/EvalPythonExec.scala:
##########
@@ -61,11 +63,15 @@ object EvalPythonExec {
*/
trait EvalPythonExec extends UnaryExecNode {
def udfs: Seq[PythonUDF]
+
+ /** The columns of the child that are passed through to the output. */
+ def requiredChildOutput: Seq[Attribute]
+
def resultAttrs: Seq[Attribute]
protected def evaluatorFactory: EvalPythonEvaluatorFactory
- override def output: Seq[Attribute] = child.output ++ resultAttrs
+ override def output: Seq[Attribute] = requiredChildOutput ++ resultAttrs
Review Comment:
Thanks, fixed in 29c9aa7. `EvalPythonExec` now has `withRequiredChildOutput`
like the logical node, and `InsertSortForLimitAndOffset` adds the ordering
columns that the evaluation does not pass through to its `requiredChildOutput`,
after propagating them below it. `InProcessArrowEvalPythonExec` passes through
its whole child, so its `withRequiredChildOutput` only checks that the columns
are in it. The two cases of `InsertSortForLimitAndOffsetSuite` pass now.
##########
python/pyspark/sql/tests/arrow/test_arrow_python_udf_cached.py:
##########
@@ -188,6 +189,87 @@ def
test_udf_on_timestamps_cached_under_different_time_zone(self):
df.unpersist()
+ def test_udfs_without_pass_through_columns(self):
Review Comment:
Fixed in 29c9aa7.
##########
sql/core/src/main/scala/org/apache/spark/sql/execution/python/ColumnarArrowEvalPythonEvaluatorFactory.scala:
##########
@@ -150,8 +156,19 @@ private[python] class
ColumnarArrowEvalPythonEvaluatorFactory(
batch.numRows() > 0
}
- evalWithRowQueue(nonEmptyIter, context, pyFuncs, argMetas,
- allInputs.toSeq, udfInputSchema, outputTypes,
resolveColumnIndices(allInputs.toSeq))
+ val inputColumnIndices = resolveColumnIndices(allInputs.toSeq)
+ if (passThroughOutput.isEmpty) {
+ // The vectors of a result batch are valid until the next one is
requested, which a
+ // consumer respecting the contract of ColumnVector does not rely on
beyond that.
+ evalPython(nonEmptyIter, context, pyFuncs, argMetas, allInputs.toSeq,
udfInputSchema,
Review Comment:
Yes, it is intended, and the comment there now says so (29c9aa7). These are
the batches Python returns, as with the direct output before SPARK-60325, and
`maxRecordsPerOutputBatch` / `maxBytesPerOutputBatch` are the configs for
bounding what goes to a columnar parent. Cutting them by `maxRecordsPerBatch`
and `maxBytesPerBatch` here would need a slicer that applies both limits at
once, since the output processors take one of them, and would slice batches
that the parent may not need cut. For a stacked UDF, the right place to bound
the batches is where it splits its input batches, which is item 9 of #59582,
and the fix for that covers any columnar child, not only this one.
##########
sql/core/src/main/scala/org/apache/spark/sql/execution/SparkStrategies.scala:
##########
@@ -927,13 +927,22 @@ abstract class SparkStrategies extends
QueryPlanner[SparkPlan] {
*/
object PythonEvals extends Strategy {
override def apply(plan: LogicalPlan): Seq[SparkPlan] = plan match {
- case ArrowEvalPython(udfs, output, child,
PythonEvalType.SQL_SCALAR_ARROW_INPROCESS_UDF) =>
+ case e @ ArrowEvalPython(
+ udfs, requiredChildOutput, resultAttrs, child,
+ PythonEvalType.SQL_SCALAR_ARROW_INPROCESS_UDF) =>
InProcessPythonUDFBuilder.checkConfiguration(conf)
- InProcessArrowEvalPythonExec(udfs, output, planLater(child)) :: Nil
- case ArrowEvalPython(udfs, output, child, evalType) =>
- ArrowEvalPythonExec(udfs, output, planLater(child), evalType) :: Nil
- case BatchEvalPython(udfs, output, child) =>
- BatchEvalPythonExec(udfs, output, planLater(child)) :: Nil
+ // The in-process evaluator passes through the whole child, so drop
what is not required.
+ val exec = InProcessArrowEvalPythonExec(udfs, resultAttrs,
planLater(child))
+ if (requiredChildOutput == child.output) {
+ exec :: Nil
+ } else {
+ ProjectExec(e.output, exec) :: Nil
Review Comment:
I'll leave it as is, so that the in-process evaluation keeps joining with
its whole child, and the `ProjectExec` is cheap.
##########
python/pyspark/sql/tests/arrow/test_arrow_python_udf_cached.py:
##########
@@ -188,6 +189,87 @@ def
test_udf_on_timestamps_cached_under_different_time_zone(self):
df.unpersist()
+ def test_udfs_without_pass_through_columns(self):
+ # Only the results are selected, so no column is passed through, and
the result batches
+ # of Python are the output batches, including those of iterator UDFs,
which may return
+ # batches of other sizes than their input.
+ import pandas as pd
+ import pyarrow as pa
+ import pyarrow.compute as pc
+
+ @pandas_udf("long")
+ def pandas_plus_one(it: Iterator[pd.Series]) -> Iterator[pd.Series]:
+ for s in it:
+ yield s + 1
+
+ @arrow_udf("long")
+ def arrow_plus_one(it: Iterator[pa.Array]) -> Iterator[pa.Array]:
+ for a in it:
+ # Splits each batch in two.
+ half = len(a) // 2
+ yield pc.add(a[:half], 1)
+ yield pc.add(a[half:], 1)
+
+ @pandas_udf("long")
+ def pandas_times_two(s: pd.Series) -> pd.Series:
+ return s * 2
+
+ num_rows = 10000
+ df = self.spark.range(0, num_rows, 1, 2).selectExpr("id", "id * 10 AS
v").cache()
+ cases = [
+ ("pandas_iter", pandas_plus_one, lambda i: i + 1),
+ ("arrow_iter", arrow_plus_one, lambda i: i + 1),
+ ("pandas", pandas_times_two, lambda i: i * 2),
+ ("udf", udf(lambda x: x + 1, "long"), lambda i: i + 1),
+ ]
+ try:
+ with
self.sql_conf({"spark.sql.execution.arrow.maxRecordsPerBatch": "1000"}):
+ for name, f, g in cases:
+ with self.subTest(udf=name):
+ expected = [Row(r=g(i)) for i in range(num_rows)]
+ result = df.select(f(col("id")).alias("r"))
+ self._assert_columnar_arrow_eval(result,
expected_nodes=1)
Review Comment:
Done in 29c9aa7: `_assert_columnar_arrow_eval` takes an optional
`pass_through_columns`, which these three tests set to `[]`, and the existing
test that selects a column with the result sets to `["s"]`.
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/Optimizer.scala:
##########
@@ -1565,6 +1565,15 @@ object ColumnPruning extends Rule[LogicalPlan] {
// prune unrequired nested fields from `Generate`.
case GeneratorNestedColumnAliasing(rewrittenPlan) => rewrittenPlan
+ // Pass through only the columns of the child of a Python UDF evaluation
that the parent uses,
+ // and prune the child to those and the arguments of the UDFs. The child
is pruned here, as
+ // the rule does not visit this Project again.
+ case p @ Project(_, e: BaseEvalPython)
+ if !e.requiredChildOutput.forall(p.references.contains) =>
+ val newEval = e.withRequiredChildOutput(
Review Comment:
Done in 29c9aa7.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: [email protected]
For queries about this service, please contact Infrastructure at:
[email protected]
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]