viirya commented on code in PR #60551:
URL: https://github.com/apache/spark/pull/60551#discussion_r4593070823


##########
sql/core/benchmarks/ColumnarUDFBenchmark-results.txt:
##########
@@ -0,0 +1,39 @@
+================================================================================================
+Columnar UDF
+================================================================================================
+
+OpenJDK 64-Bit Server VM 21.0.8 on Mac OS X 26.7.1

Review Comment:
   Will do. I will regenerate both files with the benchmark workflow, which 
also picks up the new case from [10].



##########
sql/core/src/test/scala/org/apache/spark/sql/execution/columnar/udf/ColumnarUDFSuite.scala:
##########
@@ -0,0 +1,190 @@
+/*
+ * 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 java.util.Locale
+
+import org.apache.spark.{SparkRuntimeException, 
SparkUnsupportedOperationException}
+import org.apache.spark.sql.{QueryTest, Row}
+import org.apache.spark.sql.columnar.{ColumnarScalarFunction, 
ColumnarUDFImplementation, ColumnarUserDefinedFunction}
+import org.apache.spark.sql.execution.{RowToColumnarExec, SparkPlan}
+import org.apache.spark.sql.execution.adaptive.AdaptiveSparkPlanHelper
+import org.apache.spark.sql.execution.vectorized.OnHeapColumnVector
+import org.apache.spark.sql.functions.{col, lit}
+import org.apache.spark.sql.test.SharedSparkSession
+import org.apache.spark.sql.types.{LongType, StringType}
+import org.apache.spark.sql.vectorized.{ColumnarBatch, ColumnVector}
+import org.apache.spark.unsafe.types.UTF8String
+
+/** Adds one to a bigint, and keeps nulls. */
+class AddOneFunction extends ColumnarScalarFunction {
+  override def eval(args: ColumnarBatch): ColumnVector = {
+    val n = args.numRows()
+    val in = args.column(0)
+    val out = new OnHeapColumnVector(n, LongType)
+    var i = 0
+    if (in.hasNull) {
+      while (i < n) {
+        if (in.isNullAt(i)) out.putNull(i) else out.putLong(i, in.getLong(i) + 
1)
+        i += 1
+      }
+    } else {
+      while (i < n) {
+        out.putLong(i, in.getLong(i) + 1)
+        i += 1
+      }
+    }
+    out
+  }
+}
+
+/** Adds two bigints, and returns null if either is null. */
+class AddFunction extends ColumnarScalarFunction {
+  override def eval(args: ColumnarBatch): ColumnVector = {
+    val n = args.numRows()
+    val a = args.column(0)
+    val b = args.column(1)
+    val out = new OnHeapColumnVector(n, LongType)
+    var i = 0
+    while (i < n) {
+      if (a.isNullAt(i) || b.isNullAt(i)) {
+        out.putNull(i)
+      } else {
+        out.putLong(i, a.getLong(i) + b.getLong(i))
+      }
+      i += 1
+    }
+    out
+  }
+}
+
+/** The upper case of a string, followed by an exclamation mark. */
+class ShoutFunction extends ColumnarScalarFunction {
+  override def eval(args: ColumnarBatch): ColumnVector = {
+    val n = args.numRows()
+    val in = args.column(0)
+    val out = new OnHeapColumnVector(n, StringType)
+    var i = 0
+    while (i < n) {
+      if (in.isNullAt(i)) {
+        out.putNull(i)
+      } else {
+        val upper = in.getUTF8String(i).toString.toUpperCase(Locale.ROOT)
+        val bytes = UTF8String.fromString(upper + "!").getBytes
+        out.putByteArray(i, bytes)
+      }
+      i += 1
+    }
+    out
+  }
+}
+
+class ColumnarUDFSuite extends QueryTest with SharedSparkSession with 
AdaptiveSparkPlanHelper {
+  import testImplicits._
+
+  private val addOne =
+    ColumnarUserDefinedFunction("add_one", Seq(LongType), LongType, Some(new 
AddOneFunction))
+  private val add =
+    ColumnarUserDefinedFunction("add", Seq(LongType, LongType), LongType, 
Some(new AddFunction))
+  private val shout =
+    ColumnarUserDefinedFunction("shout", Seq(StringType), StringType, Some(new 
ShoutFunction))
+
+  private def evalNodes(plan: SparkPlan): Seq[EvalColumnarUDFsExec] = 
collect(plan) {
+    case e: EvalColumnarUDFsExec => e
+  }
+
+  test("a call over a row-based child") {
+    val df = spark.range(5).select(col("id"), addOne(col("id")))
+    checkAnswer(df, (0 until 5).map(i => Row(i.toLong, i + 1L)))
+    assert(evalNodes(df.queryExecution.executedPlan).length == 1)
+  }
+
+  test("a call from SQL, with an argument that is cast") {
+    spark.udf.registerColumnar(addOne)

Review Comment:
   Fixed in 64d7b36; the tests that register functions now drop them.



##########
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)
+          }
+          val resultAttrs = validUdfs.zipWithIndex.map { case (u, i) =>
+            AttributeReference(s"columnarUDF$i", u.dataType, u.nullable)()
+          }
+          attributeMap ++= 
validUdfs.map(canonicalizeDeterministic).zip(resultAttrs)
+          val evaluation = EvalColumnarUDFs(udfsOverColumns, resultAttrs, 
input)
+          if (argAliases.isEmpty) {
+            evaluation
+          } else {
+            // Drop the columns of the arguments.
+            Project(child.output ++ resultAttrs, evaluation)

Review Comment:
   Removed in 64d7b36.



-- 
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]

Reply via email to