File size: 83,294 Bytes
8ae5fc5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
/******************************************************************************
 * Copyright (c) 2011, Duane Merrill.  All rights reserved.
 * Copyright (c) 2011-2022, NVIDIA CORPORATION.  All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *     * Redistributions of source code must retain the above copyright
 *       notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above copyright
 *       notice, this list of conditions and the following disclaimer in the
 *       documentation and/or other materials provided with the distribution.
 *     * Neither the name of the NVIDIA CORPORATION nor the
 *       names of its contributors may be used to endorse or promote products
 *       derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL NVIDIA CORPORATION BE LIABLE FOR ANY
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 ******************************************************************************/

/******************************************************************************
 * Test of DeviceRadixSort utilities
 ******************************************************************************/

// Ensure printing of CUDA runtime errors to console
#define CUB_STDERR

#include <algorithm>
#include <climits>
#include <cstdio>
#include <limits>
#include <memory>
#include <random>
#include <type_traits>
#include <typeinfo>
#include <vector>

#if !_NVHPC_CUDA
    #include <cuda_fp16.h>
#endif

#if !_NVHPC_CUDA
    #include <cuda_bf16.h>
#endif

#include <cub/detail/device_synchronize.cuh>
#include <cub/device/device_radix_sort.cuh>
#include <cub/device/device_segmented_radix_sort.cuh>
#include <cub/iterator/transform_input_iterator.cuh>
#include <cub/util_allocator.cuh>
#include <cub/util_math.cuh>

#include <thrust/device_vector.h>
#include <thrust/execution_policy.h>
#include <thrust/host_vector.h>
#include <thrust/mismatch.h>
#include <thrust/sequence.h>
#include <thrust/sort.h>
#include <thrust/system/cuda/detail/core/triple_chevron_launch.h>

#include "test_util.h"

using namespace cub;


//---------------------------------------------------------------------
// Globals, constants and typedefs
//---------------------------------------------------------------------

bool                    g_verbose                       = false;
int                     g_timing_iterations             = 0;
std::size_t             g_smallest_pre_sorted_num_items = (std::size_t(1) << 32) - 42;
CachingDeviceAllocator  g_allocator(true);

// Dispatch types
enum Backend
{
    CUB,                        // CUB method (allows overwriting of input)
    CUB_NO_OVERWRITE,           // CUB method (disallows overwriting of input)

    CUB_SEGMENTED,              // CUB method (allows overwriting of input)
    CUB_SEGMENTED_NO_OVERWRITE, // CUB method (disallows overwriting of input)

    // Same as above, but launches kernels from device using CDP.
    CDP,
    CDP_NO_OVERWRITE,
    CDP_SEGMENTED,
    CDP_SEGMENTED_NO_OVERWRITE,
};

static const char* BackendToString(Backend b)
{
  switch (b)
  {
    case CUB:
      return "CUB";
    case CUB_NO_OVERWRITE:
      return "CUB_NO_OVERWRITE";
    case CUB_SEGMENTED:
      return "CUB_SEGMENTED";
    case CUB_SEGMENTED_NO_OVERWRITE:
      return "CUB_SEGMENTED_NO_OVERWRITE";
    case CDP:
      return "CDP";
    case CDP_NO_OVERWRITE:
      return "CDP_NO_OVERWRITE";
    case CDP_SEGMENTED:
      return "CDP_SEGMENTED";
    case CDP_SEGMENTED_NO_OVERWRITE:
      return "CDP_SEGMENTED_NO_OVERWRITE";
    default:
      break;
  }

  return "";
}

//---------------------------------------------------------------------
// Dispatch to different DeviceRadixSort entrypoints
//---------------------------------------------------------------------

/**
 * Dispatch to CUB sorting entrypoint (specialized for ascending)
 */
template <typename KeyT, typename ValueT, typename BeginOffsetIteratorT, typename EndOffsetIteratorT,
          typename NumItemsT>
CUB_RUNTIME_FUNCTION
cudaError_t Dispatch(
    Int2Type<false>         /*is_descending*/,
    Int2Type<CUB>           /*dispatch_to*/,
    int                     */*d_selector*/,
    size_t                  */*d_temp_storage_bytes*/,
    cudaError_t             */*d_cdp_error*/,

    void*                   d_temp_storage,
    size_t&                 temp_storage_bytes,
    DoubleBuffer<KeyT>      &d_keys,
    DoubleBuffer<ValueT>    &d_values,
    NumItemsT               num_items,
    int                     /*num_segments*/,
    BeginOffsetIteratorT    /*d_segment_begin_offsets*/,
    EndOffsetIteratorT      /*d_segment_end_offsets*/,
    int                     begin_bit,
    int                     end_bit)
{
    return DeviceRadixSort::SortPairs(
        d_temp_storage, temp_storage_bytes,
        d_keys, d_values,
        num_items, begin_bit, end_bit);
}

/**
 * Dispatch to CUB_NO_OVERWRITE sorting entrypoint (specialized for ascending)
 */
template <typename KeyT, typename ValueT, typename BeginOffsetIteratorT, typename EndOffsetIteratorT,
          typename NumItemsT>
CUB_RUNTIME_FUNCTION
cudaError_t Dispatch(
    Int2Type<false>             /*is_descending*/,
    Int2Type<CUB_NO_OVERWRITE>  /*dispatch_to*/,
    int                         */*d_selector*/,
    size_t                      */*d_temp_storage_bytes*/,
    cudaError_t                 */*d_cdp_error*/,

    void*                   d_temp_storage,
    size_t&                 temp_storage_bytes,
    DoubleBuffer<KeyT>      &d_keys,
    DoubleBuffer<ValueT>    &d_values,
    NumItemsT               num_items,
    int                     /*num_segments*/,
    BeginOffsetIteratorT    /*d_segment_begin_offsets*/,
    EndOffsetIteratorT      /*d_segment_end_offsets*/,
    int                     begin_bit,
    int                     end_bit)
{
    KeyT      const *const_keys_itr     = d_keys.Current();
    ValueT    const *const_values_itr   = d_values.Current();

    cudaError_t retval = DeviceRadixSort::SortPairs(
        d_temp_storage, temp_storage_bytes,
        const_keys_itr, d_keys.Alternate(), const_values_itr, d_values.Alternate(),
        num_items, begin_bit, end_bit);

    d_keys.selector ^= 1;
    d_values.selector ^= 1;
    return retval;
}

/**
 * Dispatch to CUB sorting entrypoint (specialized for descending)
 */
template <typename KeyT, typename ValueT, typename BeginOffsetIteratorT, typename EndOffsetIteratorT,
          typename NumItemsT>
CUB_RUNTIME_FUNCTION
cudaError_t Dispatch(
    Int2Type<true>          /*is_descending*/,
    Int2Type<CUB>           /*dispatch_to*/,
    int                     */*d_selector*/,
    size_t                  */*d_temp_storage_bytes*/,
    cudaError_t             */*d_cdp_error*/,

    void*                   d_temp_storage,
    size_t&                 temp_storage_bytes,
    DoubleBuffer<KeyT>      &d_keys,
    DoubleBuffer<ValueT>    &d_values,
    NumItemsT               num_items,
    int                     /*num_segments*/,
    BeginOffsetIteratorT    /*d_segment_begin_offsets*/,
    EndOffsetIteratorT      /*d_segment_end_offsets*/,
    int                     begin_bit,
    int                     end_bit)
{
    return DeviceRadixSort::SortPairsDescending(
        d_temp_storage, temp_storage_bytes,
        d_keys, d_values, num_items,
        begin_bit, end_bit);
}


/**
 * Dispatch to CUB_NO_OVERWRITE sorting entrypoint (specialized for descending)
 */
template <typename KeyT, typename ValueT, typename BeginOffsetIteratorT, typename EndOffsetIteratorT,
          typename NumItemsT>
CUB_RUNTIME_FUNCTION
cudaError_t Dispatch(
    Int2Type<true>              /*is_descending*/,
    Int2Type<CUB_NO_OVERWRITE>  /*dispatch_to*/,
    int                         */*d_selector*/,
    size_t                      */*d_temp_storage_bytes*/,
    cudaError_t                 */*d_cdp_error*/,

    void*                   d_temp_storage,
    size_t&                 temp_storage_bytes,
    DoubleBuffer<KeyT>      &d_keys,
    DoubleBuffer<ValueT>    &d_values,
    NumItemsT               num_items,
    int                     /*num_segments*/,
    BeginOffsetIteratorT    /*d_segment_begin_offsets*/,
    EndOffsetIteratorT      /*d_segment_end_offsets*/,
    int                     begin_bit,
    int                     end_bit)
{
    KeyT      const *const_keys_itr     = d_keys.Current();
    ValueT    const *const_values_itr   = d_values.Current();

    cudaError_t retval = DeviceRadixSort::SortPairsDescending(
        d_temp_storage, temp_storage_bytes,
        const_keys_itr, d_keys.Alternate(), const_values_itr, d_values.Alternate(),
        num_items, begin_bit, end_bit);

    d_keys.selector ^= 1;
    d_values.selector ^= 1;
    return retval;
}

//---------------------------------------------------------------------
// Dispatch to different DeviceRadixSort entrypoints
//---------------------------------------------------------------------

// Validates that `num_items` fits into `int`
// TODO(canonizer): remove this check once num_items is templated for segmented sort.
template <typename NumItemsT>
__host__ __device__ bool ValidateNumItemsForSegmentedSort(NumItemsT num_items)
{
  if (static_cast<long long int>(num_items) <
      static_cast<long long int>(INT_MAX))
  {
    return true;
  }
  else
  {
    printf("cub::DeviceSegmentedRadixSort is currently limited by %d items but "
           "%lld were provided\n",
           INT_MAX,
           static_cast<long long int>(num_items));
  }

  return false;
}

/**
 * Dispatch to CUB_SEGMENTED sorting entrypoint (specialized for ascending)
 */
template <typename KeyT, typename ValueT, typename BeginOffsetIteratorT, typename EndOffsetIteratorT,
          typename NumItemsT>
