viirya commented on code in PR #60551:
URL: https://github.com/apache/spark/pull/60551#discussion_r4593068957
##########
sql/core/src/main/scala/org/apache/spark/sql/classic/UDFRegistration.scala:
##########
@@ -50,6 +51,18 @@ import org.apache.spark.sql.types.DataType
class UDFRegistration private[sql] (session: SparkSession, functionRegistry:
FunctionRegistry)
extends sql.UDFRegistration
with Logging {
+ /**
+ * Registers a columnar user-defined function under its name, so that SQL
can call it.
+ *
+ * @since 4.4.0
+ */
+ def registerColumnar(udf: ColumnarUserDefinedFunction):
ColumnarUserDefinedFunction = {
Review Comment:
`ColumnarUserDefinedFunction` builds a Catalyst expression, so it lives in
sql/core and the method cannot be declared on the `sql.UDFRegistration`
interface in sql/api. In 64d7b36 the method is marked `@Evolving`, and the
scaladoc says that it is a method of the classic `UDFRegistration` and shows
how to reach it. I updated the description too.
##########
sql/core/src/main/scala/org/apache/spark/sql/classic/UDFRegistration.scala:
##########
@@ -50,6 +51,18 @@ import org.apache.spark.sql.types.DataType
class UDFRegistration private[sql] (session: SparkSession, functionRegistry:
FunctionRegistry)
extends sql.UDFRegistration
with Logging {
+ /**
+ * Registers a columnar user-defined function under its name, so that SQL
can call it.
+ *
+ * @since 4.4.0
+ */
+ def registerColumnar(udf: ColumnarUserDefinedFunction):
ColumnarUserDefinedFunction = {
+ // `ExpressionInfo` accepts a fixed set of sources. This is the one of a
Scala UDF, which is
+ // what the JVM implementation of a columnar function is closest to.
+ functionRegistry.createOrReplaceTempFunction(udf.name, udf.builder,
"scala_udf")
Review Comment:
Added in 64d7b36.
##########
sql/core/src/main/scala/org/apache/spark/sql/execution/columnar/udf/ExtractColumnarUDFs.scala:
##########
@@ -0,0 +1,131 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.spark.sql.execution.columnar.udf
+
+import scala.collection.mutable
+
+import org.apache.spark.SparkException
+import org.apache.spark.sql.catalyst.expressions._
+import org.apache.spark.sql.catalyst.expressions.aggregate.AggregateExpression
+import org.apache.spark.sql.catalyst.plans.logical.{EvalColumnarUDFs,
LogicalPlan, Project, Subquery}
+import org.apache.spark.sql.catalyst.rules.Rule
+import org.apache.spark.sql.catalyst.trees.TreePattern.COLUMNAR_UDF
+
+/**
+ * Extracts the calls of columnar user-defined functions from the operators
and evaluates them
+ * in an [[EvalColumnarUDFs]] below the operator, as `ExtractPythonUDFs` does
for Python UDFs.
+ *
+ * The calls of one operator that need no other call share an
[[EvalColumnarUDFs]]. A call whose
+ * argument is another call gets its own, above that of its argument. An
argument that is not
+ * an attribute is computed by a [[Project]] below, so that the arguments of
the calls in an
+ * [[EvalColumnarUDFs]] are all columns of its child.
+ */
+object ExtractColumnarUDFs extends Rule[LogicalPlan] {
Review Comment:
Agreed that the three extractors should share this. I added the aggregate,
join condition and lambda handling to this rule directly (items 1-4), and would
rather leave the unification to the TODO of SPARK-55278 in `PlanExternalUDFs`,
since it changes the Python and external UDF rules as well.
##########
sql/core/src/main/scala/org/apache/spark/sql/execution/columnar/udf/ExtractColumnarUDFs.scala:
##########
@@ -0,0 +1,131 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.spark.sql.execution.columnar.udf
+
+import scala.collection.mutable
+
+import org.apache.spark.SparkException
+import org.apache.spark.sql.catalyst.expressions._
+import org.apache.spark.sql.catalyst.expressions.aggregate.AggregateExpression
+import org.apache.spark.sql.catalyst.plans.logical.{EvalColumnarUDFs,
LogicalPlan, Project, Subquery}
+import org.apache.spark.sql.catalyst.rules.Rule
+import org.apache.spark.sql.catalyst.trees.TreePattern.COLUMNAR_UDF
+
+/**
+ * Extracts the calls of columnar user-defined functions from the operators
and evaluates them
+ * in an [[EvalColumnarUDFs]] below the operator, as `ExtractPythonUDFs` does
for Python UDFs.
+ *
+ * The calls of one operator that need no other call share an
[[EvalColumnarUDFs]]. A call whose
+ * argument is another call gets its own, above that of its argument. An
argument that is not
+ * an attribute is computed by a [[Project]] below, so that the arguments of
the calls in an
+ * [[EvalColumnarUDFs]] are all columns of its child.
+ */
+object ExtractColumnarUDFs extends Rule[LogicalPlan] {
+
+ def apply(plan: LogicalPlan): LogicalPlan = plan match {
+ // A correlated subquery is rewritten into a join later, and goes through
this rule then.
+ case s: Subquery if s.correlated => plan
+
+ case _ => plan.transformUpWithPruning(_.containsPattern(COLUMNAR_UDF)) {
+ case e: EvalColumnarUDFs => e
+ case p: LogicalPlan => extract(p)
+ }
+ }
+
+ private def hasColumnarUDF(e: Expression): Boolean =
e.containsPattern(COLUMNAR_UDF)
+
+ /** The calls that can be evaluated now: those whose arguments contain no
other call. */
+ private def collectEvaluableUDFs(e: Expression): Seq[ColumnarUDF] = e match {
+ case udf: ColumnarUDF if !udf.children.exists(hasColumnarUDF) =>
+ // A call over an aggregate or a window function cannot move below its
operator.
+ val overAggregate = udf.exists { e =>
+ e.isInstanceOf[AggregateExpression] || e.isInstanceOf[WindowExpression]
+ }
+ if (overAggregate) {
+ Nil
+ } else {
+ Seq(udf)
+ }
+ case other => other.children.flatMap(collectEvaluableUDFs)
+ }
+
+ private def canonicalizeDeterministic(u: ColumnarUDF): ColumnarUDF = {
+ if (u.deterministic) u.canonicalized.asInstanceOf[ColumnarUDF] else u
+ }
+
+ private def extract(plan: LogicalPlan): LogicalPlan = {
+ val udfs = ExpressionSet(plan.expressions.flatMap(collectEvaluableUDFs))
+ .filter(_.references.subsetOf(plan.inputSet))
+ .toSeq.asInstanceOf[Seq[ColumnarUDF]]
+ if (udfs.isEmpty) {
+ plan
+ } else {
+ val attributeMap = mutable.HashMap[ColumnarUDF, Expression]()
+ val newChildren = plan.children.map { child =>
+ val validUdfs = udfs.filter(_.references.subsetOf(child.outputSet))
+ if (validUdfs.nonEmpty) {
+ // The arguments that are not attributes of the child are computed
below.
+ val argAliases = mutable.LinkedHashMap[Expression, Alias]()
+ val udfsOverColumns = validUdfs.map { udf =>
+ val newArgs = udf.children.map {
+ case a: Attribute => a
+ case arg =>
+ argAliases.getOrElseUpdate(
+ arg.canonicalized, Alias(arg,
s"columnarUDFArg${argAliases.size}")()).toAttribute
+ }
+ udf.withNewChildren(newArgs).asInstanceOf[ColumnarUDF]
+ }
+ val input = if (argAliases.isEmpty) {
+ child
+ } else {
+ Project(child.output ++ argAliases.values, child)
Review Comment:
That is the row-input case, which this operator does not target: Spark's
`Project` is row-based, so an argument that is not a column of the declared
type makes the input of the node rows, as a row-based child does, and the usual
transitions apply. I made this explicit in 64d7b36: the scaladoc of
`ColumnarUserDefinedFunction` and the description say when a call stays
columnar, and the benchmark has a case for a cast argument so that the cost is
visible (locally 13.4 ns per row against 4.9 for the Scala UDF). An engine
whose projection is columnar does not pay it.
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/Optimizer.scala:
##########
@@ -2873,6 +2873,7 @@ object PushPredicateThroughNonJoin extends
Rule[LogicalPlan] with PredicateHelpe
case _: ExecuteExternalUDF => true
case _: BatchEvalPython => true
case _: ArrowEvalPython => true
+ case _: EvalColumnarUDFs => true
Review Comment:
I left it out and added a comment in `LimitPushDown` (64d7b36). A local
limit is a row-based operator, so below the node it adds transitions over a
columnar child, while the limit above already stops the node after at most one
batch more than needed.
--
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]