-
Notifications
You must be signed in to change notification settings - Fork 916
/
writer_impl.cu
2181 lines (1969 loc) · 91.4 KB
/
writer_impl.cu
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (c) 2019-2022, NVIDIA CORPORATION.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* @file writer_impl.cu
* @brief cuDF-IO ORC writer class implementation
*/
#include "writer_impl.hpp"
#include <io/statistics/column_statistics.cuh>
#include <io/utilities/column_utils.cuh>
#include <cudf/detail/iterator.cuh>
#include <cudf/detail/null_mask.hpp>
#include <cudf/detail/utilities/cuda.cuh>
#include <cudf/detail/utilities/vector_factories.hpp>
#include <cudf/strings/strings_column_view.hpp>
#include <cudf/utilities/bit.hpp>
#include <cudf/utilities/span.hpp>
#include <rmm/cuda_stream_view.hpp>
#include <rmm/device_buffer.hpp>
#include <rmm/device_uvector.hpp>
#include <nvcomp/snappy.h>
#include <algorithm>
#include <cstring>
#include <numeric>
#include <utility>
#include <cuda/std/limits>
namespace cudf {
namespace io {
namespace detail {
namespace orc {
using namespace cudf::io::orc;
using namespace cudf::io;
struct row_group_index_info {
int32_t pos = -1; // Position
int32_t blk_pos = -1; // Block Position
int32_t comp_pos = -1; // Compressed Position
int32_t comp_size = -1; // Compressed size
};
namespace {
/**
* @brief Helper for pinned host memory
*/
template <typename T>
using pinned_buffer = std::unique_ptr<T, decltype(&cudaFreeHost)>;
/**
* @brief Function that translates GDF compression to ORC compression
*/
orc::CompressionKind to_orc_compression(compression_type compression)
{
switch (compression) {
case compression_type::AUTO:
case compression_type::SNAPPY: return orc::CompressionKind::SNAPPY;
case compression_type::NONE: return orc::CompressionKind::NONE;
default: CUDF_EXPECTS(false, "Unsupported compression type"); return orc::CompressionKind::NONE;
}
}
/**
* @brief Function that translates GDF dtype to ORC datatype
*/
constexpr orc::TypeKind to_orc_type(cudf::type_id id, bool list_column_as_map)
{
switch (id) {
case cudf::type_id::INT8: return TypeKind::BYTE;
case cudf::type_id::INT16: return TypeKind::SHORT;
case cudf::type_id::INT32: return TypeKind::INT;
case cudf::type_id::INT64: return TypeKind::LONG;
case cudf::type_id::FLOAT32: return TypeKind::FLOAT;
case cudf::type_id::FLOAT64: return TypeKind::DOUBLE;
case cudf::type_id::BOOL8: return TypeKind::BOOLEAN;
case cudf::type_id::TIMESTAMP_DAYS: return TypeKind::DATE;
case cudf::type_id::TIMESTAMP_SECONDS:
case cudf::type_id::TIMESTAMP_MICROSECONDS:
case cudf::type_id::TIMESTAMP_MILLISECONDS:
case cudf::type_id::TIMESTAMP_NANOSECONDS: return TypeKind::TIMESTAMP;
case cudf::type_id::STRING: return TypeKind::STRING;
case cudf::type_id::DECIMAL32:
case cudf::type_id::DECIMAL64:
case cudf::type_id::DECIMAL128: return TypeKind::DECIMAL;
case cudf::type_id::LIST: return list_column_as_map ? TypeKind::MAP : TypeKind::LIST;
case cudf::type_id::STRUCT: return TypeKind::STRUCT;
default: return TypeKind::INVALID_TYPE_KIND;
}
}
/**
* @brief Translates time unit to nanoscale multiple.
*/
constexpr int32_t to_clockscale(cudf::type_id timestamp_id)
{
switch (timestamp_id) {
case cudf::type_id::TIMESTAMP_SECONDS: return 9;
case cudf::type_id::TIMESTAMP_MILLISECONDS: return 6;
case cudf::type_id::TIMESTAMP_MICROSECONDS: return 3;
case cudf::type_id::TIMESTAMP_NANOSECONDS:
default: return 0;
}
}
/**
* @brief Returns the precision of the given decimal type.
*/
constexpr auto orc_precision(cudf::type_id decimal_id)
{
using namespace numeric;
switch (decimal_id) {
case cudf::type_id::DECIMAL32: return cuda::std::numeric_limits<decimal32::rep>::digits10;
case cudf::type_id::DECIMAL64: return cuda::std::numeric_limits<decimal64::rep>::digits10;
case cudf::type_id::DECIMAL128: return cuda::std::numeric_limits<decimal128::rep>::digits10;
default: return 0;
}
}
} // namespace
/**
* @brief Helper class that adds ORC-specific column info
*/
class orc_column_view {
public:
/**
* @brief Constructor that extracts out the string position + length pairs
* for building dictionaries for string columns
*/
explicit orc_column_view(uint32_t index,
int str_idx,
orc_column_view* parent,
column_view const& col,
column_in_metadata const& metadata)
: cudf_column{col},
_index{index},
_str_idx{str_idx},
_is_child{parent != nullptr},
_type_width{cudf::is_fixed_width(col.type()) ? cudf::size_of(col.type()) : 0},
_type_kind{to_orc_type(col.type().id(), metadata.is_map())},
_scale{(_type_kind == TypeKind::DECIMAL) ? -col.type().scale()
: to_clockscale(col.type().id())},
_precision{metadata.is_decimal_precision_set() ? metadata.get_decimal_precision()
: orc_precision(col.type().id())},
name{metadata.get_name()}
{
if (metadata.is_nullability_defined()) { nullable_from_metadata = metadata.nullable(); }
if (parent != nullptr) {
parent->add_child(_index);
_parent_index = parent->index();
}
if (_type_kind == TypeKind::MAP) {
auto const struct_col = col.child(lists_column_view::child_column_index);
CUDF_EXPECTS(struct_col.null_count() == 0,
"struct column of a MAP column should not have null elements");
CUDF_EXPECTS(struct_col.num_children() == 2, "MAP column must have two child columns");
}
}
void add_child(uint32_t child_idx) { children.emplace_back(child_idx); }
auto is_string() const noexcept { return cudf_column.type().id() == type_id::STRING; }
void set_dict_stride(size_t stride) noexcept { _dict_stride = stride; }
[[nodiscard]] auto dict_stride() const noexcept { return _dict_stride; }
/**
* @brief Function that associates an existing dictionary chunk allocation
*/
void attach_dict_chunk(gpu::DictionaryChunk const* host_dict,
gpu::DictionaryChunk const* dev_dict)
{
dict = host_dict;
d_dict = dev_dict;
}
[[nodiscard]] auto host_dict_chunk(size_t rowgroup) const
{
CUDF_EXPECTS(is_string(), "Dictionary chunks are only present in string columns.");
return &dict[rowgroup * _dict_stride + _str_idx];
}
[[nodiscard]] auto device_dict_chunk() const { return d_dict; }
[[nodiscard]] auto const& decimal_offsets() const { return d_decimal_offsets; }
void attach_decimal_offsets(uint32_t* sizes_ptr) { d_decimal_offsets = sizes_ptr; }
/**
* @brief Function that associates an existing stripe dictionary allocation
*/
void attach_stripe_dict(gpu::StripeDictionary* host_stripe_dict,
gpu::StripeDictionary* dev_stripe_dict)
{
stripe_dict = host_stripe_dict;
d_stripe_dict = dev_stripe_dict;
}
[[nodiscard]] auto host_stripe_dict(size_t stripe) const
{
CUDF_EXPECTS(is_string(), "Stripe dictionary is only present in string columns.");
return &stripe_dict[stripe * _dict_stride + _str_idx];
}
[[nodiscard]] auto device_stripe_dict() const noexcept { return d_stripe_dict; }
// Index in the table
[[nodiscard]] uint32_t index() const noexcept { return _index; }
// Id in the ORC file
[[nodiscard]] auto id() const noexcept { return _index + 1; }
[[nodiscard]] auto is_child() const noexcept { return _is_child; }
auto parent_index() const noexcept { return _parent_index.value(); }
auto child_begin() const noexcept { return children.cbegin(); }
auto child_end() const noexcept { return children.cend(); }
auto num_children() const noexcept { return children.size(); }
[[nodiscard]] auto type_width() const noexcept { return _type_width; }
auto size() const noexcept { return cudf_column.size(); }
auto null_count() const noexcept { return cudf_column.null_count(); }
auto null_mask() const noexcept { return cudf_column.null_mask(); }
[[nodiscard]] bool nullable() const noexcept { return null_mask() != nullptr; }
auto user_defined_nullable() const noexcept { return nullable_from_metadata; }
[[nodiscard]] auto scale() const noexcept { return _scale; }
[[nodiscard]] auto precision() const noexcept { return _precision; }
void set_orc_encoding(ColumnEncodingKind e) noexcept { _encoding_kind = e; }
[[nodiscard]] auto orc_kind() const noexcept { return _type_kind; }
[[nodiscard]] auto orc_encoding() const noexcept { return _encoding_kind; }
[[nodiscard]] std::string_view orc_name() const noexcept { return name; }
private:
column_view cudf_column;
// Identifier within the set of columns
uint32_t _index = 0;
// Identifier within the set of string columns
int _str_idx;
bool _is_child = false;
// ORC-related members
TypeKind _type_kind = INVALID_TYPE_KIND;
ColumnEncodingKind _encoding_kind = INVALID_ENCODING_KIND;
std::string name;
size_t _type_width = 0;
int32_t _scale = 0;
int32_t _precision = 0;
// String dictionary-related members
size_t _dict_stride = 0;
gpu::DictionaryChunk const* dict = nullptr;
gpu::StripeDictionary const* stripe_dict = nullptr;
gpu::DictionaryChunk const* d_dict = nullptr;
gpu::StripeDictionary const* d_stripe_dict = nullptr;
// Offsets for encoded decimal elements. Used to enable direct writing of encoded decimal elements
// into the output stream.
uint32_t* d_decimal_offsets = nullptr;
std::optional<bool> nullable_from_metadata;
std::vector<uint32_t> children;
std::optional<uint32_t> _parent_index;
};
size_type orc_table_view::num_rows() const noexcept
{
return columns.empty() ? 0 : columns.front().size();
}
/**
* @brief Gathers stripe information.
*
* @param columns List of columns
* @param rowgroup_bounds Ranges of rows in each rowgroup [rowgroup][column]
* @param max_stripe_size Maximum size of each stripe, both in bytes and in rows
* @return List of stripe descriptors
*/
file_segmentation calculate_segmentation(host_span<orc_column_view const> columns,
hostdevice_2dvector<rowgroup_rows>&& rowgroup_bounds,
stripe_size_limits max_stripe_size)
{
std::vector<stripe_rowgroups> infos;
auto const num_rowgroups = rowgroup_bounds.size().first;
size_t stripe_start = 0;
size_t stripe_bytes = 0;
size_type stripe_rows = 0;
for (size_t rg_idx = 0; rg_idx < num_rowgroups; ++rg_idx) {
auto const rowgroup_total_bytes =
std::accumulate(columns.begin(), columns.end(), 0ul, [&](size_t total_size, auto const& col) {
auto const rows = rowgroup_bounds[rg_idx][col.index()].size();
if (col.is_string()) {
const auto dt = col.host_dict_chunk(rg_idx);
return total_size + rows + dt->string_char_count;
} else {
return total_size + col.type_width() * rows;
}
});
auto const rowgroup_rows_max =
std::max_element(rowgroup_bounds[rg_idx].begin(),
rowgroup_bounds[rg_idx].end(),
[](auto& l, auto& r) { return l.size() < r.size(); })
->size();
// Check if adding the current rowgroup to the stripe will make the stripe too large or long
if ((rg_idx > stripe_start) && (stripe_bytes + rowgroup_total_bytes > max_stripe_size.bytes ||
stripe_rows + rowgroup_rows_max > max_stripe_size.rows)) {
infos.emplace_back(infos.size(), stripe_start, rg_idx - stripe_start);
stripe_start = rg_idx;
stripe_bytes = 0;
stripe_rows = 0;
}
stripe_bytes += rowgroup_total_bytes;
stripe_rows += rowgroup_rows_max;
if (rg_idx + 1 == num_rowgroups) {
infos.emplace_back(infos.size(), stripe_start, num_rowgroups - stripe_start);
}
}
return {std::move(rowgroup_bounds), std::move(infos)};
}
/**
* @brief Builds up column dictionaries indices
*
* @param orc_table Non-owning view of a cuDF table w/ ORC-related info
* @param rowgroup_bounds Ranges of rows in each rowgroup [rowgroup][column]
* @param dict_data Dictionary data memory
* @param dict_index Dictionary index memory
* @param dict List of dictionary chunks
* @param stream CUDA stream used for device memory operations and kernel launches
*/
void init_dictionaries(orc_table_view& orc_table,
device_2dspan<rowgroup_rows const> rowgroup_bounds,
device_span<device_span<uint32_t>> dict_data,
device_span<device_span<uint32_t>> dict_index,
hostdevice_2dvector<gpu::DictionaryChunk>* dict,
rmm::cuda_stream_view stream)
{
// Setup per-rowgroup dictionary indexes for each dictionary-aware column
for (auto col_idx : orc_table.string_column_indices) {
auto& str_column = orc_table.column(col_idx);
str_column.set_dict_stride(orc_table.num_string_columns());
str_column.attach_dict_chunk(dict->base_host_ptr(), dict->base_device_ptr());
}
// Allocate temporary memory for dictionary indices
std::vector<rmm::device_uvector<uint32_t>> dict_indices;
dict_indices.reserve(orc_table.num_string_columns());
std::transform(orc_table.string_column_indices.cbegin(),
orc_table.string_column_indices.cend(),
std::back_inserter(dict_indices),
[&](auto& col_idx) {
auto& str_column = orc_table.column(col_idx);
return cudf::detail::make_zeroed_device_uvector_async<uint32_t>(
str_column.size(), stream);
});
// Create views of the temporary buffers in device memory
std::vector<device_span<uint32_t>> dict_indices_views;
dict_indices_views.reserve(dict_indices.size());
std::transform(
dict_indices.begin(), dict_indices.end(), std::back_inserter(dict_indices_views), [](auto& di) {
return device_span<uint32_t>{di};
});
auto d_dict_indices_views = cudf::detail::make_device_uvector_async(dict_indices_views, stream);
gpu::InitDictionaryIndices(orc_table.d_columns,
*dict,
dict_data,
dict_index,
d_dict_indices_views,
rowgroup_bounds,
orc_table.d_string_column_indices,
stream);
dict->device_to_host(stream, true);
}
void writer::impl::build_dictionaries(orc_table_view& orc_table,
host_span<stripe_rowgroups const> stripe_bounds,
hostdevice_2dvector<gpu::DictionaryChunk> const& dict,
host_span<rmm::device_uvector<uint32_t>> dict_index,
host_span<bool const> dictionary_enabled,
hostdevice_2dvector<gpu::StripeDictionary>& stripe_dict)
{
const auto num_rowgroups = dict.size().first;
for (size_t dict_idx = 0; dict_idx < orc_table.num_string_columns(); ++dict_idx) {
auto& str_column = orc_table.string_column(dict_idx);
str_column.attach_stripe_dict(stripe_dict.base_host_ptr(), stripe_dict.base_device_ptr());
for (auto const& stripe : stripe_bounds) {
auto& sd = stripe_dict[stripe.id][dict_idx];
sd.dict_data = str_column.host_dict_chunk(stripe.first)->dict_data;
sd.dict_index = dict_index[dict_idx].data(); // Indexed by abs row
sd.column_id = orc_table.string_column_indices[dict_idx];
sd.start_chunk = stripe.first;
sd.num_chunks = stripe.size;
sd.dict_char_count = 0;
sd.num_strings =
std::accumulate(stripe.cbegin(), stripe.cend(), 0, [&](auto dt_str_cnt, auto rg_idx) {
const auto& dt = dict[rg_idx][dict_idx];
return dt_str_cnt + dt.num_dict_strings;
});
sd.leaf_column = dict[0][dict_idx].leaf_column;
}
if (enable_dictionary_) {
struct string_column_cost {
size_t direct = 0;
size_t dictionary = 0;
};
auto const col_cost =
std::accumulate(stripe_bounds.front().cbegin(),
stripe_bounds.back().cend(),
string_column_cost{},
[&](auto cost, auto rg_idx) -> string_column_cost {
const auto& dt = dict[rg_idx][dict_idx];
return {cost.direct + dt.string_char_count,
cost.dictionary + dt.dict_char_count + dt.num_dict_strings};
});
// Disable dictionary if it does not reduce the output size
if (!dictionary_enabled[orc_table.string_column(dict_idx).index()] ||
col_cost.dictionary >= col_cost.direct) {
for (auto const& stripe : stripe_bounds) {
stripe_dict[stripe.id][dict_idx].dict_data = nullptr;
}
}
}
}
stripe_dict.host_to_device(stream);
gpu::BuildStripeDictionaries(stripe_dict, stripe_dict, dict, stream);
stripe_dict.device_to_host(stream, true);
}
/**
* @brief Returns the maximum size of RLE encoded values of an integer type.
**/
template <typename T>
size_t max_varint_size()
{
// varint encodes 7 bits in each byte
return cudf::util::div_rounding_up_unsafe(sizeof(T) * 8, 7);
}
constexpr size_t RLE_stream_size(TypeKind kind, size_t count)
{
using cudf::util::div_rounding_up_unsafe;
constexpr auto byte_rle_max_len = 128;
switch (kind) {
case TypeKind::BOOLEAN:
return div_rounding_up_unsafe(count, byte_rle_max_len * 8) * (byte_rle_max_len + 1);
case TypeKind::BYTE:
return div_rounding_up_unsafe(count, byte_rle_max_len) * (byte_rle_max_len + 1);
case TypeKind::SHORT:
return div_rounding_up_unsafe(count, gpu::encode_block_size) *
(gpu::encode_block_size * max_varint_size<int16_t>() + 2);
case TypeKind::FLOAT:
case TypeKind::INT:
case TypeKind::DATE:
return div_rounding_up_unsafe(count, gpu::encode_block_size) *
(gpu::encode_block_size * max_varint_size<int32_t>() + 2);
case TypeKind::LONG:
case TypeKind::DOUBLE:
return div_rounding_up_unsafe(count, gpu::encode_block_size) *
(gpu::encode_block_size * max_varint_size<int64_t>() + 2);
default: CUDF_FAIL("Unsupported ORC type for RLE stream size");
}
}
orc_streams writer::impl::create_streams(host_span<orc_column_view> columns,
file_segmentation const& segmentation,
std::map<uint32_t, size_t> const& decimal_column_sizes)
{
// 'column 0' row index stream
std::vector<Stream> streams{{ROW_INDEX, 0}}; // TODO: Separate index and data streams?
// First n + 1 streams are row index streams
streams.reserve(columns.size() + 1);
std::transform(columns.begin(), columns.end(), std::back_inserter(streams), [](auto const& col) {
return Stream{ROW_INDEX, col.id()};
});
std::vector<int32_t> ids(columns.size() * gpu::CI_NUM_STREAMS, -1);
std::vector<TypeKind> types(streams.size(), INVALID_TYPE_KIND);
for (auto& column : columns) {
auto const is_nullable = [&]() -> bool {
if (single_write_mode) {
return column.nullable();
} else {
// For chunked write, when not provided nullability, we assume the worst case scenario
// that all columns are nullable.
auto const chunked_nullable = column.user_defined_nullable().value_or(true);
CUDF_EXPECTS(chunked_nullable or !column.nullable(),
"Mismatch in metadata prescribed nullability and input column nullability. "
"Metadata for nullable input column cannot prescribe nullability = false");
return chunked_nullable;
}
}();
auto RLE_column_size = [&](TypeKind type_kind) {
return std::accumulate(
thrust::make_counting_iterator(0ul),
thrust::make_counting_iterator(segmentation.num_rowgroups()),
0ul,
[&](auto data_size, auto rg_idx) {
return data_size +
RLE_stream_size(type_kind, segmentation.rowgroups[rg_idx][column.index()].size());
});
};
auto const kind = column.orc_kind();
auto add_stream =
[&](gpu::StreamIndexType index_type, StreamKind kind, TypeKind type_kind, size_t size) {
const auto base = column.index() * gpu::CI_NUM_STREAMS;
ids[base + index_type] = streams.size();
streams.push_back(orc::Stream{kind, column.id(), size});
types.push_back(type_kind);
};
auto add_RLE_stream = [&](
gpu::StreamIndexType index_type, StreamKind kind, TypeKind type_kind) {
add_stream(index_type, kind, type_kind, RLE_column_size(type_kind));
};
if (is_nullable) { add_RLE_stream(gpu::CI_PRESENT, PRESENT, TypeKind::BOOLEAN); }
switch (kind) {
case TypeKind::BOOLEAN:
case TypeKind::BYTE:
add_RLE_stream(gpu::CI_DATA, DATA, kind);
column.set_orc_encoding(DIRECT);
break;
case TypeKind::SHORT:
case TypeKind::INT:
case TypeKind::LONG:
case TypeKind::DATE:
add_RLE_stream(gpu::CI_DATA, DATA, kind);
column.set_orc_encoding(DIRECT_V2);
break;
case TypeKind::FLOAT:
case TypeKind::DOUBLE:
// Pass through if no nulls (no RLE encoding for floating point)
add_stream(
gpu::CI_DATA, DATA, kind, (column.null_count() != 0) ? RLE_column_size(kind) : 0);
column.set_orc_encoding(DIRECT);
break;
case TypeKind::STRING: {
bool enable_dict = enable_dictionary_;
size_t dict_data_size = 0;
size_t dict_strings = 0;
size_t dict_lengths_div512 = 0;
for (auto const& stripe : segmentation.stripes) {
const auto sd = column.host_stripe_dict(stripe.id);
enable_dict = (enable_dict && sd->dict_data != nullptr);
if (enable_dict) {
dict_strings += sd->num_strings;
dict_lengths_div512 += (sd->num_strings + 0x1ff) >> 9;
dict_data_size += sd->dict_char_count;
}
}
auto const direct_data_size =
segmentation.num_stripes() == 0
? 0
: std::accumulate(segmentation.stripes.front().cbegin(),
segmentation.stripes.back().cend(),
size_t{0},
[&](auto data_size, auto rg_idx) {
return data_size +
column.host_dict_chunk(rg_idx)->string_char_count;
});
if (enable_dict) {
uint32_t dict_bits = 0;
for (dict_bits = 1; dict_bits < 32; dict_bits <<= 1) {
if (dict_strings <= (1ull << dict_bits)) break;
}
const auto valid_count = column.size() - column.null_count();
dict_data_size += (dict_bits * valid_count + 7) >> 3;
}
// Decide between direct or dictionary encoding
if (enable_dict && dict_data_size < direct_data_size) {
add_RLE_stream(gpu::CI_DATA, DATA, TypeKind::INT);
add_stream(gpu::CI_DATA2, LENGTH, TypeKind::INT, dict_lengths_div512 * (512 * 4 + 2));
add_stream(
gpu::CI_DICTIONARY, DICTIONARY_DATA, TypeKind::CHAR, std::max(dict_data_size, 1ul));
column.set_orc_encoding(DICTIONARY_V2);
} else {
add_stream(gpu::CI_DATA, DATA, TypeKind::CHAR, std::max<size_t>(direct_data_size, 1));
add_RLE_stream(gpu::CI_DATA2, LENGTH, TypeKind::INT);
column.set_orc_encoding(DIRECT_V2);
}
break;
}
case TypeKind::TIMESTAMP:
add_RLE_stream(gpu::CI_DATA, DATA, TypeKind::LONG);
add_RLE_stream(gpu::CI_DATA2, SECONDARY, TypeKind::LONG);
column.set_orc_encoding(DIRECT_V2);
break;
case TypeKind::DECIMAL:
// varint values (NO RLE)
// data_stream_size = decimal_column_sizes.at(column.index());
add_stream(gpu::CI_DATA, DATA, TypeKind::DECIMAL, decimal_column_sizes.at(column.index()));
// scale stream TODO: compute exact size since all elems are equal
add_RLE_stream(gpu::CI_DATA2, SECONDARY, TypeKind::INT);
column.set_orc_encoding(DIRECT_V2);
break;
case TypeKind::LIST:
case TypeKind::MAP:
// no data stream, only lengths
add_RLE_stream(gpu::CI_DATA2, LENGTH, TypeKind::INT);
column.set_orc_encoding(DIRECT_V2);
break;
case TypeKind::STRUCT:
// Only has the present stream
break;
default: CUDF_FAIL("Unsupported ORC type kind");
}
}
return {std::move(streams), std::move(ids), std::move(types)};
}
orc_streams::orc_stream_offsets orc_streams::compute_offsets(
host_span<orc_column_view const> columns, size_t num_rowgroups) const
{
std::vector<size_t> strm_offsets(streams.size());
size_t non_rle_data_size = 0;
size_t rle_data_size = 0;
for (size_t i = 0; i < streams.size(); ++i) {
const auto& stream = streams[i];
auto const is_rle_data = [&]() {
// First stream is an index stream, don't check types, etc.
if (!stream.column_index().has_value()) return true;
auto const& column = columns[stream.column_index().value()];
// Dictionary encoded string column - dictionary characters or
// directly encoded string - column characters
if (column.orc_kind() == TypeKind::STRING &&
((stream.kind == DICTIONARY_DATA && column.orc_encoding() == DICTIONARY_V2) ||
(stream.kind == DATA && column.orc_encoding() == DIRECT_V2)))
return false;
// Decimal data
if (column.orc_kind() == TypeKind::DECIMAL && stream.kind == DATA) return false;
// Everything else uses RLE
return true;
}();
// non-RLE and RLE streams are separated in the buffer that stores encoded data
// The computed offsets do not take the streams of the other type into account
if (is_rle_data) {
strm_offsets[i] = rle_data_size;
rle_data_size += (stream.length + 7) & ~7;
} else {
strm_offsets[i] = non_rle_data_size;
non_rle_data_size += stream.length;
}
}
non_rle_data_size = (non_rle_data_size + 7) & ~7;
return {std::move(strm_offsets), non_rle_data_size, rle_data_size};
}
std::vector<std::vector<rowgroup_rows>> calculate_aligned_rowgroup_bounds(
orc_table_view const& orc_table,
file_segmentation const& segmentation,
rmm::cuda_stream_view stream)
{
if (segmentation.num_rowgroups() == 0) return {};
auto d_pd_set_counts_data = rmm::device_uvector<cudf::size_type>(
orc_table.num_columns() * segmentation.num_rowgroups(), stream);
auto const d_pd_set_counts = device_2dspan<cudf::size_type>{
d_pd_set_counts_data.data(), segmentation.num_rowgroups(), orc_table.num_columns()};
gpu::reduce_pushdown_masks(orc_table.d_columns, segmentation.rowgroups, d_pd_set_counts, stream);
auto aligned_rgs = hostdevice_2dvector<rowgroup_rows>(
segmentation.num_rowgroups(), orc_table.num_columns(), stream);
CUDA_TRY(cudaMemcpyAsync(aligned_rgs.base_device_ptr(),
segmentation.rowgroups.base_device_ptr(),
aligned_rgs.count() * sizeof(rowgroup_rows),
cudaMemcpyDefault,
stream.value()));
auto const d_stripes = cudf::detail::make_device_uvector_async(segmentation.stripes, stream);
// One thread per column, per stripe
thrust::for_each_n(
rmm::exec_policy(stream),
thrust::make_counting_iterator(0),
orc_table.num_columns() * segmentation.num_stripes(),
[columns = device_span<orc_column_device_view const>{orc_table.d_columns},
stripes = device_span<stripe_rowgroups const>{d_stripes},
d_pd_set_counts,
out_rowgroups = device_2dspan<rowgroup_rows>{aligned_rgs}] __device__(auto& idx) {
uint32_t const col_idx = idx / stripes.size();
// No alignment needed for root columns
if (not columns[col_idx].parent_index.has_value()) return;
auto const stripe_idx = idx % stripes.size();
auto const stripe = stripes[stripe_idx];
auto const parent_col_idx = columns[col_idx].parent_index.value();
auto const parent_column = columns[parent_col_idx];
auto const stripe_end = stripe.first + stripe.size;
auto seek_last_borrow_rg = [&](auto rg_idx, size_type& bits_to_borrow) {
auto curr = rg_idx + 1;
auto curr_rg_size = [&]() {
return parent_column.pushdown_mask != nullptr ? d_pd_set_counts[curr][parent_col_idx]
: out_rowgroups[curr][col_idx].size();
};
while (curr < stripe_end and curr_rg_size() <= bits_to_borrow) {
// All bits from rowgroup borrowed, make the rowgroup empty
out_rowgroups[curr][col_idx].begin = out_rowgroups[curr][col_idx].end;
bits_to_borrow -= curr_rg_size();
++curr;
}
return curr;
};
int previously_borrowed = 0;
for (auto rg_idx = stripe.first; rg_idx + 1 < stripe_end; ++rg_idx) {
auto& rg = out_rowgroups[rg_idx][col_idx];
if (parent_column.pushdown_mask == nullptr) {
// No pushdown mask, all null mask bits will be encoded
// Align on rowgroup size (can be misaligned for list children)
if (rg.size() % 8) {
auto bits_to_borrow = 8 - rg.size() % 8;
auto const last_borrow_rg_idx = seek_last_borrow_rg(rg_idx, bits_to_borrow);
if (last_borrow_rg_idx == stripe_end) {
// Didn't find enough bits to borrow, move the rowgroup end to the stripe end
rg.end = out_rowgroups[stripe_end - 1][col_idx].end;
// Done with this stripe
break;
}
auto& last_borrow_rg = out_rowgroups[last_borrow_rg_idx][col_idx];
last_borrow_rg.begin += bits_to_borrow;
rg.end = last_borrow_rg.begin;
// Skip the rowgroups we emptied in the loop
rg_idx = last_borrow_rg_idx - 1;
}
} else {
// pushdown mask present; null mask bits w/ set pushdown mask bits will be encoded
// Use the number of set bits in pushdown mask as size
auto bits_to_borrow =
8 - (d_pd_set_counts[rg_idx][parent_col_idx] - previously_borrowed) % 8;
if (bits_to_borrow == 0) {
// Didn't borrow any bits for this rowgroup
previously_borrowed = 0;
continue;
}
// Find rowgroup in which we finish the search for missing bits
auto const last_borrow_rg_idx = seek_last_borrow_rg(rg_idx, bits_to_borrow);
if (last_borrow_rg_idx == stripe_end) {
// Didn't find enough bits to borrow, move the rowgroup end to the stripe end
rg.end = out_rowgroups[stripe_end - 1][col_idx].end;
// Done with this stripe
break;
}
auto& last_borrow_rg = out_rowgroups[last_borrow_rg_idx][col_idx];
// First row that does not need to be borrowed
auto borrow_end = last_borrow_rg.begin;
// Adjust the number of bits to borrow in the next iteration
previously_borrowed = bits_to_borrow;
// Find word in which we finish the search for missing bits (guaranteed to be available)
while (bits_to_borrow != 0) {
auto const mask = cudf::detail::get_mask_offset_word(
parent_column.pushdown_mask, 0, borrow_end, borrow_end + 32);
auto const valid_in_word = __popc(mask);
if (valid_in_word > bits_to_borrow) break;
bits_to_borrow -= valid_in_word;
borrow_end += 32;
}
// Find the last of the missing bits (guaranteed to be available)
while (bits_to_borrow != 0) {
if (bit_is_set(parent_column.pushdown_mask, borrow_end)) { --bits_to_borrow; };
++borrow_end;
}
last_borrow_rg.begin = borrow_end;
rg.end = borrow_end;
// Skip the rowgroups we emptied in the loop
rg_idx = last_borrow_rg_idx - 1;
}
}
});
aligned_rgs.device_to_host(stream, true);
std::vector<std::vector<rowgroup_rows>> h_aligned_rgs;
h_aligned_rgs.reserve(segmentation.num_rowgroups());
std::transform(thrust::make_counting_iterator(0ul),
thrust::make_counting_iterator(segmentation.num_rowgroups()),
std::back_inserter(h_aligned_rgs),
[&](auto idx) -> std::vector<rowgroup_rows> {
return {aligned_rgs[idx].begin(), aligned_rgs[idx].end()};
});
return h_aligned_rgs;
}
struct segmented_valid_cnt_input {
bitmask_type const* mask;
std::vector<size_type> indices;
};
encoded_data encode_columns(orc_table_view const& orc_table,
string_dictionaries&& dictionaries,
encoder_decimal_info&& dec_chunk_sizes,
file_segmentation const& segmentation,
orc_streams const& streams,
rmm::cuda_stream_view stream)
{
auto const num_columns = orc_table.num_columns();
hostdevice_2dvector<gpu::EncChunk> chunks(num_columns, segmentation.num_rowgroups(), stream);
auto const stream_offsets =
streams.compute_offsets(orc_table.columns, segmentation.num_rowgroups());
rmm::device_uvector<uint8_t> encoded_data(stream_offsets.data_size(), stream);
auto const aligned_rowgroups = calculate_aligned_rowgroup_bounds(orc_table, segmentation, stream);
// Initialize column chunks' descriptions
std::map<size_type, segmented_valid_cnt_input> validity_check_inputs;
for (auto const& column : orc_table.columns) {
for (auto const& stripe : segmentation.stripes) {
for (auto rg_idx_it = stripe.cbegin(); rg_idx_it < stripe.cend(); ++rg_idx_it) {
auto const rg_idx = *rg_idx_it;
auto& ck = chunks[column.index()][rg_idx];
ck.start_row = segmentation.rowgroups[rg_idx][column.index()].begin;
ck.num_rows = segmentation.rowgroups[rg_idx][column.index()].size();
ck.null_mask_start_row = aligned_rowgroups[rg_idx][column.index()].begin;
ck.null_mask_num_rows = aligned_rowgroups[rg_idx][column.index()].size();
ck.encoding_kind = column.orc_encoding();
ck.type_kind = column.orc_kind();
if (ck.type_kind == TypeKind::STRING) {
ck.dict_index = (ck.encoding_kind == DICTIONARY_V2)
? column.host_stripe_dict(stripe.id)->dict_index
: nullptr;
ck.dtype_len = 1;
} else {
ck.dtype_len = column.type_width();
}
ck.scale = column.scale();
if (ck.type_kind == TypeKind::DECIMAL) { ck.decimal_offsets = column.decimal_offsets(); }
}
}
}
chunks.host_to_device(stream);
// TODO (future): pass columns separately from chunks (to skip this step)
// and remove info from chunks that is common for the entire column
thrust::for_each_n(
rmm::exec_policy(stream),
thrust::make_counting_iterator(0ul),
chunks.count(),
[chunks = device_2dspan<gpu::EncChunk>{chunks},
cols = device_span<orc_column_device_view const>{orc_table.d_columns}] __device__(auto& idx) {
auto const col_idx = idx / chunks.size().second;
auto const rg_idx = idx % chunks.size().second;
chunks[col_idx][rg_idx].column = &cols[col_idx];
});
auto validity_check_indices = [&](size_t col_idx) {
std::vector<size_type> indices;
for (auto const& stripe : segmentation.stripes) {
for (auto rg_idx_it = stripe.cbegin(); rg_idx_it < stripe.cend() - 1; ++rg_idx_it) {
auto const& chunk = chunks[col_idx][*rg_idx_it];
indices.push_back(chunk.start_row);
indices.push_back(chunk.start_row + chunk.num_rows);
}
}
return indices;
};
for (auto const& column : orc_table.columns) {
if (column.orc_kind() == TypeKind::BOOLEAN && column.nullable()) {
validity_check_inputs[column.index()] = {column.null_mask(),
validity_check_indices(column.index())};
}
}
for (auto& cnt_in : validity_check_inputs) {
auto const valid_counts =
cudf::detail::segmented_valid_count(cnt_in.second.mask, cnt_in.second.indices, stream);
CUDF_EXPECTS(
std::none_of(valid_counts.cbegin(),
valid_counts.cend(),
[](auto valid_count) { return valid_count % 8; }),
"There's currently a bug in encoding boolean columns. Suggested workaround is to convert "
"to int8 type."
" Please see https://github.com/rapidsai/cudf/issues/6763 for more information.");
}
hostdevice_2dvector<gpu::encoder_chunk_streams> chunk_streams(
num_columns, segmentation.num_rowgroups(), stream);
for (size_t col_idx = 0; col_idx < num_columns; col_idx++) {
auto const& column = orc_table.column(col_idx);
auto col_streams = chunk_streams[col_idx];
for (auto const& stripe : segmentation.stripes) {
for (auto rg_idx_it = stripe.cbegin(); rg_idx_it < stripe.cend(); ++rg_idx_it) {
auto const rg_idx = *rg_idx_it;
auto const& ck = chunks[col_idx][rg_idx];
auto& strm = col_streams[rg_idx];
for (int strm_type = 0; strm_type < gpu::CI_NUM_STREAMS; ++strm_type) {
auto const strm_id = streams.id(col_idx * gpu::CI_NUM_STREAMS + strm_type);
strm.ids[strm_type] = strm_id;
if (strm_id >= 0) {
if ((strm_type == gpu::CI_DICTIONARY) ||
(strm_type == gpu::CI_DATA2 && ck.encoding_kind == DICTIONARY_V2)) {
if (rg_idx_it == stripe.cbegin()) {
const int32_t dict_stride = column.dict_stride();
const auto stripe_dict = column.host_stripe_dict(stripe.id);
strm.lengths[strm_type] =
(strm_type == gpu::CI_DICTIONARY)
? stripe_dict->dict_char_count
: (((stripe_dict->num_strings + 0x1ff) >> 9) * (512 * 4 + 2));
if (stripe.id == 0) {
strm.data_ptrs[strm_type] = encoded_data.data() + stream_offsets.offsets[strm_id];
// Dictionary lengths are encoded as RLE, which are all stored after non-RLE data:
// include non-RLE data size in the offset only in that case
if (strm_type == gpu::CI_DATA2 && ck.encoding_kind == DICTIONARY_V2)
strm.data_ptrs[strm_type] += stream_offsets.non_rle_data_size;
} else {
auto const& strm_up = col_streams[stripe_dict[-dict_stride].start_chunk];
strm.data_ptrs[strm_type] =
strm_up.data_ptrs[strm_type] + strm_up.lengths[strm_type];
}
} else {
strm.lengths[strm_type] = 0;
strm.data_ptrs[strm_type] = col_streams[rg_idx - 1].data_ptrs[strm_type];
}
} else if (strm_type == gpu::CI_DATA && ck.type_kind == TypeKind::STRING &&
ck.encoding_kind == DIRECT_V2) {
strm.lengths[strm_type] = column.host_dict_chunk(rg_idx)->string_char_count;
strm.data_ptrs[strm_type] = (rg_idx == 0)
? encoded_data.data() + stream_offsets.offsets[strm_id]
: (col_streams[rg_idx - 1].data_ptrs[strm_type] +
col_streams[rg_idx - 1].lengths[strm_type]);
} else if (strm_type == gpu::CI_DATA && streams[strm_id].length == 0 &&
(ck.type_kind == DOUBLE || ck.type_kind == FLOAT)) {
// Pass-through
strm.lengths[strm_type] = ck.num_rows * ck.dtype_len;
strm.data_ptrs[strm_type] = nullptr;
} else if (ck.type_kind == DECIMAL && strm_type == gpu::CI_DATA) {
strm.lengths[strm_type] = dec_chunk_sizes.rg_sizes.at(col_idx)[rg_idx];
strm.data_ptrs[strm_type] = (rg_idx == 0)
? encoded_data.data() + stream_offsets.offsets[strm_id]
: (col_streams[rg_idx - 1].data_ptrs[strm_type] +
col_streams[rg_idx - 1].lengths[strm_type]);
} else {
strm.lengths[strm_type] = RLE_stream_size(streams.type(strm_id), ck.num_rows);
// RLE encoded streams are stored after all non-RLE streams
strm.data_ptrs[strm_type] =
(rg_idx == 0) ? (encoded_data.data() + stream_offsets.non_rle_data_size +
stream_offsets.offsets[strm_id])
: (col_streams[rg_idx - 1].data_ptrs[strm_type] +
col_streams[rg_idx - 1].lengths[strm_type]);
}
} else {
strm.lengths[strm_type] = 0;
strm.data_ptrs[strm_type] = nullptr;
}
}
}
}
}
chunk_streams.host_to_device(stream);
if (orc_table.num_rows() > 0) {
if (orc_table.num_string_columns() != 0) {
auto d_stripe_dict = orc_table.string_column(0).device_stripe_dict();
gpu::EncodeStripeDictionaries(d_stripe_dict,
chunks,
orc_table.num_string_columns(),