CUB_RUNTIME_FUNCTION
cudaError_t Dispatch(
    Int2Type<false>         /*is_descending*/,
    Int2Type<CUB_SEGMENTED> /*dispatch_to*/,
    int                     */*d_selector*/,
    size_t                  */*d_temp_storage_bytes*/,
    cudaError_t             */*d_cdp_error*/,

    void*                   d_temp_storage,
    size_t&                 temp_storage_bytes,
    DoubleBuffer<KeyT>      &d_keys,
    DoubleBuffer<ValueT>    &d_values,
    NumItemsT               num_items,
    int                     num_segments,
    BeginOffsetIteratorT    d_segment_begin_offsets,
    EndOffsetIteratorT      d_segment_end_offsets,
    int                     begin_bit,
    int                     end_bit)
{
  if (ValidateNumItemsForSegmentedSort(num_items))
  {
    return DeviceSegmentedRadixSort::SortPairs(d_temp_storage,
                                               temp_storage_bytes,
                                               d_keys,
                                               d_values,
                                               static_cast<int>(num_items),
                                               num_segments,
                                               d_segment_begin_offsets,
                                               d_segment_end_offsets,
                                               begin_bit,
                                               end_bit);
  }

  return cudaErrorInvalidValue;
}

/**
 * Dispatch to CUB_SEGMENTED_NO_OVERWRITE sorting entrypoint (specialized for ascending)
 */
template <typename KeyT, typename ValueT, typename BeginOffsetIteratorT, typename EndOffsetIteratorT,
          typename NumItemsT>
CUB_RUNTIME_FUNCTION
cudaError_t Dispatch(
    Int2Type<false>                         /*is_descending*/,
    Int2Type<CUB_SEGMENTED_NO_OVERWRITE>    /*dispatch_to*/,
    int                                     */*d_selector*/,
    size_t                                  */*d_temp_storage_bytes*/,
    cudaError_t                             */*d_cdp_error*/,

    void*                   d_temp_storage,
    size_t&                 temp_storage_bytes,
    DoubleBuffer<KeyT>      &d_keys,
    DoubleBuffer<ValueT>    &d_values,
    NumItemsT               num_items,
    int                     num_segments,
    BeginOffsetIteratorT    d_segment_begin_offsets,
    EndOffsetIteratorT      d_segment_end_offsets,
    int                     begin_bit,
    int                     end_bit)
{
  if (ValidateNumItemsForSegmentedSort(num_items))
  {
    KeyT const *const_keys_itr     = d_keys.Current();
    ValueT const *const_values_itr = d_values.Current();

    cudaError_t retval =
      DeviceSegmentedRadixSort::SortPairs(d_temp_storage,
                                          temp_storage_bytes,
                                          const_keys_itr,
                                          d_keys.Alternate(),
                                          const_values_itr,
                                          d_values.Alternate(),
                                          static_cast<int>(num_items),
                                          num_segments,
                                          d_segment_begin_offsets,
                                          d_segment_end_offsets,
                                          begin_bit,
                                          end_bit);

    d_keys.selector ^= 1;
    d_values.selector ^= 1;
    return retval;
  }

  return cudaErrorInvalidValue;
}


/**
 * Dispatch to CUB_SEGMENTED sorting entrypoint (specialized for descending)
 */
template <typename KeyT, typename ValueT, typename BeginOffsetIteratorT, typename EndOffsetIteratorT,
          typename NumItemsT>
CUB_RUNTIME_FUNCTION
cudaError_t Dispatch(
    Int2Type<true>          /*is_descending*/,
    Int2Type<CUB_SEGMENTED> /*dispatch_to*/,
    int                     */*d_selector*/,
    size_t                  */*d_temp_storage_bytes*/,
    cudaError_t             */*d_cdp_error*/,

    void*                   d_temp_storage,
    size_t&                 temp_storage_bytes,
    DoubleBuffer<KeyT>      &d_keys,
    DoubleBuffer<ValueT>    &d_values,
    NumItemsT               num_items,
    int                     num_segments,
    BeginOffsetIteratorT    d_segment_begin_offsets,
    EndOffsetIteratorT      d_segment_end_offsets,
    int                     begin_bit,
    int                     end_bit)
{
  if (ValidateNumItemsForSegmentedSort(num_items))
  {
    return DeviceSegmentedRadixSort::SortPairsDescending(
      d_temp_storage,
      temp_storage_bytes,
      d_keys,
      d_values,
      static_cast<int>(num_items),
      num_segments,
      d_segment_begin_offsets,
      d_segment_end_offsets,
      begin_bit,
      end_bit);
  }

  return cudaErrorInvalidValue;
}

/**
 * Dispatch to CUB_SEGMENTED_NO_OVERWRITE sorting entrypoint (specialized for descending)
 */
template <typename KeyT, typename ValueT, typename BeginOffsetIteratorT, typename EndOffsetIteratorT,
          typename NumItemsT>
CUB_RUNTIME_FUNCTION
cudaError_t Dispatch(
    Int2Type<true>                          /*is_descending*/,
    Int2Type<CUB_SEGMENTED_NO_OVERWRITE>    /*dispatch_to*/,
    int                                     */*d_selector*/,
    size_t                                  */*d_temp_storage_bytes*/,
    cudaError_t                             */*d_cdp_error*/,

    void*                   d_temp_storage,
    size_t&                 temp_storage_bytes,
    DoubleBuffer<KeyT>      &d_keys,
    DoubleBuffer<ValueT>    &d_values,
    NumItemsT               num_items,
    int                     num_segments,
    BeginOffsetIteratorT    d_segment_begin_offsets,
    EndOffsetIteratorT      d_segment_end_offsets,
    int                     begin_bit,
    int                     end_bit)
{
  if (ValidateNumItemsForSegmentedSort(num_items))
  {
    KeyT const *const_keys_itr     = d_keys.Current();
    ValueT const *const_values_itr = d_values.Current();

    cudaError_t retval =
      DeviceSegmentedRadixSort::SortPairsDescending(d_temp_storage,
                                                    temp_storage_bytes,
                                                    const_keys_itr,
                                                    d_keys.Alternate(),
                                                    const_values_itr,
                                                    d_values.Alternate(),
                                                    static_cast<int>(num_items),
                                                    num_segments,
                                                    d_segment_begin_offsets,
                                                    d_segment_end_offsets,
                                                    begin_bit,
                                                    end_bit);

    d_keys.selector ^= 1;
    d_values.selector ^= 1;
    return retval;
  }

  return cudaErrorInvalidValue;
}

//---------------------------------------------------------------------
// CUDA Nested Parallelism Test Kernel
//---------------------------------------------------------------------

#if TEST_CDP == 1

/**
 * Simple wrapper kernel to invoke DeviceRadixSort
 */
template <int IsDescending,
          int CubBackend,
          typename KeyT,
          typename ValueT,
          typename BeginOffsetIteratorT,
          typename EndOffsetIteratorT,
          typename NumItemsT>
__global__ void CDPDispatchKernel(Int2Type<IsDescending> is_descending,
                                  Int2Type<CubBackend>   cub_backend,
                                  int                   *d_selector,
                                  size_t                *d_temp_storage_bytes,
                                  cudaError_t           *d_cdp_error,
                                  void                  *d_temp_storage,
                                  size_t                 temp_storage_bytes,
                                  DoubleBuffer<KeyT>     d_keys,
                                  DoubleBuffer<ValueT>   d_values,
                                  NumItemsT              num_items,
                                  int                    num_segments,
                                  BeginOffsetIteratorT d_segment_begin_offsets,
                                  EndOffsetIteratorT   d_segment_end_offsets,
                                  int                  begin_bit,
                                  int                  end_bit)
{
  *d_cdp_error = Dispatch(is_descending,
                          cub_backend,
                          d_selector,
                          d_temp_storage_bytes,
                          d_cdp_error,
                          d_temp_storage,
                          temp_storage_bytes,
                          d_keys,
                          d_values,
                          num_items,
                          num_segments,
                          d_segment_begin_offsets,
                          d_segment_end_offsets,
                          begin_bit,
                          end_bit);

  *d_temp_storage_bytes = temp_storage_bytes;
  *d_selector           = d_keys.selector;
}

/**
 * Launch kernel and dispatch on device. Should only be called from host code.
 * The CubBackend should be one of the non-CDP CUB backends to invoke from the
 * device.
 */
template <int IsDescending,
          int CubBackend,
          typename KeyT,
          typename ValueT,
          typename BeginOffsetIteratorT,
          typename EndOffsetIteratorT,
          typename NumItemsT>
cudaError_t LaunchCDPKernel(Int2Type<IsDescending> is_descending,
                            Int2Type<CubBackend>   cub_backend,
                            int                   *d_selector,
                            size_t                *d_temp_storage_bytes,
                            cudaError_t           *d_cdp_error,

                            void                 *d_temp_storage,
                            size_t               &temp_storage_bytes,
                            DoubleBuffer<KeyT>   &d_keys,
                            DoubleBuffer<ValueT> &d_values,
                            NumItemsT             num_items,
                            int                   num_segments,
                            BeginOffsetIteratorT  d_segment_begin_offsets,
                            EndOffsetIteratorT    d_segment_end_offsets,
                            int                   begin_bit,
                            int                   end_bit)
{
  // Invoke kernel to invoke device-side dispatch:
  cudaError_t retval =
    thrust::cuda_cub::launcher::triple_chevron(1, 1, 0, 0)
      .doit(CDPDispatchKernel<IsDescending,
                              CubBackend,
                              KeyT,
                              ValueT,
                              BeginOffsetIteratorT,
                              EndOffsetIteratorT,
                              NumItemsT>,
            is_descending,
            cub_backend,
            d_selector,
            d_temp_storage_bytes,
            d_cdp_error,
            d_temp_storage,
            temp_storage_bytes,
            d_keys,
            d_values,
            num_items,
            num_segments,
            d_segment_begin_offsets,
            d_segment_end_offsets,
            begin_bit,
            end_bit);
  CubDebugExit(retval);
  CubDebugExit(cub::detail::device_synchronize());

  // Copy out selector
  CubDebugExit(cudaMemcpy(&d_keys.selector,
                          d_selector,
                          sizeof(int) * 1,
                          cudaMemcpyDeviceToHost));
  d_values.selector = d_keys.selector;

  // Copy out temp_storage_bytes
  CubDebugExit(cudaMemcpy(&temp_storage_bytes,
                          d_temp_storage_bytes,
                          sizeof(size_t) * 1,
                          cudaMemcpyDeviceToHost));

  // Copy out error
  CubDebugExit(cudaMemcpy(&retval,
                          d_cdp_error,
                          sizeof(cudaError_t) * 1,
                          cudaMemcpyDeviceToHost));

  return retval;
}

