advancedxy commented on code in PR #88: URL: https://github.com/apache/arrow-datafusion-comet/pull/88#discussion_r1499297266
########## spark/src/main/scala/org/apache/spark/sql/comet/CometTakeOrderedAndProjectExec.scala: ########## @@ -0,0 +1,224 @@ +/* + * 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.comet + +import scala.collection.JavaConverters.asJavaIterableConverter + +import org.apache.spark.rdd.{ParallelCollectionRDD, RDD} +import org.apache.spark.serializer.Serializer +import org.apache.spark.sql.catalyst.expressions.{Attribute, NamedExpression, SortOrder} +import org.apache.spark.sql.catalyst.util.truncatedString +import org.apache.spark.sql.comet.execution.shuffle.{CometShuffledBatchRDD, CometShuffleExchangeExec} +import org.apache.spark.sql.execution.{SparkPlan, UnaryExecNode, UnsafeRowSerializer} +import org.apache.spark.sql.execution.metric.{SQLMetrics, SQLShuffleReadMetricsReporter, SQLShuffleWriteMetricsReporter} +import org.apache.spark.sql.execution.metric.SQLMetric +import org.apache.spark.sql.vectorized.ColumnarBatch + +import org.apache.comet.serde.OperatorOuterClass +import org.apache.comet.serde.OperatorOuterClass.Operator +import org.apache.comet.serde.QueryPlanSerde.{exprToProto, serializeDataType} + +/** + * Comet physical plan node for Spark `TakeOrderedAndProjectExec`. + * + * It is used to execute a `TakeOrderedAndProjectExec` physical operator by using Comet native + * engine. It is not like other physical plan nodes which are wrapped by `CometExec`, because it + * contains two native executions separated by a Comet shuffle exchange. + */ +case class CometTakeOrderedAndProjectExec( + override val originalPlan: SparkPlan, + limit: Int, + sortOrder: Seq[SortOrder], + projectList: Seq[NamedExpression], + child: SparkPlan) + extends CometExec + with UnaryExecNode { + override def output: Seq[Attribute] = projectList.map(_.toAttribute) + + private lazy val writeMetrics = + SQLShuffleWriteMetricsReporter.createShuffleWriteMetrics(sparkContext) + private lazy val readMetrics = + SQLShuffleReadMetricsReporter.createShuffleReadMetrics(sparkContext) + override lazy val metrics: Map[String, SQLMetric] = Map( + "dataSize" -> SQLMetrics.createSizeMetric(sparkContext, "data size"), + "shuffleReadElapsedCompute" -> + SQLMetrics.createNanoTimingMetric(sparkContext, "shuffle read elapsed compute at native"), + "numPartitions" -> SQLMetrics.createMetric( + sparkContext, + "number of partitions")) ++ readMetrics ++ writeMetrics + + private lazy val serializer: Serializer = + new UnsafeRowSerializer(child.output.size, longMetric("dataSize")) + + // Exposed for testing. + lazy val orderingSatisfies: Boolean = + SortOrder.orderingSatisfies(child.outputOrdering, sortOrder) + + protected override def doExecuteColumnar(): RDD[ColumnarBatch] = { Review Comment: do we need to override `executeCollect` here? Per my understanding, it seems `CometTakeOrderedAndProjectExec` leverages `ColumnarToRow` in `CometExec` to collect internal rows? ########## spark/src/main/scala/org/apache/spark/sql/comet/CometTakeOrderedAndProjectExec.scala: ########## @@ -0,0 +1,224 @@ +/* + * 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.comet + +import scala.collection.JavaConverters.asJavaIterableConverter + +import org.apache.spark.rdd.{ParallelCollectionRDD, RDD} +import org.apache.spark.serializer.Serializer +import org.apache.spark.sql.catalyst.expressions.{Attribute, NamedExpression, SortOrder} +import org.apache.spark.sql.catalyst.util.truncatedString +import org.apache.spark.sql.comet.execution.shuffle.{CometShuffledBatchRDD, CometShuffleExchangeExec} +import org.apache.spark.sql.execution.{SparkPlan, UnaryExecNode, UnsafeRowSerializer} +import org.apache.spark.sql.execution.metric.{SQLMetrics, SQLShuffleReadMetricsReporter, SQLShuffleWriteMetricsReporter} +import org.apache.spark.sql.execution.metric.SQLMetric +import org.apache.spark.sql.vectorized.ColumnarBatch + +import org.apache.comet.serde.OperatorOuterClass +import org.apache.comet.serde.OperatorOuterClass.Operator +import org.apache.comet.serde.QueryPlanSerde.{exprToProto, serializeDataType} + +/** + * Comet physical plan node for Spark `TakeOrderedAndProjectExec`. + * + * It is used to execute a `TakeOrderedAndProjectExec` physical operator by using Comet native + * engine. It is not like other physical plan nodes which are wrapped by `CometExec`, because it + * contains two native executions separated by a Comet shuffle exchange. + */ +case class CometTakeOrderedAndProjectExec( + override val originalPlan: SparkPlan, + limit: Int, + sortOrder: Seq[SortOrder], + projectList: Seq[NamedExpression], + child: SparkPlan) + extends CometExec + with UnaryExecNode { + override def output: Seq[Attribute] = projectList.map(_.toAttribute) + + private lazy val writeMetrics = + SQLShuffleWriteMetricsReporter.createShuffleWriteMetrics(sparkContext) + private lazy val readMetrics = + SQLShuffleReadMetricsReporter.createShuffleReadMetrics(sparkContext) + override lazy val metrics: Map[String, SQLMetric] = Map( + "dataSize" -> SQLMetrics.createSizeMetric(sparkContext, "data size"), + "shuffleReadElapsedCompute" -> + SQLMetrics.createNanoTimingMetric(sparkContext, "shuffle read elapsed compute at native"), + "numPartitions" -> SQLMetrics.createMetric( + sparkContext, + "number of partitions")) ++ readMetrics ++ writeMetrics + + private lazy val serializer: Serializer = + new UnsafeRowSerializer(child.output.size, longMetric("dataSize")) + + // Exposed for testing. + lazy val orderingSatisfies: Boolean = + SortOrder.orderingSatisfies(child.outputOrdering, sortOrder) + + protected override def doExecuteColumnar(): RDD[ColumnarBatch] = { + val childRDD = child.executeColumnar() + if (childRDD.getNumPartitions == 0) { + new ParallelCollectionRDD(sparkContext, Seq.empty[ColumnarBatch], 1, Map.empty) + } else { + val singlePartitionRDD = if (childRDD.getNumPartitions == 1) { + childRDD + } else { + val localTopK = if (orderingSatisfies) { + childRDD.mapPartitionsInternal { iter => + val limitOp = + CometTakeOrderedAndProjectExec.getLimitNativePlan(output, limit).get + CometExec.getCometIterator(Seq(iter), limitOp) + } + } else { + childRDD.mapPartitionsInternal { iter => + val topK = + CometTakeOrderedAndProjectExec + .getTopKNativePlan(output, sortOrder, child, limit) + .get + CometExec.getCometIterator(Seq(iter), topK) + } + } + + // Shuffle to Single Partition using Comet native shuffle + val dep = CometShuffleExchangeExec.prepareShuffleDependency( + localTopK, + child.output, + outputPartitioning, + serializer, + metrics) + metrics("numPartitions").set(dep.partitioner.numPartitions) + + new CometShuffledBatchRDD(dep, readMetrics) + } + + singlePartitionRDD.mapPartitionsInternal { iter => + val topKAndProjection = CometTakeOrderedAndProjectExec + .getProjectionNativePlan(projectList, output, sortOrder, child, limit) + .get + CometExec.getCometIterator(Seq(iter), topKAndProjection) + } + } + } + + override def simpleString(maxFields: Int): String = { + val orderByString = truncatedString(sortOrder, "[", ",", "]", maxFields) + val outputString = truncatedString(output, "[", ",", "]", maxFields) + + s"CometTakeOrderedAndProjectExec(limit=$limit, orderBy=$orderByString, output=$outputString)" + } + + override protected def withNewChildInternal(newChild: SparkPlan): SparkPlan = + this.copy(child = newChild) +} + +object CometTakeOrderedAndProjectExec { + def isSupported( + projectList: Seq[NamedExpression], + sortOrder: Seq[SortOrder], + child: SparkPlan): Boolean = { + val exprs = projectList.map(exprToProto(_, child.output)) + val sortOrders = sortOrder.map(exprToProto(_, child.output)) + exprs.forall(_.isDefined) && sortOrders.forall(_.isDefined) + } + + /** + * Prepare Projection + TopK native plan for CometTakeOrderedAndProjectExec. + */ + def getProjectionNativePlan( + projectList: Seq[NamedExpression], + outputAttributes: Seq[Attribute], + sortOrder: Seq[SortOrder], + child: SparkPlan, + limit: Int): Option[Operator] = { + getTopKNativePlan(outputAttributes, sortOrder, child, limit).flatMap { topK => + val exprs = projectList.map(exprToProto(_, child.output)) + + if (exprs.forall(_.isDefined)) { + val projectBuilder = OperatorOuterClass.Projection.newBuilder() + projectBuilder.addAllProjectList(exprs.map(_.get).asJava) + val opBuilder = OperatorOuterClass.Operator + .newBuilder() + .addChildren(topK) + Some(opBuilder.setProjection(projectBuilder).build()) + } else { + None + } + } + } + + def getLimitNativePlan(outputAttributes: Seq[Attribute], limit: Int): Option[Operator] = { Review Comment: I was also implementing `CollectLimitExec`, which is similar to `takeOrderedAndProjectExec`. Do you think it's a good idea to move this method(s) into a more generic place so that other operators(such as `CometCollectLimitExec`) could also leverage this methods. ########## spark/src/main/scala/org/apache/spark/sql/comet/CometTakeOrderedAndProjectExec.scala: ########## @@ -0,0 +1,224 @@ +/* + * 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.comet + +import scala.collection.JavaConverters.asJavaIterableConverter + +import org.apache.spark.rdd.{ParallelCollectionRDD, RDD} +import org.apache.spark.serializer.Serializer +import org.apache.spark.sql.catalyst.expressions.{Attribute, NamedExpression, SortOrder} +import org.apache.spark.sql.catalyst.util.truncatedString +import org.apache.spark.sql.comet.execution.shuffle.{CometShuffledBatchRDD, CometShuffleExchangeExec} +import org.apache.spark.sql.execution.{SparkPlan, UnaryExecNode, UnsafeRowSerializer} +import org.apache.spark.sql.execution.metric.{SQLMetrics, SQLShuffleReadMetricsReporter, SQLShuffleWriteMetricsReporter} +import org.apache.spark.sql.execution.metric.SQLMetric +import org.apache.spark.sql.vectorized.ColumnarBatch + +import org.apache.comet.serde.OperatorOuterClass +import org.apache.comet.serde.OperatorOuterClass.Operator +import org.apache.comet.serde.QueryPlanSerde.{exprToProto, serializeDataType} + +/** + * Comet physical plan node for Spark `TakeOrderedAndProjectExec`. + * + * It is used to execute a `TakeOrderedAndProjectExec` physical operator by using Comet native + * engine. It is not like other physical plan nodes which are wrapped by `CometExec`, because it + * contains two native executions separated by a Comet shuffle exchange. + */ +case class CometTakeOrderedAndProjectExec( + override val originalPlan: SparkPlan, + limit: Int, + sortOrder: Seq[SortOrder], + projectList: Seq[NamedExpression], + child: SparkPlan) + extends CometExec + with UnaryExecNode { + override def output: Seq[Attribute] = projectList.map(_.toAttribute) + + private lazy val writeMetrics = + SQLShuffleWriteMetricsReporter.createShuffleWriteMetrics(sparkContext) + private lazy val readMetrics = + SQLShuffleReadMetricsReporter.createShuffleReadMetrics(sparkContext) + override lazy val metrics: Map[String, SQLMetric] = Map( + "dataSize" -> SQLMetrics.createSizeMetric(sparkContext, "data size"), + "shuffleReadElapsedCompute" -> + SQLMetrics.createNanoTimingMetric(sparkContext, "shuffle read elapsed compute at native"), + "numPartitions" -> SQLMetrics.createMetric( + sparkContext, + "number of partitions")) ++ readMetrics ++ writeMetrics + + private lazy val serializer: Serializer = + new UnsafeRowSerializer(child.output.size, longMetric("dataSize")) + + // Exposed for testing. + lazy val orderingSatisfies: Boolean = + SortOrder.orderingSatisfies(child.outputOrdering, sortOrder) + + protected override def doExecuteColumnar(): RDD[ColumnarBatch] = { + val childRDD = child.executeColumnar() + if (childRDD.getNumPartitions == 0) { + new ParallelCollectionRDD(sparkContext, Seq.empty[ColumnarBatch], 1, Map.empty) + } else { + val singlePartitionRDD = if (childRDD.getNumPartitions == 1) { + childRDD + } else { + val localTopK = if (orderingSatisfies) { + childRDD.mapPartitionsInternal { iter => + val limitOp = + CometTakeOrderedAndProjectExec.getLimitNativePlan(output, limit).get + CometExec.getCometIterator(Seq(iter), limitOp) + } + } else { + childRDD.mapPartitionsInternal { iter => + val topK = + CometTakeOrderedAndProjectExec + .getTopKNativePlan(output, sortOrder, child, limit) + .get + CometExec.getCometIterator(Seq(iter), topK) + } + } + + // Shuffle to Single Partition using Comet native shuffle + val dep = CometShuffleExchangeExec.prepareShuffleDependency( + localTopK, + child.output, + outputPartitioning, + serializer, + metrics) + metrics("numPartitions").set(dep.partitioner.numPartitions) + + new CometShuffledBatchRDD(dep, readMetrics) + } + + singlePartitionRDD.mapPartitionsInternal { iter => + val topKAndProjection = CometTakeOrderedAndProjectExec + .getProjectionNativePlan(projectList, output, sortOrder, child, limit) + .get + CometExec.getCometIterator(Seq(iter), topKAndProjection) + } + } + } + + override def simpleString(maxFields: Int): String = { + val orderByString = truncatedString(sortOrder, "[", ",", "]", maxFields) + val outputString = truncatedString(output, "[", ",", "]", maxFields) + + s"CometTakeOrderedAndProjectExec(limit=$limit, orderBy=$orderByString, output=$outputString)" + } + + override protected def withNewChildInternal(newChild: SparkPlan): SparkPlan = + this.copy(child = newChild) +} + +object CometTakeOrderedAndProjectExec { + def isSupported( + projectList: Seq[NamedExpression], + sortOrder: Seq[SortOrder], + child: SparkPlan): Boolean = { + val exprs = projectList.map(exprToProto(_, child.output)) + val sortOrders = sortOrder.map(exprToProto(_, child.output)) + exprs.forall(_.isDefined) && sortOrders.forall(_.isDefined) + } + + /** + * Prepare Projection + TopK native plan for CometTakeOrderedAndProjectExec. + */ + def getProjectionNativePlan( + projectList: Seq[NamedExpression], + outputAttributes: Seq[Attribute], + sortOrder: Seq[SortOrder], + child: SparkPlan, + limit: Int): Option[Operator] = { + getTopKNativePlan(outputAttributes, sortOrder, child, limit).flatMap { topK => + val exprs = projectList.map(exprToProto(_, child.output)) + + if (exprs.forall(_.isDefined)) { + val projectBuilder = OperatorOuterClass.Projection.newBuilder() + projectBuilder.addAllProjectList(exprs.map(_.get).asJava) + val opBuilder = OperatorOuterClass.Operator + .newBuilder() + .addChildren(topK) + Some(opBuilder.setProjection(projectBuilder).build()) + } else { + None + } + } + } + + def getLimitNativePlan(outputAttributes: Seq[Attribute], limit: Int): Option[Operator] = { + val scanBuilder = OperatorOuterClass.Scan.newBuilder() + val scanOpBuilder = OperatorOuterClass.Operator.newBuilder() + + val scanTypes = outputAttributes.flatten { attr => + serializeDataType(attr.dataType) + } + + if (scanTypes.length == outputAttributes.length) { + scanBuilder.addAllFields(scanTypes.asJava) + + val limitBuilder = OperatorOuterClass.Limit.newBuilder() + limitBuilder.setLimit(limit) + + val limitOpBuilder = OperatorOuterClass.Operator + .newBuilder() + .addChildren(scanOpBuilder.setScan(scanBuilder)) + Some(limitOpBuilder.setLimit(limitBuilder).build()) + } else { + None + } + } + + /** + * Prepare TopK native plan for CometTakeOrderedAndProjectExec. + */ + def getTopKNativePlan( + outputAttributes: Seq[Attribute], + sortOrder: Seq[SortOrder], + child: SparkPlan, + limit: Int): Option[Operator] = { + val scanBuilder = OperatorOuterClass.Scan.newBuilder() + val scanOpBuilder = OperatorOuterClass.Operator.newBuilder() + + val scanTypes = outputAttributes.flatten { attr => + serializeDataType(attr.dataType) + } + + if (scanTypes.length == outputAttributes.length) { + scanBuilder.addAllFields(scanTypes.asJava) + + val sortOrders = sortOrder.map(exprToProto(_, child.output)) + + if (sortOrders.forall(_.isDefined)) { + val sortBuilder = OperatorOuterClass.Sort.newBuilder() + sortBuilder.addAllSortOrders(sortOrders.map(_.get).asJava) + sortBuilder.setFetch(limit) Review Comment: Just to confirm, sort + `fetch limit` is converted to a TopK execution in Datafusion? -- 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]
