-
Notifications
You must be signed in to change notification settings - Fork 915
/
writer_impl.cu
2830 lines (2526 loc) · 120 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-2024, NVIDIA CORPORATION.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* @file writer_impl.cu
* @brief cuDF-IO parquet writer class implementation
*/
#include "arrow_schema_writer.hpp"
#include "compact_protocol_reader.hpp"
#include "compact_protocol_writer.hpp"
#include "io/comp/nvcomp_adapter.hpp"
#include "io/parquet/parquet.hpp"
#include "io/parquet/parquet_gpu.hpp"
#include "io/statistics/column_statistics.cuh"
#include "io/utilities/column_utils.cuh"
#include "parquet_common.hpp"
#include "parquet_gpu.cuh"
#include "writer_impl.hpp"
#include "writer_impl_helpers.hpp"
#include <cudf/column/column_device_view.cuh>
#include <cudf/copying.hpp>
#include <cudf/detail/get_value.cuh>
#include <cudf/detail/utilities/integer_utils.hpp>
#include <cudf/detail/utilities/linked_column.hpp>
#include <cudf/detail/utilities/logger.hpp>
#include <cudf/detail/utilities/vector_factories.hpp>
#include <cudf/lists/detail/dremel.hpp>
#include <cudf/lists/lists_column_view.hpp>
#include <cudf/table/table_device_view.cuh>
#include <rmm/cuda_stream_view.hpp>
#include <rmm/device_buffer.hpp>
#include <rmm/device_uvector.hpp>
#include <thrust/fill.h>
#include <thrust/for_each.h>
#include <algorithm>
#include <cstring>
#include <iterator>
#include <numeric>
#include <utility>
#ifndef CUDF_VERSION
#error "CUDF_VERSION is not defined"
#endif
namespace cudf::io::parquet::detail {
using namespace cudf::io::detail;
struct aggregate_writer_metadata {
aggregate_writer_metadata(host_span<partition_info const> partitions,
host_span<std::map<std::string, std::string> const> kv_md,
host_span<SchemaElement const> tbl_schema,
size_type num_columns,
statistics_freq stats_granularity,
std::string const arrow_schema_ipc_message)
: version(1),
schema(std::vector<SchemaElement>(tbl_schema.begin(), tbl_schema.end())),
files(partitions.size())
{
for (size_t i = 0; i < partitions.size(); ++i) {
this->files[i].num_rows = partitions[i].num_rows;
}
if (stats_granularity != statistics_freq::STATISTICS_NONE) {
ColumnOrder default_order = {ColumnOrder::TYPE_ORDER};
this->column_orders = std::vector<ColumnOrder>(num_columns, default_order);
}
for (size_t p = 0; p < kv_md.size(); ++p) {
std::transform(kv_md[p].begin(),
kv_md[p].end(),
std::back_inserter(this->files[p].key_value_metadata),
[](auto const& kv) {
return KeyValue{kv.first, kv.second};
});
}
// Append arrow schema to the key-value metadata
if (not arrow_schema_ipc_message.empty()) {
std::for_each(this->files.begin(), this->files.end(), [&](auto& file) {
file.key_value_metadata.emplace_back(KeyValue{ARROW_SCHEMA_KEY, arrow_schema_ipc_message});
});
}
}
aggregate_writer_metadata(aggregate_writer_metadata const&) = default;
void update_files(host_span<partition_info const> partitions)
{
CUDF_EXPECTS(partitions.size() == this->files.size(),
"New partitions must be same size as previously passed number of partitions");
for (size_t i = 0; i < partitions.size(); ++i) {
this->files[i].num_rows += partitions[i].num_rows;
}
}
FileMetaData get_metadata(size_t part)
{
CUDF_EXPECTS(part < files.size(), "Invalid part index queried");
FileMetaData meta{};
meta.version = this->version;
meta.schema = this->schema;
meta.num_rows = this->files[part].num_rows;
meta.row_groups = this->files[part].row_groups;
meta.key_value_metadata = this->files[part].key_value_metadata;
meta.created_by = "cudf version " CUDF_STRINGIFY(CUDF_VERSION);
meta.column_orders = this->column_orders;
return meta;
}
void set_file_paths(host_span<std::string const> column_chunks_file_path)
{
for (size_t p = 0; p < this->files.size(); ++p) {
auto& file = this->files[p];
auto const& file_path = column_chunks_file_path[p];
for (auto& rowgroup : file.row_groups) {
for (auto& col : rowgroup.columns) {
col.file_path = file_path;
}
}
}
}
FileMetaData get_merged_metadata()
{
FileMetaData merged_md;
for (size_t p = 0; p < this->files.size(); ++p) {
auto& file = this->files[p];
if (p == 0) {
merged_md = this->get_metadata(0);
} else {
merged_md.row_groups.insert(merged_md.row_groups.end(),
std::make_move_iterator(file.row_groups.begin()),
std::make_move_iterator(file.row_groups.end()));
merged_md.num_rows += file.num_rows;
}
}
return merged_md;
}
std::vector<size_t> num_row_groups_per_file()
{
std::vector<size_t> global_rowgroup_base;
std::transform(this->files.begin(),
this->files.end(),
std::back_inserter(global_rowgroup_base),
[](auto const& part) { return part.row_groups.size(); });
return global_rowgroup_base;
}
[[nodiscard]] bool schema_matches(std::vector<SchemaElement> const& schema) const
{
return this->schema == schema;
}
auto& file(size_t p) { return files[p]; }
[[nodiscard]] size_t num_files() const { return files.size(); }
private:
int32_t version = 0;
std::vector<SchemaElement> schema;
struct per_file_metadata {
int64_t num_rows = 0;
std::vector<RowGroup> row_groups;
std::vector<KeyValue> key_value_metadata;
std::vector<OffsetIndex> offset_indexes;
std::vector<std::vector<uint8_t>> column_indexes;
};
std::vector<per_file_metadata> files;
thrust::optional<std::vector<ColumnOrder>> column_orders = thrust::nullopt;
};
namespace {
/**
* @brief Convert a mask of encodings to a vector.
*
* @param encodings Vector of `Encoding`s to populate
* @param enc_mask Mask of encodings used
*/
void update_chunk_encodings(std::vector<Encoding>& encodings, uint32_t enc_mask)
{
for (uint8_t enc = 0; enc < static_cast<uint8_t>(Encoding::NUM_ENCODINGS); enc++) {
auto const enc_enum = static_cast<Encoding>(enc);
if ((enc_mask & encoding_to_mask(enc_enum)) != 0) { encodings.push_back(enc_enum); }
}
}
/**
* @brief Update the encoding_stats field in the column chunk metadata.
*
* @param chunk_meta The `ColumnChunkMetaData` struct for the column chunk
* @param ck The column chunk to summarize stats for
* @param is_v2 True if V2 page headers are used
*/
void update_chunk_encoding_stats(ColumnChunkMetaData& chunk_meta,
EncColumnChunk const& ck,
bool is_v2)
{
// don't set encoding stats if there are no pages
if (ck.num_pages == 0) { return; }
// NOTE: since cudf doesn't use mixed encodings for a chunk, we really only need to account
// for the dictionary page (if there is one), and the encoding used for the data pages. We can
// examine the chunk's encodings field to figure out the encodings without having to examine
// the page data.
auto const num_data_pages = static_cast<int32_t>(ck.num_data_pages());
auto const data_page_type = is_v2 ? PageType::DATA_PAGE_V2 : PageType::DATA_PAGE;
std::vector<PageEncodingStats> result;
if (ck.use_dictionary) {
// For dictionary encoding, if V1 then both data and dictionary use PLAIN_DICTIONARY. For V2
// the dictionary uses PLAIN and the data RLE_DICTIONARY.
auto const dict_enc = is_v2 ? Encoding::PLAIN : Encoding::PLAIN_DICTIONARY;
auto const data_enc = is_v2 ? Encoding::RLE_DICTIONARY : Encoding::PLAIN_DICTIONARY;
result.push_back({PageType::DICTIONARY_PAGE, dict_enc, 1});
if (num_data_pages > 0) { result.push_back({data_page_type, data_enc, num_data_pages}); }
} else {
// No dictionary page, the pages are encoded with something other than RLE (unless it's a
// boolean column).
for (auto const enc : chunk_meta.encodings) {
if (enc != Encoding::RLE) {
result.push_back({data_page_type, enc, num_data_pages});
break;
}
}
// if result is empty and we're using V2 headers, then assume the data is RLE as well
if (result.empty() and is_v2 and (ck.encodings & encoding_to_mask(Encoding::RLE)) != 0) {
result.push_back({data_page_type, Encoding::RLE, num_data_pages});
}
}
if (not result.empty()) { chunk_meta.encoding_stats = std::move(result); }
}
/**
* @brief Compute size (in bytes) of the data stored in the given column.
*
* @param column The input column
* @param stream CUDA stream used for device memory operations and kernel launches
* @return The data size of the input
*/
size_t column_size(column_view const& column, rmm::cuda_stream_view stream)
{
if (column.is_empty()) { return 0; }
if (is_fixed_width(column.type())) {
return size_of(column.type()) * column.size();
} else if (column.type().id() == type_id::STRING) {
auto const scol = strings_column_view(column);
return cudf::strings::detail::get_offset_value(
scol.offsets(), column.size() + column.offset(), stream) -
cudf::strings::detail::get_offset_value(scol.offsets(), column.offset(), stream);
} else if (column.type().id() == type_id::STRUCT) {
auto const scol = structs_column_view(column);
size_t ret = 0;
for (int i = 0; i < scol.num_children(); i++) {
ret += column_size(scol.get_sliced_child(i, stream), stream);
}
return ret;
} else if (column.type().id() == type_id::LIST) {
auto const lcol = lists_column_view(column);
return column_size(lcol.get_sliced_child(stream), stream);
}
CUDF_FAIL("Unexpected compound type");
}
/**
* @brief Extends SchemaElement to add members required in constructing parquet_column_view
*
* Added members are:
* 1. leaf_column: Pointer to leaf linked_column_view which points to the corresponding data stream
* of a leaf schema node. For non-leaf struct node, this is nullptr.
* 2. stats_dtype: datatype for statistics calculation required for the data stream of a leaf node.
* 3. ts_scale: scale to multiply or divide timestamp by in order to convert timestamp to parquet
* supported types
* 4. requested_encoding: A user provided encoding to use for the column.
*/
struct schema_tree_node : public SchemaElement {
cudf::detail::LinkedColPtr leaf_column;
statistics_dtype stats_dtype;
int32_t ts_scale;
column_encoding requested_encoding;
bool skip_compression;
// TODO(fut): Think about making schema a class that holds a vector of schema_tree_nodes. The
// function construct_schema_tree could be its constructor. It can have method to get the per
// column nullability given a schema node index corresponding to a leaf schema. Much easier than
// that is a method to get path in schema, given a leaf node
};
struct leaf_schema_fn {
schema_tree_node& col_schema;
cudf::detail::LinkedColPtr const& col;
column_in_metadata const& col_meta;
bool timestamp_is_int96;
bool timestamp_is_utc;
bool write_arrow_schema;
template <typename T>
std::enable_if_t<std::is_same_v<T, bool>, void> operator()()
{
col_schema.type = Type::BOOLEAN;
col_schema.stats_dtype = statistics_dtype::dtype_bool;
// BOOLEAN needs no converted or logical type
}
template <typename T>
std::enable_if_t<std::is_same_v<T, int8_t>, void> operator()()
{
col_schema.type = Type::INT32;
col_schema.converted_type = ConvertedType::INT_8;
col_schema.stats_dtype = statistics_dtype::dtype_int8;
col_schema.logical_type = LogicalType{IntType{8, true}};
}
template <typename T>
std::enable_if_t<std::is_same_v<T, int16_t>, void> operator()()
{
col_schema.type = Type::INT32;
col_schema.converted_type = ConvertedType::INT_16;
col_schema.stats_dtype = statistics_dtype::dtype_int16;
col_schema.logical_type = LogicalType{IntType{16, true}};
}
template <typename T>
std::enable_if_t<std::is_same_v<T, int32_t>, void> operator()()
{
col_schema.type = Type::INT32;
col_schema.stats_dtype = statistics_dtype::dtype_int32;
// INT32 needs no converted or logical type
}
template <typename T>
std::enable_if_t<std::is_same_v<T, int64_t>, void> operator()()
{
col_schema.type = Type::INT64;
col_schema.stats_dtype = statistics_dtype::dtype_int64;
// INT64 needs no converted or logical type
}
template <typename T>
std::enable_if_t<std::is_same_v<T, uint8_t>, void> operator()()
{
col_schema.type = Type::INT32;
col_schema.converted_type = ConvertedType::UINT_8;
col_schema.stats_dtype = statistics_dtype::dtype_int8;
col_schema.logical_type = LogicalType{IntType{8, false}};
}
template <typename T>
std::enable_if_t<std::is_same_v<T, uint16_t>, void> operator()()
{
col_schema.type = Type::INT32;
col_schema.converted_type = ConvertedType::UINT_16;
col_schema.stats_dtype = statistics_dtype::dtype_int16;
col_schema.logical_type = LogicalType{IntType{16, false}};
}
template <typename T>
std::enable_if_t<std::is_same_v<T, uint32_t>, void> operator()()
{
col_schema.type = Type::INT32;
col_schema.converted_type = ConvertedType::UINT_32;
col_schema.stats_dtype = statistics_dtype::dtype_int32;
col_schema.logical_type = LogicalType{IntType{32, false}};
}
template <typename T>
std::enable_if_t<std::is_same_v<T, uint64_t>, void> operator()()
{
col_schema.type = Type::INT64;
col_schema.converted_type = ConvertedType::UINT_64;
col_schema.stats_dtype = statistics_dtype::dtype_int64;
col_schema.logical_type = LogicalType{IntType{64, false}};
}
template <typename T>
std::enable_if_t<std::is_same_v<T, float>, void> operator()()
{
col_schema.type = Type::FLOAT;
col_schema.stats_dtype = statistics_dtype::dtype_float32;
// FLOAT needs no converted or logical type
}
template <typename T>
std::enable_if_t<std::is_same_v<T, double>, void> operator()()
{
col_schema.type = Type::DOUBLE;
col_schema.stats_dtype = statistics_dtype::dtype_float64;
// DOUBLE needs no converted or logical type
}
template <typename T>
std::enable_if_t<std::is_same_v<T, cudf::string_view>, void> operator()()
{
col_schema.type = Type::BYTE_ARRAY;
if (col_meta.is_enabled_output_as_binary()) {
col_schema.stats_dtype = statistics_dtype::dtype_byte_array;
// BYTE_ARRAY needs no converted or logical type
} else {
col_schema.converted_type = ConvertedType::UTF8;
col_schema.stats_dtype = statistics_dtype::dtype_string;
col_schema.logical_type = LogicalType{LogicalType::STRING};
}
}
template <typename T>
std::enable_if_t<std::is_same_v<T, cudf::timestamp_D>, void> operator()()
{
col_schema.type = Type::INT32;
col_schema.converted_type = ConvertedType::DATE;
col_schema.stats_dtype = statistics_dtype::dtype_int32;
col_schema.logical_type = LogicalType{LogicalType::DATE};
}
template <typename T>
std::enable_if_t<std::is_same_v<T, cudf::timestamp_s>, void> operator()()
{
col_schema.type = (timestamp_is_int96) ? Type::INT96 : Type::INT64;
col_schema.stats_dtype = statistics_dtype::dtype_timestamp64;
col_schema.ts_scale = 1000;
if (not timestamp_is_int96) {
col_schema.converted_type = ConvertedType::TIMESTAMP_MILLIS;
col_schema.logical_type = LogicalType{TimestampType{timestamp_is_utc, TimeUnit::MILLIS}};
}
}
template <typename T>
std::enable_if_t<std::is_same_v<T, cudf::timestamp_ms>, void> operator()()
{
col_schema.type = (timestamp_is_int96) ? Type::INT96 : Type::INT64;
col_schema.stats_dtype = statistics_dtype::dtype_timestamp64;
if (not timestamp_is_int96) {
col_schema.converted_type = ConvertedType::TIMESTAMP_MILLIS;
col_schema.logical_type = LogicalType{TimestampType{timestamp_is_utc, TimeUnit::MILLIS}};
}
}
template <typename T>
std::enable_if_t<std::is_same_v<T, cudf::timestamp_us>, void> operator()()
{
col_schema.type = (timestamp_is_int96) ? Type::INT96 : Type::INT64;
col_schema.stats_dtype = statistics_dtype::dtype_timestamp64;
if (not timestamp_is_int96) {
col_schema.converted_type = ConvertedType::TIMESTAMP_MICROS;
col_schema.logical_type = LogicalType{TimestampType{timestamp_is_utc, TimeUnit::MICROS}};
}
}
template <typename T>
std::enable_if_t<std::is_same_v<T, cudf::timestamp_ns>, void> operator()()
{
col_schema.type = (timestamp_is_int96) ? Type::INT96 : Type::INT64;
col_schema.converted_type = thrust::nullopt;
col_schema.stats_dtype = statistics_dtype::dtype_timestamp64;
if (timestamp_is_int96) {
col_schema.ts_scale = -1000; // negative value indicates division by absolute value
}
// set logical type if it's not int96
else {
col_schema.logical_type = LogicalType{TimestampType{timestamp_is_utc, TimeUnit::NANOS}};
}
}
template <typename T>
std::enable_if_t<std::is_same_v<T, cudf::duration_D>, void> operator()()
{
// duration_D is based on int32_t and not a valid arrow duration type so simply convert to
// time32(ms).
col_schema.type = Type::INT32;
col_schema.converted_type = ConvertedType::TIME_MILLIS;
col_schema.stats_dtype = statistics_dtype::dtype_int32;
col_schema.ts_scale = 24 * 60 * 60 * 1000;
col_schema.logical_type = LogicalType{TimeType{timestamp_is_utc, TimeUnit::MILLIS}};
}
template <typename T>
std::enable_if_t<std::is_same_v<T, cudf::duration_s>, void> operator()()
{
// If writing arrow schema, no logical type nor converted type is necessary
if (write_arrow_schema) {
col_schema.type = Type::INT64;
col_schema.stats_dtype = statistics_dtype::dtype_int64;
} else {
// Write as Time32 logical type otherwise. Parquet TIME_MILLIS annotates INT32
col_schema.type = Type::INT32;
col_schema.stats_dtype = statistics_dtype::dtype_int32;
col_schema.converted_type = ConvertedType::TIME_MILLIS;
col_schema.logical_type = LogicalType{TimeType{timestamp_is_utc, TimeUnit::MILLIS}};
col_schema.ts_scale = 1000;
}
}
template <typename T>
std::enable_if_t<std::is_same_v<T, cudf::duration_ms>, void> operator()()
{
// If writing arrow schema, no logical type nor converted type is necessary
if (write_arrow_schema) {
col_schema.type = Type::INT64;
col_schema.stats_dtype = statistics_dtype::dtype_int64;
} else {
// Write as Time32 logical type otherwise. Parquet TIME_MILLIS annotates INT32
col_schema.type = Type::INT32;
col_schema.stats_dtype = statistics_dtype::dtype_int32;
col_schema.converted_type = ConvertedType::TIME_MILLIS;
col_schema.logical_type = LogicalType{TimeType{timestamp_is_utc, TimeUnit::MILLIS}};
}
}
template <typename T>
std::enable_if_t<std::is_same_v<T, cudf::duration_us>, void> operator()()
{
col_schema.type = Type::INT64;
col_schema.stats_dtype = statistics_dtype::dtype_int64;
// Only write as time64 logical type if not writing arrow schema
if (not write_arrow_schema) {
col_schema.converted_type = ConvertedType::TIME_MICROS;
col_schema.logical_type = LogicalType{TimeType{timestamp_is_utc, TimeUnit::MICROS}};
}
}
template <typename T>
std::enable_if_t<std::is_same_v<T, cudf::duration_ns>, void> operator()()
{
col_schema.type = Type::INT64;
col_schema.stats_dtype = statistics_dtype::dtype_int64;
// Only write as time64 logical type if not writing arrow schema
if (not write_arrow_schema) {
col_schema.logical_type = LogicalType{TimeType{timestamp_is_utc, TimeUnit::NANOS}};
}
}
template <typename T>
std::enable_if_t<cudf::is_fixed_point<T>(), void> operator()()
{
// If writing arrow schema, then convert d32 and d64 to d128
if (write_arrow_schema or std::is_same_v<T, numeric::decimal128>) {
col_schema.type = Type::FIXED_LEN_BYTE_ARRAY;
col_schema.type_length = sizeof(__int128_t);
col_schema.stats_dtype = statistics_dtype::dtype_decimal128;
col_schema.decimal_precision = MAX_DECIMAL128_PRECISION;
col_schema.logical_type = LogicalType{DecimalType{0, MAX_DECIMAL128_PRECISION}};
} else {
if (std::is_same_v<T, numeric::decimal32>) {
col_schema.type = Type::INT32;
col_schema.stats_dtype = statistics_dtype::dtype_int32;
col_schema.decimal_precision = MAX_DECIMAL32_PRECISION;
col_schema.logical_type = LogicalType{DecimalType{0, MAX_DECIMAL32_PRECISION}};
} else if (std::is_same_v<T, numeric::decimal64>) {
col_schema.type = Type::INT64;
col_schema.stats_dtype = statistics_dtype::dtype_decimal64;
col_schema.decimal_precision = MAX_DECIMAL64_PRECISION;
col_schema.logical_type = LogicalType{DecimalType{0, MAX_DECIMAL64_PRECISION}};
} else {
CUDF_FAIL("Unsupported fixed point type for parquet writer");
}
}
// Write logical and converted types, decimal scale and precision
col_schema.converted_type = ConvertedType::DECIMAL;
col_schema.decimal_scale = -col->type().scale(); // parquet and cudf disagree about scale signs
col_schema.logical_type->decimal_type->scale = -col->type().scale();
if (col_meta.is_decimal_precision_set()) {
CUDF_EXPECTS(col_meta.get_decimal_precision() >= col_schema.decimal_scale,
"Precision must be equal to or greater than scale!");
if (col_schema.type == Type::INT64 and col_meta.get_decimal_precision() < 10) {
CUDF_LOG_WARN("Parquet writer: writing a decimal column with precision < 10 as int64");
}
col_schema.decimal_precision = col_meta.get_decimal_precision();
col_schema.logical_type->decimal_type->precision = col_meta.get_decimal_precision();
}
}
template <typename T>
std::enable_if_t<cudf::is_nested<T>(), void> operator()()
{
CUDF_FAIL("This functor is only meant for physical data types");
}
template <typename T>
std::enable_if_t<cudf::is_dictionary<T>(), void> operator()()
{
CUDF_FAIL("Dictionary columns are not supported for writing");
}
};
/**
* @brief Construct schema from input columns and per-column input options
*
* Recursively traverses through linked_columns and corresponding metadata to construct schema tree.
* The resulting schema tree is stored in a vector in pre-order traversal order.
*/
std::vector<schema_tree_node> construct_parquet_schema_tree(
cudf::detail::LinkedColVector const& linked_columns,
table_input_metadata& metadata,
single_write_mode write_mode,
bool int96_timestamps,
bool utc_timestamps,
bool write_arrow_schema)
{
std::vector<schema_tree_node> schema;
schema_tree_node root{};
root.type = UNDEFINED_TYPE;
root.repetition_type = NO_REPETITION_TYPE;
root.name = "schema";
root.num_children = linked_columns.size();
root.parent_idx = -1; // root schema has no parent
schema.push_back(std::move(root));
std::function<void(cudf::detail::LinkedColPtr const&, column_in_metadata&, size_t)> add_schema =
[&](cudf::detail::LinkedColPtr const& col, column_in_metadata& col_meta, size_t parent_idx) {
bool const col_nullable = is_output_column_nullable(col, col_meta, write_mode);
auto set_field_id = [&schema, parent_idx](schema_tree_node& s,
column_in_metadata const& col_meta) {
if (schema[parent_idx].name != "list" and col_meta.is_parquet_field_id_set()) {
s.field_id = col_meta.get_parquet_field_id();
}
};
auto is_last_list_child = [](cudf::detail::LinkedColPtr col) {
if (col->type().id() != type_id::LIST) { return false; }
auto const child_col_type =
col->children[lists_column_view::child_column_index]->type().id();
return child_col_type == type_id::UINT8;
};
// only call this after col_schema.type has been set
auto set_encoding = [&schema, parent_idx](schema_tree_node& s,
column_in_metadata const& col_meta) {
s.requested_encoding = column_encoding::USE_DEFAULT;
if (s.name != "list" and col_meta.get_encoding() != column_encoding::USE_DEFAULT) {
// do some validation
switch (col_meta.get_encoding()) {
case column_encoding::DELTA_BINARY_PACKED:
if (s.type != Type::INT32 && s.type != Type::INT64) {
CUDF_LOG_WARN(
"DELTA_BINARY_PACKED encoding is only supported for INT32 and INT64 columns; the "
"requested encoding will be ignored");
return;
}
break;
case column_encoding::DELTA_LENGTH_BYTE_ARRAY:
if (s.type != Type::BYTE_ARRAY) {
CUDF_LOG_WARN(
"DELTA_LENGTH_BYTE_ARRAY encoding is only supported for BYTE_ARRAY columns; the "
"requested encoding will be ignored");
return;
}
// we don't yet allow encoding decimal128 with DELTA_LENGTH_BYTE_ARRAY (nor with
// the BYTE_ARRAY physical type, but check anyway)
if (s.converted_type.value_or(ConvertedType::UNKNOWN) == ConvertedType::DECIMAL) {
CUDF_LOG_WARN(
"Decimal types cannot yet be encoded as DELTA_LENGTH_BYTE_ARRAY; the "
"requested encoding will be ignored");
return;
}
break;
case column_encoding::DELTA_BYTE_ARRAY:
if (s.type != Type::BYTE_ARRAY && s.type != Type::FIXED_LEN_BYTE_ARRAY) {
CUDF_LOG_WARN(
"DELTA_BYTE_ARRAY encoding is only supported for BYTE_ARRAY and "
"FIXED_LEN_BYTE_ARRAY columns; the requested encoding will be ignored");
return;
}
// we don't yet allow encoding decimal128 with DELTA_BYTE_ARRAY
if (s.converted_type.value_or(ConvertedType::UNKNOWN) == ConvertedType::DECIMAL) {
CUDF_LOG_WARN(
"Decimal types cannot yet be encoded as DELTA_BYTE_ARRAY; the "
"requested encoding will be ignored");
return;
}
break;
case column_encoding::BYTE_STREAM_SPLIT:
if (s.type == Type::BYTE_ARRAY) {
CUDF_LOG_WARN(
"BYTE_STREAM_SPLIT encoding is only supported for fixed width columns; the "
"requested encoding will be ignored");
return;
}
if (s.type == Type::INT96) {
CUDF_LOG_WARN(
"BYTE_STREAM_SPLIT encoding is not supported for INT96 columns; the "
"requested encoding will be ignored");
return;
}
break;
// supported parquet encodings
case column_encoding::PLAIN:
case column_encoding::DICTIONARY: break;
// all others
default:
CUDF_LOG_WARN(
"Unsupported page encoding requested: {}; the requested encoding will be ignored",
static_cast<int>(col_meta.get_encoding()));
return;
}
// requested encoding seems to be ok, set it
s.requested_encoding = col_meta.get_encoding();
}
};
// There is a special case for a list<int8> column with one byte column child. This column can
// have a special flag that indicates we write this out as binary instead of a list. This is a
// more efficient storage mechanism for a single-depth list of bytes, but is a departure from
// original cuIO behavior so it is locked behind the option. If the option is selected on a
// column that isn't a single-depth list<int8> the code will throw.
if (col_meta.is_enabled_output_as_binary() && is_last_list_child(col)) {
CUDF_EXPECTS(col_meta.num_children() == 2 or col_meta.num_children() == 0,
"Binary column's corresponding metadata should have zero or two children");
if (col_meta.num_children() > 0) {
CUDF_EXPECTS(col->children[lists_column_view::child_column_index]->children.empty(),
"Binary column must not be nested");
}
schema_tree_node col_schema{};
// test if this should be output as FIXED_LEN_BYTE_ARRAY
if (col_meta.is_type_length_set()) {
col_schema.type = Type::FIXED_LEN_BYTE_ARRAY;
col_schema.type_length = col_meta.get_type_length();
} else {
col_schema.type = Type::BYTE_ARRAY;
}
col_schema.converted_type = thrust::nullopt;
col_schema.stats_dtype = statistics_dtype::dtype_byte_array;
col_schema.repetition_type = col_nullable ? OPTIONAL : REQUIRED;
col_schema.name = (schema[parent_idx].name == "list") ? "element" : col_meta.get_name();
col_schema.parent_idx = parent_idx;
col_schema.leaf_column = col;
set_field_id(col_schema, col_meta);
set_encoding(col_schema, col_meta);
col_schema.output_as_byte_array = col_meta.is_enabled_output_as_binary();
col_schema.skip_compression = col_meta.is_enabled_skip_compression();
schema.push_back(col_schema);
} else if (col->type().id() == type_id::STRUCT) {
// if struct, add current and recursively call for all children
schema_tree_node struct_schema{};
struct_schema.repetition_type =
col_nullable ? FieldRepetitionType::OPTIONAL : FieldRepetitionType::REQUIRED;
struct_schema.name = (schema[parent_idx].name == "list") ? "element" : col_meta.get_name();
struct_schema.num_children = col->children.size();
struct_schema.parent_idx = parent_idx;
set_field_id(struct_schema, col_meta);
schema.push_back(std::move(struct_schema));
auto struct_node_index = schema.size() - 1;
// for (auto child_it = col->children.begin(); child_it < col->children.end(); child_it++) {
// add_schema(*child_it, struct_node_index);
// }
CUDF_EXPECTS(col->children.size() == static_cast<size_t>(col_meta.num_children()),
"Mismatch in number of child columns between input table and metadata");
for (size_t i = 0; i < col->children.size(); ++i) {
add_schema(col->children[i], col_meta.child(i), struct_node_index);
}
} else if (col->type().id() == type_id::LIST && !col_meta.is_map()) {
// List schema is denoted by two levels for each nesting level and one final level for leaf.
// The top level is the same name as the column name.
// So e.g. List<List<int>> is denoted in the schema by
// "col_name" : { "list" : { "element" : { "list" : { "element" } } } }
schema_tree_node list_schema_1{};
list_schema_1.converted_type = ConvertedType::LIST;
list_schema_1.repetition_type =
col_nullable ? FieldRepetitionType::OPTIONAL : FieldRepetitionType::REQUIRED;
list_schema_1.name = (schema[parent_idx].name == "list") ? "element" : col_meta.get_name();
list_schema_1.num_children = 1;
list_schema_1.parent_idx = parent_idx;
set_field_id(list_schema_1, col_meta);
schema.push_back(std::move(list_schema_1));
schema_tree_node list_schema_2{};
list_schema_2.repetition_type = FieldRepetitionType::REPEATED;
list_schema_2.name = "list";
list_schema_2.num_children = 1;
list_schema_2.parent_idx = schema.size() - 1; // Parent is list_schema_1, last added.
schema.push_back(std::move(list_schema_2));
CUDF_EXPECTS(col_meta.num_children() == 2,
"List column's metadata should have exactly two children");
add_schema(col->children[lists_column_view::child_column_index],
col_meta.child(lists_column_view::child_column_index),
schema.size() - 1);
} else if (col->type().id() == type_id::LIST && col_meta.is_map()) {
// Map schema is denoted by a list of struct
// e.g. List<Struct<String,String>> will be
// "col_name" : { "key_value" : { "key", "value" } }
// verify the List child structure is a struct<left_child, right_child>
column_view struct_col = *col->children[lists_column_view::child_column_index];
CUDF_EXPECTS(struct_col.type().id() == type_id::STRUCT, "Map should be a List of struct");
CUDF_EXPECTS(struct_col.num_children() == 2,
"Map should be a List of struct with two children only but found " +
std::to_string(struct_col.num_children()));
schema_tree_node map_schema{};
map_schema.converted_type = ConvertedType::MAP;
map_schema.repetition_type =
col_nullable ? FieldRepetitionType::OPTIONAL : FieldRepetitionType::REQUIRED;
map_schema.name = col_meta.get_name();
if (col_meta.is_parquet_field_id_set()) {
map_schema.field_id = col_meta.get_parquet_field_id();
}
map_schema.num_children = 1;
map_schema.parent_idx = parent_idx;
schema.push_back(std::move(map_schema));
schema_tree_node repeat_group{};
repeat_group.repetition_type = FieldRepetitionType::REPEATED;
repeat_group.name = "key_value";
repeat_group.num_children = 2;
repeat_group.parent_idx = schema.size() - 1; // Parent is map_schema, last added.
schema.push_back(std::move(repeat_group));
CUDF_EXPECTS(col_meta.num_children() == 2,
"List column's metadata should have exactly two children");
CUDF_EXPECTS(col_meta.child(lists_column_view::child_column_index).num_children() == 2,
"Map struct column should have exactly two children");
// verify the col meta of children of the struct have name key and value
auto& left_child_meta = col_meta.child(lists_column_view::child_column_index).child(0);
left_child_meta.set_name("key");
left_child_meta.set_nullability(false);
auto& right_child_meta = col_meta.child(lists_column_view::child_column_index).child(1);
right_child_meta.set_name("value");
// check the repetition type of key is required i.e. the col should be non-nullable
auto key_col = col->children[lists_column_view::child_column_index]->children[0];
CUDF_EXPECTS(!is_output_column_nullable(key_col, left_child_meta, write_mode),
"key column cannot be nullable. For chunked writing, explicitly set the "
"nullability to false in metadata");
// process key
size_type struct_col_index = schema.size() - 1;
add_schema(key_col, left_child_meta, struct_col_index);
// process value
add_schema(col->children[lists_column_view::child_column_index]->children[1],
right_child_meta,
struct_col_index);
} else {
// if leaf, add current
if (col->type().id() == type_id::STRING) {
if (col_meta.is_enabled_output_as_binary()) {
CUDF_EXPECTS(col_meta.num_children() == 2 or col_meta.num_children() == 0,
"Binary column's corresponding metadata should have zero or two children");
} else {
CUDF_EXPECTS(col_meta.num_children() == 1 or col_meta.num_children() == 0,
"String column's corresponding metadata should have zero or one children");
}
} else {
CUDF_EXPECTS(col_meta.num_children() == 0,
"Leaf column's corresponding metadata cannot have children");
}
schema_tree_node col_schema{};
bool timestamp_is_int96 = int96_timestamps or col_meta.is_enabled_int96_timestamps();
cudf::type_dispatcher(
col->type(),
leaf_schema_fn{
col_schema, col, col_meta, timestamp_is_int96, utc_timestamps, write_arrow_schema});
col_schema.repetition_type = col_nullable ? OPTIONAL : REQUIRED;
col_schema.name = (schema[parent_idx].name == "list") ? "element" : col_meta.get_name();
col_schema.parent_idx = parent_idx;
col_schema.leaf_column = col;
set_field_id(col_schema, col_meta);
set_encoding(col_schema, col_meta);
col_schema.skip_compression = col_meta.is_enabled_skip_compression();
schema.push_back(col_schema);
}
};
CUDF_EXPECTS(metadata.column_metadata.size() == linked_columns.size(),
"Mismatch in the number of columns and the corresponding metadata elements");
// Add all linked_columns to schema using parent_idx = 0 (root)
for (size_t i = 0; i < linked_columns.size(); ++i) {
add_schema(linked_columns[i], metadata.column_metadata[i], 0);
}
return schema;
}
/**
* @brief Class to store parquet specific information for one data stream.
*
* Contains information about a single data stream. In case of struct columns, a data stream is one
* of the child leaf columns that contains data.
* e.g. A column Struct<int, List<float>> contains 2 data streams:
* - Struct<int>
* - Struct<List<float>>
*
*/
struct parquet_column_view {
parquet_column_view(schema_tree_node const& schema_node,
std::vector<schema_tree_node> const& schema_tree,
rmm::cuda_stream_view stream);
[[nodiscard]] parquet_column_device_view get_device_view(rmm::cuda_stream_view stream) const;
[[nodiscard]] column_view cudf_column_view() const { return cudf_col; }
[[nodiscard]] Type physical_type() const { return schema_node.type; }
[[nodiscard]] ConvertedType converted_type() const
{
return schema_node.converted_type.value_or(UNKNOWN);
}
// Checks to see if the given column has a fixed-width data type. This doesn't
// check every value, so it assumes string and list columns are not fixed-width, even
// if each value has the same size.
[[nodiscard]] bool is_fixed_width() const
{
// lists and strings are not fixed width
return max_rep_level() == 0 and physical_type() != Type::BYTE_ARRAY;
}
std::vector<std::string> const& get_path_in_schema() { return path_in_schema; }
// LIST related member functions
[[nodiscard]] uint8_t max_def_level() const noexcept { return _max_def_level; }
[[nodiscard]] uint8_t max_rep_level() const noexcept { return _max_rep_level; }
[[nodiscard]] bool is_list() const noexcept { return _is_list; }
private:
// Schema related members
schema_tree_node schema_node;
std::vector<std::string> path_in_schema;
uint8_t _max_def_level = 0;
uint8_t _max_rep_level = 0;
rmm::device_uvector<uint8_t> _d_nullability;
column_view cudf_col;
// List-related members
bool _is_list;
rmm::device_uvector<size_type>
_dremel_offsets; ///< For each row, the absolute offset into the repetition and definition
///< level vectors. O(num rows)
rmm::device_uvector<uint8_t> _rep_level;
rmm::device_uvector<uint8_t> _def_level;
std::vector<uint8_t> _nullability;
size_type _data_count = 0;
};
parquet_column_view::parquet_column_view(schema_tree_node const& schema_node,
std::vector<schema_tree_node> const& schema_tree,
rmm::cuda_stream_view stream)
: schema_node(schema_node),
_d_nullability(0, stream),
_dremel_offsets(0, stream),
_rep_level(0, stream),
_def_level(0, stream)
{
// Construct single inheritance column_view from linked_column_view
auto curr_col = schema_node.leaf_column.get();
column_view single_inheritance_cudf_col = *curr_col;
while (curr_col->parent) {
auto const& parent = *curr_col->parent;
// For list columns, we still need to retain the offset child column.
auto children =
(parent.type().id() == type_id::LIST)
? std::vector<column_view>{*parent.children[lists_column_view::offsets_column_index],
single_inheritance_cudf_col}
: std::vector<column_view>{single_inheritance_cudf_col};
single_inheritance_cudf_col = column_view(parent.type(),
parent.size(),
parent.head(),
parent.null_mask(),
parent.null_count(),
parent.offset(),