// Specializations of Dispatch that translate the CDP backend to the appropriate
// CUB backend, and uses the CUB backend to launch the CDP kernel.
#define DEFINE_CDP_DISPATCHER(CdpBackend, CubBackend)                          \
  template <int IsDescending,                                                  \
            typename KeyT,                                                     \
            typename ValueT,                                                   \
            typename BeginOffsetIteratorT,                                     \
            typename EndOffsetIteratorT,                                       \
            typename NumItemsT>                                                \
  cudaError_t Dispatch(Int2Type<IsDescending> is_descending,                   \
                       Int2Type<CdpBackend> /*dispatch_to*/,                   \
                       int         *d_selector,                                \
                       size_t      *d_temp_storage_bytes,                      \
                       cudaError_t *d_cdp_error,                               \
                                                                               \
                       void                 *d_temp_storage,                   \
                       size_t               &temp_storage_bytes,               \
                       DoubleBuffer<KeyT>   &d_keys,                           \
                       DoubleBuffer<ValueT> &d_values,                         \
                       NumItemsT             num_items,                        \
                       int                   num_segments,                     \
                       BeginOffsetIteratorT  d_segment_begin_offsets,          \
                       EndOffsetIteratorT    d_segment_end_offsets,            \
                       int                   begin_bit,                        \
                       int                   end_bit)                          \
  {                                                                            \
    Int2Type<CubBackend> cub_backend{};                                        \
    return LaunchCDPKernel(is_descending,                                      \
                           cub_backend,                                        \
                           d_selector,                                         \
                           d_temp_storage_bytes,                               \
                           d_cdp_error,                                        \
                           d_temp_storage,                                     \
                           temp_storage_bytes,                                 \
                           d_keys,                                             \
                           d_values,                                           \
                           num_items,                                          \
                           num_segments,                                       \
                           d_segment_begin_offsets,                            \
                           d_segment_end_offsets,                              \
                           begin_bit,                                          \
                           end_bit);                                           \
  }

DEFINE_CDP_DISPATCHER(CDP, CUB)
DEFINE_CDP_DISPATCHER(CDP_NO_OVERWRITE, CUB_NO_OVERWRITE)
DEFINE_CDP_DISPATCHER(CDP_SEGMENTED, CUB_SEGMENTED)
DEFINE_CDP_DISPATCHER(CDP_SEGMENTED_NO_OVERWRITE, CUB_SEGMENTED_NO_OVERWRITE)

#undef DEFINE_CDP_DISPATCHER

#endif // TEST_CDP

//---------------------------------------------------------------------
// Problem generation
//---------------------------------------------------------------------


/**
 * Simple key-value pairing
 */
template <
    typename KeyT,
    typename ValueT>
struct Pair
{
    KeyT     key;
    ValueT   value;

    bool operator<(const Pair &b) const
    {
        return (key < b.key);
    }
};


/**
 * Simple key-value pairing (specialized for bool types)
 */
template <typename ValueT>
struct Pair<bool, ValueT>
{
    bool     key;
    ValueT   value;

    bool operator<(const Pair &b) const
    {
        return (!key && b.key);
    }
};


/**
 * Initialize key data
 */
template <typename KeyT, typename NumItemsT>
void InitializeKeyBits(
    GenMode         gen_mode,
    KeyT            *h_keys,
    NumItemsT       num_items,
    int             /*entropy_reduction*/)
{
    for (NumItemsT i = 0; i < num_items; ++i)
        InitValue(gen_mode, h_keys[i], i);
}

template <typename KeyT,
          typename UnsignedBits = typename cub::Traits<KeyT>::UnsignedBits>
UnsignedBits KeyBits(KeyT key)
{
    UnsignedBits bits;
    memcpy(&bits, &key, sizeof(KeyT));
    return bits;
}

/** Initialize the reference array monotonically. */
template <typename KeyT, typename NumItemsT>
void InitializeKeysSorted(
    KeyT            *h_keys,
    NumItemsT       num_items)
{
    using TraitsT = cub::Traits<KeyT>;
    using UnsignedBits = typename TraitsT::UnsignedBits;

    // Numbers to generate random runs.
    UnsignedBits max_inc = 1 << (sizeof(UnsignedBits) < 4 ? 3 :
                                 (sizeof(UnsignedBits) < 8 ? 14 : 24));
    UnsignedBits min_bits = TraitsT::TwiddleIn(KeyBits(TraitsT::Lowest()));
    UnsignedBits max_bits = TraitsT::TwiddleIn(KeyBits(TraitsT::Max()));
    NumItemsT max_run = std::max(
        NumItemsT(double(num_items) * (max_inc + 1) / max_bits),
        NumItemsT(1 << 14));

    UnsignedBits *h_key_bits = reinterpret_cast<UnsignedBits*>(h_keys);
    NumItemsT i = 0;
    // Start with the minimum twiddled key.
    UnsignedBits twiddled_key = min_bits;
    while (i < num_items)
    {
        // Generate random increment (avoid overflow).
        UnsignedBits inc_bits = 0;
        RandomBits(inc_bits);
        // twiddled_key < max_bits at this point.
        UnsignedBits inc = static_cast<UnsignedBits>(std::min(1 + inc_bits % max_inc, max_bits - twiddled_key));
        twiddled_key += inc;

        // Generate random run length (ensure there are enough values to fill the rest).
        NumItemsT run_bits = 0;
        RandomBits(run_bits);
        NumItemsT run_length = std::min(1 + run_bits % max_run, num_items - i);
        if (twiddled_key == max_bits) run_length = num_items - i;
        NumItemsT run_end = i + run_length;

        // Fill the array.
        UnsignedBits key = TraitsT::TwiddleOut(twiddled_key);
        // Avoid -0.0 for floating-point keys.
        UnsignedBits negative_zero = UnsignedBits(1) << UnsignedBits(sizeof(UnsignedBits) * 8 - 1);
        if (TraitsT::CATEGORY == cub::FLOATING_POINT && key == negative_zero)
        {
            key = 0;
        }

        for (; i < run_end; ++i)
        {
            h_key_bits[i] = key;
        }
    }
}


/**
 * Initialize solution
 */
template <bool IS_DESCENDING, bool WANT_RANKS, typename KeyT, typename NumItemsT>
void InitializeSolution(
    KeyT       *h_keys,
    NumItemsT  num_items,
    int        num_segments,
    bool       pre_sorted,
    NumItemsT  *h_segment_offsets,
    int        begin_bit,
    int        end_bit,
    NumItemsT  *&h_reference_ranks,
    KeyT       *&h_reference_keys)
{
    if (num_items == 0)
    {
        h_reference_ranks = nullptr;
        h_reference_keys = nullptr;
        return;
    }

    if (pre_sorted)
    {
        printf("Shuffling reference solution on CPU\n");
        // Note: begin_bit and end_bit are ignored here, and assumed to have the
        // default values (begin_bit == 0, end_bit == 8 * sizeof(KeyT)).
        // Otherwise, pre-sorting won't work, as it doesn't necessarily
        // correspond to the order of keys sorted by a subrange of bits.
        // num_segments is also ignored as assumed to be 1, as pre-sorted tests
        // are currently not supported for multiple segments.
        //
        // Pre-sorted tests with non-default begin_bit, end_bit or num_segments
        // != 1 are skipped in TestBits() and TestSegments(), respectively.
        AssertEquals(begin_bit, 0);
        AssertEquals(end_bit, static_cast<int>(8 * sizeof(KeyT)));
        AssertEquals(num_segments, 1);

        // Copy to the reference solution.
        h_reference_keys = new KeyT[num_items];
        if (IS_DESCENDING)
        {
            // Copy in reverse.
            for (NumItemsT i = 0; i < num_items; ++i)
            {
                h_reference_keys[i] = h_keys[num_items - 1 - i];
            }
            // Copy back.
            memcpy(h_keys, h_reference_keys, num_items * sizeof(KeyT));
        }
        else
        {
            memcpy(h_reference_keys, h_keys, num_items * sizeof(KeyT));
        }

        // Summarize the pre-sorted array (element, 1st position, count).
        struct Element
        {
            KeyT key;
            NumItemsT num;
            NumItemsT index;
        };

        std::vector<Element> summary;
        KeyT cur_key = h_reference_keys[0];
        summary.push_back(Element{cur_key, 1, 0});
        for (NumItemsT i = 1; i < num_items; ++i)
        {
            KeyT key = h_reference_keys[i];
            if (key == cur_key)
            {
                // Same key.
                summary.back().num++;
                continue;
            }

            // Different key.
            cur_key = key;
            summary.push_back(Element{cur_key, 1, i});
        }

        // Generate a random permutation from the summary. Such a complicated
        // approach is used to permute the array and compute ranks in a
        // cache-friendly way and in a short time.
        if (WANT_RANKS)
        {
            h_reference_ranks = new NumItemsT[num_items];
        }
        NumItemsT max_run = 32;
        NumItemsT run = 0;
        NumItemsT i = 0;
        while (summary.size() > 0)
        {
            // Pick up a random element and a run.
            NumItemsT bits = 0;
            RandomBits(bits);
            NumItemsT summary_id = bits % summary.size();
            Element& element = summary[summary_id];
            run = std::min(1 + bits % (max_run - 1), element.num);
            for (NumItemsT j = 0; j < run; ++j)
            {
                h_keys[i + j] = element.key;
                if (WANT_RANKS)
                {
                    h_reference_ranks[element.index + j] = i + j;
                }
            }
            i += run;
            element.index += run;
            element.num -= run;
            if (element.num == 0)
            {
                // Remove the empty entry.
                std::swap(summary[summary_id], summary.back());
                summary.pop_back();
            }
        }
        printf(" Done.\n");
    }
    else
    {
        typedef Pair<KeyT, NumItemsT> PairT;

        PairT *h_pairs = new PairT[num_items];

        int num_bits = end_bit - begin_bit;
        for (NumItemsT i = 0; i < num_items; ++i)
        {

            // Mask off unwanted portions
            if (num_bits < static_cast<int>(sizeof(KeyT) * 8))
            {
                using UnsignedBits = typename cub::Traits<KeyT>::UnsignedBits;

                UnsignedBits base = 0;
                memcpy(&base, &h_keys[i], sizeof(KeyT));
                base &= ((UnsignedBits{1} << num_bits) - 1) << begin_bit;
                memcpy(&h_pairs[i].key, &base, sizeof(KeyT));
            }
            else
            {
                h_pairs[i].key = h_keys[i];
            }

            h_pairs[i].value = i;
        }

        printf("\nSorting reference solution on CPU "
               "(%zd items, %d segments, %zd items/seg)...",
               static_cast<std::size_t>(num_items),
               num_segments,
               static_cast<std::size_t>(num_items / num_segments));
        fflush(stdout);

        for (int i = 0; i < num_segments; ++i)
        {
            if (IS_DESCENDING) std::reverse(h_pairs + h_segment_offsets[i], h_pairs + h_segment_offsets[i + 1]);
            std::stable_sort(               h_pairs + h_segment_offsets[i], h_pairs + h_segment_offsets[i + 1]);
            if (IS_DESCENDING) std::reverse(h_pairs + h_segment_offsets[i], h_pairs + h_segment_offsets[i + 1]);
        }

        printf(" Done.\n"); fflush(stdout);

        if (WANT_RANKS)
        {
            h_reference_ranks  = new NumItemsT[num_items];
        }
        h_reference_keys   = new KeyT[num_items];

        for (NumItemsT i = 0; i < num_items; ++i)
        {
            if (WANT_RANKS)
            {
                h_reference_ranks[i]    = h_pairs[i].value;
            }
            h_reference_keys[i]     = h_keys[h_pairs[i].value];
        }

        if (h_pairs) delete[] h_pairs;
    }
}

