-
Notifications
You must be signed in to change notification settings - Fork 917
/
reader_impl_chunking.cu
1680 lines (1487 loc) · 68.2 KB
/
reader_impl_chunking.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) 2023-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.
*/
#include "compact_protocol_reader.hpp"
#include "io/comp/nvcomp_adapter.hpp"
#include "io/utilities/config_utils.hpp"
#include "io/utilities/time_utils.cuh"
#include "reader_impl.hpp"
#include "reader_impl_chunking.hpp"
#include <cudf/detail/iterator.cuh>
#include <cudf/detail/nvtx/ranges.hpp>
#include <cudf/detail/utilities/integer_utils.hpp>
#include <cudf/detail/utilities/vector_factories.hpp>
#include <rmm/exec_policy.hpp>
#include <cuda/functional>
#include <thrust/binary_search.h>
#include <thrust/iterator/constant_iterator.h>
#include <thrust/iterator/discard_iterator.h>
#include <thrust/logical.h>
#include <thrust/sort.h>
#include <thrust/transform_scan.h>
#include <thrust/unique.h>
#include <numeric>
namespace cudf::io::parquet::detail {
namespace {
struct split_info {
row_range rows;
int64_t split_pos;
};
struct cumulative_page_info {
size_t end_row_index; // end row index (start_row + num_rows for the corresponding page)
size_t size_bytes; // cumulative size in bytes
int key; // schema index
};
// the minimum amount of memory we can safely expect to be enough to
// do a subpass decode. if the difference between the user specified limit and
// the actual memory used for compressed/temp data is > than this value, we will still use
// at least this many additional bytes.
// Example:
// - user has specified 1 GB limit
// - we have read in 900 MB of compressed data
// - that leaves us 100 MB of space for decompression batches
// - to keep the gpu busy, we really don't want to do less than 200 MB at a time so we're just going
// to use 200 MB of space
// even if that goes past the user-specified limit.
constexpr size_t minimum_subpass_expected_size = 200 * 1024 * 1024;
// percentage of the total available input read limit that should be reserved for compressed
// data vs uncompressed data.
constexpr float input_limit_compression_reserve = 0.3f;
#if defined(CHUNKING_DEBUG)
void print_cumulative_page_info(device_span<PageInfo const> d_pages,
device_span<ColumnChunkDesc const> d_chunks,
device_span<cumulative_page_info const> d_c_info,
rmm::cuda_stream_view stream)
{
std::vector<PageInfo> pages = cudf::detail::make_std_vector_sync(d_pages, stream);
std::vector<ColumnChunkDesc> chunks = cudf::detail::make_std_vector_sync(d_chunks, stream);
std::vector<cumulative_page_info> c_info = cudf::detail::make_std_vector_sync(d_c_info, stream);
printf("------------\nCumulative sizes by page\n");
std::vector<int> schemas(pages.size());
auto schema_iter = cudf::detail::make_counting_transform_iterator(
0, [&](size_type i) { return pages[i].src_col_schema; });
thrust::copy(thrust::seq, schema_iter, schema_iter + pages.size(), schemas.begin());
auto last = thrust::unique(thrust::seq, schemas.begin(), schemas.end());
schemas.resize(last - schemas.begin());
printf("Num schemas: %lu\n", schemas.size());
for (size_t idx = 0; idx < schemas.size(); idx++) {
printf("Schema %d\n", schemas[idx]);
for (size_t pidx = 0; pidx < pages.size(); pidx++) {
auto const& page = pages[pidx];
if (page.flags & PAGEINFO_FLAGS_DICTIONARY || page.src_col_schema != schemas[idx]) {
continue;
}
bool const is_list = chunks[page.chunk_idx].max_level[level_type::REPETITION] > 0;
printf("\tP %s: {%lu, %lu, %lu}\n",
is_list ? "(L)" : "",
pidx,
c_info[pidx].end_row_index,
c_info[pidx].size_bytes);
}
}
}
void print_cumulative_row_info(host_span<cumulative_page_info const> sizes,
std::string const& label,
std::optional<std::vector<row_range>> splits = std::nullopt)
{
if (splits.has_value()) {
printf("------------\nSplits (skip_rows, num_rows)\n");
for (size_t idx = 0; idx < splits->size(); idx++) {
printf("{%lu, %lu}\n", splits.value()[idx].skip_rows, splits.value()[idx].num_rows);
}
}
printf("------------\nCumulative sizes %s (index, row_index, size_bytes, page_key)\n",
label.c_str());
for (size_t idx = 0; idx < sizes.size(); idx++) {
printf(
"{%lu, %lu, %lu, %d}", idx, sizes[idx].end_row_index, sizes[idx].size_bytes, sizes[idx].key);
if (splits.has_value()) {
// if we have a split at this row count and this is the last instance of this row count
auto start = thrust::make_transform_iterator(splits->begin(),
[](row_range const& i) { return i.skip_rows; });
auto end = start + splits->size();
auto split = std::find(start, end, sizes[idx].end_row_index);
auto const split_index = [&]() -> int {
if (split != end && ((idx == sizes.size() - 1) ||
(sizes[idx + 1].end_row_index > sizes[idx].end_row_index))) {
return static_cast<int>(std::distance(start, split));
}
return idx == 0 ? 0 : -1;
}();
if (split_index >= 0) {
printf(" <-- split {%lu, %lu}",
splits.value()[split_index].skip_rows,
splits.value()[split_index].num_rows);
}
}
printf("\n");
}
}
#endif // CHUNKING_DEBUG
/**
* @brief Functor which reduces two cumulative_page_info structs of the same key.
*/
struct cumulative_page_sum {
cumulative_page_info operator()
__device__(cumulative_page_info const& a, cumulative_page_info const& b) const
{
return cumulative_page_info{0, a.size_bytes + b.size_bytes, a.key};
}
};
/**
* @brief Functor which computes the total data size for a given type of cudf column.
*
* In the case of strings, the return size does not include the chars themselves. That
* information is tracked separately (see PageInfo::str_bytes).
*/
struct row_size_functor {
__device__ size_t validity_size(size_t num_rows, bool nullable)
{
return nullable ? (cudf::util::div_rounding_up_safe(num_rows, size_t{32}) * 4) : 0;
}
template <typename T>
__device__ size_t operator()(size_t num_rows, bool nullable)
{
auto const element_size = sizeof(device_storage_type_t<T>);
return (element_size * num_rows) + validity_size(num_rows, nullable);
}
};
template <>
__device__ size_t row_size_functor::operator()<list_view>(size_t num_rows, bool nullable)
{
auto const offset_size = sizeof(size_type);
// NOTE: Adding the + 1 offset here isn't strictly correct. There will only be 1 extra offset
// for the entire column, whereas this is adding an extra offset per page. So we will get a
// small over-estimate of the real size of the order : # of pages * 4 bytes. It seems better
// to overestimate size somewhat than to underestimate it and potentially generate chunks
// that are too large.
return (offset_size * (num_rows + 1)) + validity_size(num_rows, nullable);
}
template <>
__device__ size_t row_size_functor::operator()<struct_view>(size_t num_rows, bool nullable)
{
return validity_size(num_rows, nullable);
}
template <>
__device__ size_t row_size_functor::operator()<string_view>(size_t num_rows, bool nullable)
{
// only returns the size of offsets and validity. the size of the actual string chars
// is tracked separately.
auto const offset_size = sizeof(size_type);
// see note about offsets in the list_view template.
return (offset_size * (num_rows + 1)) + validity_size(num_rows, nullable);
}
/**
* @brief Functor which computes the total output cudf data size for all of
* the data in this page.
*
* Sums across all nesting levels.
*/
struct get_page_output_size {
__device__ cumulative_page_info operator()(PageInfo const& page) const
{
if (page.flags & PAGEINFO_FLAGS_DICTIONARY) {
return cumulative_page_info{0, 0, page.src_col_schema};
}
// total nested size, not counting string data
auto iter = cudf::detail::make_counting_transform_iterator(
0, cuda::proclaim_return_type<size_t>([page] __device__(size_type i) {
auto const& pni = page.nesting[i];
return cudf::type_dispatcher(
data_type{pni.type}, row_size_functor{}, pni.size, pni.nullable);
}));
return {
0,
thrust::reduce(thrust::seq, iter, iter + page.num_output_nesting_levels) + page.str_bytes,
page.src_col_schema};
}
};
/**
* @brief Functor which sets the (uncompressed) size of a page.
*/
struct get_page_input_size {
__device__ cumulative_page_info operator()(PageInfo const& page) const
{
// we treat dictionary page sizes as 0 for subpasses because we have already paid the price for
// them at the pass level.
if (page.flags & PAGEINFO_FLAGS_DICTIONARY) { return {0, 0, page.src_col_schema}; }
return {0, static_cast<size_t>(page.uncompressed_page_size), page.src_col_schema};
}
};
/**
* @brief Functor which sets the absolute row index of a page in a cumulative_page_info struct
*/
struct set_row_index {
device_span<ColumnChunkDesc const> chunks;
device_span<PageInfo const> pages;
device_span<cumulative_page_info> c_info;
size_t max_row;
__device__ void operator()(size_t i)
{
auto const& page = pages[i];
auto const& chunk = chunks[page.chunk_idx];
size_t const page_end_row = chunk.start_row + page.chunk_row + page.num_rows;
// this cap is necessary because in the chunked reader, we use estimations for the row
// counts for list columns, which can result in values > than the absolute number of rows.
c_info[i].end_row_index = min(max_row, page_end_row);
}
};
/**
* @brief Functor which computes the effective size of all input columns by page.
*
* For a given row, we want to find the cost of all pages for all columns involved
* in loading up to that row. The complication here is that not all pages are the
* same size between columns. Example:
*
* page row counts
* Column A: 0 <----> 100 <----> 200
* Column B: 0 <---------------> 200 <--------> 400
|
* if we decide to split at row 100, we don't really know the actual amount of bytes in column B
* at that point. So we have to proceed as if we are taking the bytes from all 200 rows of that
* page. Essentially, a conservative over-estimate of the real size.
*/
struct page_total_size {
cumulative_page_info const* c_info;
size_type const* key_offsets;
size_t num_keys;
__device__ cumulative_page_info operator()(cumulative_page_info const& i) const
{
// sum sizes for each input column at this row
size_t sum = 0;
for (int idx = 0; idx < num_keys; idx++) {
auto const start = key_offsets[idx];
auto const end = key_offsets[idx + 1];
auto iter = cudf::detail::make_counting_transform_iterator(
0, cuda::proclaim_return_type<size_t>([&] __device__(size_type i) {
return c_info[i].end_row_index;
}));
auto const page_index =
thrust::lower_bound(thrust::seq, iter + start, iter + end, i.end_row_index) - iter;
sum += c_info[page_index].size_bytes;
}
return {i.end_row_index, sum, i.key};
}
};
/**
* @brief Functor which returns the compressed data size for a chunk
*/
struct get_chunk_compressed_size {
__device__ size_t operator()(ColumnChunkDesc const& chunk) const { return chunk.compressed_size; }
};
/**
* @brief Find the first entry in the aggreggated_info that corresponds to the specified row
*
*/
size_t find_start_index(cudf::host_span<cumulative_page_info const> aggregated_info,
size_t start_row)
{
auto start = thrust::make_transform_iterator(
aggregated_info.begin(), [&](cumulative_page_info const& i) { return i.end_row_index; });
return thrust::lower_bound(thrust::host, start, start + aggregated_info.size(), start_row) -
start;
}
/**
* @brief Given a current position and row index, find the next split based on the
* specified size limit
*
* @returns The inclusive index within `sizes` where the next split should happen
*
*/
int64_t find_next_split(int64_t cur_pos,
size_t cur_row_index,
size_t cur_cumulative_size,
cudf::host_span<cumulative_page_info const> sizes,
size_t size_limit,
size_t min_row_count)
{
auto const start = thrust::make_transform_iterator(
sizes.begin(),
[&](cumulative_page_info const& i) { return i.size_bytes - cur_cumulative_size; });
auto const end = start + sizes.size();
int64_t split_pos = thrust::lower_bound(thrust::seq, start + cur_pos, end, size_limit) - start;
// if we're past the end, or if the returned bucket is > than the chunk_read_limit, move back
// one as long as this doesn't put us before our starting point.
if (static_cast<size_t>(split_pos) >= sizes.size() ||
((split_pos > cur_pos) && (sizes[split_pos].size_bytes - cur_cumulative_size > size_limit))) {
split_pos--;
}
// move forward until we find the next group of pages that will actually advance our row count.
// this guarantees that even if we cannot fit the set of rows represented by our where our cur_pos
// is, we will still move forward instead of failing.
while (split_pos < (static_cast<int64_t>(sizes.size()) - 1) &&
(sizes[split_pos].end_row_index - cur_row_index < min_row_count)) {
split_pos++;
}
return split_pos;
}
/**
* @brief Converts cuDF units to Parquet units.
*
* @return A tuple of Parquet clock rate and Parquet decimal type.
*/
[[nodiscard]] std::tuple<int32_t, thrust::optional<LogicalType>> conversion_info(
type_id column_type_id,
type_id timestamp_type_id,
Type physical,
thrust::optional<LogicalType> logical_type)
{
int32_t const clock_rate =
is_chrono(data_type{column_type_id}) ? to_clockrate(timestamp_type_id) : 0;
// TODO(ets): this is leftover from the original code, but will we ever output decimal as
// anything but fixed point?
if (logical_type.has_value() and logical_type->type == LogicalType::DECIMAL) {
// if decimal but not outputting as float or decimal, then convert to no logical type
if (column_type_id != type_id::FLOAT64 and
not cudf::is_fixed_point(data_type{column_type_id})) {
return std::make_tuple(clock_rate, thrust::nullopt);
}
}
return std::make_tuple(clock_rate, std::move(logical_type));
}
/**
* @brief Return the required number of bits to store a value.
*/
template <typename T = uint8_t>
[[nodiscard]] T required_bits(uint32_t max_level)
{
return static_cast<T>(CompactProtocolReader::NumRequiredBits(max_level));
}
struct row_count_less {
__device__ bool operator()(cumulative_page_info const& a, cumulative_page_info const& b) const
{
return a.end_row_index < b.end_row_index;
}
};
/**
* @brief return compressed and total size of the data in a row group
*
*/
std::pair<size_t, size_t> get_row_group_size(RowGroup const& rg)
{
auto compressed_size_iter = thrust::make_transform_iterator(
rg.columns.begin(), [](ColumnChunk const& c) { return c.meta_data.total_compressed_size; });
// the trick is that total temp space needed is tricky to know
auto const compressed_size =
std::reduce(compressed_size_iter, compressed_size_iter + rg.columns.size());
auto const total_size = compressed_size + rg.total_byte_size;
return {compressed_size, total_size};
}
/**
* @brief For a set of cumulative_page_info data, adjust the size_bytes field
* such that it reflects the worst case for all pages that span the same rows.
*
* By doing this, we can now look at row X and know the total
* byte cost for all pages that span row X, not just the cost up to row X itself.
*
* This function is asynchronous. Call stream.synchronize() before using the
* results.
*/
std::pair<rmm::device_uvector<cumulative_page_info>, rmm::device_uvector<int32_t>>
adjust_cumulative_sizes(device_span<cumulative_page_info const> c_info,
device_span<PageInfo const> pages,
rmm::cuda_stream_view stream)
{
// sort by row count
rmm::device_uvector<cumulative_page_info> c_info_sorted =
make_device_uvector_async(c_info, stream, rmm::mr::get_current_device_resource());
thrust::sort(
rmm::exec_policy_nosync(stream), c_info_sorted.begin(), c_info_sorted.end(), row_count_less{});
// page keys grouped by split.
rmm::device_uvector<int32_t> page_keys_by_split{c_info.size(), stream};
thrust::transform(rmm::exec_policy_nosync(stream),
c_info_sorted.begin(),
c_info_sorted.end(),
page_keys_by_split.begin(),
cuda::proclaim_return_type<int>(
[] __device__(cumulative_page_info const& c) { return c.key; }));
// generate key offsets (offsets to the start of each partition of keys). worst case is 1 page per
// key
rmm::device_uvector<size_type> key_offsets(pages.size() + 1, stream);
auto page_keys = make_page_key_iterator(pages);
auto const key_offsets_end = thrust::reduce_by_key(rmm::exec_policy(stream),
page_keys,
page_keys + pages.size(),
thrust::make_constant_iterator(1),
thrust::make_discard_iterator(),
key_offsets.begin())
.second;
size_t const num_unique_keys = key_offsets_end - key_offsets.begin();
thrust::exclusive_scan(
rmm::exec_policy_nosync(stream), key_offsets.begin(), key_offsets.end(), key_offsets.begin());
// adjust the cumulative info such that for each row count, the size includes any pages that span
// that row count. this is so that if we have this case:
// page row counts
// Column A: 0 <----> 100 <----> 200
// Column B: 0 <---------------> 200 <--------> 400
// |
// if we decide to split at row 100, we don't really know the actual amount of bytes in column B
// at that point. So we have to proceed as if we are taking the bytes from all 200 rows of that
// page.
//
rmm::device_uvector<cumulative_page_info> aggregated_info(c_info.size(), stream);
thrust::transform(rmm::exec_policy_nosync(stream),
c_info_sorted.begin(),
c_info_sorted.end(),
aggregated_info.begin(),
page_total_size{c_info.data(), key_offsets.data(), num_unique_keys});
return {std::move(aggregated_info), std::move(page_keys_by_split)};
}
struct page_span {
size_t start, end;
};
struct get_page_end_row_index {
device_span<cumulative_page_info const> c_info;
__device__ size_t operator()(size_t i) const { return c_info[i].end_row_index; }
};
/**
* @brief Return the span of page indices for a given column index that spans start_row and end_row
*
*/
template <typename RowIndexIter>
struct get_page_span {
device_span<size_type const> page_offsets;
device_span<ColumnChunkDesc const> chunks;
RowIndexIter page_row_index;
size_t const start_row;
size_t const end_row;
get_page_span(device_span<size_type const> _page_offsets,
device_span<ColumnChunkDesc const> _chunks,
RowIndexIter _page_row_index,
size_t _start_row,
size_t _end_row)
: page_offsets(_page_offsets),
chunks(_chunks),
page_row_index(_page_row_index),
start_row(_start_row),
end_row(_end_row)
{
}
__device__ page_span operator()(size_t column_index) const
{
auto const first_page_index = page_offsets[column_index];
auto const column_page_start = page_row_index + first_page_index;
auto const column_page_end = page_row_index + page_offsets[column_index + 1];
auto const num_pages = column_page_end - column_page_start;
bool const is_list = chunks[column_index].max_level[level_type::REPETITION] > 0;
auto start_page =
(thrust::lower_bound(thrust::seq, column_page_start, column_page_end, start_row) -
column_page_start) +
first_page_index;
// list rows can span page boundaries, so it is not always safe to assume that the row
// represented by end_row_index starts on the subsequent page. It is possible that
// the values for row end_row_index start within the page itself. so we must
// include the page in that case.
if (page_row_index[start_page] == start_row && !is_list) { start_page++; }
auto end_page = (thrust::lower_bound(thrust::seq, column_page_start, column_page_end, end_row) -
column_page_start) +
first_page_index;
if (end_page < (first_page_index + num_pages)) { end_page++; }
return {static_cast<size_t>(start_page), static_cast<size_t>(end_page)};
}
};
/**
* @brief Return the span of page indices for a given column index
*/
struct get_page_span_by_column {
cudf::device_span<size_type const> page_offsets;
__device__ page_span operator()(size_t i) const
{
return {static_cast<size_t>(page_offsets[i]), static_cast<size_t>(page_offsets[i + 1])};
}
};
/**
* @brief Return the size of a span
*
*/
struct get_span_size {
CUDF_HOST_DEVICE size_t operator()(page_span const& s) const { return s.end - s.start; }
};
/**
* @brief Return the size of a span in an array of spans, handling out-of-bounds indices.
*
*/
struct get_span_size_by_index {
cudf::device_span<page_span const> page_indices;
__device__ size_t operator()(size_t i) const
{
return i >= page_indices.size() ? 0 : page_indices[i].end - page_indices[i].start;
}
};
/**
* @brief Copy page from appropriate source location (as defined by page_offsets) to the destination
* location, and store the index mapping.
*/
struct copy_subpass_page {
cudf::device_span<PageInfo const> src_pages;
cudf::device_span<PageInfo> dst_pages;
cudf::device_span<size_t> page_src_index;
cudf::device_span<size_t const> page_offsets;
cudf::device_span<page_span const> page_indices;
__device__ void operator()(size_t i) const
{
auto const index =
thrust::lower_bound(thrust::seq, page_offsets.begin(), page_offsets.end(), i) -
page_offsets.begin();
auto const col_index = page_offsets[index] == i ? index : index - 1;
// index within the pages for the column
auto const col_page_index = i - page_offsets[col_index];
auto const src_page_index = page_indices[col_index].start + col_page_index;
dst_pages[i] = src_pages[src_page_index];
page_src_index[i] = src_page_index;
}
};
/**
* @brief Computes the next subpass within the current pass.
*
* A subpass is a subset of the pages within the parent pass that is decompressed
* as a batch and decoded. Subpasses are the level at which we control memory intermediate
* memory usage. A pass consists of >= 1 subpass. We cannot compute all subpasses in one
* shot because we do not know how many rows we actually have in the pages of list columns.
* So we have to make an educated guess that fits within the memory limits, and then adjust
* for subsequent subpasses when we see how many rows we actually receive.
*
* @param c_info The cumulative page size information (row count and byte size) per column
* @param pages All of the pages in the pass
* @param chunks All of the chunks in the pass
* @param page_offsets Offsets into the pages array representing the first page for each column
* @param start_row The row to start the subpass at
* @param size_limit The size limit in bytes of the subpass
* @param num_columns The number of columns
* @param stream The stream to execute cuda operations on
* @returns A tuple containing a vector of page_span structs indicating the page indices to include
* for each column to be processed, the total number of pages over all columns, and the total
* expected memory usage (including scratch space)
*
*/
std::tuple<rmm::device_uvector<page_span>, size_t, size_t> compute_next_subpass(
device_span<cumulative_page_info const> c_info,
device_span<PageInfo const> pages,
device_span<ColumnChunkDesc const> chunks,
device_span<size_type const> page_offsets,
size_t start_row,
size_t size_limit,
size_t num_columns,
rmm::cuda_stream_view stream)
{
auto [aggregated_info, page_keys_by_split] = adjust_cumulative_sizes(c_info, pages, stream);
// bring back to the cpu
auto const h_aggregated_info = cudf::detail::make_std_vector_sync(aggregated_info, stream);
// print_cumulative_row_info(h_aggregated_info, "adjusted");
// TODO: if the user has explicitly specified skip_rows/num_rows we could be more intelligent
// about skipping subpasses/pages that do not fall within the range of values, but only if the
// data does not contain lists (because our row counts are only estimates in that case)
// find the next split
auto const start_index = find_start_index(h_aggregated_info, start_row);
auto const cumulative_size =
start_row == 0 || start_index == 0 ? 0 : h_aggregated_info[start_index - 1].size_bytes;
// when choosing subpasses, we need to guarantee at least 2 rows in the included pages so that all
// list columns have a clear start and end.
auto const end_index =
find_next_split(start_index, start_row, cumulative_size, h_aggregated_info, size_limit, 2);
auto const end_row = h_aggregated_info[end_index].end_row_index;
// for each column, collect the set of pages that spans start_row / end_row
rmm::device_uvector<page_span> page_bounds(num_columns, stream);
auto iter = thrust::make_counting_iterator(size_t{0});
auto page_row_index =
cudf::detail::make_counting_transform_iterator(0, get_page_end_row_index{c_info});
thrust::transform(rmm::exec_policy_nosync(stream),
iter,
iter + num_columns,
page_bounds.begin(),
get_page_span{page_offsets, chunks, page_row_index, start_row, end_row});
// total page count over all columns
auto page_count_iter = thrust::make_transform_iterator(page_bounds.begin(), get_span_size{});
size_t const total_pages =
thrust::reduce(rmm::exec_policy(stream), page_count_iter, page_count_iter + num_columns);
return {
std::move(page_bounds), total_pages, h_aggregated_info[end_index].size_bytes - cumulative_size};
}
std::vector<row_range> compute_page_splits_by_row(device_span<cumulative_page_info const> c_info,
device_span<PageInfo const> pages,
size_t skip_rows,
size_t num_rows,
size_t size_limit,
rmm::cuda_stream_view stream)
{
auto [aggregated_info, page_keys_by_split] = adjust_cumulative_sizes(c_info, pages, stream);
// bring back to the cpu
std::vector<cumulative_page_info> h_aggregated_info =
cudf::detail::make_std_vector_sync(aggregated_info, stream);
// print_cumulative_row_info(h_aggregated_info, "adjusted");
std::vector<row_range> splits;
// note: we are working with absolute row indices so skip_rows represents the absolute min row
// index we care about
size_t cur_pos = find_start_index(h_aggregated_info, skip_rows);
size_t cur_row_index = skip_rows;
size_t cur_cumulative_size = 0;
auto const max_row = min(skip_rows + num_rows, h_aggregated_info.back().end_row_index);
while (cur_row_index < max_row) {
auto const split_pos = find_next_split(
cur_pos, cur_row_index, cur_cumulative_size, h_aggregated_info, size_limit, 1);
auto const start_row = cur_row_index;
cur_row_index = min(max_row, h_aggregated_info[split_pos].end_row_index);
splits.push_back({start_row, cur_row_index - start_row});
cur_pos = split_pos;
cur_cumulative_size = h_aggregated_info[split_pos].size_bytes;
}
// print_cumulative_row_info(h_aggregated_info, "adjusted w/splits", splits);
return splits;
}
/**
* @brief Decompresses a set of pages contained in the set of chunks.
*
* This function handles the case where `pages` is only a subset of all available
* pages in `chunks`.
*
* @param chunks List of column chunk descriptors
* @param pages List of page information
* @param dict_pages If true, decompress dictionary pages only. Otherwise decompress non-dictionary
* pages only.
* @param stream CUDA stream used for device memory operations and kernel launches
*
* @return Device buffer to decompressed page data
*/
[[nodiscard]] rmm::device_buffer decompress_page_data(
cudf::detail::hostdevice_span<ColumnChunkDesc const> chunks,
cudf::detail::hostdevice_span<PageInfo> pages,
bool dict_pages,
rmm::cuda_stream_view stream)
{
CUDF_FUNC_RANGE();
auto for_each_codec_page = [&](Compression codec, std::function<void(size_t)> const& f) {
for (size_t p = 0; p < pages.size(); p++) {
if (chunks[pages[p].chunk_idx].codec == codec &&
((dict_pages && (pages[p].flags & PAGEINFO_FLAGS_DICTIONARY)) ||
(!dict_pages && !(pages[p].flags & PAGEINFO_FLAGS_DICTIONARY)))) {
f(p);
}
}
};
// Brotli scratch memory for decompressing
rmm::device_buffer debrotli_scratch;
// Count the exact number of compressed pages
size_t num_comp_pages = 0;
size_t total_decomp_size = 0;
struct codec_stats {
Compression compression_type = UNCOMPRESSED;
size_t num_pages = 0;
int32_t max_decompressed_size = 0;
size_t total_decomp_size = 0;
};
std::array codecs{codec_stats{GZIP},
codec_stats{SNAPPY},
codec_stats{BROTLI},
codec_stats{ZSTD},
codec_stats{LZ4_RAW}};
auto is_codec_supported = [&codecs](int8_t codec) {
if (codec == UNCOMPRESSED) return true;
return std::find_if(codecs.begin(), codecs.end(), [codec](auto& cstats) {
return codec == cstats.compression_type;
}) != codecs.end();
};
CUDF_EXPECTS(std::all_of(chunks.host_begin(),
chunks.host_end(),
[&is_codec_supported](auto const& chunk) {
return is_codec_supported(chunk.codec);
}),
"Unsupported compression type");
for (auto& codec : codecs) {
for_each_codec_page(codec.compression_type, [&](size_t page) {
auto page_uncomp_size = pages[page].uncompressed_page_size;
total_decomp_size += page_uncomp_size;
codec.total_decomp_size += page_uncomp_size;
codec.max_decompressed_size = std::max(codec.max_decompressed_size, page_uncomp_size);
codec.num_pages++;
num_comp_pages++;
});
if (codec.compression_type == BROTLI && codec.num_pages > 0) {
debrotli_scratch.resize(get_gpu_debrotli_scratch_size(codec.num_pages), stream);
}
}
// Dispatch batches of pages to decompress for each codec.
// Buffer needs to be padded, required by `gpuDecodePageData`.
rmm::device_buffer decomp_pages(
cudf::util::round_up_safe(total_decomp_size, BUFFER_PADDING_MULTIPLE), stream);
std::vector<device_span<uint8_t const>> comp_in;
comp_in.reserve(num_comp_pages);
std::vector<device_span<uint8_t>> comp_out;
comp_out.reserve(num_comp_pages);
// vectors to save v2 def and rep level data, if any
std::vector<device_span<uint8_t const>> copy_in;
copy_in.reserve(num_comp_pages);
std::vector<device_span<uint8_t>> copy_out;
copy_out.reserve(num_comp_pages);
rmm::device_uvector<compression_result> comp_res(num_comp_pages, stream);
thrust::fill(rmm::exec_policy_nosync(stream),
comp_res.begin(),
comp_res.end(),
compression_result{0, compression_status::FAILURE});
size_t decomp_offset = 0;
int32_t start_pos = 0;
for (auto const& codec : codecs) {
if (codec.num_pages == 0) { continue; }
for_each_codec_page(codec.compression_type, [&](size_t page_idx) {
auto const dst_base = static_cast<uint8_t*>(decomp_pages.data()) + decomp_offset;
auto& page = pages[page_idx];
// offset will only be non-zero for V2 pages
auto const offset =
page.lvl_bytes[level_type::DEFINITION] + page.lvl_bytes[level_type::REPETITION];
// for V2 need to copy def and rep level info into place, and then offset the
// input and output buffers. otherwise we'd have to keep both the compressed
// and decompressed data.
if (offset != 0) {
copy_in.emplace_back(page.page_data, offset);
copy_out.emplace_back(dst_base, offset);
}
comp_in.emplace_back(page.page_data + offset,
static_cast<size_t>(page.compressed_page_size - offset));
comp_out.emplace_back(dst_base + offset,
static_cast<size_t>(page.uncompressed_page_size - offset));
page.page_data = dst_base;
decomp_offset += page.uncompressed_page_size;
});
host_span<device_span<uint8_t const> const> comp_in_view{comp_in.data() + start_pos,
codec.num_pages};
auto const d_comp_in = cudf::detail::make_device_uvector_async(
comp_in_view, stream, rmm::mr::get_current_device_resource());
host_span<device_span<uint8_t> const> comp_out_view(comp_out.data() + start_pos,
codec.num_pages);
auto const d_comp_out = cudf::detail::make_device_uvector_async(
comp_out_view, stream, rmm::mr::get_current_device_resource());
device_span<compression_result> d_comp_res_view(comp_res.data() + start_pos, codec.num_pages);
switch (codec.compression_type) {
case GZIP:
gpuinflate(d_comp_in, d_comp_out, d_comp_res_view, gzip_header_included::YES, stream);
break;
case SNAPPY:
if (cudf::io::detail::nvcomp_integration::is_stable_enabled()) {
nvcomp::batched_decompress(nvcomp::compression_type::SNAPPY,
d_comp_in,
d_comp_out,
d_comp_res_view,
codec.max_decompressed_size,
codec.total_decomp_size,
stream);
} else {
gpu_unsnap(d_comp_in, d_comp_out, d_comp_res_view, stream);
}
break;
case ZSTD:
nvcomp::batched_decompress(nvcomp::compression_type::ZSTD,
d_comp_in,
d_comp_out,
d_comp_res_view,
codec.max_decompressed_size,
codec.total_decomp_size,
stream);
break;
case BROTLI:
gpu_debrotli(d_comp_in,
d_comp_out,
d_comp_res_view,
debrotli_scratch.data(),
debrotli_scratch.size(),
stream);
break;
case LZ4_RAW:
nvcomp::batched_decompress(nvcomp::compression_type::LZ4,
d_comp_in,
d_comp_out,
d_comp_res_view,
codec.max_decompressed_size,
codec.total_decomp_size,
stream);
break;
default: CUDF_FAIL("Unexpected decompression dispatch"); break;
}
start_pos += codec.num_pages;
}
CUDF_EXPECTS(thrust::all_of(rmm::exec_policy(stream),
comp_res.begin(),
comp_res.end(),
cuda::proclaim_return_type<bool>([] __device__(auto const& res) {
return res.status == compression_status::SUCCESS;
})),
"Error during decompression");
// now copy the uncompressed V2 def and rep level data
if (not copy_in.empty()) {
auto const d_copy_in = cudf::detail::make_device_uvector_async(
copy_in, stream, rmm::mr::get_current_device_resource());
auto const d_copy_out = cudf::detail::make_device_uvector_async(
copy_out, stream, rmm::mr::get_current_device_resource());
gpu_copy_uncompressed_blocks(d_copy_in, d_copy_out, stream);
stream.synchronize();
}
pages.host_to_device_async(stream);
stream.synchronize();
return decomp_pages;
}
struct flat_column_num_rows {
ColumnChunkDesc const* chunks;
__device__ size_type operator()(PageInfo const& page) const
{
// ignore dictionary pages and pages belonging to any column containing repetition (lists)
if ((page.flags & PAGEINFO_FLAGS_DICTIONARY) ||
(chunks[page.chunk_idx].max_level[level_type::REPETITION] > 0)) {
return 0;
}
return page.num_rows;
}
};
struct row_counts_nonzero {
__device__ bool operator()(size_type count) const { return count > 0; }
};
struct row_counts_different {
size_type const expected;
__device__ bool operator()(size_type count) const { return (count != 0) && (count != expected); }
};
/**
* @brief Detect malformed parquet input data.
*
* We have seen cases where parquet files can be oddly malformed. This function specifically
* detects one case in particular:
*
* - When you have a file containing N rows
* - For some reason, the sum total of the number of rows over all pages for a given column
* is != N
*
* @param pages All pages to be decoded
* @param chunks Chunk data
* @param expected_row_count Expected row count, if applicable
* @param stream CUDA stream used for device memory operations and kernel launches
*/
void detect_malformed_pages(device_span<PageInfo const> pages,
device_span<ColumnChunkDesc const> chunks,
std::optional<size_t> expected_row_count,
rmm::cuda_stream_view stream)
{
CUDF_FUNC_RANGE();
// sum row counts for all non-dictionary, non-list columns. other columns will be indicated as 0
rmm::device_uvector<size_type> row_counts(pages.size(),
stream); // worst case: num keys == num pages
auto const size_iter =
thrust::make_transform_iterator(pages.begin(), flat_column_num_rows{chunks.data()});
auto const row_counts_begin = row_counts.begin();
auto page_keys = make_page_key_iterator(pages);
auto const row_counts_end = thrust::reduce_by_key(rmm::exec_policy(stream),
page_keys,
page_keys + pages.size(),
size_iter,
thrust::make_discard_iterator(),
row_counts_begin)
.second;
// make sure all non-zero row counts are the same
rmm::device_uvector<size_type> compacted_row_counts(pages.size(), stream);
auto const compacted_row_counts_begin = compacted_row_counts.begin();
auto const compacted_row_counts_end = thrust::copy_if(rmm::exec_policy(stream),
row_counts_begin,
row_counts_end,
compacted_row_counts_begin,
row_counts_nonzero{});