Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix aqe_test failures on [databricks] 14.3. #11750

Merged
merged 3 commits into from
Nov 25, 2024
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 2 additions & 4 deletions integration_tests/src/main/python/aqe_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -338,10 +338,10 @@ def do_it(spark):

# this should be fixed by https://github.com/NVIDIA/spark-rapids/issues/11120
aqe_join_with_dpp_fallback=["FilterExec"] if (is_databricks_runtime() or is_before_spark_330()) else []
if is_databricks_version_or_later(14, 3):
aqe_join_with_dpp_fallback.append("CollectLimitExec")
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why does a collect limit show up in these queries? This scares me a bit because CollectLimitExec implies a non-deterministic result.

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm not sure. DB-14.3 seems to be inserting this into the plan, albeit with a large collection limit:

+- Project [toprettystring(site_id#6, Some(UTC)) AS toprettystring(site_id)#42, toprettystring(day#5, Some(UTC)) AS toprettystring(day)#43, toprettystring(test_id#7, Some(UTC)) AS toprettystring(test_id)#44, toprettystring(test_id#0, Some(UTC)) AS toprettystring(test_id)#45, toprettystring(site_id#1, Some(UTC)) AS toprettystring(site_id)#46]
   +- BroadcastHashJoin [test_id#7, site_id#6], [test_id#0, site_id#1], Inner, BuildRight, false, true
      :- Union
      :  :- Project [site_id#6, day#5, test_id#7]
      :  :  +- FileScan parquet [day#5,site_id#6,test_id#7] Batched: true, DataFilters: [], Format: Parquet, Location: InMemoryFileIndex(1 paths)[file:/tmp/myth/PARQUET_DATA/infoA], PartitionFilters: [isnotnull(day#5), (day#5 = 1990-01-01), site_id#6 IN (site_0,site_1), isnotnull(test_id#7), isno..., PushedFilters: [], ReadSchema: struct<>
      :  :        :- SubqueryBroadcast dynamicpruning#53, [0], [test_id#0], true, [id=#322]
      :  :        :  +- AdaptiveSparkPlan isFinalPlan=false
      :  :        :     +- CollectLimit 3000001
      :  :        :        +- HashAggregate(keys=[test_id#0], functions=[], output=[test_id#0])
      :  :        :           +- ShuffleQueryStage 2, Statistics(sizeInBytes=942.0 B, rowCount=34, ColumnStat: N/A, isRuntime=true)
      :  :        :              +- ReusedExchange [test_id#0, site_id#1], GpuColumnarExchange gpusinglepartitioning$(), EXECUTOR_BROADCAST, [plan_id=238], [loreId=17]
      :  :        +- SubqueryBroadcast dynamicpruning#54, [0], [site_id#1], true, [id=#335]
      :  :           +- AdaptiveSparkPlan isFinalPlan=false
      :  :              +- CollectLimit 3000001
      :  :                 +- HashAggregate(keys=[site_id#1], functions=[], output=[site_id#1])
      :  :                    +- ShuffleQueryStage 4, Statistics(sizeInBytes=942.0 B, rowCount=34, ColumnStat: N/A, isRuntime=true)
      :  :                       +- ReusedExchange [test_id#0, site_id#1], GpuColumnarExchange gpusinglepartitioning$(), EXECUTOR_BROADCAST, [plan_id=238], [loreId=17]
      :  +- Project [CASE WHEN (site_id#15 = LONG_SITE_NAME_0) THEN site_0 WHEN (site_id#15 = LONG_SITE_NAME_1) THEN site_1 ELSE site_id#15 END AS site_id#30, day#14, test_spec#12 AS test_id#31]
      :     +- Filter isnotnull(test_spec#12)
      :        +- FileScan parquet [test_spec#12,day#14,site_id#15] Batched: true, DataFilters: [isnotnull(test_spec#12), dynamicpruningexpression(test_spec#12 IN dynamicpruning#53)], Format: Parquet, Location: InMemoryFileIndex(1 paths)[file:/tmp/myth/PARQUET_DATA/infoB], PartitionFilters: [isnotnull(day#14), (day#14 = 1990-01-01), CASE WHEN (site_id#15 = LONG_SITE_NAME_0) THEN site_0 ..., PushedFilters: [IsNotNull(test_spec)], ReadSchema: struct<test_spec:string>
      :              :- ReusedSubquery SubqueryBroadcast dynamicpruning#54, [0], [site_id#1], true, [id=#335]
      :              +- ReusedSubquery SubqueryBroadcast dynamicpruning#53, [0], [test_id#0], true, [id=#322]
      +- ShuffleQueryStage 0, Statistics(sizeInBytes=942.0 B, rowCount=34, ColumnStat: N/A, isRuntime=true)
         +- GpuColumnarExchange gpusinglepartitioning$(), EXECUTOR_BROADCAST, [plan_id=238], [loreId=17]
            +- GpuCoalesceBatches targetsize(1073741824), [loreId=16]
               +- GpuFilter ((gpuisnotnull(test_id#0) AND gpuisnotnull(site_id#1)) AND site_id#1 INSET site_0, site_1), [loreId=15]
                  +- GpuFileGpuScan parquet [test_id#0,site_id#1] Batched: true, DataFilters: [isnotnull(test_id#0), isnotnull(site_id#1), site_id#1 IN (site_0,site_1)], Format: Parquet, Location: InMemoryFileIndex[file:/tmp/myth/PARQUET_DATA/tests], PartitionFilters: [], PushedFilters: [IsNotNull(test_id), IsNotNull(site_id), In(site_id, [site_0,site_1])], ReadSchema: struct<test_id:string,site_id:string>

I don't think it's spark-rapids inserting this, but I'm checking.

Copy link
Collaborator Author

@mythrocks mythrocks Nov 23, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The above is for the query:

with tmp as 
(SELECT
   site_id, day, test_id
 FROM infoA
 UNION ALL
 SELECT
   CASE
     WHEN site_id = 'LONG_SITE_NAME_0' then 'site_0'
     WHEN site_id = 'LONG_SITE_NAME_1' then 'site_1'
     ELSE site_id
   END AS site_id, day, test_spec AS test_id
 FROM infoB)
 SELECT *
 FROM tmp a JOIN tests b ON a.test_id = b.test_id AND a.site_id = b.site_id
 WHERE day = '1990-01-01'
 AND a.site_id IN ('site_0', 'site_1')

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

That is a really interesting optimization. Can you file an issue for us to explore this more closely. It looks like they are doing dynamic pruning. Not sure why they insert in the CollectLimit. We might want to be a bit smarter about how we are dealing with that operator in the future.

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I've filed #11764 to explore this further.


# Verify that DPP and AQE can coexist in even some odd cases involving multiple tables
@pytest.mark.skipif(condition=is_databricks_version_or_later(14, 3),
reason="https://github.com/NVIDIA/spark-rapids/issues/11643")
@ignore_order(local=True)
@allow_non_gpu(*aqe_join_with_dpp_fallback)
def test_aqe_join_with_dpp(spark_tmp_path):
Expand Down Expand Up @@ -395,8 +395,6 @@ def run_test(spark):
assert_gpu_and_cpu_are_equal_collect(run_test, conf=_adaptive_conf)

# Verify that DPP and AQE can coexist in even some odd cases involving 2 tables with multiple columns
@pytest.mark.skipif(condition=is_databricks_version_or_later(14, 3),
reason="https://github.com/NVIDIA/spark-rapids/issues/11643")
@ignore_order(local=True)
@allow_non_gpu(*aqe_join_with_dpp_fallback)
def test_aqe_join_with_dpp_multi_columns(spark_tmp_path):
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -126,8 +126,10 @@ abstract class GpuSubqueryBroadcastMetaBase(
} else {
willNotWorkOnGpu("underlying BroadcastExchange can not run in the GPU.")
}
case _ =>
throw new AssertionError("should not reach here")

case unexpected =>
throw new AssertionError("Unexpected child exec in AdaptiveSparkPlan: " +
s"${unexpected.getClass.getName}")
}

case _ =>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,96 +30,15 @@ import org.apache.spark.sql.execution.adaptive.{BroadcastQueryStageExec}
import org.apache.spark.sql.execution.exchange.{BroadcastExchangeExec, ReusedExchangeExec}
import org.apache.spark.sql.execution.joins.HashedRelationBroadcastMode

class GpuSubqueryBroadcastMeta(
s: SubqueryBroadcastExec,
conf: RapidsConf,
p: Option[RapidsMeta[_, _, _]],
r: DataFromReplacementRule) extends
SparkPlanMeta[SubqueryBroadcastExec](s, conf, p, r) {
private var broadcastBuilder: () => SparkPlan = _

override val childExprs: Seq[BaseExprMeta[_]] = Nil

override val childPlans: Seq[SparkPlanMeta[SparkPlan]] = Nil

override def tagPlanForGpu(): Unit = s.child match {
// DPP: For AQE off, in this case, we handle DPP by converting the underlying
// BroadcastExchangeExec to GpuBroadcastExchangeExec.
// This is slightly different from the Apache Spark case, because Spark
// sends the underlying plan into the plugin in advance via the PlanSubqueries rule.
// Here, we have the full non-GPU subquery plan, so we convert the whole
// thing.
case ex @ BroadcastExchangeExec(_, child) =>
val exMeta = new GpuBroadcastMeta(ex.copy(child = child), conf, p, r)
exMeta.tagForGpu()
if (exMeta.canThisBeReplaced) {
broadcastBuilder = () => exMeta.convertToGpu()
} else {
willNotWorkOnGpu("underlying BroadcastExchange can not run in the GPU.")
}
// DPP: For AQE on, we have an almost completely different scenario then before,
// Databricks uses a BroadcastQueryStageExec and either:
// 1) provide an underlying BroadcastExchangeExec that we will have to convert
// somehow
// 2) might already do the reuse work for us. The ReusedExchange is now a
// part of the SubqueryBroadcast, so we send it back here as underlying the
// GpuSubqueryBroadcastExchangeExec
case bqse: BroadcastQueryStageExec =>
bqse.plan match {
case ex: BroadcastExchangeExec =>
val exMeta = new GpuBroadcastMeta(ex, conf, p, r)
exMeta.tagForGpu()
if (exMeta.canThisBeReplaced) {
broadcastBuilder = () => exMeta.convertToGpu()
} else {
willNotWorkOnGpu("underlying BroadcastExchange can not run in the GPU.")
}
case reuse: ReusedExchangeExec =>
reuse.child match {
case _: GpuBroadcastExchangeExec =>
// A BroadcastExchange has already been replaced, so it can run on the GPU
broadcastBuilder = () => reuse
case _ =>
willNotWorkOnGpu("underlying BroadcastExchange can not run in the GPU.")
}
}
case _ =>
willNotWorkOnGpu("the subquery to broadcast can not entirely run in the GPU.")
}
/**
* Simply returns the original plan. Because its only child, BroadcastExchange, doesn't
* need to change if SubqueryBroadcastExec falls back to the CPU.
*/
override def convertToCpu(): SparkPlan = s
class GpuSubqueryBroadcastMeta(s: SubqueryBroadcastExec,
conf: RapidsConf,
p: Option[RapidsMeta[_, _, _]],
r: DataFromReplacementRule)
extends GpuSubqueryBroadcastMeta330DBBase(s, conf, p, r) {

override def convertToGpu(): GpuExec = {
GpuSubqueryBroadcastExec(s.name, Seq(s.index), s.buildKeys, broadcastBuilder())(
getBroadcastModeKeyExprs)
}

/** Extract the broadcast mode key expressions if there are any. */
private def getBroadcastModeKeyExprs: Option[Seq[Expression]] = {
val broadcastMode = s.child match {
case b: BroadcastExchangeExec =>
b.mode
case bqse: BroadcastQueryStageExec =>
bqse.plan match {
case b: BroadcastExchangeExec =>
b.mode
case reuse: ReusedExchangeExec =>
reuse.child match {
case g: GpuBroadcastExchangeExec =>
g.mode
}
case _ =>
throw new AssertionError("should not reach here")
}
}

broadcastMode match {
case HashedRelationBroadcastMode(keys, _) => Some(keys)
case IdentityBroadcastMode => None
case m => throw new UnsupportedOperationException(s"Unknown broadcast mode $m")
}
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,122 @@
/*
* Copyright (c) 2024, NVIDIA CORPORATION.
*
* Licensed 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.
*/

/*** spark-rapids-shim-json-lines
{"spark": "330db"}
{"spark": "332db"}
{"spark": "341db"}
{"spark": "350db143"}
{"spark": "400"}
spark-rapids-shim-json-lines ***/
package org.apache.spark.sql.rapids.execution

import com.nvidia.spark.rapids.{BaseExprMeta, DataFromReplacementRule, RapidsConf, RapidsMeta, SparkPlanMeta}

import org.apache.spark.sql.catalyst.expressions.Expression
import org.apache.spark.sql.catalyst.plans.physical.IdentityBroadcastMode
import org.apache.spark.sql.execution.{SparkPlan, SubqueryBroadcastExec}
import org.apache.spark.sql.execution.adaptive.{BroadcastQueryStageExec}
import org.apache.spark.sql.execution.exchange.{BroadcastExchangeExec, ReusedExchangeExec}
import org.apache.spark.sql.execution.joins.HashedRelationBroadcastMode

abstract class GpuSubqueryBroadcastMeta330DBBase(s: SubqueryBroadcastExec,
conf: RapidsConf,
p: Option[RapidsMeta[_, _, _]],
r: DataFromReplacementRule) extends
SparkPlanMeta[SubqueryBroadcastExec](s, conf, p, r) {
protected var broadcastBuilder: () => SparkPlan = _

override val childExprs: Seq[BaseExprMeta[_]] = Nil

override val childPlans: Seq[SparkPlanMeta[SparkPlan]] = Nil

override def tagPlanForGpu(): Unit = s.child match {
// DPP: For AQE off, in this case, we handle DPP by converting the underlying
// BroadcastExchangeExec to GpuBroadcastExchangeExec.
// This is slightly different from the Apache Spark case, because Spark
// sends the underlying plan into the plugin in advance via the PlanSubqueries rule.
// Here, we have the full non-GPU subquery plan, so we convert the whole
// thing.
case ex @ BroadcastExchangeExec(_, child) =>
val exMeta = new GpuBroadcastMeta(ex.copy(child = child), conf, p, r)
exMeta.tagForGpu()
if (exMeta.canThisBeReplaced) {
broadcastBuilder = () => exMeta.convertToGpu()
} else {
willNotWorkOnGpu("underlying BroadcastExchange can not run in the GPU.")
}
// DPP: For AQE on, we have an almost completely different scenario then before,
// Databricks uses a BroadcastQueryStageExec and either:
// 1) provide an underlying BroadcastExchangeExec that we will have to convert
// somehow
// 2) might already do the reuse work for us. The ReusedExchange is now a
// part of the SubqueryBroadcast, so we send it back here as underlying the
// GpuSubqueryBroadcastExchangeExec
case bqse: BroadcastQueryStageExec =>
bqse.plan match {
case ex: BroadcastExchangeExec =>
val exMeta = new GpuBroadcastMeta(ex, conf, p, r)
exMeta.tagForGpu()
if (exMeta.canThisBeReplaced) {
broadcastBuilder = () => exMeta.convertToGpu()
} else {
willNotWorkOnGpu("underlying BroadcastExchange can not run in the GPU.")
}
case reuse: ReusedExchangeExec =>
reuse.child match {
case _: GpuBroadcastExchangeExec =>
// A BroadcastExchange has already been replaced, so it can run on the GPU
broadcastBuilder = () => reuse
case _ =>
willNotWorkOnGpu("underlying BroadcastExchange can not run in the GPU.")
}
}
case _ =>
willNotWorkOnGpu("the subquery to broadcast can not entirely run in the GPU.")
}
/**
* Simply returns the original plan. Because its only child, BroadcastExchange, doesn't
* need to change if SubqueryBroadcastExec falls back to the CPU.
*/
override def convertToCpu(): SparkPlan = s

/** Extract the broadcast mode key expressions if there are any. */
protected def getBroadcastModeKeyExprs: Option[Seq[Expression]] = {
val broadcastMode = s.child match {
case b: BroadcastExchangeExec =>
b.mode
case bqse: BroadcastQueryStageExec =>
bqse.plan match {
case b: BroadcastExchangeExec =>
b.mode
case reuse: ReusedExchangeExec =>
reuse.child match {
case g: GpuBroadcastExchangeExec =>
g.mode
}
case _ =>
throw new AssertionError("should not reach here")
}
}

broadcastMode match {
case HashedRelationBroadcastMode(keys, _) => Some(keys)
case IdentityBroadcastMode => None
case m => throw new UnsupportedOperationException(s"Unknown broadcast mode $m")
}
}
}

Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ class GpuSubqueryBroadcastMeta(
conf: RapidsConf,
p: Option[RapidsMeta[_, _, _]],
r: DataFromReplacementRule) extends
GpuSubqueryBroadcastMetaBase(s, conf, p, r) {
GpuSubqueryBroadcastMeta330DBBase(s, conf, p, r) {
mythrocks marked this conversation as resolved.
Show resolved Hide resolved
override def convertToGpu(): GpuExec = {
GpuSubqueryBroadcastExec(s.name, s.indices, s.buildKeys, broadcastBuilder())(
getBroadcastModeKeyExprs)
Expand Down