template <bool IS_DESCENDING, typename KeyT, typename NumItemsT>
void ResetKeys(KeyT *h_keys, NumItemsT num_items, bool pre_sorted, KeyT *reference_keys)
{
    if (!pre_sorted) return;

    // Copy the reference keys back.
    if (IS_DESCENDING)
    {
        // Keys need to be copied in reverse.
        for (NumItemsT i = 0; i < num_items; ++i)
        {
            h_keys[i] = reference_keys[num_items - 1 - i];
        }
    }
    else
    {
        memcpy(h_keys, reference_keys, num_items * sizeof(KeyT));
    }
}


//---------------------------------------------------------------------
// Test generation
//---------------------------------------------------------------------

template <typename T>
struct UnwrapHalfAndBfloat16 {
    using Type = T;
};

#if !_NVHPC_CUDA
template <>
struct UnwrapHalfAndBfloat16<half_t> {
    using Type = __half;
};
#endif

#if !_NVHPC_CUDA
template <>
struct UnwrapHalfAndBfloat16<bfloat16_t> {
    using Type = __nv_bfloat16;
};
#endif

template <class T, class NumItemsT>
int compare_device_arrays(T* host_reference, T* d_tmp_buffer, T* d_data, NumItemsT num_items)
{
    CubDebugExit(cudaMemcpy(d_tmp_buffer, host_reference, sizeof(T) * num_items, cudaMemcpyHostToDevice));

    auto d_reference_begin = d_tmp_buffer;
    auto d_reference_end = d_tmp_buffer + num_items;
    auto err = thrust::mismatch(thrust::device, d_reference_begin, d_reference_end, d_data);

    if (err.first != d_reference_end)
    {
        const auto index = thrust::distance(d_reference_begin, err.first);
        return CompareDeviceResults(host_reference + index, d_data + index, 1, true, g_verbose);
    }

    return 0;
}

template <class NumItemsT>
int compare_device_arrays(
    CUB_NS_QUALIFIER::NullType */* h_reference */,
    CUB_NS_QUALIFIER::NullType */* d_tmp_buffer */,
    CUB_NS_QUALIFIER::NullType */* d_data */,
    NumItemsT /* num_items */)
{
    return 0;
}

/**
 * Test DeviceRadixSort
 */
template <
    Backend     BACKEND,
    bool        IS_DESCENDING,
    typename    KeyT,
    typename    ValueT,
    typename    BeginOffsetIteratorT,
    typename    EndOffsetIteratorT,
    typename    NumItemsT>
void Test(
    KeyT                 *h_keys,
    ValueT               *h_values,
    NumItemsT            num_items,
    int                  num_segments,
    BeginOffsetIteratorT d_segment_begin_offsets,
    EndOffsetIteratorT   d_segment_end_offsets,
    int                  begin_bit,
    int                  end_bit,
    KeyT                 *h_reference_keys,
    ValueT               *h_reference_values)
{
    // Key alias type
    using KeyAliasT = typename UnwrapHalfAndBfloat16<KeyT>::Type;

    const bool KEYS_ONLY = std::is_same<ValueT, NullType>::value;

    printf("%s %s cub::DeviceRadixSort %zd items, %d segments, "
           "%d-byte keys (%s) %d-byte values (%s), %d-byte num_items (%s), "
           "descending %d, begin_bit %d, end_bit %d\n",
           BackendToString(BACKEND),
           (KEYS_ONLY) ? "keys-only" : "key-value",
           static_cast<std::size_t>(num_items),
           num_segments,
           static_cast<int>(sizeof(KeyT)),
           typeid(KeyT).name(),
           (KEYS_ONLY) ? 0 : static_cast<int>(sizeof(ValueT)),
           typeid(ValueT).name(),
           static_cast<int>(sizeof(NumItemsT)),
           typeid(NumItemsT).name(),
           IS_DESCENDING,
           begin_bit,
           end_bit);

    if (g_verbose)
    {
        printf("Input keys:\n");
        DisplayResults(h_keys, num_items);
        printf("\n\n");
    }

    // Allocate device arrays
    DoubleBuffer<KeyAliasT> d_keys;
    DoubleBuffer<ValueT>    d_values;
    int                     *d_selector;
    size_t                  *d_temp_storage_bytes;
    cudaError_t             *d_cdp_error;
    CubDebugExit(g_allocator.DeviceAllocate((void**)&d_keys.d_buffers[0], sizeof(KeyT) * num_items));
    CubDebugExit(g_allocator.DeviceAllocate((void**)&d_keys.d_buffers[1], sizeof(KeyT) * num_items));
    CubDebugExit(g_allocator.DeviceAllocate((void**)&d_selector, sizeof(int) * 1));
    CubDebugExit(g_allocator.DeviceAllocate((void**)&d_temp_storage_bytes, sizeof(size_t) * 1));
    CubDebugExit(g_allocator.DeviceAllocate((void**)&d_cdp_error, sizeof(cudaError_t) * 1));
    if (!KEYS_ONLY)
    {
        CubDebugExit(g_allocator.DeviceAllocate((void**)&d_values.d_buffers[0], sizeof(ValueT) * num_items));
        CubDebugExit(g_allocator.DeviceAllocate((void**)&d_values.d_buffers[1], sizeof(ValueT) * num_items));
    }

    // Allocate temporary storage (and make it un-aligned)
    size_t  temp_storage_bytes  = 0;
    void    *d_temp_storage     = NULL;
    CubDebugExit(Dispatch(
        Int2Type<IS_DESCENDING>(), Int2Type<BACKEND>(), d_selector, d_temp_storage_bytes, d_cdp_error,
        d_temp_storage, temp_storage_bytes, d_keys, d_values,
        num_items, num_segments, d_segment_begin_offsets, d_segment_end_offsets,
        begin_bit, end_bit));

    CubDebugExit(g_allocator.DeviceAllocate(&d_temp_storage, temp_storage_bytes + 1));
    void* mis_aligned_temp = static_cast<char*>(d_temp_storage) + 1;

    // Initialize/clear device arrays
    d_keys.selector = 0;
    CubDebugExit(cudaMemcpy(d_keys.d_buffers[0], h_keys, sizeof(KeyT) * num_items, cudaMemcpyHostToDevice));
    CubDebugExit(cudaMemset(d_keys.d_buffers[1], 0, sizeof(KeyT) * num_items));
    if (!KEYS_ONLY)
    {
        d_values.selector = 0;
        CubDebugExit(cudaMemcpy(d_values.d_buffers[0], h_values, sizeof(ValueT) * num_items, cudaMemcpyHostToDevice));
        CubDebugExit(cudaMemset(d_values.d_buffers[1], 0, sizeof(ValueT) * num_items));
    }

    // Run warmup/correctness iteration
    CubDebugExit(Dispatch(
        Int2Type<IS_DESCENDING>(), Int2Type<BACKEND>(), d_selector, d_temp_storage_bytes, d_cdp_error,
        mis_aligned_temp, temp_storage_bytes, d_keys, d_values,
        num_items, num_segments, d_segment_begin_offsets, d_segment_end_offsets,
        begin_bit, end_bit));

    // Flush any stdout/stderr
    fflush(stdout);
    fflush(stderr);

    // Check for correctness (and display results, if specified)
    printf("Warmup done.  Checking results:\n"); fflush(stdout);

    int compare = 0;

    // If in/out API is used, we are not allowed to overwrite the input. 
    // Let's check that the input buffer is not overwritten by the algorithm.
    if (BACKEND == CUB_NO_OVERWRITE)
    {
        KeyT *d_input_keys = reinterpret_cast<KeyT*>(d_keys.d_buffers[0]);

        if (temp_storage_bytes < sizeof(KeyT) * num_items)
        {
            // For small input sizes, temporary storage is not large enough to fit keys.
            compare = CompareDeviceResults(h_keys, d_input_keys, num_items, true, g_verbose);
        }
        else 
        {
            // If overwrite is not allowed, temporary storage is large enough to fit keys.
            KeyT* temp_keys = reinterpret_cast<KeyT*>(d_temp_storage);

            compare = compare_device_arrays(h_keys, temp_keys, d_input_keys, num_items);
            printf("\t Compare input keys: %s ", compare ? "FAIL" : "PASS"); fflush(stdout);
        }
    }

    // After the previous check is done, we can safely reuse alternative buffer to store 
    // the reference results and compare current output.
    compare |= compare_device_arrays(h_reference_keys,
                                     reinterpret_cast<KeyT *>(d_keys.Alternate()),
                                     reinterpret_cast<KeyT *>(d_keys.Current()),
                                     num_items);

    printf("\t Compare keys (selector %d): %s ", d_keys.selector, compare ? "FAIL" : "PASS"); fflush(stdout);

    if (!KEYS_ONLY)
    {
        int values_compare = compare_device_arrays(h_reference_values,
                                                   d_values.Alternate(),
                                                   d_values.Current(),
                                                   num_items);

        compare |= values_compare;
        printf("\t Compare values (selector %d): %s ", d_values.selector, values_compare ? "FAIL" : "PASS"); fflush(stdout);
    }

    // Performance
    if (g_timing_iterations)
        printf("\nPerforming timing iterations:\n"); fflush(stdout);

    GpuTimer gpu_timer;
    float elapsed_millis = 0.0f;
    for (int i = 0; i < g_timing_iterations; ++i)
    {
        // Initialize/clear device arrays
        CubDebugExit(cudaMemcpy(d_keys.d_buffers[d_keys.selector], h_keys, sizeof(KeyT) * num_items, cudaMemcpyHostToDevice));
        CubDebugExit(cudaMemset(d_keys.d_buffers[d_keys.selector ^ 1], 0, sizeof(KeyT) * num_items));
        if (!KEYS_ONLY)
        {
            CubDebugExit(cudaMemcpy(d_values.d_buffers[d_values.selector], h_values, sizeof(ValueT) * num_items, cudaMemcpyHostToDevice));
            CubDebugExit(cudaMemset(d_values.d_buffers[d_values.selector ^ 1], 0, sizeof(ValueT) * num_items));
        }

        gpu_timer.Start();
        CubDebugExit(Dispatch(
            Int2Type<IS_DESCENDING>(), Int2Type<BACKEND>(), d_selector, d_temp_storage_bytes, d_cdp_error,
            mis_aligned_temp, temp_storage_bytes, d_keys, d_values,
            num_items, num_segments, d_segment_begin_offsets, d_segment_end_offsets,
            begin_bit, end_bit));
        gpu_timer.Stop();
        elapsed_millis += gpu_timer.ElapsedMillis();
    }

    // Display performance
    if (g_timing_iterations > 0)
    {
        float avg_millis = elapsed_millis / g_timing_iterations;
        float giga_rate = float(num_items) / avg_millis / 1000.0f / 1000.0f;
        float giga_bandwidth = (KEYS_ONLY) ?
            giga_rate * sizeof(KeyT) * 2 :
            giga_rate * (sizeof(KeyT) + sizeof(ValueT)) * 2;
        printf("\n%.3f elapsed ms, %.3f avg ms, %.3f billion items/s, %.3f logical GB/s", elapsed_millis, avg_millis, giga_rate, giga_bandwidth);
    }

    printf("\n\n");

    // Cleanup
    if (d_keys.d_buffers[0]) CubDebugExit(g_allocator.DeviceFree(d_keys.d_buffers[0]));
    if (d_keys.d_buffers[1]) CubDebugExit(g_allocator.DeviceFree(d_keys.d_buffers[1]));
    if (d_values.d_buffers[0]) CubDebugExit(g_allocator.DeviceFree(d_values.d_buffers[0]));
    if (d_values.d_buffers[1]) CubDebugExit(g_allocator.DeviceFree(d_values.d_buffers[1]));
    if (d_temp_storage) CubDebugExit(g_allocator.DeviceFree(d_temp_storage));
    if (d_cdp_error) CubDebugExit(g_allocator.DeviceFree(d_cdp_error));
    if (d_selector) CubDebugExit(g_allocator.DeviceFree(d_selector));
    if (d_temp_storage_bytes) CubDebugExit(g_allocator.DeviceFree(d_temp_storage_bytes));

    // Correctness asserts
    AssertEquals(0, compare);
}

