-
Notifications
You must be signed in to change notification settings - Fork 228
/
collectionOperations.scala
1534 lines (1344 loc) · 58.8 KB
/
collectionOperations.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) 2021-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 org.apache.spark.sql.rapids
import java.util.Optional
import ai.rapids.cudf
import ai.rapids.cudf.{BinaryOp, ColumnVector, ColumnView, DType, Scalar, SegmentedReductionAggregation, Table}
import com.nvidia.spark.rapids._
import com.nvidia.spark.rapids.ArrayIndexUtils.firstIndexAndNumElementUnchecked
import com.nvidia.spark.rapids.BoolUtils.isAllValidTrue
import com.nvidia.spark.rapids.GpuExpressionsUtils.columnarEvalToColumn
import com.nvidia.spark.rapids.RapidsPluginImplicits._
import com.nvidia.spark.rapids.shims.ShimExpression
import org.apache.spark.sql.catalyst.analysis.{TypeCheckResult, TypeCoercion}
import org.apache.spark.sql.catalyst.expressions.{ElementAt, ExpectsInputTypes, Expression, ImplicitCastInputTypes, NamedExpression, NullIntolerant, RowOrdering, Sequence, TimeZoneAwareExpression}
import org.apache.spark.sql.catalyst.util.GenericArrayData
import org.apache.spark.sql.rapids.shims.RapidsErrorUtils
import org.apache.spark.sql.types._
import org.apache.spark.sql.vectorized.ColumnarBatch
import org.apache.spark.unsafe.array.ByteArrayMethods.MAX_ROUNDED_ARRAY_LENGTH
case class GpuConcat(children: Seq[Expression]) extends GpuComplexTypeMergingExpression {
@transient override lazy val dataType: DataType = {
if (children.isEmpty) {
StringType
} else {
super.dataType
}
}
override def nullable: Boolean = children.exists(_.nullable)
override def columnarEval(batch: ColumnarBatch): Any = dataType match {
// Explicitly return null for empty concat as Spark, since cuDF doesn't support empty concat.
case dt if children.isEmpty => GpuScalar.from(null, dt)
// For single column concat, we pass the result of child node to avoid extra cuDF call.
case _ if children.length == 1 => children.head.columnarEval(batch)
case StringType => stringConcat(batch)
case ArrayType(_, _) => listConcat(batch)
case _ => throw new IllegalArgumentException(s"unsupported dataType $dataType")
}
private def stringConcat(batch: ColumnarBatch): GpuColumnVector = {
withResource(children.safeMap(columnarEvalToColumn(_, batch).getBase())) {cols =>
// run string concatenate
GpuColumnVector.from(
cudf.ColumnVector.stringConcatenate(cols.toArray[ColumnView]), StringType)
}
}
private def listConcat(batch: ColumnarBatch): GpuColumnVector = {
withResource(children.safeMap(columnarEvalToColumn(_, batch).getBase())) {cols =>
// run list concatenate
GpuColumnVector.from(cudf.ColumnVector.listConcatenateByRow(cols: _*), dataType)
}
}
}
case class GpuMapConcat(children: Seq[Expression]) extends GpuComplexTypeMergingExpression {
override lazy val hasSideEffects: Boolean =
GpuCreateMap.exceptionOnDupKeys || super.hasSideEffects
@transient override lazy val dataType: MapType = {
if (children.isEmpty) {
MapType(StringType, StringType)
} else {
super.dataType.asInstanceOf[MapType]
}
}
override def nullable: Boolean = children.exists(_.nullable)
override def columnarEval(batch: ColumnarBatch): Any = (dataType, children.length) match {
// Explicitly return null for empty concat as Spark, since cuDF doesn't support empty concat.
case (dt, 0) => GpuColumnVector.fromNull(batch.numRows(), dt)
// For single column concat, we pass the result of child node to avoid extra cuDF call.
case (_, 1) => children.head.columnarEval(batch)
case (dt, _) => {
withResource(children.safeMap(columnarEvalToColumn(_, batch).getBase())) {cols =>
withResource(cudf.ColumnVector.listConcatenateByRow(cols: _*)) {structs =>
GpuCreateMap.createMapFromKeysValuesAsStructs(dataType, structs)
}
}
}
}
}
object GpuElementAtMeta {
/**
* Construct the expression rule for `ElementAt`.
* @param nullOnInvalidAccessToMap
* Returns `null` or throws an exception on invalid access to map column.
* For Spark 3.4+ and DB11.3+, this argument is `true`,
* and for other Spark versions, it is `false`.
*/
def elementAtRule(nullOnInvalidAccessToMap: Boolean): ExprRule[_ <: Expression] = {
GpuOverrides.expr[ElementAt](
"Returns element of array at given(1-based) index in value if column is array. " +
"Returns value for the given key in value if column is map.",
ExprChecks.binaryProject(
(TypeSig.commonCudfTypes + TypeSig.ARRAY + TypeSig.STRUCT + TypeSig.NULL +
TypeSig.DECIMAL_128 + TypeSig.MAP + TypeSig.BINARY).nested(), TypeSig.all,
("array/map", TypeSig.ARRAY.nested(TypeSig.commonCudfTypes + TypeSig.ARRAY +
TypeSig.STRUCT + TypeSig.NULL + TypeSig.DECIMAL_128 + TypeSig.MAP + TypeSig.BINARY) +
TypeSig.MAP.nested(TypeSig.commonCudfTypes + TypeSig.ARRAY + TypeSig.STRUCT +
TypeSig.NULL + TypeSig.DECIMAL_128 + TypeSig.MAP + TypeSig.BINARY)
.withPsNote(TypeEnum.MAP, "If it's map, only primitive key types are supported."),
TypeSig.ARRAY.nested(TypeSig.all) + TypeSig.MAP.nested(TypeSig.all)),
("index/key", (TypeSig.commonCudfTypes + TypeSig.DECIMAL_128)
.withPsNote(
Seq(TypeEnum.BOOLEAN, TypeEnum.BYTE, TypeEnum.SHORT, TypeEnum.LONG,
TypeEnum.FLOAT, TypeEnum.DOUBLE, TypeEnum.DATE, TypeEnum.TIMESTAMP,
TypeEnum.STRING, TypeEnum.DECIMAL), "Unsupported as array index."),
TypeSig.all)),
(in, conf, p, r) => new BinaryExprMeta[ElementAt](in, conf, p, r) {
override def tagExprForGpu(): Unit = {
// To distinguish the supported nested type between Array and Map
val checks = in.left.dataType match {
case _: MapType =>
// Match exactly with the checks for GetMapValue
ExprChecks.binaryProject(
(TypeSig.commonCudfTypes + TypeSig.ARRAY + TypeSig.STRUCT + TypeSig.NULL +
TypeSig.DECIMAL_128 + TypeSig.MAP + TypeSig.BINARY).nested(),
TypeSig.all,
("map",
TypeSig.MAP.nested(TypeSig.commonCudfTypes + TypeSig.ARRAY + TypeSig.STRUCT +
TypeSig.NULL + TypeSig.DECIMAL_128 + TypeSig.MAP + TypeSig.BINARY),
TypeSig.MAP.nested(TypeSig.all)),
("key", TypeSig.commonCudfTypes + TypeSig.DECIMAL_128, TypeSig.all))
case _: ArrayType =>
// Match exactly with the checks for GetArrayItem
ExprChecks.binaryProject(
(TypeSig.commonCudfTypes + TypeSig.ARRAY + TypeSig.STRUCT + TypeSig.NULL +
TypeSig.DECIMAL_128 + TypeSig.MAP + TypeSig.BINARY).nested(),
TypeSig.all,
("array", TypeSig.ARRAY.nested(TypeSig.commonCudfTypes + TypeSig.ARRAY +
TypeSig.STRUCT + TypeSig.NULL + TypeSig.DECIMAL_128 + TypeSig.MAP +
TypeSig.BINARY),
TypeSig.ARRAY.nested(TypeSig.all)),
("ordinal", TypeSig.INT, TypeSig.INT))
case _ => throw new IllegalStateException("Only Array or Map is supported as input.")
}
checks.tag(this)
}
override def convertToGpu(lhs: Expression, rhs: Expression): GpuExpression = {
val failOnError = if (nullOnInvalidAccessToMap) {
in.failOnError && lhs.dataType.isInstanceOf[ArrayType]
} else {
in.failOnError
}
GpuElementAt(lhs, rhs, failOnError)
}
})
}
}
case class GpuElementAt(left: Expression, right: Expression, failOnError: Boolean)
extends GpuBinaryExpression with ExpectsInputTypes {
override def hasSideEffects: Boolean = super.hasSideEffects || failOnError
override lazy val dataType: DataType = left.dataType match {
case ArrayType(elementType, _) => elementType
case MapType(_, valueType, _) => valueType
}
override def inputTypes: Seq[AbstractDataType] = {
(left.dataType, right.dataType) match {
case (arr: ArrayType, e2: IntegralType) if e2 != LongType =>
Seq(arr, IntegerType)
case (MapType(keyType, valueType, hasNull), e2) =>
TypeCoercion.findTightestCommonType(keyType, e2) match {
case Some(dt) => Seq(MapType(dt, valueType, hasNull), dt)
case _ => Seq.empty
}
case _ => Seq.empty
}
}
override def checkInputDataTypes(): TypeCheckResult = {
(left.dataType, right.dataType) match {
case (_: ArrayType, e2) if e2 != IntegerType =>
TypeCheckResult.TypeCheckFailure(s"Input to function $prettyName should have " +
s"been ${ArrayType.simpleString} followed by a ${IntegerType.simpleString}, but it's " +
s"[${left.dataType.catalogString}, ${right.dataType.catalogString}].")
case (MapType(e1, _, _), e2) if !e2.sameType(e1) =>
TypeCheckResult.TypeCheckFailure(s"Input to function $prettyName should have " +
s"been ${MapType.simpleString} followed by a value of same key type, but it's " +
s"[${left.dataType.catalogString}, ${right.dataType.catalogString}].")
case (e1, _) if !e1.isInstanceOf[MapType] && !e1.isInstanceOf[ArrayType] =>
TypeCheckResult.TypeCheckFailure(s"The first argument to function $prettyName should " +
s"have been ${ArrayType.simpleString} or ${MapType.simpleString} type, but its " +
s"${left.dataType.catalogString} type.")
case _ => TypeCheckResult.TypeCheckSuccess
}
}
// Eventually we need something more full featured like
// GetArrayItemUtil.computeNullabilityFromArray
override def nullable: Boolean = true
@transient
private lazy val doElementAtV: (ColumnVector, ColumnVector) => cudf.ColumnVector =
left.dataType match {
case _: ArrayType =>
(array, indices) => {
if (failOnError) {
// Check if any index is out of bound only when ansi mode is enabled. Nulls in either
// array or indices are skipped during this computation. Then no exception will be
// raised if no valid entry (An entry is valid when both the array row and its index
// are not null), the same with what Spark does.
withResource(array.countElements()) { numElements =>
val hasLargerIndices = withResource(indices.abs()) { absIndices =>
absIndices.greaterThan(numElements)
}
withResource(hasLargerIndices) { _ =>
if (BoolUtils.isAnyValidTrue(hasLargerIndices)) {
val (index, numElem) = firstIndexAndNumElementUnchecked(hasLargerIndices,
indices, numElements)
throw RapidsErrorUtils.invalidArrayIndexError(index, numElem, true)
}
}
}
} // end of "if (failOnError)"
// convert to zero-based indices for positive values
val indicesCol = withResource(Scalar.fromInt(0)) { zeroS =>
// No exception should be raised if no valid entry (An entry is valid when both
// the array row and its index are not null), the same with what Spark does.
val hasValidEntryCV = indices.mergeAndSetValidity(BinaryOp.BITWISE_AND,
indices, array)
withResource(hasValidEntryCV) { _ =>
if (hasValidEntryCV.contains(zeroS)) {
throw RapidsErrorUtils.sqlArrayIndexNotStartAtOneError()
}
}
val zeroBasedIndices = withResource(Scalar.fromInt(1)) { oneS =>
indices.sub(oneS, indices.getType)
}
withResource(zeroBasedIndices) { _ =>
withResource(indices.greaterThan(zeroS)) { hasPositiveIndices =>
hasPositiveIndices.ifElse(zeroBasedIndices, indices)
}
}
}
withResource(indicesCol) { _ =>
array.extractListElement(indicesCol)
}
}
case _: MapType =>
(map, indices) => {
if (failOnError) {
GpuMapUtils.getMapValueOrThrow(map, indices, right.dataType, origin)
}
else {
map.getMapValue(indices)
}
}
}
override def doColumnar(lhs: GpuColumnVector, rhs: GpuColumnVector): cudf.ColumnVector =
doElementAtV(lhs.getBase, rhs.getBase)
override def doColumnar(lhs: GpuScalar, rhs: GpuColumnVector): cudf.ColumnVector =
withResource(ColumnVector.fromScalar(lhs.getBase, rhs.getRowCount.toInt)) { expandedCV =>
doElementAtV(expandedCV, rhs.getBase)
}
@transient
private lazy val doElementAtS: (ColumnView, GpuScalar) => cudf.ColumnVector =
left.dataType match {
case _: ArrayType =>
(array, indexS) => {
if (!indexS.isValid || array.getRowCount == array.getNullCount) {
// Return nulls when index is null or all the array rows are null,
// the same with what Spark does.
GpuColumnVector.columnVectorFromNull(array.getRowCount.toInt, dataType)
} else {
// The index is valid, and array column contains at least one non-null row.
val index = indexS.getValue.asInstanceOf[Int]
if (failOnError) {
// Check if index is out of bound only when ansi mode is enabled, since cuDF
// returns nulls if index is out of bound, the same with what Spark does when
// ansi mode is disabled.
withResource(array.countElements()) { numElementsCV =>
withResource(numElementsCV.min) { minScalar =>
val minNumElements = minScalar.getInt
if (math.abs(index) > minNumElements) {
throw RapidsErrorUtils.invalidArrayIndexError(index, minNumElements, true)
}
}
}
}
// convert to zero-based index if it is positive
val idx = if (index == 0) {
throw RapidsErrorUtils.sqlArrayIndexNotStartAtOneError()
} else if (index > 0) {
index - 1
} else {
index
}
array.extractListElement(idx)
}
}
case MapType(keyType, _, _) =>
(map, keyS) => {
val key = keyS.getBase
if (failOnError) {
withResource(map.getMapKeyExistence(key)){ keyExistenceColumn =>
withResource(keyExistenceColumn.all()) { exist =>
if (!exist.isValid || exist.getBoolean) {
map.getMapValue(key)
} else {
throw RapidsErrorUtils.mapKeyNotExistError(keyS.getValue.toString, keyType,
origin)
}
}
}
} else {
map.getMapValue(key)
}
}
}
override def doColumnar(lhs: GpuColumnVector, rhs: GpuScalar): cudf.ColumnVector =
doElementAtS(lhs.getBase, rhs)
override def doColumnar(numRows: Int, lhs: GpuScalar, rhs: GpuScalar): cudf.ColumnVector =
withResource(ColumnVector.fromScalar(lhs.getBase, numRows)) { expandedCV =>
doElementAtS(expandedCV, rhs)
}
override def prettyName: String = "element_at"
}
case class GpuSize(child: Expression, legacySizeOfNull: Boolean)
extends GpuUnaryExpression {
require(child.dataType.isInstanceOf[ArrayType] || child.dataType.isInstanceOf[MapType],
s"The size function doesn't support the operand type ${child.dataType}")
override def dataType: DataType = IntegerType
override def nullable: Boolean = if (legacySizeOfNull) false else super.nullable
override protected def doColumnar(input: GpuColumnVector): cudf.ColumnVector = {
// Compute sizes of cuDF.ListType to get sizes of each ArrayData or MapData, considering
// MapData is represented as List of Struct in terms of cuDF.
withResource(input.getBase.countElements()) { collectionSize =>
if (legacySizeOfNull) {
withResource(Scalar.fromInt(-1)) { nullScalar =>
withResource(input.getBase.isNull) { inputIsNull =>
inputIsNull.ifElse(nullScalar, collectionSize)
}
}
} else {
collectionSize.incRefCount()
}
}
}
}
case class GpuReverse(child: Expression) extends GpuUnaryExpression {
require(child.dataType.isInstanceOf[StringType] || child.dataType.isInstanceOf[ArrayType],
s"The reverse function doesn't support the operand type ${child.dataType}")
override def dataType: DataType = child.dataType
override protected def doColumnar(input: GpuColumnVector): ColumnVector = {
input.getBase.reverseStringsOrLists()
}
}
case class GpuMapKeys(child: Expression)
extends GpuUnaryExpression with ExpectsInputTypes {
override def inputTypes: Seq[AbstractDataType] = Seq(MapType)
override def dataType: DataType = ArrayType(child.dataType.asInstanceOf[MapType].keyType)
override def prettyName: String = "map_keys"
override protected def doColumnar(input: GpuColumnVector): cudf.ColumnVector = {
withResource(GpuMapUtils.getKeysAsListView(input.getBase)) { retView =>
retView.copyToColumnVector()
}
}
}
case class GpuMapValues(child: Expression)
extends GpuUnaryExpression with ExpectsInputTypes {
override def inputTypes: Seq[AbstractDataType] = Seq(MapType)
override def dataType: DataType = {
val mt = child.dataType.asInstanceOf[MapType]
ArrayType(mt.valueType, containsNull = mt.valueContainsNull)
}
override def prettyName: String = "map_values"
override protected def doColumnar(input: GpuColumnVector): cudf.ColumnVector = {
withResource(GpuMapUtils.getValuesAsListView(input.getBase)) { retView =>
retView.copyToColumnVector()
}
}
}
case class GpuMapEntries(child: Expression) extends GpuUnaryExpression with ExpectsInputTypes {
override def inputTypes: Seq[AbstractDataType] = Seq(MapType)
@transient private lazy val childDataType: MapType = child.dataType.asInstanceOf[MapType]
override def dataType: DataType = {
ArrayType(
StructType(
StructField("key", childDataType.keyType, false) ::
StructField("value", childDataType.valueType, childDataType.valueContainsNull) ::
Nil),
false)
}
override def prettyName: String = "map_entries"
override protected def doColumnar(input: GpuColumnVector): cudf.ColumnVector = {
// Internally the format for a list of key/value structs is the same, so just
// return the same thing, and let Spark think it is a different type.
input.getBase.incRefCount()
}
}
case class GpuSortArray(base: Expression, ascendingOrder: Expression)
extends GpuBinaryExpression with ExpectsInputTypes {
override def left: Expression = base
override def right: Expression = ascendingOrder
override def dataType: DataType = base.dataType
override def inputTypes: Seq[AbstractDataType] = Seq(ArrayType, BooleanType)
override def checkInputDataTypes(): TypeCheckResult = base.dataType match {
case ArrayType(dt, _) if RowOrdering.isOrderable(dt) =>
ascendingOrder match {
// replace Literal with GpuLiteral here
case GpuLiteral(_: Boolean, BooleanType) =>
TypeCheckResult.TypeCheckSuccess
case order =>
TypeCheckResult.TypeCheckFailure(
s"Sort order in second argument requires a boolean literal, but found $order")
}
case ArrayType(dt, _) =>
val dtSimple = dt.catalogString
TypeCheckResult.TypeCheckFailure(
s"$prettyName does not support sorting array of type $dtSimple which is not orderable")
case dt =>
TypeCheckResult.TypeCheckFailure(s"$prettyName only supports array input, but found $dt")
}
override def doColumnar(lhs: GpuColumnVector, rhs: GpuColumnVector): cudf.ColumnVector =
throw new IllegalArgumentException("lhs has to be a vector and rhs has to be a scalar for " +
"the sort_array operator to work")
override def doColumnar(lhs: GpuScalar, rhs: GpuColumnVector): cudf.ColumnVector =
throw new IllegalArgumentException("lhs has to be a vector and rhs has to be a scalar for " +
"the sort_array operator to work")
override def doColumnar(lhs: GpuColumnVector, rhs: GpuScalar): cudf.ColumnVector = {
val isDescending = isDescendingOrder(rhs)
lhs.getBase.listSortRows(isDescending, true)
}
override def doColumnar(numRows: Int, lhs: GpuScalar, rhs: GpuScalar): cudf.ColumnVector = {
withResource(GpuColumnVector.from(lhs, numRows, left.dataType)) { cv =>
doColumnar(cv, rhs)
}
}
private def isDescendingOrder(scalar: GpuScalar): Boolean = scalar.getValue match {
case ascending: Boolean => !ascending
case invalidValue => throw new IllegalArgumentException(s"invalid value $invalidValue")
}
}
object GpuArrayMin {
def apply(child: Expression): GpuArrayMin = {
child.dataType match {
case ArrayType(FloatType | DoubleType, _) => GpuFloatArrayMin(child)
case ArrayType(_, _) => GpuBasicArrayMin(child)
case _ => throw new IllegalStateException(s"array_min accepts only arrays.")
}
}
}
abstract class GpuArrayMin(child: Expression) extends GpuUnaryExpression
with ImplicitCastInputTypes
with Serializable {
override def nullable: Boolean = true
override def inputTypes: Seq[AbstractDataType] = Seq(ArrayType)
@transient override lazy val dataType: DataType = child.dataType match {
case ArrayType(dt, _) => dt
case _ => throw new IllegalStateException(s"$prettyName accepts only arrays.")
}
override def prettyName: String = "array_min"
override protected def doColumnar(input: GpuColumnVector): cudf.ColumnVector =
input.getBase.listReduce(SegmentedReductionAggregation.min())
}
/** ArrayMin without `Nan` handling */
case class GpuBasicArrayMin(child: Expression) extends GpuArrayMin(child)
/** ArrayMin for FloatType and DoubleType to handle `Nan`s.
*
* In Spark, `Nan` is the max float value, however in cuDF, the calculation
* involving `Nan` is undefined.
* We design a workaround method here to match the Spark's behaviour.
* The high level idea is:
* if one list contains only `Nan`s or `null`s
* then
if the list contains `Nan`
* then return `Nan`
* else return null
* else
* replace all `Nan`s with nulls;
* use cuDF kernel to find the min value
*/
case class GpuFloatArrayMin(child: Expression) extends GpuArrayMin(child) {
@transient override lazy val dataType: DataType = child.dataType match {
case ArrayType(FloatType, _) => FloatType
case ArrayType(DoubleType, _) => DoubleType
case _ => throw new IllegalStateException(
s"GpuFloatArrayMin accepts only float array and double array."
)
}
protected def getNanScalar: Scalar = dataType match {
case FloatType => Scalar.fromFloat(Float.NaN)
case DoubleType => Scalar.fromDouble(Double.NaN)
case t => throw new IllegalStateException(s"dataType $t is not FloatType or DoubleType")
}
protected def getNullScalar: Scalar = dataType match {
case FloatType => Scalar.fromNull(DType.FLOAT32)
case DoubleType => Scalar.fromNull(DType.FLOAT64)
case t => throw new IllegalStateException(s"dataType $t is not FloatType or DoubleType")
}
override protected def doColumnar(input: GpuColumnVector): cudf.ColumnVector = {
val listAll = SegmentedReductionAggregation.all()
val listAny = SegmentedReductionAggregation.max()
val base = input.getBase()
withResource(base.getChildColumnView(0)) { child =>
withResource(child.isNan()){ childIsNan =>
// if all values in each list are nans or nulls
val allNanOrNull = {
val childIsNanOrNull = withResource(child.isNull()) {_.or(childIsNan)}
val nanOrNullList = withResource(childIsNanOrNull) {base.replaceListChild(_)}
withResource(nanOrNullList) {_.listReduce(listAll)}
}
withResource(allNanOrNull){ allNanOrNull =>
// return nan if the list contains nan, else return null
val trueOption = {
val anyNan = withResource(base.replaceListChild(childIsNan)) {
_.listReduce(listAny)
}
withResource(anyNan) { anyNan =>
withResource(getNanScalar) { nanScalar =>
withResource(getNullScalar) { nullScalar =>
anyNan.ifElse(nanScalar, nullScalar)
}
}
}
}
withResource(trueOption){ trueOption =>
// replace all nans to nulls, and then find the min value.
val falseOption = withResource(child.nansToNulls()) { nanToNullChild =>
withResource(base.replaceListChild(nanToNullChild)) { nanToNullList =>
nanToNullList.listReduce(SegmentedReductionAggregation.min())
}
}
// if a list contains values other than nan or null
// return `trueOption`, else return `falseOption`.
withResource(falseOption){ falseOption =>
allNanOrNull.ifElse(trueOption, falseOption)
}
}
}
}
}
}
}
object GpuArrayMax {
def apply(child: Expression): GpuArrayMax = {
child.dataType match {
case ArrayType(FloatType | DoubleType, _) => GpuFloatArrayMax(child)
case ArrayType(_, _) => GpuBasicArrayMax(child)
case _ => throw new IllegalStateException(s"array_max accepts only arrays.")
}
}
}
abstract class GpuArrayMax(child: Expression) extends GpuUnaryExpression
with ImplicitCastInputTypes
with Serializable{
override def nullable: Boolean = true
override def inputTypes: Seq[AbstractDataType] = Seq(ArrayType)
@transient override lazy val dataType: DataType = child.dataType match {
case ArrayType(dt, _) => dt
case _ => throw new IllegalStateException(s"$prettyName accepts only arrays.")
}
override def prettyName: String = "array_max"
override protected def doColumnar(input: GpuColumnVector): cudf.ColumnVector =
input.getBase.listReduce(SegmentedReductionAggregation.max())
}
/** ArrayMax without `NaN` handling */
case class GpuBasicArrayMax(child: Expression) extends GpuArrayMax(child)
/** ArrayMax for FloatType and DoubleType to handle `Nan`s.
*
* In Spark, `Nan` is the max float value, however in cuDF, the calculation
* involving `Nan` is undefined.
* We design a workaround method here to match the Spark's behaviour.
* The high level idea is that, we firstly check if each list contains `Nan`.
* If it is, the max value is `Nan`, else we use the cuDF kernel to
* calculate the max value.
*/
case class GpuFloatArrayMax(child: Expression) extends GpuArrayMax(child){
@transient override lazy val dataType: DataType = child.dataType match {
case ArrayType(FloatType, _) => FloatType
case ArrayType(DoubleType, _) => DoubleType
case _ => throw new IllegalStateException(
s"GpuFloatArrayMax accepts only float array and double array."
)
}
protected def getNanSalar: Scalar = dataType match {
case FloatType => Scalar.fromFloat(Float.NaN)
case DoubleType => Scalar.fromDouble(Double.NaN)
case t => throw new IllegalStateException(s"dataType $t is not FloatType or DoubleType")
}
override protected def doColumnar(input: GpuColumnVector): cudf.ColumnVector = {
withResource(getNanSalar){nan =>
withResource(input.getBase().listContains(nan)){hasNan =>
withResource(input.getBase().listReduce(SegmentedReductionAggregation.max())) {max =>
hasNan.ifElse(nan, max)
}
}
}
}
}
case class GpuArrayRepeat(left: Expression, right: Expression) extends GpuBinaryExpression {
override def dataType: DataType = ArrayType(left.dataType, left.nullable)
override def doColumnar(lhs: GpuColumnVector, rhs: GpuColumnVector): ColumnVector = {
// The primary issue of array_repeat is to workaround the null and negative count.
// Spark returns a null (list) when encountering a null count, and an
// empty list when encountering a negative count.
// cudf does not handle these cases properly.
// Step 1. replace invalid counts
// null -> 0
// negative values -> 0
val refinedCount = withResource(GpuScalar.from(0, DataTypes.IntegerType)) { zero =>
withResource(rhs.getBase.replaceNulls(zero)) { notNull =>
withResource(notNull.lessThan(zero)) { lessThanZero =>
lessThanZero.ifElse(zero, notNull)
}
}
}
// Step 2. perform cuDF repeat
val repeated = closeOnExcept(refinedCount) { cnt =>
withResource(new Table(lhs.getBase)) { table =>
table.repeat(cnt).getColumn(0)
}
}
// Step 3. generate list offsets from refined counts
val offsets = closeOnExcept(repeated) { _ =>
withResource(refinedCount) { cnt =>
cnt.generateListOffsets()
}
}
// Step 4. make the result list column with offsets and child column
val list = withResource(offsets) { offsets =>
withResource(repeated) { repeated =>
repeated.makeListFromOffsets(lhs.getRowCount, offsets)
}
}
// Step 5. merge the validity of count column to the result
withResource(list) { list =>
list.mergeAndSetValidity(BinaryOp.BITWISE_AND, rhs.getBase)
}
}
override def doColumnar(lhs: GpuScalar, rhs: GpuColumnVector): ColumnVector = {
withResource(GpuColumnVector.from(lhs, rhs.getRowCount.toInt, lhs.dataType)) { left =>
doColumnar(left, rhs)
}
}
override def doColumnar(lhs: GpuColumnVector, rhs: GpuScalar): ColumnVector = {
val numRows = lhs.getRowCount.toInt
if (!rhs.isValid) {
GpuColumnVector.fromNull(numRows, dataType).getBase
} else {
val count = rhs.getValue.asInstanceOf[Int] max 0
val offsets = withResource(GpuScalar.from(count, IntegerType)) { cntScalar =>
withResource(GpuColumnVector.from(cntScalar, numRows, rhs.dataType)) { cnt =>
cnt.getBase.generateListOffsets()
}
}
withResource(offsets) { offsets =>
withResource(new Table(lhs.getBase)) { table =>
withResource(table.repeat(count).getColumn(0)) { repeated =>
repeated.makeListFromOffsets(lhs.getRowCount, offsets)
}
}
}
}
}
override def doColumnar(numRows: Int, lhs: GpuScalar, rhs: GpuScalar): ColumnVector = {
if (!rhs.isValid) {
GpuColumnVector.fromNull(numRows, dataType).getBase
} else {
withResource(GpuColumnVector.from(lhs, numRows, lhs.dataType)) { left =>
doColumnar(left, rhs)
}
}
}
}
case class GpuArraysZip(children: Seq[Expression]) extends GpuExpression with ShimExpression
with ExpectsInputTypes {
override def inputTypes: Seq[AbstractDataType] = Seq.fill(children.length)(ArrayType)
@transient override lazy val dataType: DataType = {
val fields = children.zip(arrayElementTypes).zipWithIndex.map {
case ((expr: NamedExpression, elementType), _) =>
StructField(expr.name, elementType, nullable = true)
case ((_, elementType), idx) =>
StructField(idx.toString, elementType, nullable = true)
}
ArrayType(StructType(fields), containsNull = false)
}
override def nullable: Boolean = children.exists(_.nullable)
@transient private lazy val arrayElementTypes =
children.map(_.dataType.asInstanceOf[ArrayType].elementType)
override def columnarEval(batch: ColumnarBatch): Any = {
if (children.isEmpty) {
return GpuScalar(new GenericArrayData(Array.empty[Any]), dataType)
}
// Prepare input columns
val inputs = children.safeMap { expr =>
GpuExpressionsUtils.columnarEvalToColumn(expr, batch).getBase
}
val cleanedInputs = withResource(inputs) { inputs =>
normalizeNulls(inputs)
}
val padded = withResource(cleanedInputs) { cleanedInputs =>
padArraysToMaxLength(cleanedInputs)
}
withResource(padded) { _ =>
closeOnExcept(zipArrays(padded)) { ret =>
GpuColumnVector.from(ret, dataType)
}
}
}
/**
* Segmented gather in CUDF produces a NULL output for a NULL input. But we need to produce
* child columns that we can put together in a struct. This requires them all to have the
* same length. To make this work we need to make sure all of the inputs have nulls in the
* same places at the top level. That way when we gather things we get the same output
* size for all of the children of the input columns. The result of this will have the same
* validity for all top level columns, but possibly different offsets.
*/
private def normalizeNulls(inputs: Seq[cudf.ColumnVector]): Seq[ColumnVector] = {
// First let's figure out if there are any nulls at all, because if there are not we don't
// need to do anything.
if (inputs.exists(_.hasNulls)) {
var nullOutput = inputs.head.isNull
try {
inputs.drop(1).foreach { cv =>
val combinedIsNull = withResource(cv.isNull) { tmpIsNull =>
tmpIsNull.or(nullOutput)
}
closeOnExcept(combinedIsNull) { _ =>
nullOutput.close()
nullOutput = combinedIsNull
}
}
// input1: [[A, B, C], [D, E], [F], [G]]
// input2: [[a, b], [c, d, e], null, [f, g]]
// combinedIsNull, false, false, true, false
// output1: [[A, B, C], [D, E], null, [G]]
// output2: [[a, b], [c, d, e], null, [f, g]]
inputs.zip(children).safeMap { case (cv, child) =>
withResource(GpuScalar.from(null, child.dataType)) { nullArray =>
nullOutput.ifElse(nullArray, cv)
}
}
} finally {
nullOutput.close()
}
} else {
inputs.map(_.incRefCount())
}
}
private def computeMaxArraySize(inputs: Seq[ColumnVector]): ColumnVector = {
// Compute array sizes of input arrays
val arraySizes = inputs.safeMap(_.countElements())
// Pick max array size of each row.
// Replace with zero if there exists null among input values.
// [1, 3, 5, null, 4]
// [2, 4, 3, 8, 0] => [4, 4, 5, 0, 7]
// [4, 2, 3, 10, 7]
val arraySizeList = withResource(arraySizes) { sizes =>
ColumnVector.makeList(sizes: _*)
}
val maxArraySizeWithNull = withResource(arraySizeList) { list =>
list.listReduce(SegmentedReductionAggregation.max())
}
withResource(maxArraySizeWithNull) { max =>
withResource(GpuScalar.from(0, IntegerType)) { zero =>
max.replaceNulls(zero)
}
}
}
private def generateSeqIndices(maxArraySize: ColumnVector): ColumnVector = {
withResource(GpuScalar.from(0, IntegerType)) { s =>
withResource(ColumnVector.fromScalar(s, maxArraySize.getRowCount.toInt)) { zero =>
ColumnVector.sequence(zero, maxArraySize)
}
}
}
/**
* Do a segmented gather on the inputs so that they are padded with nulls to make sure each LIST
* on the same row, at the top level, has the same length. The columns returned should have the
* same offsets and the same validity. This assumes that the validity on the inputs all match.
*/
private def padArraysToMaxLength(inputs: Seq[ColumnVector]): Seq[ColumnVector] = {
// Compute max size of input arrays for each row, this is to know how we need to pad things.
//
// input1: [[A, B, C], [D, E], null, [G]]
// input2: [[a, b], [c, d, e], null, [f, g]]
// max array size: [3, 3, 0, 2]
val seqIndices = withResource(computeMaxArraySize(inputs)) { maxArraySize =>
// Generate sequence indices for gathering children of input arrays
//
// [3, 3, 0, 2] => [[0, 1, 2], [0, 1, 2], [], [0, 1]]
generateSeqIndices(maxArraySize)
}
// Perform segment gather on input columns with indices covering each element
//
// input1: [[A, B, C], [D, E], null, [G]]
// input2: [[a, b], [c, d, e], null, [f, g]]
// indices: [[0, 1, 2], [0, 1, 2], [], [0, 1]]
// output1: [[A, B, C], [D, E, null], null, [G, null]]
// output2: [[a, b, null], [c, d, e], null, [f, g]]
withResource(seqIndices) { _ =>
inputs.safeMap { cv =>
cv.segmentedGather(seqIndices)
}
}
}
/**
* This turns LIST[X], LIST[Y], ... into a LIST[ STRUCT[X, Y, ...] ] but requires that
* the input LIST columns all have the same validity and offsets.
*/
private def zipArrays(padded: Seq[ColumnVector]): ColumnVector = {
// Get the data column from the children, without any offsets
withResource(padded.safeMap(_.getChildColumnView(0))) { children =>
// Put them into a struct column view
withResource(ColumnView.makeStructView(children: _*)) { structView =>
// Make the struct a list using the input's offsets and validity
// in the cheapest way possible.
val proto = padded.head
withResource(proto.getValid) { valid =>
withResource(proto.getOffsets) { offsets =>
withResource(new ColumnView(DType.LIST, proto.getRowCount,
java.util.Optional.of[java.lang.Long](proto.getNullCount),
valid, offsets, Array(structView))) { retView =>
// Finally copy the result out to a ColumnVector so we can return it
retView.copyToColumnVector()
}
}
}
}
}
}
}
// Base class for GpuArrayExcept, GpuArrayUnion, GpuArrayIntersect
trait GpuArrayBinaryLike extends GpuComplexTypeMergingExpression with NullIntolerant {
val left: Expression
val right: Expression
@transient override final lazy val children: Seq[Expression] = IndexedSeq(left, right)
def doColumnar(lhs: GpuColumnVector, rhs: GpuColumnVector): ColumnVector
def doColumnar(lhs: GpuScalar, rhs: GpuColumnVector): ColumnVector
def doColumnar(lhs: GpuColumnVector, rhs: GpuScalar): ColumnVector
def doColumnar(numRows: Int, lhs: GpuScalar, rhs: GpuScalar): ColumnVector
override def columnarEval(batch: ColumnarBatch): Any = {
withResourceIfAllowed(left.columnarEval(batch)) { lhs =>
withResourceIfAllowed(right.columnarEval(batch)) { rhs =>
(lhs, rhs) match {
case (l: GpuColumnVector, r: GpuColumnVector) =>
GpuColumnVector.from(doColumnar(l, r), dataType)
case (l: GpuScalar, r: GpuColumnVector) =>
GpuColumnVector.from(doColumnar(l, r), dataType)
case (l: GpuColumnVector, r: GpuScalar) =>
GpuColumnVector.from(doColumnar(l, r), dataType)
case (l: GpuScalar, r: GpuScalar) =>
GpuColumnVector.from(doColumnar(batch.numRows(), l, r), dataType)
case (l, r) =>
throw new UnsupportedOperationException(s"Unsupported data '($l: " +
s"${l.getClass}, $r: ${r.getClass})' for GPU binary expression.")
}
}
}
}
}
case class GpuArrayExcept(left: Expression, right: Expression)
extends GpuArrayBinaryLike with ExpectsInputTypes {
override def inputTypes: Seq[AbstractDataType] = Seq(ArrayType, ArrayType)
override def checkInputDataTypes(): TypeCheckResult =
(left.dataType, right.dataType) match {
case (ArrayType(ldt, _), ArrayType(rdt, _)) =>
if (ldt.sameType(rdt)) {
TypeCheckResult.TypeCheckSuccess
} else {
TypeCheckResult.TypeCheckFailure(
s"Array_intersect requires both array params to have the same subType: $ldt != $rdt")
}
case dt =>
TypeCheckResult.TypeCheckFailure(s"$prettyName only supports array input, but found $dt")
}