-
Notifications
You must be signed in to change notification settings - Fork 242
/
Copy pathSparkQueryCompareTestSuite.scala
2274 lines (2068 loc) · 77.6 KB
/
SparkQueryCompareTestSuite.scala
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (c) 2019-2023, 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.
*/
package com.nvidia.spark.rapids
import java.io.{File, IOException}
import java.nio.file.Files
import java.sql.{Date, Timestamp}
import java.util.{Locale, TimeZone, UUID}
import scala.reflect.ClassTag
import scala.util.{Failure, Try}
import org.apache.hadoop.fs.FileUtil
import org.scalatest.{Assertion, BeforeAndAfterAll}
import org.scalatest.funsuite.AnyFunSuite
import org.apache.spark.SparkConf
import org.apache.spark.internal.Logging
import org.apache.spark.sql.{DataFrame, Row, SparkSession}
import org.apache.spark.sql.execution.SparkPlan
import org.apache.spark.sql.execution.command.{CreateViewCommand, ExecutedCommandExec}
import org.apache.spark.sql.internal.SQLConf
import org.apache.spark.sql.rapids.ExecutionPlanCaptureCallback
import org.apache.spark.sql.rapids.execution.TrampolineUtil
import org.apache.spark.sql.types._
object TestResourceFinder {
private [this] var resourcePrefix: String = _
def setPrefix(prefix: String): Unit = {
resourcePrefix = prefix
}
def getResourcePath(path: String): String = {
if (resourcePrefix == null) {
val resource = this.getClass.getClassLoader.getResource(path)
if (resource == null) {
throw new IllegalStateException(s"Could not find $path with " +
s"classloader ${this.getClass.getClassLoader}")
}
resource.toString
} else {
resourcePrefix + "/" + path
}
}
}
object SparkSessionHolder extends Logging {
private var spark = createSparkSession()
private var origConf = spark.conf.getAll
private var origConfKeys = origConf.keys.toSet
private def setAllConfs(confs: Array[(String, String)]): Unit = confs.foreach {
case (key, value) if spark.conf.get(key, null) != value =>
spark.conf.set(key, value)
case _ => // No need to modify it
}
private def createSparkSession(): SparkSession = {
TrampolineUtil.cleanupAnyExistingSession()
// Timezone is fixed to UTC to allow timestamps to work by default
TimeZone.setDefault(TimeZone.getTimeZone("UTC"))
// Add Locale setting
Locale.setDefault(Locale.US)
val builder = SparkSession.builder()
.master("local[1]")
.config("spark.sql.adaptive.enabled", "false")
.config("spark.rapids.sql.enabled", "false")
.config("spark.rapids.sql.test.enabled", "false")
.config("spark.plugins", "com.nvidia.spark.SQLPlugin")
.config("spark.sql.queryExecutionListeners",
"org.apache.spark.sql.rapids.ExecutionPlanCaptureCallback")
.config("spark.sql.warehouse.dir", sparkWarehouseDir.getAbsolutePath)
.appName("rapids spark plugin integration tests (scala)")
// comma separated config from command line
val commandLineVariables = System.getenv("SPARK_CONF")
if (commandLineVariables != null) {
commandLineVariables.split(",").foreach { s =>
val a = s.split("=")
builder.config(a(0), a(1))
}
}
builder.getOrCreate()
}
private def reinitSession(): Unit = {
spark = createSparkSession()
origConf = spark.conf.getAll
origConfKeys = origConf.keys.toSet
}
def sparkSession: SparkSession = {
if (SparkSession.getActiveSession.isEmpty) {
reinitSession()
}
spark
}
def resetSparkSessionConf(): Unit = {
if (SparkSession.getActiveSession.isEmpty) {
reinitSession()
} else {
setAllConfs(origConf.toArray)
val currentKeys = spark.conf.getAll.keys.toSet
val toRemove = currentKeys -- origConfKeys
if (toRemove.contains("spark.shuffle.manager")) {
// cannot unset the config so need to reinitialize
reinitSession()
} else {
toRemove.foreach(spark.conf.unset)
}
}
logDebug(s"RESET CONF TO: ${spark.conf.getAll}")
}
def withSparkSession[U](conf: SparkConf, f: SparkSession => U): U = {
resetSparkSessionConf
logDebug(s"SETTING CONF: ${conf.getAll.toMap}")
setAllConfs(conf.getAll)
logDebug(s"RUN WITH CONF: ${spark.conf.getAll}\n")
f(spark)
}
private lazy val sparkWarehouseDir: File = {
val path = Files.createTempDirectory("spark-warehouse")
val file = new File(path.toString)
file.deleteOnExit()
file
}
}
/**
* Set of tests that compare the output using the CPU version of spark vs our GPU version.
*/
trait SparkQueryCompareTestSuite extends AnyFunSuite with BeforeAndAfterAll {
import SparkSessionHolder.withSparkSession
def enableCsvConf(): SparkConf = enableCsvConf(new SparkConf())
override def afterAll(): Unit = {
super.afterAll()
TrampolineUtil.cleanupAnyExistingSession()
}
def enableCsvConf(conf: SparkConf): SparkConf = {
conf
.set(RapidsConf.ENABLE_READ_CSV_FLOATS.key, "true")
.set(RapidsConf.ENABLE_READ_CSV_DOUBLES.key, "true")
.set(RapidsConf.ENABLE_READ_CSV_DECIMALS.key, "true")
.set(RapidsConf.ENABLE_READ_JSON_FLOATS.key, "true")
.set(RapidsConf.ENABLE_READ_JSON_DOUBLES.key, "true")
.set(RapidsConf.ENABLE_READ_JSON_DECIMALS.key, "true")
}
// @see java.lang.Float#intBitsToFloat
// <quote>
// If the argument is any value in the range `0x7f800001` through `0x7fffffff` or
// in the range `0xff800001` through `0xffffffff`, the result is a NaN
// </quote>
val FLOAT_POSITIVE_NAN_LOWER_RANGE = java.lang.Float.intBitsToFloat(0x7f800001)
val FLOAT_POSITIVE_NAN_UPPER_RANGE = java.lang.Float.intBitsToFloat(0x7fffffff)
val FLOAT_NEGATIVE_NAN_LOWER_RANGE = java.lang.Float.intBitsToFloat(0xff800001)
val FLOAT_NEGATIVE_NAN_UPPER_RANGE = java.lang.Float.intBitsToFloat(0xffffffff)
// see java.lang.Double#longBitsToDouble
// <quote>
// <p>If the argument is any value in the range `0x7ff0000000000001L` through
// `0x7fffffffffffffffL` or in the range
// `0xfff0000000000001L` through
// `0xffffffffffffffffL`, the result is a NaN
val DOUBLE_POSITIVE_NAN_LOWER_RANGE = java.lang.Double.longBitsToDouble(0x7ff0000000000001L)
val DOUBLE_POSITIVE_NAN_UPPER_RANGE = java.lang.Double.longBitsToDouble(0x7fffffffffffffffL)
val DOUBLE_NEGATIVE_NAN_LOWER_RANGE = java.lang.Double.longBitsToDouble(0xfff0000000000001L)
val DOUBLE_NEGATIVE_NAN_UPPER_RANGE = java.lang.Double.longBitsToDouble(0xffffffffffffffffL)
def withGpuSparkSession[U](f: SparkSession => U, conf: SparkConf = new SparkConf()): U = {
val c = conf.clone()
.set(RapidsConf.SQL_ENABLED.key, "true")
.set(RapidsConf.TEST_CONF.key, "true")
.set(RapidsConf.EXPLAIN.key, "ALL")
withSparkSession(c, f)
}
def withCpuSparkSession[U](f: SparkSession => U, conf: SparkConf = new SparkConf()): U = {
val c = conf.clone()
.set(RapidsConf.SQL_ENABLED.key, "false") // Just to be sure
withSparkSession(c, f)
}
def compare(expected: Any, actual: Any, epsilon: Double = 0.0): Boolean = {
def doublesAreEqualWithinPercentage(expected: Double, actual: Double): (String, Boolean) = {
if (!compare(expected, actual)) {
if (expected != 0) {
val v = Math.abs((expected - actual) / expected)
(s"\n\nABS($expected - $actual) / ABS($actual) == $v is not <= $epsilon ", v <= epsilon)
} else {
val v = Math.abs(expected - actual)
(s"\n\nABS($expected - $actual) == $v is not <= $epsilon ", v <= epsilon)
}
} else {
("SUCCESS", true)
}
}
(expected, actual) match {
case (a: Float, b: Float) if a.isNaN && b.isNaN => true
case (a: Double, b: Double) if a.isNaN && b.isNaN => true
case (null, null) => true
case (null, _) => false
case (_, null) => false
case (a: Array[_], b: Array[_]) =>
a.length == b.length && a.zip(b).forall { case (l, r) => compare(l, r, epsilon) }
case (a: Map[_, _], b: Map[_, _]) =>
a.size == b.size && a.keys.forall { aKey =>
b.keys.find(bKey => compare(aKey, bKey))
.exists(bKey => compare(a(aKey), b(bKey), epsilon))
}
case (a: Iterable[_], b: Iterable[_]) =>
a.size == b.size && a.zip(b).forall { case (l, r) => compare(l, r, epsilon) }
case (a: Product, b: Product) =>
compare(a.productIterator.toSeq, b.productIterator.toSeq, epsilon)
case (a: Row, b: Row) =>
compare(a.toSeq, b.toSeq, epsilon)
// 0.0 == -0.0, turn float/double to bits before comparison, to distinguish 0.0 and -0.0.
case (a: Double, b: Double) if epsilon <= 0 =>
java.lang.Double.doubleToRawLongBits(a) == java.lang.Double.doubleToRawLongBits(b)
case (a: Double, b: Double) if epsilon > 0 =>
val ret = doublesAreEqualWithinPercentage(a, b)
if (!ret._2) {
System.err.println(ret._1 + " (double)")
}
ret._2
case (a: Float, b: Float) if epsilon <= 0 =>
java.lang.Float.floatToRawIntBits(a) == java.lang.Float.floatToRawIntBits(b)
case (a: Float, b: Float) if epsilon > 0 =>
val ret = doublesAreEqualWithinPercentage(a, b)
if (!ret._2) {
System.err.println(ret._1 + " (float)")
}
ret._2
case (a, b) => a == b
}
}
def executeFunOnCpuAndGpuWithCapture(df: SparkSession => DataFrame,
fun: DataFrame => Unit,
conf: SparkConf = new SparkConf(),
repart: Integer = 1)
: (SparkPlan, SparkPlan) = {
conf.setIfMissing("spark.sql.shuffle.partitions", "2")
// force a new session to avoid accidentally capturing a late callback from a previous query
TrampolineUtil.cleanupAnyExistingSession()
ExecutionPlanCaptureCallback.startCapture()
var cpuPlans: Array[SparkPlan] = Array.empty
try {
withCpuSparkSession(session => {
var data = df(session)
if (repart > 0) {
// repartition the data so it is turned into a projection,
// not folded into the table scan exec
data = data.repartition(repart)
}
fun(data)
}, conf)
} finally {
cpuPlans = ExecutionPlanCaptureCallback.getResultsWithTimeout()
}
cpuPlans = filterCapturedPlans(cpuPlans)
assert(cpuPlans.nonEmpty, "Did not capture CPU plan")
assert(cpuPlans.length == 1, s"Captured more than one CPU plan: ${cpuPlans.mkString("\n")}")
ExecutionPlanCaptureCallback.startCapture()
var gpuPlans: Array[SparkPlan] = Array.empty
try {
withGpuSparkSession(session => {
var data = df(session)
if (repart > 0) {
// repartition the data so it is turned into a projection,
// not folded into the table scan exec
data = data.repartition(repart)
}
fun(data)
}, conf)
} finally {
gpuPlans = ExecutionPlanCaptureCallback.getResultsWithTimeout()
}
gpuPlans = filterCapturedPlans(gpuPlans)
assert(gpuPlans.nonEmpty, "Did not capture GPU plan")
assert(gpuPlans.length == 1, s"Captured more than one GPU plan: ${gpuPlans.mkString("\n")}")
(cpuPlans.head, gpuPlans.head)
}
// filter out "uninteresting" plans like view creation, etc.
protected def filterCapturedPlans(plans: Array[SparkPlan]): Array[SparkPlan] = {
plans.filter {
case ExecutedCommandExec(_: CreateViewCommand) => false
case _ => true
}
}
def runOnCpuAndGpuWithCapture(df: SparkSession => DataFrame,
fun: DataFrame => DataFrame,
conf: SparkConf = new SparkConf(),
repart: Integer = 1)
: (Array[Row], SparkPlan, Array[Row], SparkPlan) = {
conf.setIfMissing("spark.sql.shuffle.partitions", "2")
// force a new session to avoid accidentally capturing a late callback from a previous query
TrampolineUtil.cleanupAnyExistingSession()
ExecutionPlanCaptureCallback.startCapture()
var cpuPlans: Array[SparkPlan] = Array.empty
val fromCpu =
try {
withCpuSparkSession(session => {
var data = df(session)
if (repart > 0) {
// repartition the data so it is turned into a projection,
// not folded into the table scan exec
data = data.repartition(repart)
}
fun(data).collect()
}, conf)
} finally {
cpuPlans = ExecutionPlanCaptureCallback.getResultsWithTimeout()
}
cpuPlans = filterCapturedPlans(cpuPlans)
assert(cpuPlans.nonEmpty, "Did not capture CPU plan")
assert(cpuPlans.length == 1, s"Captured more than one CPU plan: ${cpuPlans.mkString("\n")}")
ExecutionPlanCaptureCallback.startCapture()
var gpuPlans: Array[SparkPlan] = Array.empty
val fromGpu =
try {
withGpuSparkSession(session => {
var data = df(session)
if (repart > 0) {
// repartition the data so it is turned into a projection,
// not folded into the table scan exec
data = data.repartition(repart)
}
fun(data).collect()
}, conf)
} finally {
gpuPlans = ExecutionPlanCaptureCallback.getResultsWithTimeout()
}
gpuPlans = filterCapturedPlans(gpuPlans)
assert(gpuPlans.nonEmpty, "Did not capture GPU plan")
assert(gpuPlans.length == 1, s"Captured more than one GPU plan: ${gpuPlans.mkString("\n")}")
(fromCpu, cpuPlans.head, fromGpu, gpuPlans.head)
}
def testGpuWriteFallback(testName: String,
fallbackCpuClass: String,
df: SparkSession => DataFrame,
conf: SparkConf = new SparkConf(),
repart: Integer = 1,
sort: Boolean = false,
maxFloatDiff: Double = 0.0,
incompat: Boolean = false,
execsAllowedNonGpu: Seq[String] = Seq.empty,
sortBeforeRepart: Boolean = false)
(fun: DataFrame => Unit): Unit = {
val (testConf, qualifiedTestName) =
setupTestConfAndQualifierName(testName, incompat, sort, conf, execsAllowedNonGpu,
maxFloatDiff, sortBeforeRepart)
test(qualifiedTestName) {
val (_, gpuPlan) = executeFunOnCpuAndGpuWithCapture(df, fun,
conf = testConf,
repart = repart)
// Now check the GPU Conditions
ExecutionPlanCaptureCallback.assertDidFallBack(gpuPlan, fallbackCpuClass)
}
}
// use a write function to write test file with cpu then check gpu fallback
// useful when only want to test reading or writing is not supported on gpu
def testGpuReadFallback(testName: String,
fallbackCpuClass: String,
readFunc: File => (SparkSession => DataFrame),
writeFun: (SparkSession, File) => Unit,
conf: SparkConf = new SparkConf(),
repart: Integer = 1,
sort: Boolean = false,
maxFloatDiff: Double = 0.0,
incompat: Boolean = false,
execsAllowedNonGpu: Seq[String] = Seq.empty,
sortBeforeRepart: Boolean = false)
(fun: DataFrame => DataFrame): Unit = {
val (testConf, qualifiedTestName) =
setupTestConfAndQualifierName(testName, incompat, sort, conf, execsAllowedNonGpu,
maxFloatDiff, sortBeforeRepart)
test(qualifiedTestName) {
withTempPath { file =>
withCpuSparkSession { spark =>
writeFun(spark, file)
}
val (fromCpu, _, fromGpu, gpuPlan) = runOnCpuAndGpuWithCapture(readFunc(file), fun,
conf = testConf,
repart = repart)
// Now check the GPU Conditions
ExecutionPlanCaptureCallback.assertDidFallBack(gpuPlan, fallbackCpuClass)
compareResults(sort, maxFloatDiff, fromCpu, fromGpu)
}
}
}
def testGpuFallback(testName: String,
fallbackCpuClass: String,
df: SparkSession => DataFrame,
conf: SparkConf = new SparkConf(),
repart: Integer = 1,
sort: Boolean = false,
maxFloatDiff: Double = 0.0,
incompat: Boolean = false,
execsAllowedNonGpu: Seq[String] = Seq.empty,
sortBeforeRepart: Boolean = false)
(fun: DataFrame => DataFrame): Unit = {
val (testConf, qualifiedTestName) =
setupTestConfAndQualifierName(testName, incompat, sort, conf, execsAllowedNonGpu,
maxFloatDiff, sortBeforeRepart)
test(qualifiedTestName) {
val (fromCpu, _, fromGpu, gpuPlan) = runOnCpuAndGpuWithCapture(df, fun,
conf = testConf,
repart = repart)
// Now check the GPU Conditions
ExecutionPlanCaptureCallback.assertDidFallBack(gpuPlan, fallbackCpuClass)
compareResults(sort, maxFloatDiff, fromCpu, fromGpu)
}
}
/**
* Runs a test defined by fun, using dataframe df.
*
* @param df the DataFrame to use as input
* @param fun the function to transform the DataFrame (produces another DataFrame)
* @param conf spark conf
* @return tuple of (cpu results, gpu results) as arrays of Row
*/
def runOnCpuAndGpu(
df: SparkSession => DataFrame,
fun: DataFrame => DataFrame,
conf: SparkConf = new SparkConf(),
repart: Integer = 1,
skipCanonicalizationCheck: Boolean = false,
existClasses: String = null,
nonExistClasses: String = null): (Array[Row], Array[Row]) = {
conf.setIfMissing("spark.sql.shuffle.partitions", "2")
val (planCpu, canonicalizationMatchesCpu, fromCpu) = withCpuSparkSession( session => {
var data = df(session)
if (repart > 0) {
// repartition the data so it is turned into a projection,
// not folded into the table scan exec
data = data.repartition(repart)
}
collect(fun, data)
}, conf)
val (planGpu, canonicalizationMatchesGpu, fromGpu) = withGpuSparkSession( session => {
var data = df(session)
if (repart > 0) {
// repartition the data so it is turned into a projection,
// not folded into the table scan exec
data = data.repartition(repart)
}
collect(fun, data, existClasses, nonExistClasses)
}, conf)
if (!skipCanonicalizationCheck && (canonicalizationMatchesCpu != canonicalizationMatchesGpu)) {
fail(s"canonicalizationMatchesCpu=$canonicalizationMatchesCpu != " +
s"canonicalizationMatchesGpu=$canonicalizationMatchesGpu\n" +
s"CPU plan: $planCpu\n" +
s"GPU plan: $planGpu")
}
(fromCpu, fromGpu)
}
/**
* Runs a test defined by fun, using 2 dataframes dfA and dfB.
*
* @param dfA the first DataFrame to use as input
* @param dfB the second DataFrame to use as input
* @param fun the function to transform the DataFrame (produces another DataFrame)
* @param conf spark conf
* @return tuple of (cpu results, gpu results) as arrays of Row
*/
def runOnCpuAndGpu2(dfA: SparkSession => DataFrame,
dfB: SparkSession => DataFrame,
fun: (DataFrame, DataFrame) => DataFrame,
conf: SparkConf = new SparkConf(),
repart: Integer = 1): (Array[Row], Array[Row]) = {
val fromCpu = withCpuSparkSession((session) => {
var dataA = dfA(session)
var dataB = dfB(session)
if (repart > 0) {
// repartition the data so it is turned into a projection,
// not folded into the table scan exec
dataA = dataA.repartition(repart)
dataB = dataB.repartition(repart)
}
fun(dataA, dataB).collect()
}, conf)
val fromGpu = withGpuSparkSession((session) => {
var dataA = dfA(session)
var dataB = dfB(session)
if (repart > 0) {
// repartition the data so it is turned into a projection,
// not folded into the table scan exec
dataA = dataA.repartition(repart)
dataB = dataB.repartition(repart)
}
fun(dataA, dataB).collect()
}, conf)
(fromCpu, fromGpu)
}
def collect(
fun: DataFrame => DataFrame,
data: DataFrame, existClasses: String = null,
nonExistClasses: String = null): (SparkPlan, Boolean, Array[Row]) = {
val plan1 = fun(data)
val plan2 = fun(data)
val canonicalizationMatches = plan1.queryExecution.executedPlan.canonicalized ==
plan2.queryExecution.executedPlan.canonicalized
if (existClasses != null) {
existClasses.split(",").foreach { cls =>
ExecutionPlanCaptureCallback.assertContains(plan1, cls)
}
}
if (nonExistClasses != null) {
nonExistClasses.split(",").foreach { cls =>
ExecutionPlanCaptureCallback.assertNotContain(plan1, cls)
}
}
(plan1.queryExecution.executedPlan.canonicalized, canonicalizationMatches, plan1.collect())
}
def INCOMPAT_testSparkResultsAreEqual(
testName: String,
df: SparkSession => DataFrame,
maxFloatDiff: Double = 0.0,
conf: SparkConf = new SparkConf(),
sort: Boolean = false,
repart: Integer = 1,
sortBeforeRepart: Boolean = false)
(fun: DataFrame => DataFrame): Unit = {
testSparkResultsAreEqual(testName, df,
conf=conf,
repart=repart,
sort=sort,
maxFloatDiff=maxFloatDiff,
incompat=true,
sortBeforeRepart = sortBeforeRepart)(fun)
}
def ALLOW_NON_GPU_testSparkResultsAreEqual(
testName: String,
df: SparkSession => DataFrame,
execsAllowedNonGpu: Seq[String],
conf: SparkConf = new SparkConf(),
sortBeforeRepart: Boolean = false,
skipCanonicalizationCheck: Boolean = false)(fun: DataFrame => DataFrame): Unit = {
testSparkResultsAreEqual(testName, df,
conf=conf,
execsAllowedNonGpu=execsAllowedNonGpu,
sortBeforeRepart = sortBeforeRepart,
skipCanonicalizationCheck = skipCanonicalizationCheck)(fun)
}
def ALLOW_NON_GPU_testSparkResultsAreEqualWithCapture(
testName: String,
df: SparkSession => DataFrame,
execsAllowedNonGpu: Seq[String],
conf: SparkConf = new SparkConf(),
sortBeforeRepart: Boolean = false)
(fun: DataFrame => DataFrame)
(validateCapturedPlans: (SparkPlan, SparkPlan) => Unit): Unit = {
testSparkResultsAreEqualWithCapture(testName, df,
conf=conf,
execsAllowedNonGpu=execsAllowedNonGpu,
sortBeforeRepart = sortBeforeRepart)(fun)(validateCapturedPlans)
}
def IGNORE_ORDER_ALLOW_NON_GPU_testSparkResultsAreEqual(
testName: String,
df: SparkSession => DataFrame,
execsAllowedNonGpu: Seq[String],
repart: Integer = 1,
conf: SparkConf = new SparkConf(),
sortBeforeRepart: Boolean = false)(fun: DataFrame => DataFrame): Unit = {
testSparkResultsAreEqual(testName, df,
conf=conf,
execsAllowedNonGpu=execsAllowedNonGpu,
repart=repart,
sort=true,
sortBeforeRepart = sortBeforeRepart)(fun)
}
def IGNORE_ORDER_ALLOW_NON_GPU_testSparkResultsAreEqualWithCapture(
testName: String,
df: SparkSession => DataFrame,
execsAllowedNonGpu: Seq[String],
repart: Integer = 1,
conf: SparkConf = new SparkConf(),
sortBeforeRepart: Boolean = false)
(fun: DataFrame => DataFrame)
(validateCapturedPlans: (SparkPlan, SparkPlan) => Unit): Unit = {
testSparkResultsAreEqualWithCapture(testName, df,
conf=conf,
execsAllowedNonGpu=execsAllowedNonGpu,
repart=repart,
sort=true,
sortBeforeRepart = sortBeforeRepart)(fun)(validateCapturedPlans)
}
def IGNORE_ORDER_testSparkResultsAreEqual(
testName: String,
df: SparkSession => DataFrame,
repart: Integer = 1,
conf: SparkConf = new SparkConf(),
sortBeforeRepart: Boolean = false,
skipCanonicalizationCheck: Boolean = false)(fun: DataFrame => DataFrame): Unit = {
testSparkResultsAreEqual(testName, df,
conf=conf,
repart=repart,
sort=true,
sortBeforeRepart = sortBeforeRepart,
skipCanonicalizationCheck = skipCanonicalizationCheck)(fun)
}
def IGNORE_ORDER_testSparkResultsAreEqualWithCapture(
testName: String,
df: SparkSession => DataFrame,
repart: Integer = 1,
conf: SparkConf = new SparkConf(),
sortBeforeRepart: Boolean = false)
(fun: DataFrame => DataFrame)
(validateCapturedPlans: (SparkPlan, SparkPlan) => Unit): Unit = {
testSparkResultsAreEqualWithCapture(testName, df,
conf=conf,
repart=repart,
sort=true,
sortBeforeRepart = sortBeforeRepart)(fun)(validateCapturedPlans)
}
def INCOMPAT_IGNORE_ORDER_testSparkResultsAreEqual(
testName: String,
df: SparkSession => DataFrame,
repart: Integer = 1,
conf: SparkConf = new SparkConf(),
sortBeforeRepart: Boolean = false)(fun: DataFrame => DataFrame): Unit = {
testSparkResultsAreEqual(testName, df,
conf=conf,
repart=repart,
incompat=true,
sort=true,
sortBeforeRepart = sortBeforeRepart)(fun)
}
/**
* Writes and reads a dataframe to a file using the CPU and the GPU.
*
* @param df the DataFrame to use as input
* @param writer the function to write the data to a file
* @param reader the function to read the data from a file
* @param conf spark conf
* @return tuple of (cpu results, gpu results) as arrays of Row
*/
def writeWithCpuAndGpu(
df: SparkSession => DataFrame,
writer: (DataFrame, String) => Unit,
reader: (SparkSession, String) => DataFrame,
conf: SparkConf = new SparkConf()): (Array[Row], Array[Row]) = {
conf.setIfMissing("spark.sql.shuffle.partitions", "2")
var tempCpuFile: File = null
var tempGpuFile: File = null
try {
tempCpuFile = File.createTempFile("testdata", "cpu")
// remove the empty file to prevent "file already exists" from writers
tempCpuFile.delete()
withCpuSparkSession(session => {
val data = df(session)
writer(data, tempCpuFile.getAbsolutePath)
}, conf)
tempGpuFile = File.createTempFile("testdata", "gpu")
// remove the empty file to prevent "file already exists" from writers
tempGpuFile.delete()
withGpuSparkSession(session => {
val data = df(session)
writer(data, tempGpuFile.getAbsolutePath)
}, conf)
val (fromCpu, fromGpu) = withCpuSparkSession(session => {
val cpuData = reader(session, tempCpuFile.getAbsolutePath)
val gpuData = reader(session, tempGpuFile.getAbsolutePath)
(cpuData.collect, gpuData.collect)
}, conf)
(fromCpu, fromGpu)
} finally {
if (tempCpuFile != null) {
tempCpuFile.delete()
}
if (tempGpuFile != null) {
tempGpuFile.delete()
}
}
}
// we guarantee that the types will be the same
private def seqLt(a: Seq[Any], b: Seq[Any]): Boolean = {
if (a.length < b.length) {
return true
}
// lengths are the same
for (i <- a.indices) {
val v1 = a(i)
val v2 = b(i)
if (v1 != v2) {
// null is always < anything but null
if (v1 == null) {
return true
}
if (v2 == null) {
return false
}
(v1, v2) match {
case (i1: Int, i2: Int) => if (i1 < i2) {
return true
} else if (i1 > i2) {
return false
}// else equal go on
case (i1: Long, i2: Long) => if (i1 < i2) {
return true
} else if (i1 > i2) {
return false
} // else equal go on
case (i1: Float, i2: Float) => if (i1.isNaN() && !i2.isNaN()) return false
else if (!i1.isNaN() && i2.isNaN()) return true
else if (i1 < i2) {
return true
} else if (i1 > i2) {
return false
} // else equal go on
case (i1: Date, i2: Date) => if (i1.before(i2)) {
return true
} else if (i1.after(i2)) {
return false
} // else equal go on
case (i1: Double, i2: Double) => if (i1.isNaN() && !i2.isNaN()) return false
else if (!i1.isNaN() && i2.isNaN()) return true
else if (i1 < i2) {
return true
} else if (i1 > i2) {
return false
} // else equal go on
case (i1: Short, i2: Short) => if (i1 < i2) {
return true
} else if (i1 > i2) {
return false
} // else equal go on
case (i1: Timestamp, i2: Timestamp) => if (i1.before(i2)) {
return true
} else if (i1.after(i2)) {
return false
} // else equal go on
case (s1: String, s2: String) =>
val cmp = s1.compareTo(s2)
if (cmp < 0) {
return true
} else if (cmp > 0) {
return false
} // else equal go on
case (o1, _) =>
throw new UnsupportedOperationException(o1.getClass + " is not supported yet")
}
}
}
// They are equal...
false
}
def setupTestConfAndQualifierName(
testName: String,
incompat: Boolean,
sort: Boolean,
conf: SparkConf,
execsAllowedNonGpu: Seq[String],
maxFloatDiff: Double,
sortBeforeRepart: Boolean): (SparkConf, String) = {
var qualifiers = Set[String]()
var testConf = conf
if (incompat) {
testConf = testConf.clone().set(RapidsConf.INCOMPATIBLE_OPS.key, "true")
qualifiers = qualifiers + "INCOMPAT"
} else if (maxFloatDiff > 0.0) {
qualifiers = qualifiers + "APPROXIMATE FLOAT"
}
if (sort) {
qualifiers = qualifiers + "IGNORE ORDER"
}
if (execsAllowedNonGpu.nonEmpty) {
val execStr = execsAllowedNonGpu.mkString(",")
testConf = testConf.clone().set(RapidsConf.TEST_ALLOWED_NONGPU.key, execStr)
qualifiers = qualifiers + s"NOT ON GPU[$execStr]"
}
testConf.set("spark.sql.execution.sortBeforeRepartition", sortBeforeRepart.toString)
val qualifiedTestName = qualifiers.mkString("", ", ",
(if (qualifiers.nonEmpty) ": " else "") + testName)
(testConf, qualifiedTestName)
}
def compareResults(
sort: Boolean,
floatEpsilon:Double,
fromCpu: Array[Row],
fromGpu: Array[Row]): Unit = {
val relaxedFloatDisclaimer = if (floatEpsilon > 0) {
"(relaxed float comparison)"
} else {
""
}
if (sort) {
val cpu = fromCpu.map(_.toSeq).sortWith(seqLt)
val gpu = fromGpu.map(_.toSeq).sortWith(seqLt)
if (!compare(cpu, gpu, floatEpsilon)) {
fail(
s"""
|Running on the GPU and on the CPU did not match $relaxedFloatDisclaimer
|CPU: ${cpu.seq}
|GPU: ${gpu.seq}
""".
stripMargin)
}
} else {
if (!compare(fromCpu, fromGpu, floatEpsilon)) {
fail(
s"""
|Running on the GPU and on the CPU did not match $relaxedFloatDisclaimer
|CPU: ${fromCpu.toSeq}
|GPU: ${fromGpu.toSeq}
""".
stripMargin)
}
}
}
def testSparkResultsAreEqual(
testName: String,
df: SparkSession => DataFrame,
conf: SparkConf = new SparkConf(),
repart: Integer = 1,
sort: Boolean = false,
maxFloatDiff: Double = 0.0,
incompat: Boolean = false,
execsAllowedNonGpu: Seq[String] = Seq.empty,
sortBeforeRepart: Boolean = false,
assumeCondition: SparkSession => (Boolean, String) = null,
skipCanonicalizationCheck: Boolean = false,
existClasses: String = null, // Gpu plan should contain the `existClasses`
nonExistClasses: String = null) // Gpu plan should not contain the `nonExistClasses`
(fun: DataFrame => DataFrame): Unit = {
val (testConf, qualifiedTestName) =
setupTestConfAndQualifierName(testName, incompat, sort, conf, execsAllowedNonGpu,
maxFloatDiff, sortBeforeRepart)
test(qualifiedTestName) {
if (assumeCondition != null) {
val (isAllowed, reason) = withCpuSparkSession(assumeCondition, conf = testConf)
assume(isAllowed, reason)
}
val (fromCpu, fromGpu) = runOnCpuAndGpu(df, fun,
conf = testConf,
repart = repart,
skipCanonicalizationCheck = skipCanonicalizationCheck,
existClasses = existClasses,
nonExistClasses = nonExistClasses)
compareResults(sort, maxFloatDiff, fromCpu, fromGpu)
}
}
// use a write function to write test file with cpu then check cpu gpu read equality
// useful when only want to test reading or writing is not supported on gpu
def testSparkReadResultsAreEqual(
testName: String,
readFunc: File => (SparkSession => DataFrame),
writeFun: (SparkSession, File) => Unit,
conf: SparkConf = new SparkConf(),
repart: Integer = 1,
sort: Boolean = false,
maxFloatDiff: Double = 0.0,
incompat: Boolean = false,
execsAllowedNonGpu: Seq[String] = Seq.empty,
sortBeforeRepart: Boolean = false,
assumeCondition: SparkSession => (Boolean, String) = null,
skipCanonicalizationCheck: Boolean = false,
existClasses: String = null, // Gpu plan should contain the `existClasses`
nonExistClasses: String = null) // Gpu plan should not contain the `nonExistClasses`
(fun: DataFrame => DataFrame): Unit = {
val (testConf, qualifiedTestName) =
setupTestConfAndQualifierName(testName, incompat, sort, conf, execsAllowedNonGpu,
maxFloatDiff, sortBeforeRepart)
test(qualifiedTestName) {
if (assumeCondition != null) {
val (isAllowed, reason) = withCpuSparkSession(assumeCondition, conf = testConf)
assume(isAllowed, reason)
}
withTempPath { file =>
withCpuSparkSession { spark =>
writeFun(spark, file)
}
val (fromCpu, fromGpu) = runOnCpuAndGpu(readFunc(file), fun,
conf = testConf,
repart = repart,
skipCanonicalizationCheck = skipCanonicalizationCheck,
existClasses = existClasses,
nonExistClasses = nonExistClasses)
compareResults(sort, maxFloatDiff, fromCpu, fromGpu)
}
}
}
def testSparkResultsAreEqualWithCapture(
testName: String,
df: SparkSession => DataFrame,
conf: SparkConf = new SparkConf(),
repart: Integer = 1,
sort: Boolean = false,
maxFloatDiff: Double = 0.0,
incompat: Boolean = false,
execsAllowedNonGpu: Seq[String] = Seq.empty,
sortBeforeRepart: Boolean = false)
(fun: DataFrame => DataFrame)
(validateCapturedPlans: (SparkPlan, SparkPlan) => Unit): Unit = {
val (testConf, qualifiedTestName) =
setupTestConfAndQualifierName(testName, incompat, sort, conf, execsAllowedNonGpu,
maxFloatDiff, sortBeforeRepart)
test(qualifiedTestName) {
val (fromCpu, cpuPlan, fromGpu, gpuPlan) = runOnCpuAndGpuWithCapture(df, fun,
conf = testConf,
repart = repart)
compareResults(sort, maxFloatDiff, fromCpu, fromGpu)
validateCapturedPlans(cpuPlan, gpuPlan)
}
}
/** Create a DataFrame from a sequence of values and execution a transformation on CPU and GPU,
* and compare results */
def testUnaryFunction(
conf: SparkConf,
values: Seq[Any],
maxFloatDiff: Double = 0.0,
sort: Boolean = false,
repart: Integer = 1)(fun: DataFrame => DataFrame): Unit = {
val df: SparkSession => DataFrame =
(sparkSession: SparkSession) => createDataFrame(sparkSession, values)
val (fromCpu, fromGpu) = runOnCpuAndGpu(df, fun,
conf,
repart = repart)
compareResults(sort, maxFloatDiff, fromCpu, fromGpu)