// Returns whether there is enough memory for the test.
template <typename KeyT, typename ValueT>
bool HasEnoughMemory(std::size_t num_items, bool overwrite)
{
    std::size_t total_mem = TotalGlobalMem();
    std::size_t value_size = std::is_same<ValueT, NullType>::value
                           ? 0
                           : sizeof(ValueT);
    // A conservative estimate of the amount of memory required.
    double factor = overwrite ? 2.25 : 3.25;
    std::size_t test_mem = static_cast<std::size_t>
      (num_items * (sizeof(KeyT) + value_size) * factor);
    return test_mem < total_mem;
}


/**
 * Test backend
 */
template <bool IS_DESCENDING,
          typename KeyT,
          typename ValueT,
          typename BeginOffsetIteratorT,
          typename EndOffsetIteratorT,
          typename NumItemsT>
void TestBackend(KeyT                *h_keys,
                 NumItemsT            num_items,
                 int                  num_segments,
                 BeginOffsetIteratorT d_segment_begin_offsets,
                 EndOffsetIteratorT   d_segment_end_offsets,
                 int                  begin_bit,
                 int                  end_bit,
                 KeyT                *h_reference_keys,
                 NumItemsT           *h_reference_ranks)
{
#if TEST_CDP == 0
  constexpr auto NonSegmentedOverwrite   = CUB;
  constexpr auto NonSegmentedNoOverwrite = CUB_NO_OVERWRITE;
  constexpr auto SegmentedOverwrite      = CUB_SEGMENTED;
  constexpr auto SegmentedNoOverwrite    = CUB_SEGMENTED_NO_OVERWRITE;
#else  // TEST_CDP
  constexpr auto NonSegmentedOverwrite   = CDP;
  constexpr auto NonSegmentedNoOverwrite = CDP_NO_OVERWRITE;
  constexpr auto SegmentedOverwrite      = CDP_SEGMENTED;
  constexpr auto SegmentedNoOverwrite    = CDP_SEGMENTED_NO_OVERWRITE;
#endif // TEST_CDP

  const bool KEYS_ONLY = std::is_same<ValueT, NullType>::value;

  // A conservative check assuming overwrite is allowed.
  if (!HasEnoughMemory<KeyT, ValueT>(static_cast<std::size_t>(num_items), true))
  {
    printf("Skipping the test due to insufficient device memory\n");
    return;
  }

  std::unique_ptr<ValueT[]> h_value_data{};

  ValueT *h_values           = nullptr;
  ValueT *h_reference_values = nullptr;

  if (!KEYS_ONLY)
  {
    h_value_data.reset(new ValueT[2 * static_cast<std::size_t>(num_items)]);
    h_values           = h_value_data.get();
    h_reference_values = h_value_data.get() + num_items;

    for (NumItemsT i = 0; i < num_items; ++i)
    {
      InitValue(INTEGER_SEED, h_values[i], i);
      InitValue(INTEGER_SEED, h_reference_values[i], h_reference_ranks[i]);
    }
  }

  // Skip segmented sort if num_items isn't int.
  // TODO(64bit-seg-sort): re-enable these tests once num_items is templated for
  // segmented sort.
  if (std::is_same<NumItemsT, int>::value)
  {
    printf("Testing segmented sort with overwrite\n");
    Test<SegmentedOverwrite, IS_DESCENDING>(h_keys,
                                            h_values,
                                            num_items,
                                            num_segments,
                                            d_segment_begin_offsets,
                                            d_segment_end_offsets,
                                            begin_bit,
                                            end_bit,
                                            h_reference_keys,
                                            h_reference_values);
    printf("Testing segmented sort with no overwrite\n");
    Test<SegmentedNoOverwrite, IS_DESCENDING>(h_keys,
                                              h_values,
                                              num_items,
                                              num_segments,
                                              d_segment_begin_offsets,
                                              d_segment_end_offsets,
                                              begin_bit,
                                              end_bit,
                                              h_reference_keys,
                                              h_reference_values);
  }
  else
  {
    printf("Skipping segmented sort tests (NumItemsT != int)\n");
  }

  if (num_segments == 1)
  {
    printf("Testing non-segmented sort with overwrite\n");
    Test<NonSegmentedOverwrite, IS_DESCENDING>(h_keys,
                                               h_values,
                                               num_items,
                                               num_segments,
                                               d_segment_begin_offsets,
                                               d_segment_end_offsets,
                                               begin_bit,
                                               end_bit,
                                               h_reference_keys,
                                               h_reference_values);
    if (HasEnoughMemory<KeyT, ValueT>(static_cast<std::size_t>(num_items),
                                      false))
    {
      printf("Testing non-segmented sort with no overwrite\n");
      Test<NonSegmentedNoOverwrite, IS_DESCENDING>(h_keys,
                                                   h_values,
                                                   num_items,
                                                   num_segments,
                                                   d_segment_begin_offsets,
                                                   d_segment_end_offsets,
                                                   begin_bit,
                                                   end_bit,
                                                   h_reference_keys,
                                                   h_reference_values);
    }
    else
    {
      printf("Skipping no-overwrite tests with %zd items due to "
             "insufficient memory\n",
             static_cast<std::size_t>(num_items));
    }
  }
}


// Smallest value type for TEST_VALUE_TYPE.
// Unless TEST_VALUE_TYPE == 3, this is the only value type tested.
#if TEST_VALUE_TYPE == 0
// Test keys-only
using SmallestValueT = NullType;
#elif TEST_VALUE_TYPE == 1
// Test with 8b value
using SmallestValueT = unsigned char;
#elif TEST_VALUE_TYPE == 2
// Test with 32b value
using SmallestValueT = unsigned int;
// Test with 64b value
#elif TEST_VALUE_TYPE == 3
using SmallestValueT = unsigned long long;
#endif


/**
 * Test value type
 */
template <bool IS_DESCENDING, typename KeyT, typename BeginOffsetIteratorT, typename EndOffsetIteratorT, typename NumItemsT>
void TestValueTypes(
    KeyT                 *h_keys,
    NumItemsT            num_items,
    int                  num_segments,
    bool                 pre_sorted,
    NumItemsT            *h_segment_offsets,
    BeginOffsetIteratorT d_segment_begin_offsets,
    EndOffsetIteratorT   d_segment_end_offsets,
    int                  begin_bit,
    int                  end_bit)
{
    // Initialize the solution
    NumItemsT *h_reference_ranks = NULL;
    KeyT *h_reference_keys = NULL;
    // If TEST_VALUE_TYPE == 0, no values are sorted, only keys.
    // Since ranks are only necessary when checking for values,
    // they are not computed in this case.
    InitializeSolution<IS_DESCENDING, TEST_VALUE_TYPE != 0>(h_keys, num_items, num_segments, pre_sorted, h_segment_offsets, begin_bit, end_bit, h_reference_ranks, h_reference_keys);

    TestBackend<IS_DESCENDING, KeyT, SmallestValueT>          (h_keys, num_items, num_segments, d_segment_begin_offsets, d_segment_end_offsets, begin_bit, end_bit, h_reference_keys, h_reference_ranks);

#if TEST_VALUE_TYPE == 3
    // Test with non-trivially-constructable value
    // These are cheap to build, so lump them in with the 64b value tests.
    TestBackend<IS_DESCENDING, KeyT, TestBar>           (h_keys, num_items, num_segments, d_segment_begin_offsets, d_segment_end_offsets, begin_bit, end_bit, h_reference_keys, h_reference_ranks);
#endif

    // Cleanup
    ResetKeys<IS_DESCENDING>(h_keys, num_items, pre_sorted, h_reference_keys);
    if (h_reference_ranks) delete[] h_reference_ranks;
    if (h_reference_keys) delete[] h_reference_keys;
}



/**
 * Test ascending/descending
 */
template <typename KeyT, typename BeginOffsetIteratorT, typename EndOffsetIteratorT,
          typename NumItemsT>
void TestDirection(
    KeyT                 *h_keys,
    NumItemsT            num_items,
    int                  num_segments,
    bool                 pre_sorted,
    NumItemsT            *h_segment_offsets,
    BeginOffsetIteratorT d_segment_begin_offsets,
    EndOffsetIteratorT   d_segment_end_offsets,
    int                  begin_bit,
    int                  end_bit)
{
    TestValueTypes<true>(h_keys, num_items, num_segments, pre_sorted, h_segment_offsets, d_segment_begin_offsets, d_segment_end_offsets, begin_bit, end_bit);
    TestValueTypes<false>(h_keys, num_items, num_segments, pre_sorted, h_segment_offsets, d_segment_begin_offsets, d_segment_end_offsets, begin_bit, end_bit);
}


/**
 * Test different bit ranges
 */
template <typename KeyT, typename BeginOffsetIteratorT, typename EndOffsetIteratorT,
          typename NumItemsT>
void TestBits(
    KeyT                 *h_keys,
    NumItemsT            num_items,
    int                  num_segments,
    bool                 pre_sorted,
    NumItemsT            *h_segment_offsets,
    BeginOffsetIteratorT d_segment_begin_offsets,
    EndOffsetIteratorT   d_segment_end_offsets)
{
    // Don't test partial-word sorting for boolean, fp, or signed types (the bit-flipping techniques get in the way) or pre-sorted keys
    if ((Traits<KeyT>::CATEGORY == UNSIGNED_INTEGER)
        && (!std::is_same<KeyT, bool>::value)
        && !pre_sorted)
    {
        // Partial bits
        int begin_bit = 1;
        int end_bit = (sizeof(KeyT) * 8) - 1;
        printf("Testing key bits [%d,%d)\n", begin_bit, end_bit); fflush(stdout);
        TestDirection(h_keys, num_items, num_segments, pre_sorted, h_segment_offsets, d_segment_begin_offsets, d_segment_end_offsets, begin_bit, end_bit);

        // Equal bits
        begin_bit = end_bit = 0;
        printf("Testing key bits [%d,%d)\n", begin_bit, end_bit); fflush(stdout);
        TestDirection(h_keys, num_items, num_segments, pre_sorted, h_segment_offsets, d_segment_begin_offsets, d_segment_end_offsets, begin_bit, end_bit);

        // Across subword boundaries
        int mid_bit = sizeof(KeyT) * 4;
        printf("Testing key bits [%d,%d)\n", mid_bit - 1, mid_bit + 1); fflush(stdout);
        TestDirection(h_keys, num_items, num_segments, pre_sorted, h_segment_offsets, d_segment_begin_offsets, d_segment_end_offsets, mid_bit - 1, mid_bit + 1);
    }

    printf("Testing key bits [%d,%d)\n", 0, int(sizeof(KeyT)) * 8); fflush(stdout);
    TestDirection(h_keys, num_items, num_segments, pre_sorted, h_segment_offsets, d_segment_begin_offsets, d_segment_end_offsets, 0, sizeof(KeyT) * 8);
}


template<typename OffsetT>
struct TransformFunctor1
{
    __host__ __device__ __forceinline__ OffsetT operator()(OffsetT offset) const
    {
        return offset;
    }
};

template<typename OffsetT>
struct TransformFunctor2
{
    __host__ __device__ __forceinline__ OffsetT operator()(OffsetT offset) const
    {
        return offset;
    }
};


/**
* Test different segment iterators
*/
template <typename KeyT, typename NumItemsT>
void TestSegmentIterators(
    KeyT           *h_keys,
    NumItemsT      num_items,
    int            num_segments,
    bool           pre_sorted,
    NumItemsT     *h_segment_offsets,
    NumItemsT     *d_segment_offsets)
{
    InitializeSegments(num_items, num_segments, h_segment_offsets);
    CubDebugExit(cudaMemcpy(d_segment_offsets, h_segment_offsets, sizeof(NumItemsT) * (num_segments + 1), cudaMemcpyHostToDevice));

    // Test with segment pointer.
    // This is also used to test non-segmented sort.
    TestBits(h_keys, num_items, num_segments, pre_sorted, h_segment_offsets, d_segment_offsets, d_segment_offsets + 1);

    if (num_segments > 1)
    {
        // Test with transform iterators of different types
        typedef TransformFunctor1<NumItemsT> TransformFunctor1T;
        typedef TransformFunctor2<NumItemsT> TransformFunctor2T;

        TransformInputIterator<NumItemsT, TransformFunctor1T, NumItemsT*, NumItemsT> d_segment_begin_offsets_itr(d_segment_offsets, TransformFunctor1T());
        TransformInputIterator<NumItemsT, TransformFunctor2T, NumItemsT*, NumItemsT> d_segment_end_offsets_itr(d_segment_offsets + 1, TransformFunctor2T());

        TestBits(h_keys, num_items, num_segments, pre_sorted, h_segment_offsets, d_segment_begin_offsets_itr, d_segment_end_offsets_itr);
    }
}


/**
 * Test different segment compositions
 */
template <typename KeyT, typename NumItemsT>
void TestSegments(
    KeyT         *h_keys,
    NumItemsT    num_items,
    int          max_segments,
    bool         pre_sorted)
{
    max_segments = static_cast<int>(CUB_MIN(num_items, static_cast<NumItemsT>(max_segments)));
    NumItemsT *h_segment_offsets = new NumItemsT[max_segments + 1];

    NumItemsT *d_segment_offsets = nullptr;
    CubDebugExit(g_allocator.DeviceAllocate((void**)&d_segment_offsets, sizeof(NumItemsT) * (max_segments + 1)));

    for (int num_segments = max_segments; num_segments > 1; num_segments = cub::DivideAndRoundUp(num_segments, 64))
    {
        // Pre-sorted tests are not supported for segmented sort
        if (num_items / num_segments < 128 * 1000 && !pre_sorted) {
            // Right now we assign a single thread block to each segment, so lets keep it to under 128K items per segment
            TestSegmentIterators(h_keys, num_items, num_segments, pre_sorted, h_segment_offsets, d_segment_offsets);
        }
    }

    // Test single segment
    if (num_items > 0)
    {
      if (num_items < 128 * 1000 || pre_sorted)
      {
        // Right now we assign a single thread block to each segment, so lets
        // keep it to under 128K items per segment
        TestSegmentIterators(h_keys,
                             num_items,
                             1,
                             pre_sorted,
                             h_segment_offsets,
                             d_segment_offsets);
      }
    }

    if (h_segment_offsets) delete[] h_segment_offsets;
    if (d_segment_offsets) CubDebugExit(g_allocator.DeviceFree(d_segment_offsets));
}

/** 
 * Test different NumItemsT, i.e. types of num_items 
 */
template <typename KeyT>
void TestNumItems(KeyT         *h_keys,
                  std::size_t  num_items,
                  int          max_segments,
                  bool         pre_sorted)
{
    if (!pre_sorted && num_items <= std::size_t(std::numeric_limits<int>::max()))
    {
        TestSegments<KeyT, int>(h_keys, static_cast<int>(num_items), max_segments, pre_sorted);
    }
    if (pre_sorted && num_items <= std::size_t(std::numeric_limits<std::uint32_t>::max()))
    {
        TestSegments<KeyT, std::uint32_t>(h_keys, static_cast<std::uint32_t>(num_items), max_segments, pre_sorted);
    }
    TestSegments<KeyT, std::size_t>(h_keys, num_items, max_segments, pre_sorted);
}


/**
 * Test different (sub)lengths and number of segments
 */
template <typename KeyT>
void TestSizes(KeyT* h_keys,
               std::size_t max_items,
               int max_segments,
               bool pre_sorted)
{
    if (pre_sorted)
    {
        // run a specific list of sizes, up to max_items
        std::size_t sizes[] = {g_smallest_pre_sorted_num_items, 4350000007ull};
        for (std::size_t num_items : sizes)
        {
            if (num_items > max_items) break;
            TestNumItems(h_keys, num_items, max_segments, pre_sorted);
        }
    }
    else
    {
        for (std::size_t num_items = max_items;
             num_items > 1;
             num_items = cub::DivideAndRoundUp(num_items, 64))
        {
            TestNumItems(h_keys, num_items, max_segments, pre_sorted);
        }
    }
}

/**
 * Test key sampling distributions
 */
template <typename KeyT, bool WITH_PRE_SORTED>
void TestGen(
    std::size_t     max_items,
    int             max_segments)
{
    if (max_items == ~std::size_t(0))
    {
        max_items = 8000003;
    }

    if (max_segments < 0)
    {
        max_segments = 5003;
    }

    std::unique_ptr<KeyT[]> h_keys(new KeyT[max_items]);

    // Test trivial problems sizes
    h_keys[0] = static_cast<KeyT>(42);
    TestNumItems(h_keys.get(), 0, 0, false);
    TestNumItems(h_keys.get(), 1, 1, false);

    for (int entropy_reduction = 0; entropy_reduction <= 6; entropy_reduction += 6)
    {
        printf("\nTesting random %s keys with entropy reduction factor %d\n", typeid(KeyT).name(), entropy_reduction); fflush(stdout);
        InitializeKeyBits(RANDOM, h_keys.get(), max_items, entropy_reduction);
        TestSizes(h_keys.get(), max_items, max_segments, false);
    }

    if (cub::Traits<KeyT>::CATEGORY == cub::FLOATING_POINT)
    {
        printf("\nTesting random %s keys with some replaced with -0.0 or +0.0 \n", typeid(KeyT).name());
        fflush(stdout);
        InitializeKeyBits(RANDOM_MINUS_PLUS_ZERO, h_keys.get(), max_items, 0);
        // This just tests +/- 0 handling -- don't need to test multiple sizes
        TestNumItems(h_keys.get(), max_items, max_segments, false);
    }

    printf("\nTesting uniform %s keys\n", typeid(KeyT).name()); fflush(stdout);
    InitializeKeyBits(UNIFORM, h_keys.get(), max_items, 0);
    TestSizes(h_keys.get(), max_items, max_segments, false);

    printf("\nTesting natural number %s keys\n", typeid(KeyT).name()); fflush(stdout);
    InitializeKeyBits(INTEGER_SEED, h_keys.get(), max_items, 0);
    TestSizes(h_keys.get(), max_items, max_segments, false);

    if (WITH_PRE_SORTED)
    {
        // Presorting is only used for testing large input arrays.
        const std::size_t large_num_items = std::size_t(4350000007ull);

        // A conservative check for memory, as we don't know ValueT or whether
        // the overwrite is allowed until later.
        // For ValueT, the check is actually exact unless TEST_VALUE_TYPE == 3.
        if (!HasEnoughMemory<KeyT, SmallestValueT>(large_num_items, true))
        {
            printf("Skipping the permutation-based test due to insufficient device memory\n");
            return;
        }

        h_keys.reset(nullptr); // Explicitly free old buffer before allocating.
        h_keys.reset(new KeyT[large_num_items]);

        printf("\nTesting pre-sorted and randomly permuted %s keys\n", typeid(KeyT).name());
        fflush(stdout);
        InitializeKeysSorted(h_keys.get(), large_num_items);
        fflush(stdout);
        TestSizes(h_keys.get(), large_num_items, max_segments, true);
        fflush(stdout);
    }
}


//---------------------------------------------------------------------
// Simple test
//---------------------------------------------------------------------

template <
    Backend     BACKEND,
    typename    KeyT,
    typename    ValueT,
    bool        IS_DESCENDING>
void Test(
    std::size_t num_items,
    int         num_segments,
    GenMode     gen_mode,
    int         entropy_reduction,
    int         begin_bit,
    int         end_bit)
{
    const bool KEYS_ONLY = std::is_same<ValueT, NullType>::value;

    KeyT         *h_keys             = new KeyT[num_items];
    std::size_t  *h_reference_ranks  = NULL;
    KeyT         *h_reference_keys   = NULL;
    ValueT       *h_values           = NULL;
    ValueT       *h_reference_values = NULL;
    size_t       *h_segment_offsets  = new std::size_t[num_segments + 1];

    std::size_t* d_segment_offsets = nullptr;
    CubDebugExit(g_allocator.DeviceAllocate((void**)&d_segment_offsets, sizeof(std::size_t) * (num_segments + 1)));

    if (end_bit < 0)
        end_bit = sizeof(KeyT) * 8;

    InitializeKeyBits(gen_mode, h_keys, num_items, entropy_reduction);
    InitializeSegments(num_items, num_segments, h_segment_offsets);
    CubDebugExit(cudaMemcpy(d_segment_offsets, h_segment_offsets, sizeof(std::size_t) * (num_segments + 1), cudaMemcpyHostToDevice));
    InitializeSolution<IS_DESCENDING, !KEYS_ONLY>(
        h_keys, num_items, num_segments, false, h_segment_offsets,
        begin_bit, end_bit, h_reference_ranks, h_reference_keys);

    if (!KEYS_ONLY)
    {
        h_values            = new ValueT[num_items];
        h_reference_values  = new ValueT[num_items];

        for (std::size_t i = 0; i < num_items; ++i)
        {
            InitValue(INTEGER_SEED, h_values[i], i);
            InitValue(INTEGER_SEED, h_reference_values[i], h_reference_ranks[i]);
        }
    }
    if (h_reference_ranks) delete[] h_reference_ranks;

    printf("\nTesting bits [%d,%d) of %s keys with gen-mode %d\n", begin_bit, end_bit, typeid(KeyT).name(), gen_mode); fflush(stdout);
    Test<BACKEND, IS_DESCENDING>(
        h_keys, h_values,
        num_items, num_segments, d_segment_offsets, d_segment_offsets + 1,
        begin_bit, end_bit, h_reference_keys, h_reference_values);

    if (h_keys)             delete[] h_keys;
    if (h_reference_keys)   delete[] h_reference_keys;
    if (h_values)           delete[] h_values;
    if (h_reference_values) delete[] h_reference_values;
    if (h_segment_offsets)  delete[] h_segment_offsets;
    if (d_segment_offsets) CubDebugExit(g_allocator.DeviceFree(d_segment_offsets));
}

#if TEST_VALUE_TYPE == 0
void TestUnspecifiedRanges()
{
  const std::size_t num_items = 1024 * 1024;
  const std::size_t max_segments = 42;
  const std::size_t avg_segment_size = num_items / max_segments;

  for (int iteration = 0; iteration < 4; iteration++)
  {
    thrust::host_vector<int> h_offsets_begin;
    thrust::host_vector<int> h_offsets_end;

    h_offsets_begin.reserve(max_segments + 1);
    h_offsets_end.reserve(max_segments + 1);

    {
      int offset = 0;

      for (std::size_t sid = 0; sid < max_segments; sid++)
      {
        const int segment_size = 
          static_cast<int>(RandomValue(avg_segment_size));

        const bool segment_is_utilized = segment_size > 0 
                                       && RandomValue(100) > 60;

        if (segment_is_utilized)
        {
          h_offsets_begin.push_back(offset);
          h_offsets_end.push_back(offset + segment_size);
        }

        offset += segment_size;
      }

      if (h_offsets_begin.empty())
      {
        h_offsets_begin.push_back(avg_segment_size);
        h_offsets_end.push_back(num_items);
      }
    }

    thrust::device_vector<int> keys(num_items);
    thrust::device_vector<int> values(num_items);

    thrust::sequence(keys.rbegin(), keys.rend());
    thrust::sequence(values.rbegin(), values.rend());

    thrust::device_vector<int> d_offsets_begin = h_offsets_begin;
    thrust::device_vector<int> d_offsets_end = h_offsets_end;

    thrust::device_vector<int> expected_keys = keys;
    thrust::device_vector<int> expected_values = values;

    const int num_segments = static_cast<int>(h_offsets_begin.size());

    thrust::device_vector<int> result_keys = keys;
    thrust::device_vector<int> result_values = values;

    for (int sid = 0; sid < num_segments; sid++)
    {
      const int segment_begin = h_offsets_begin[sid];
      const int segment_end = h_offsets_end[sid];

      thrust::sort_by_key(expected_keys.begin() + segment_begin,
                          expected_keys.begin() + segment_end,
                          expected_values.begin() + segment_begin);
    }

    {
      cub::DoubleBuffer<int> keys_buffer(
          thrust::raw_pointer_cast(keys.data()), 
          thrust::raw_pointer_cast(result_keys.data()));

      cub::DoubleBuffer<int> values_buffer(
          thrust::raw_pointer_cast(values.data()), 
          thrust::raw_pointer_cast(result_values.data()));

      std::size_t temp_storage_bytes{};
      std::uint8_t *d_temp_storage{nullptr};

      CubDebugExit(cub::DeviceSegmentedRadixSort::SortPairs(
          d_temp_storage, temp_storage_bytes, 
          keys_buffer, values_buffer, 
          num_items, num_segments, 
          thrust::raw_pointer_cast(d_offsets_begin.data()),
          thrust::raw_pointer_cast(d_offsets_end.data()),
          0, sizeof(int) * 8));

      thrust::device_vector<std::uint8_t> temp_storage(temp_storage_bytes);
      d_temp_storage = thrust::raw_pointer_cast(temp_storage.data());

      CubDebugExit(cub::DeviceSegmentedRadixSort::SortPairs(
          d_temp_storage, temp_storage_bytes, 
          keys_buffer, values_buffer, 
          num_items, num_segments, 
          thrust::raw_pointer_cast(d_offsets_begin.data()),
          thrust::raw_pointer_cast(d_offsets_end.data()),
          0, sizeof(int) * 8));

      for (int sid = 0; sid < num_segments; sid++)
      {
        const int segment_begin = h_offsets_begin[sid];
        const int segment_end = h_offsets_end[sid];

        if (keys_buffer.selector == 0)
        {
          thrust::copy(
              keys.begin() + segment_begin,
              keys.begin() + segment_end,
              result_keys.begin() + segment_begin);
        }
                       
        if (values_buffer.selector == 0)
        {
          thrust::copy(
              values.begin() + segment_begin,
              values.begin() + segment_end,
              result_values.begin() + segment_begin);
        }
      }
    }

    AssertEquals(result_keys, expected_keys); 
    AssertEquals(result_values, expected_values);

    thrust::sequence(keys.rbegin(), keys.rend());
    thrust::sequence(values.rbegin(), values.rend());

    result_keys = keys;
    result_values = values;

    {
      std::size_t temp_storage_bytes{};
      std::uint8_t *d_temp_storage{};

      CubDebugExit(cub::DeviceSegmentedRadixSort::SortPairs(
          d_temp_storage, temp_storage_bytes, 
          thrust::raw_pointer_cast(keys.data()), 
          thrust::raw_pointer_cast(result_keys.data()), 
          thrust::raw_pointer_cast(values.data()), 
          thrust::raw_pointer_cast(result_values.data()), 
          num_items, num_segments, 
          thrust::raw_pointer_cast(d_offsets_begin.data()),
          thrust::raw_pointer_cast(d_offsets_end.data()),
          0, sizeof(int) * 8));

      thrust::device_vector<std::uint8_t> temp_storage(temp_storage_bytes);
      d_temp_storage = thrust::raw_pointer_cast(temp_storage.data());

      CubDebugExit(cub::DeviceSegmentedRadixSort::SortPairs(
          d_temp_storage, temp_storage_bytes, 
          thrust::raw_pointer_cast(keys.data()), 
          thrust::raw_pointer_cast(result_keys.data()), 
          thrust::raw_pointer_cast(values.data()), 
          thrust::raw_pointer_cast(result_values.data()), 
          num_items, num_segments, 
          thrust::raw_pointer_cast(d_offsets_begin.data()),
          thrust::raw_pointer_cast(d_offsets_end.data()),
          0, sizeof(int) * 8));
    }

    AssertEquals(result_values, expected_values);
    AssertEquals(result_keys, expected_keys);
  }
}
#endif

#if TEST_KEY_BYTES == 4
// Following tests check that new decomposer API doesn't break old API. 
// It's disabled because some compilers don't like implicit conversions, which
// is required for the test. Once we figure out how to temporarily enable conversion, we can
// re-enable the test.
#define ENABLING_CONVERSION_IS_FIGURED_OUT 0
#if ENABLING_CONVERSION_IS_FIGURED_OUT 
struct bit_selector
{
  int bit;

  operator int() const
  {
    return bit;
  }
};

template <class BeginBitT, class EndBitT, class... Ts>
void device_radix_sort_keys_allows_implicit_conversions_for_bits_helper(BeginBitT begin_bit, EndBitT end_bit, Ts... args)
{
  const int num_items = 0;

  {
    std::size_t temp_storage_bytes = 0;
    std::uint8_t *d_temp_storage   = nullptr;

    cub::DeviceRadixSort::SortKeys(d_temp_storage,
                                   temp_storage_bytes,
                                   args...,
                                   num_items,
                                   begin_bit,
                                   end_bit);
  }

  {
    std::size_t temp_storage_bytes = 0;
    std::uint8_t *d_temp_storage   = nullptr;

    cub::DeviceRadixSort::SortKeys(d_temp_storage,
                                   temp_storage_bytes,
                                   args...,
                                   num_items,
                                   begin_bit);
  }

  {
    std::size_t temp_storage_bytes = 0;
    std::uint8_t *d_temp_storage   = nullptr;

    cub::DeviceRadixSort::SortKeysDescending(d_temp_storage,
                                             temp_storage_bytes,
                                             args...,
                                             num_items,
                                             begin_bit,
                                             end_bit);
  }

  {
    std::size_t temp_storage_bytes = 0;
    std::uint8_t *d_temp_storage   = nullptr;

    cub::DeviceRadixSort::SortKeysDescending(d_temp_storage,
                                             temp_storage_bytes,
                                             args...,
                                             num_items,
                                             begin_bit);
  }
}

template <class BeginBitT, class EndBitT, class... Ts>
void device_radix_sort_pairs_allows_implicit_conversions_for_bits_helper(BeginBitT begin_bit,
                                                                         EndBitT end_bit,
                                                                         Ts... args)
{
  const int num_items = 0;

  {
    std::size_t temp_storage_bytes = 0;
    std::uint8_t *d_temp_storage   = nullptr;

    cub::DeviceRadixSort::SortPairs(d_temp_storage,
                                    temp_storage_bytes,
                                    args...,
                                    num_items,
                                    begin_bit,
                                    end_bit);
  }

  {
    std::size_t temp_storage_bytes = 0;
    std::uint8_t *d_temp_storage   = nullptr;

    cub::DeviceRadixSort::SortPairs(d_temp_storage,
                                    temp_storage_bytes,
                                    args...,
                                    num_items,
                                    begin_bit);
  }

  {
    std::size_t temp_storage_bytes = 0;
    std::uint8_t *d_temp_storage   = nullptr;

    cub::DeviceRadixSort::SortPairsDescending(d_temp_storage,
                                              temp_storage_bytes,
                                              args...,
                                              num_items,
                                              begin_bit,
                                              end_bit);
  }

  {
    std::size_t temp_storage_bytes = 0;
    std::uint8_t *d_temp_storage   = nullptr;

    cub::DeviceRadixSort::SortPairsDescending(d_temp_storage,
                                              temp_storage_bytes,
                                              args...,
                                              num_items,
                                              begin_bit);
  }
}

template <class BeginBitT, class EndBitT>
void device_radix_sort_allows_implicit_conversions_for_bits(BeginBitT begin_bit, EndBitT end_bit)
{
  int *d_i_ptr = nullptr;

  device_radix_sort_keys_allows_implicit_conversions_for_bits_helper(begin_bit,
                                                                     end_bit,
                                                                     d_i_ptr,
                                                                     d_i_ptr);

  cub::DoubleBuffer<int> keys(d_i_ptr, d_i_ptr);
  device_radix_sort_keys_allows_implicit_conversions_for_bits_helper(begin_bit, end_bit, keys);

  #if TEST_VALUE_TYPE == 2
  unsigned int *d_u_ptr = nullptr;

  device_radix_sort_pairs_allows_implicit_conversions_for_bits_helper(begin_bit,
                                                                      end_bit,
                                                                      d_i_ptr,
                                                                      d_i_ptr,
                                                                      d_u_ptr,
                                                                      d_u_ptr);

  cub::DoubleBuffer<unsigned int> pairs(d_u_ptr, d_u_ptr);
  device_radix_sort_pairs_allows_implicit_conversions_for_bits_helper(begin_bit,
                                                                      end_bit,
                                                                      keys,
                                                                      pairs);
  #endif
}

void device_radix_sort_allows_implicit_conversions_for_bits()
{
  int begin_i = 0;
  long long int begin_lli = 0;
  bit_selector begin_bs{0};

  int end_i = 2;
  long long int end_lli = 2;
  bit_selector end_bs{2};

  device_radix_sort_allows_implicit_conversions_for_bits(begin_i, end_i);
  device_radix_sort_allows_implicit_conversions_for_bits(begin_i, end_lli);
  device_radix_sort_allows_implicit_conversions_for_bits(begin_i, end_bs);
  device_radix_sort_allows_implicit_conversions_for_bits(begin_lli, end_i);
  device_radix_sort_allows_implicit_conversions_for_bits(begin_lli, end_lli);
  device_radix_sort_allows_implicit_conversions_for_bits(begin_lli, end_bs);
  device_radix_sort_allows_implicit_conversions_for_bits(begin_bs, end_i);
  device_radix_sort_allows_implicit_conversions_for_bits(begin_bs, end_lli);
  device_radix_sort_allows_implicit_conversions_for_bits(begin_bs, end_bs);
}
#endif // ENABLING_CONVERSION_IS_FIGURED_OUT 
#endif // TEST_KEY_BYTES == 4

//---------------------------------------------------------------------
// Main
//---------------------------------------------------------------------

/**
 * Main
 */
int main(int argc, char** argv)
{
    std::size_t num_items = ~std::size_t(0);
    int num_segments = -1;

    // Initialize command line
    CommandLineArgs args(argc, argv);
    g_verbose = args.CheckCmdLineFlag("v");
    args.GetCmdLineArgument("n", num_items);
    args.GetCmdLineArgument("s", num_segments);
    args.GetCmdLineArgument("i", g_timing_iterations);

    // Print usage
    if (args.CheckCmdLineFlag("help"))
    {
        printf("%s "
            "[--n=<input items> "
            "[--s=<num segments> "
            "[--i=<timing iterations> "
            "[--device=<device-id>] "
            "[--v] "
            "\n", argv[0]);
        exit(0);
    }

    // Initialize device
    CubDebugExit(args.DeviceInit());

    // %PARAM% TEST_CDP cdp 0:1
    // %PARAM% TEST_KEY_BYTES bytes 1:2:4:8:16
    // %PARAM% TEST_VALUE_TYPE pairs 0:1:2:3
    //   0->Keys only
    //   1->uchar
    //   2->uint
    //   3->[ull,TestBar] (TestBar is cheap to build, included here to
    //                     reduce total number of targets)

    // To reduce testing time, some key types are only tested when not
    // testing pairs:
#if TEST_VALUE_TYPE == 0
#define TEST_EXTENDED_KEY_TYPES
#endif

    // Compile/run thorough tests
#if TEST_KEY_BYTES == 1

    TestGen<signed char, true>        (num_items, num_segments);

#ifdef TEST_EXTENDED_KEY_TYPES
    TestGen<bool, false>              (num_items, num_segments);
    TestGen<signed char, false>       (num_items, num_segments);
    TestGen<unsigned char, false>     (num_items, num_segments);
#endif // TEST_EXTENDED_KEY_TYPES

#elif TEST_KEY_BYTES == 2
    TestGen<unsigned short, true>     (num_items, num_segments);

#ifdef TEST_EXTENDED_KEY_TYPES
    TestGen<short, false>             (num_items, num_segments);

#if !_NVHPC_CUDA
    TestGen<half_t, false>            (num_items, num_segments);
#endif // CTK >= 9

#if !_NVHPC_CUDA
#if !defined(__ICC)
    // Fails with `-0 != 0` with ICC for unknown reasons. See #333.
    TestGen<bfloat16_t, false>        (num_items, num_segments);
#endif // !ICC
#endif // CTK >= 11

#endif // TEST_EXTENDED_KEY_TYPES

#elif TEST_KEY_BYTES == 4

    TestGen<int, true>                (num_items, num_segments);

#if TEST_VALUE_TYPE == 0
    TestUnspecifiedRanges();
#endif

#if ENABLING_CONVERSION_IS_FIGURED_OUT 
    device_radix_sort_allows_implicit_conversions_for_bits();
#endif

#ifdef TEST_EXTENDED_KEY_TYPES
    TestGen<float, false>             (num_items, num_segments);
    TestGen<unsigned int, false>      (num_items, num_segments);
#endif // TEST_EXTENDED_KEY_TYPES

#elif TEST_KEY_BYTES == 8

    TestGen<double, true>             (num_items, num_segments);

#ifdef TEST_EXTENDED_KEY_TYPES
    TestGen<long long, false>         (num_items, num_segments);
    TestGen<unsigned long long, false>(num_items, num_segments);
#endif // TEST_EXTENDED_KEY_TYPES

#elif TEST_KEY_BYTES == 16

#if CUB_IS_INT128_ENABLED 
    TestGen<__int128_t,  false>(num_items, num_segments);
    TestGen<__uint128_t, false>(num_items, num_segments);
#else
    // Fix unused static function for MSVC
    BackendToString(CUB);
#endif

#endif // TEST_KEY_BYTES switch

    return 0;
}