-
Notifications
You must be signed in to change notification settings - Fork 919
/
Copy pathpage_enc.cu
3485 lines (3165 loc) · 135 KB
/
page_enc.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.
*/
#include "delta_enc.cuh"
#include "io/utilities/block_utils.cuh"
#include "page_string_utils.cuh"
#include "parquet_gpu.cuh"
#include <cudf/detail/iterator.cuh>
#include <cudf/detail/utilities/assert.cuh>
#include <cudf/detail/utilities/cuda.cuh>
#include <cudf/detail/utilities/stream_pool.hpp>
#include <cudf/detail/utilities/vector_factories.hpp>
#include <rmm/cuda_stream_view.hpp>
#include <rmm/exec_policy.hpp>
#include <cub/cub.cuh>
#include <cuda/std/chrono>
#include <thrust/binary_search.h>
#include <thrust/distance.h>
#include <thrust/gather.h>
#include <thrust/iterator/discard_iterator.h>
#include <thrust/iterator/reverse_iterator.h>
#include <thrust/iterator/transform_iterator.h>
#include <thrust/iterator/zip_iterator.h>
#include <thrust/merge.h>
#include <thrust/scan.h>
#include <thrust/scatter.h>
#include <thrust/tuple.h>
#include <bitset>
namespace cudf::io::parquet::detail {
namespace {
using ::cudf::detail::device_2dspan;
constexpr int encode_block_size = 128;
constexpr int rle_buffer_size = 2 * encode_block_size;
constexpr int num_encode_warps = encode_block_size / cudf::detail::warp_size;
constexpr int rolling_idx(int pos) { return rolling_index<rle_buffer_size>(pos); }
// max V1 header size
// also valid for dict page header (V1 or V2)
constexpr int MAX_V1_HDR_SIZE = util::round_up_unsafe(27, 8);
// max V2 header size
constexpr int MAX_V2_HDR_SIZE = util::round_up_unsafe(49, 8);
// do not truncate statistics
constexpr int32_t NO_TRUNC_STATS = 0;
// minimum scratch space required for encoding statistics
constexpr size_t MIN_STATS_SCRATCH_SIZE = sizeof(__int128_t);
// mask to determine lane id
constexpr uint32_t WARP_MASK = cudf::detail::warp_size - 1;
// currently 64k - 1
constexpr uint32_t MAX_GRID_Y_SIZE = (1 << 16) - 1;
// space needed for RLE length field
constexpr int RLE_LENGTH_FIELD_LEN = 4;
struct frag_init_state_s {
parquet_column_device_view col;
PageFragment frag;
};
template <int rle_buf_size>
struct page_enc_state_s {
uint8_t* cur; //!< current output ptr
uint8_t* rle_out; //!< current RLE write ptr
uint8_t* rle_len_pos; //!< position to write RLE length (for V2 boolean data)
uint32_t rle_run; //!< current RLE run
uint32_t run_val; //!< current RLE run value
uint32_t rle_pos; //!< RLE encoder positions
uint32_t rle_numvals; //!< RLE input value count
uint32_t rle_lit_count;
uint32_t rle_rpt_count;
uint32_t page_start_val;
uint32_t chunk_start_val;
uint32_t rpt_map[num_encode_warps];
EncPage page;
EncColumnChunk ck;
parquet_column_device_view col;
uint32_t vals[rle_buf_size];
};
using rle_page_enc_state_s = page_enc_state_s<rle_buffer_size>;
/**
* @brief Returns the size of the type in the Parquet file.
*/
constexpr uint32_t physical_type_len(Type physical_type, type_id id)
{
if (physical_type == FIXED_LEN_BYTE_ARRAY and id == type_id::DECIMAL128) {
return sizeof(__int128_t);
}
switch (physical_type) {
case INT96: return 12u;
case INT64:
case DOUBLE: return sizeof(int64_t);
case BOOLEAN: return 1u;
default: return sizeof(int32_t);
}
}
constexpr uint32_t max_RLE_page_size(uint8_t value_bit_width, uint32_t num_values)
{
if (value_bit_width == 0) return 0;
// Run length = 4, max(rle/bitpack header) = 5. bitpacking worst case is one byte every 8 values
// (because bitpacked runs are a multiple of 8). Don't need to round up the last term since that
// overhead is accounted for in the '5'.
// TODO: this formula does not take into account the data for RLE runs. The worst realistic case
// is repeated runs of 8 bitpacked, 2 RLE values. In this case, the formula would be
// 0.8 * (num_values * bw / 8 + num_values / 8) + 0.2 * (num_values / 2 * (1 + (bw+7)/8))
// for bw < 8 the above value will be larger than below, but in testing it seems like for low
// bitwidths it's hard to get the pathological 8:2 split.
// If the encoder starts printing the data corruption warning, then this will need to be
// revisited.
return 4 + 5 + util::div_rounding_up_unsafe(num_values * value_bit_width, 8) + (num_values / 8);
}
// subtract b from a, but return 0 if this would underflow
constexpr size_t underflow_safe_subtract(size_t a, size_t b)
{
if (b > a) { return 0; }
return a - b;
}
void __device__ init_frag_state(frag_init_state_s* const s,
uint32_t fragment_size,
int part_end_row)
{
// frag.num_rows = fragment_size except for the last fragment in partition which can be
// smaller. num_rows is fixed but fragment size could be larger if the data is strings or
// nested.
s->frag.num_rows = min(fragment_size, part_end_row - s->frag.start_row);
s->frag.num_dict_vals = 0;
s->frag.fragment_data_size = 0;
s->frag.dict_data_size = 0;
s->frag.start_value_idx = row_to_value_idx(s->frag.start_row, s->col);
auto const end_value_idx = row_to_value_idx(s->frag.start_row + s->frag.num_rows, s->col);
s->frag.num_leaf_values = end_value_idx - s->frag.start_value_idx;
if (s->col.level_offsets != nullptr) {
// For nested schemas, the number of values in a fragment is not directly related to the
// number of encoded data elements or the number of rows. It is simply the number of
// repetition/definition values which together encode validity and nesting information.
auto const first_level_val_idx = s->col.level_offsets[s->frag.start_row];
auto const last_level_val_idx = s->col.level_offsets[s->frag.start_row + s->frag.num_rows];
s->frag.num_values = last_level_val_idx - first_level_val_idx;
} else {
s->frag.num_values = s->frag.num_rows;
}
}
template <int block_size>
void __device__ calculate_frag_size(frag_init_state_s* const s, int t)
{
using block_reduce = cub::BlockReduce<uint32_t, block_size>;
__shared__ typename block_reduce::TempStorage reduce_storage;
auto const physical_type = s->col.physical_type;
auto const leaf_type = s->col.leaf_column->type().id();
auto const dtype_len = physical_type_len(physical_type, leaf_type);
auto const nvals = s->frag.num_leaf_values;
auto const start_value_idx = s->frag.start_value_idx;
uint32_t num_valid = 0;
uint32_t len = 0;
for (uint32_t i = 0; i < nvals; i += block_size) {
auto const val_idx = start_value_idx + i + t;
auto const is_valid = i + t < nvals && val_idx < s->col.leaf_column->size() &&
s->col.leaf_column->is_valid(val_idx);
if (is_valid) {
num_valid++;
len += dtype_len;
if (physical_type == BYTE_ARRAY) {
switch (leaf_type) {
case type_id::STRING: {
auto str = s->col.leaf_column->element<string_view>(val_idx);
len += str.size_bytes();
} break;
case type_id::LIST: {
auto list_element =
get_element<statistics::byte_array_view>(*s->col.leaf_column, val_idx);
len += list_element.size_bytes();
} break;
default: CUDF_UNREACHABLE("Unsupported data type for leaf column");
}
}
}
}
auto const total_len = block_reduce(reduce_storage).Sum(len);
__syncthreads();
auto const total_valid = block_reduce(reduce_storage).Sum(num_valid);
if (t == 0) {
s->frag.fragment_data_size = total_len;
s->frag.num_valid = total_valid;
}
__syncthreads();
// page fragment size must fit in a 32-bit signed integer
if (s->frag.fragment_data_size > static_cast<uint32_t>(std::numeric_limits<int32_t>::max())) {
// TODO need to propagate this error back to the host
CUDF_UNREACHABLE("page fragment size exceeds maximum for i32");
}
}
/**
* @brief Determine the correct page encoding for the given page parameters.
*
* This is only used by the plain and dictionary encoders. Delta encoders will set the page
* encoding directly.
*/
Encoding __device__ determine_encoding(PageType page_type,
Type physical_type,
bool use_dictionary,
bool write_v2_headers)
{
// NOTE: For dictionary encoding, parquet v2 recommends using PLAIN in dictionary page and
// RLE_DICTIONARY in data page, but parquet v1 uses PLAIN_DICTIONARY in both dictionary and
// data pages (actual encoding is identical).
switch (page_type) {
case PageType::DATA_PAGE: return use_dictionary ? Encoding::PLAIN_DICTIONARY : Encoding::PLAIN;
case PageType::DATA_PAGE_V2:
return physical_type == BOOLEAN ? Encoding::RLE
: use_dictionary ? Encoding::RLE_DICTIONARY
: Encoding::PLAIN;
case PageType::DICTIONARY_PAGE:
return write_v2_headers ? Encoding::PLAIN : Encoding::PLAIN_DICTIONARY;
default: CUDF_UNREACHABLE("unsupported page type");
}
}
/**
* @brief Generate level histogram for a page.
*
* For definition levels, the histogram values h(0)...h(max_def-1) represent nulls at
* various levels of the hierarchy, and h(max_def) is the number of non-null values (num_valid).
* If the leaf level is nullable, then num_leaf_values is h(max_def-1) + h(max_def),
* and h(max_def-1) is num_leaf_values - num_valid. h(0) is derivable as num_values -
* sum(h(1)..h(max_def)).
*
* For repetition levels, h(0) equals the number of rows. Here we can calculate
* h(1)..h(max_rep-1), set h(0) directly, and then obtain h(max_rep) in the same way as
* for the definition levels.
*
* @param hist Pointer to the histogram (size is max_level + 1)
* @param s Page encode state
* @param lvl_data Pointer to the global repetition or definition level data
* @param lvl_end Last element of the histogram to encode (exclusive)
*/
template <int block_size, typename state_buf>
void __device__
generate_page_histogram(uint32_t* hist, state_buf const* s, uint8_t const* lvl_data, int lvl_end)
{
using block_reduce = cub::BlockReduce<int, block_size>;
__shared__ typename block_reduce::TempStorage temp_storage;
auto const t = threadIdx.x;
auto const page_first_val_idx = s->col.level_offsets[s->page.start_row];
auto const col_last_val_idx = s->col.level_offsets[s->col.num_rows];
// h(0) is always derivable, so start at 1
for (int lvl = 1; lvl < lvl_end; lvl++) {
int nval_in_level = 0;
for (int i = 0; i < s->page.num_values; i += block_size) {
auto const lidx = i + t;
auto const gidx = page_first_val_idx + lidx;
if (lidx < s->page.num_values && gidx < col_last_val_idx && lvl_data[gidx] == lvl) {
nval_in_level++;
}
}
__syncthreads();
auto const lvl_sum = block_reduce(temp_storage).Sum(nval_in_level);
if (t == 0) { hist[lvl] = lvl_sum; }
}
}
/**
* @brief Generate definition level histogram for a block of values.
*
* This is used when the max repetition level is 0 (no lists) and the definition
* level data is not calculated in advance for the entire column.
*
* @param hist Pointer to the histogram (size is max_def_level + 1)
* @param s Page encode state
* @param nrows Number of rows to process
* @param rle_numvals Index (relative to start of page) of the first level value
* @param maxlvl Last element of the histogram to encode (exclusive)
*/
template <int block_size>
void __device__ generate_def_level_histogram(uint32_t* hist,
rle_page_enc_state_s const* s,
uint32_t nrows,
uint32_t rle_numvals,
uint32_t maxlvl)
{
using block_reduce = cub::BlockReduce<uint32_t, block_size>;
__shared__ typename block_reduce::TempStorage temp_storage;
auto const t = threadIdx.x;
// Do a block sum for each level rather than each thread trying an atomicAdd.
// This way is much faster.
auto const mylvl = s->vals[rolling_index<rle_buffer_size>(rle_numvals + t)];
// We can start at 1 because hist[0] can be derived.
for (uint32_t lvl = 1; lvl < maxlvl; lvl++) {
uint32_t const is_yes = t < nrows and mylvl == lvl;
auto const lvl_sum = block_reduce(temp_storage).Sum(is_yes);
if (t == 0) { hist[lvl] += lvl_sum; }
__syncthreads();
}
}
// operator to use with warp_reduce. stolen from cub::Sum
struct BitwiseOr {
/// Binary OR operator, returns <tt>a | b</tt>
template <typename T>
__host__ __device__ __forceinline__ T operator()(T const& a, T const& b) const
{
return a | b;
}
};
// PT is the parquet physical type (INT32 or INT64).
// I is the column type from the input table.
template <Type PT, typename I>
__device__ uint8_t const* delta_encode(page_enc_state_s<0>* s, uint64_t* buffer, void* temp_space)
{
using output_type = std::conditional_t<PT == INT32, int32_t, int64_t>;
__shared__ delta_binary_packer<output_type> packer;
auto const t = threadIdx.x;
if (t == 0) {
packer.init(s->cur, s->page.num_valid, reinterpret_cast<output_type*>(buffer), temp_space);
}
__syncthreads();
// TODO(ets): in the plain encoder the scaling is a little different for INT32 than INT64.
// might need to modify this if there's a big performance hit in the 32-bit case.
int32_t const scale = s->col.ts_scale == 0 ? 1 : s->col.ts_scale;
for (uint32_t cur_val_idx = 0; cur_val_idx < s->page.num_leaf_values;) {
uint32_t const nvals = min(s->page.num_leaf_values - cur_val_idx, delta::block_size);
size_type const val_idx_in_block = cur_val_idx + t;
size_type const val_idx = s->page_start_val + val_idx_in_block;
bool const is_valid =
(val_idx < s->col.leaf_column->size() && val_idx_in_block < s->page.num_leaf_values)
? s->col.leaf_column->is_valid(val_idx)
: false;
cur_val_idx += nvals;
output_type v = is_valid ? s->col.leaf_column->element<I>(val_idx) : 0;
if (scale < 0) {
v /= -scale;
} else {
v *= scale;
}
packer.add_value(v, is_valid);
}
return packer.flush();
}
/**
* @brief Sets `s->cur` to point to the start of encoded page data.
*
* For V1 headers, this will be immediately after the repetition and definition level data. For V2,
* it will be at the next properly aligned location after the level data. The padding in V2 is
* needed for compressors that require aligned input.
*/
template <typename state_type>
inline void __device__ set_page_data_start(state_type* s)
{
s->cur = s->page.page_data + s->page.max_hdr_size;
switch (s->page.page_type) {
case PageType::DATA_PAGE:
s->cur += s->page.level_bytes();
if (s->col.num_def_level_bits() != 0) { s->cur += RLE_LENGTH_FIELD_LEN; }
if (s->col.num_rep_level_bits() != 0) { s->cur += RLE_LENGTH_FIELD_LEN; }
break;
case PageType::DATA_PAGE_V2: s->cur += s->page.max_lvl_size; break;
}
}
} // anonymous namespace
// blockDim {512,1,1}
template <int block_size>
CUDF_KERNEL void __launch_bounds__(block_size)
gpuInitRowGroupFragments(device_2dspan<PageFragment> frag,
device_span<parquet_column_device_view const> col_desc,
device_span<partition_info const> partitions,
device_span<int const> part_frag_offset,
uint32_t fragment_size)
{
__shared__ __align__(16) frag_init_state_s state_g;
frag_init_state_s* const s = &state_g;
auto const t = threadIdx.x;
auto const num_fragments_per_column = frag.size().second;
if (t == 0) { s->col = col_desc[blockIdx.x]; }
__syncthreads();
for (uint32_t frag_y = blockIdx.y; frag_y < num_fragments_per_column; frag_y += gridDim.y) {
if (t == 0) {
// Find which partition this fragment came from
auto it =
thrust::upper_bound(thrust::seq, part_frag_offset.begin(), part_frag_offset.end(), frag_y);
int const p = it - part_frag_offset.begin() - 1;
int const part_end_row = partitions[p].start_row + partitions[p].num_rows;
s->frag.start_row = (frag_y - part_frag_offset[p]) * fragment_size + partitions[p].start_row;
s->frag.chunk = frag[blockIdx.x][frag_y].chunk;
init_frag_state(s, fragment_size, part_end_row);
}
__syncthreads();
calculate_frag_size<block_size>(s, t);
__syncthreads();
if (t == 0) { frag[blockIdx.x][frag_y] = s->frag; }
}
}
// blockDim {512,1,1}
template <int block_size>
CUDF_KERNEL void __launch_bounds__(block_size)
gpuCalculatePageFragments(device_span<PageFragment> frag,
device_span<size_type const> column_frag_sizes)
{
__shared__ __align__(16) frag_init_state_s state_g;
EncColumnChunk* const ck_g = frag[blockIdx.x].chunk;
frag_init_state_s* const s = &state_g;
uint32_t const t = threadIdx.x;
auto const fragment_size = column_frag_sizes[ck_g->col_desc_id];
if (t == 0) { s->col = *ck_g->col_desc; }
__syncthreads();
if (t == 0) {
int const part_end_row = ck_g->start_row + ck_g->num_rows;
s->frag.start_row = ck_g->start_row + (blockIdx.x - ck_g->first_fragment) * fragment_size;
s->frag.chunk = ck_g;
init_frag_state(s, fragment_size, part_end_row);
}
__syncthreads();
calculate_frag_size<block_size>(s, t);
if (t == 0) { frag[blockIdx.x] = s->frag; }
}
// blockDim {128,1,1}
CUDF_KERNEL void __launch_bounds__(128)
gpuInitFragmentStats(device_span<statistics_group> groups,
device_span<PageFragment const> fragments)
{
uint32_t const lane_id = threadIdx.x & WARP_MASK;
uint32_t const frag_id = blockIdx.x * 4 + (threadIdx.x / cudf::detail::warp_size);
if (frag_id < fragments.size()) {
if (lane_id == 0) {
statistics_group g;
auto* const ck_g = fragments[frag_id].chunk;
g.col = ck_g->col_desc;
g.start_row = fragments[frag_id].start_value_idx;
g.num_rows = fragments[frag_id].num_leaf_values;
g.non_leaf_nulls = fragments[frag_id].num_values - g.num_rows;
groups[frag_id] = g;
}
}
}
// given a column chunk, determine which data encoding to use
__device__ encode_kernel_mask data_encoding_for_col(EncColumnChunk const* chunk,
parquet_column_device_view const* col_desc,
bool write_v2_headers)
{
// first check for dictionary (boolean always uses dict encoder)
if (chunk->use_dictionary or col_desc->physical_type == BOOLEAN) {
return encode_kernel_mask::DICTIONARY;
}
// next check for user requested encoding, but skip if user requested dictionary encoding
// (if we could use the requested dict encoding, we'd have returned above)
if (col_desc->requested_encoding != column_encoding::USE_DEFAULT and
col_desc->requested_encoding != column_encoding::DICTIONARY) {
switch (col_desc->requested_encoding) {
case column_encoding::PLAIN: return encode_kernel_mask::PLAIN;
case column_encoding::DELTA_BINARY_PACKED: return encode_kernel_mask::DELTA_BINARY;
case column_encoding::DELTA_LENGTH_BYTE_ARRAY: return encode_kernel_mask::DELTA_LENGTH_BA;
case column_encoding::DELTA_BYTE_ARRAY: return encode_kernel_mask::DELTA_BYTE_ARRAY;
}
}
// Select a fallback encoding. For V1, we always choose PLAIN. For V2 we'll use
// DELTA_BINARY_PACKED for INT32 and INT64, and DELTA_LENGTH_BYTE_ARRAY for
// BYTE_ARRAY. Everything else will still fall back to PLAIN.
if (write_v2_headers) {
switch (col_desc->physical_type) {
case INT32:
case INT64: return encode_kernel_mask::DELTA_BINARY;
case BYTE_ARRAY: return encode_kernel_mask::DELTA_LENGTH_BA;
}
}
return encode_kernel_mask::PLAIN;
}
__device__ size_t delta_data_len(Type physical_type,
cudf::type_id type_id,
uint32_t num_values,
size_t page_size,
encode_kernel_mask encoding)
{
auto const dtype_len_out = physical_type_len(physical_type, type_id);
auto const dtype_len = [&]() -> uint32_t {
if (physical_type == INT32) { return int32_logical_len(type_id); }
if (physical_type == INT96) { return sizeof(int64_t); }
return dtype_len_out;
}();
auto const vals_per_block = delta::block_size;
size_t const num_blocks = util::div_rounding_up_unsafe(num_values, vals_per_block);
// need max dtype_len + 1 bytes for min_delta (because we only encode 7 bits per byte)
// one byte per mini block for the bitwidth
auto const mini_block_header_size = dtype_len + 1 + delta::num_mini_blocks;
// each encoded value can be at most sizeof(type) * 8 + 1 bits
auto const max_bits = dtype_len * 8 + 1;
// each data block will then be max_bits * values per block. vals_per_block is guaranteed to be
// divisible by 128 (via static assert on delta::block_size), but do safe division anyway.
auto const bytes_per_block = cudf::util::div_rounding_up_unsafe(max_bits * vals_per_block, 8);
auto const block_size = mini_block_header_size + bytes_per_block;
// the number of DELTA_BINARY_PACKED blocks to encode
auto const num_dbp_blocks = encoding == encode_kernel_mask::DELTA_BYTE_ARRAY ? 2 : 1;
// delta header is 2 bytes for the block_size, 1 byte for number of mini-blocks,
// max 5 bytes for number of values, and max dtype_len + 1 for first value.
// TODO: if we ever allow configurable block sizes then this calculation will need to be
// modified.
auto const header_size = 2 + 1 + 5 + dtype_len + 1;
// The above is just a size estimate for a DELTA_BINARY_PACKED data page. For BYTE_ARRAY
// data we also need to add size of the char data. `page_size` that is passed in is the
// plain encoded size (i.e. num_values * sizeof(size_type) + char_data_len), so the char
// data len is `page_size` minus the first term. For FIXED_LEN_BYTE_ARRAY there are no
// lengths, so just use `page_size`.
// `num_dbp_blocks` takes into account the two delta binary blocks for DELTA_BYTE_ARRAY.
size_t char_data_len = 0;
if (physical_type == BYTE_ARRAY) {
char_data_len = page_size - num_values * sizeof(size_type);
} else if (physical_type == FIXED_LEN_BYTE_ARRAY) {
char_data_len = page_size;
}
return header_size + num_blocks * num_dbp_blocks * block_size + char_data_len;
}
// blockDim {128,1,1}
CUDF_KERNEL void __launch_bounds__(128)
gpuInitPages(device_2dspan<EncColumnChunk> chunks,
device_span<EncPage> pages,
device_span<size_type> page_sizes,
device_span<size_type> comp_page_sizes,
device_span<parquet_column_device_view const> col_desc,
statistics_merge_group* page_grstats,
statistics_merge_group* chunk_grstats,
int32_t num_columns,
size_t max_page_size_bytes,
size_type max_page_size_rows,
uint32_t page_align,
bool write_v2_headers)
{
// TODO: All writing seems to be done by thread 0. Could be replaced by thrust foreach
__shared__ __align__(8) parquet_column_device_view col_g;
__shared__ __align__(8) EncColumnChunk ck_g;
__shared__ __align__(8) PageFragment frag_g;
__shared__ __align__(8) EncPage page_g;
__shared__ __align__(8) statistics_merge_group pagestats_g;
uint32_t const t = threadIdx.x;
auto const data_page_type = write_v2_headers ? PageType::DATA_PAGE_V2 : PageType::DATA_PAGE;
// Max page header size excluding statistics
auto const max_data_page_hdr_size = write_v2_headers ? MAX_V2_HDR_SIZE : MAX_V1_HDR_SIZE;
if (t == 0) {
col_g = col_desc[blockIdx.x];
ck_g = chunks[blockIdx.y][blockIdx.x];
page_g = {};
}
__syncthreads();
// if writing delta encoded values, we're going to need to know the data length to get a guess
// at the worst case number of bytes needed to encode.
auto const physical_type = col_g.physical_type;
auto const type_id = col_g.leaf_column->type().id();
// figure out kernel encoding to use for data pages
auto const column_data_encoding = data_encoding_for_col(&ck_g, &col_g, write_v2_headers);
auto const is_use_delta = column_data_encoding == encode_kernel_mask::DELTA_BINARY or
column_data_encoding == encode_kernel_mask::DELTA_LENGTH_BA or
column_data_encoding == encode_kernel_mask::DELTA_BYTE_ARRAY;
if (t < 32) {
uint32_t fragments_in_chunk = 0;
uint32_t rows_in_page = 0;
uint32_t values_in_page = 0;
uint32_t leaf_values_in_page = 0;
uint32_t num_valid = 0;
size_t page_size = 0;
size_t var_bytes_size = 0;
uint32_t num_pages = 0;
uint32_t num_rows = 0;
uint32_t page_start = 0;
uint32_t page_offset = ck_g.ck_stat_size;
uint32_t num_dict_entries = 0;
uint32_t comp_page_offset = ck_g.ck_stat_size;
uint32_t page_headers_size = 0;
uint32_t max_page_data_size = 0;
uint32_t cur_row = ck_g.start_row;
uint32_t ck_max_stats_len = 0;
uint32_t max_stats_len = 0;
if (!t) {
pagestats_g.col_dtype = col_g.leaf_column->type();
pagestats_g.stats_dtype = col_g.stats_dtype;
pagestats_g.start_chunk = ck_g.first_fragment;
pagestats_g.num_chunks = 0;
}
if (ck_g.use_dictionary) {
if (!t) {
page_g.page_data = ck_g.uncompressed_bfr + page_offset;
page_g.compressed_data = ck_g.compressed_bfr + comp_page_offset;
page_g.num_fragments = 0;
page_g.page_type = PageType::DICTIONARY_PAGE;
page_g.chunk = &chunks[blockIdx.y][blockIdx.x];
page_g.chunk_id = blockIdx.y * num_columns + blockIdx.x;
page_g.hdr_size = 0;
page_g.def_lvl_bytes = 0;
page_g.rep_lvl_bytes = 0;
page_g.max_lvl_size = 0;
page_g.comp_data_size = 0;
page_g.max_hdr_size = MAX_V1_HDR_SIZE;
page_g.max_data_size = ck_g.uniq_data_size;
page_g.data_size = ck_g.uniq_data_size;
page_g.start_row = cur_row;
page_g.num_rows = ck_g.num_dict_entries;
page_g.num_leaf_values = ck_g.num_dict_entries;
page_g.num_values = ck_g.num_dict_entries; // TODO: shouldn't matter for dict page
page_offset +=
util::round_up_unsafe(page_g.max_hdr_size + page_g.max_data_size, page_align);
if (not comp_page_sizes.empty()) {
comp_page_offset += page_g.max_hdr_size + comp_page_sizes[ck_g.first_page];
}
page_headers_size += page_g.max_hdr_size;
max_page_data_size = max(max_page_data_size, page_g.max_data_size);
}
__syncwarp();
if (t == 0) {
if (not pages.empty()) {
page_g.kernel_mask = encode_kernel_mask::PLAIN;
pages[ck_g.first_page] = page_g;
}
if (not page_sizes.empty()) { page_sizes[ck_g.first_page] = page_g.max_data_size; }
if (page_grstats) { page_grstats[ck_g.first_page] = pagestats_g; }
}
num_pages = 1;
}
__syncwarp();
// page padding needed for RLE encoded boolean data
auto const rle_pad =
write_v2_headers && col_g.physical_type == BOOLEAN ? RLE_LENGTH_FIELD_LEN : 0;
// This loop goes over one page fragment at a time and adds it to page.
// When page size crosses a particular limit, then it moves on to the next page and then next
// page fragment gets added to that one.
// This doesn't actually deal with data. It's agnostic. It only cares about number of rows and
// page size.
do {
uint32_t minmax_len = 0;
__syncwarp();
if (num_rows < ck_g.num_rows) {
if (t == 0) { frag_g = ck_g.fragments[fragments_in_chunk]; }
if (!t && ck_g.stats) {
if (col_g.stats_dtype == dtype_string) {
minmax_len = max(ck_g.stats[fragments_in_chunk].min_value.str_val.length,
ck_g.stats[fragments_in_chunk].max_value.str_val.length);
} else if (col_g.stats_dtype == dtype_byte_array) {
minmax_len = max(ck_g.stats[fragments_in_chunk].min_value.byte_val.length,
ck_g.stats[fragments_in_chunk].max_value.byte_val.length);
}
}
} else if (!t) {
frag_g.fragment_data_size = 0;
frag_g.num_rows = 0;
}
__syncwarp();
uint32_t fragment_data_size =
(ck_g.use_dictionary)
? frag_g.num_leaf_values * util::div_rounding_up_unsafe(ck_g.dict_rle_bits, 8)
: frag_g.fragment_data_size;
// page fragment size must fit in a 32-bit signed integer
if (fragment_data_size > std::numeric_limits<int32_t>::max()) {
CUDF_UNREACHABLE("page fragment size exceeds maximum for i32");
}
// TODO (dm): this convoluted logic to limit page size needs refactoring
size_t this_max_page_size = (values_in_page * 2 >= ck_g.num_values) ? 256 * 1024
: (values_in_page * 3 >= ck_g.num_values) ? 384 * 1024
: 512 * 1024;
// override this_max_page_size if the requested size is smaller
this_max_page_size = min(this_max_page_size, max_page_size_bytes);
// subtract size of rep and def level vectors and RLE length field
auto num_vals = values_in_page + frag_g.num_values;
this_max_page_size = underflow_safe_subtract(
this_max_page_size,
max_RLE_page_size(col_g.num_def_level_bits(), num_vals) +
max_RLE_page_size(col_g.num_rep_level_bits(), num_vals) + rle_pad);
// checks to see when we need to close the current page and start a new one
auto const is_last_chunk = num_rows >= ck_g.num_rows;
auto const is_page_bytes_exceeded = page_size + fragment_data_size > this_max_page_size;
auto const is_page_rows_exceeded = rows_in_page + frag_g.num_rows > max_page_size_rows;
// only check for limit overflow if there's already at least one fragment for this page
auto const is_page_too_big =
values_in_page > 0 && (is_page_bytes_exceeded || is_page_rows_exceeded);
if (is_last_chunk || is_page_too_big) {
if (ck_g.use_dictionary) {
// Additional byte to store entry bit width
page_size = 1 + max_RLE_page_size(ck_g.dict_rle_bits, values_in_page);
}
if (!t) {
page_g.num_fragments = fragments_in_chunk - page_start;
page_g.chunk = &chunks[blockIdx.y][blockIdx.x];
page_g.chunk_id = blockIdx.y * num_columns + blockIdx.x;
page_g.page_type = data_page_type;
page_g.hdr_size = 0;
page_g.def_lvl_bytes = 0;
page_g.rep_lvl_bytes = 0;
page_g.max_lvl_size = 0;
page_g.data_size = 0;
page_g.comp_data_size = 0;
page_g.max_hdr_size = max_data_page_hdr_size; // Max size excluding statistics
if (ck_g.stats) {
uint32_t stats_hdr_len = 16;
if (col_g.stats_dtype == dtype_string || col_g.stats_dtype == dtype_byte_array) {
stats_hdr_len += 5 * 3 + 2 * max_stats_len;
} else {
stats_hdr_len += ((col_g.stats_dtype >= dtype_int64) ? 10 : 5) * 3;
}
page_g.max_hdr_size += stats_hdr_len;
}
page_g.max_hdr_size = util::round_up_unsafe(page_g.max_hdr_size, page_align);
page_g.page_data = ck_g.uncompressed_bfr + page_offset;
if (not comp_page_sizes.empty()) {
page_g.compressed_data = ck_g.compressed_bfr + comp_page_offset;
}
page_g.start_row = cur_row;
page_g.num_rows = rows_in_page;
page_g.num_leaf_values = leaf_values_in_page;
page_g.num_values = values_in_page;
page_g.num_valid = num_valid;
auto const def_level_size = max_RLE_page_size(col_g.num_def_level_bits(), values_in_page);
auto const rep_level_size = max_RLE_page_size(col_g.num_rep_level_bits(), values_in_page);
if (write_v2_headers) {
page_g.max_lvl_size =
util::round_up_unsafe(def_level_size + rep_level_size, page_align);
}
// get a different bound if using delta encoding
if (is_use_delta) {
auto const delta_len = delta_data_len(
physical_type, type_id, page_g.num_leaf_values, page_size, column_data_encoding);
page_size = max(page_size, delta_len);
}
auto const max_data_size =
page_size + rle_pad +
(write_v2_headers ? page_g.max_lvl_size : def_level_size + rep_level_size);
// page size must fit in 32-bit signed integer
if (max_data_size > std::numeric_limits<int32_t>::max()) {
CUDF_UNREACHABLE("page size exceeds maximum for i32");
}
// if byte_array then save the variable bytes size
if (ck_g.col_desc->physical_type == BYTE_ARRAY) {
// Page size is the sum of frag sizes, and frag sizes for strings includes the
// 4-byte length indicator, so subtract that.
page_g.var_bytes_size = var_bytes_size;
}
page_g.kernel_mask = column_data_encoding;
page_g.max_data_size = static_cast<uint32_t>(max_data_size);
pagestats_g.start_chunk = ck_g.first_fragment + page_start;
pagestats_g.num_chunks = page_g.num_fragments;
page_offset +=
util::round_up_unsafe(page_g.max_hdr_size + page_g.max_data_size, page_align);
// if encoding delta_byte_array, need to allocate some space for scratch data.
// if there are leaf nulls, we need space for a mapping array:
// sizeof(size_type) * num_leaf_values
// we always need prefix lengths: sizeof(size_type) * num_valid
if (page_g.kernel_mask == encode_kernel_mask::DELTA_BYTE_ARRAY) {
// scratch needs to be aligned to a size_type boundary
auto const pg_end = reinterpret_cast<uintptr_t>(ck_g.uncompressed_bfr + page_offset);
auto scratch = util::round_up_unsafe(pg_end, sizeof(size_type));
if (page_g.num_valid != page_g.num_leaf_values) {
scratch += sizeof(size_type) * page_g.num_leaf_values;
}
scratch += sizeof(size_type) * page_g.num_valid;
page_offset =
thrust::distance(ck_g.uncompressed_bfr, reinterpret_cast<uint8_t*>(scratch));
}
if (not comp_page_sizes.empty()) {
// V2 does not include level data in compressed size estimate
comp_page_offset += page_g.max_hdr_size + page_g.max_lvl_size +
comp_page_sizes[ck_g.first_page + num_pages];
}
page_headers_size += page_g.max_hdr_size;
max_page_data_size = max(max_page_data_size, page_g.max_data_size);
cur_row += rows_in_page;
ck_max_stats_len = max(ck_max_stats_len, max_stats_len);
}
__syncwarp();
if (t == 0) {
if (not pages.empty()) {
// need space for the chunk histograms plus data page histograms
auto const num_histograms = num_pages - ck_g.num_dict_pages();
if (ck_g.def_histogram_data != nullptr && col_g.max_def_level > 0) {
page_g.def_histogram =
ck_g.def_histogram_data + num_histograms * (col_g.max_def_level + 1);
}
if (ck_g.rep_histogram_data != nullptr && col_g.max_rep_level > 0) {
page_g.rep_histogram =
ck_g.rep_histogram_data + num_histograms * (col_g.max_rep_level + 1);
}
pages[ck_g.first_page + num_pages] = page_g;
}
// page_sizes should be the number of bytes to be compressed, so don't include level
// data for V2.
if (not page_sizes.empty()) {
page_sizes[ck_g.first_page + num_pages] = page_g.max_data_size - page_g.max_lvl_size;
}
if (page_grstats) { page_grstats[ck_g.first_page + num_pages] = pagestats_g; }
}
num_pages++;
page_size = 0;
var_bytes_size = 0;
rows_in_page = 0;
values_in_page = 0;
leaf_values_in_page = 0;
num_valid = 0;
page_start = fragments_in_chunk;
max_stats_len = 0;
}
max_stats_len = max(max_stats_len, minmax_len);
num_dict_entries += frag_g.num_dict_vals;
page_size += fragment_data_size;
// fragment_data_size includes the length indicator...remove it
var_bytes_size += frag_g.fragment_data_size - frag_g.num_valid * sizeof(size_type);
rows_in_page += frag_g.num_rows;
values_in_page += frag_g.num_values;
leaf_values_in_page += frag_g.num_leaf_values;
num_valid += frag_g.num_valid;
num_rows += frag_g.num_rows;
fragments_in_chunk++;
} while (frag_g.num_rows != 0);
__syncwarp();
if (!t) {
if (ck_g.ck_stat_size == 0 && ck_g.stats) {
uint32_t ck_stat_size = util::round_up_unsafe(48 + 2 * ck_max_stats_len, page_align);
page_offset += ck_stat_size;
comp_page_offset += ck_stat_size;
ck_g.ck_stat_size = ck_stat_size;
}
ck_g.num_pages = num_pages;
ck_g.bfr_size = page_offset;
ck_g.page_headers_size = page_headers_size;
ck_g.max_page_data_size = max_page_data_size;
if (not comp_page_sizes.empty()) { ck_g.compressed_size = comp_page_offset; }
pagestats_g.start_chunk = ck_g.first_page + ck_g.use_dictionary; // Exclude dictionary
pagestats_g.num_chunks = num_pages - ck_g.use_dictionary;
}
}
__syncthreads();
if (t == 0) {
if (not pages.empty()) ck_g.pages = &pages[ck_g.first_page];
chunks[blockIdx.y][blockIdx.x] = ck_g;
if (chunk_grstats) chunk_grstats[blockIdx.y * num_columns + blockIdx.x] = pagestats_g;
}
}
/**
* @brief Mask table representing how many consecutive repeats are needed to code a repeat run
*[nbits-1]
*/
static __device__ __constant__ uint32_t kRleRunMask[24] = {
0x00ff'ffff, 0x0fff, 0x00ff, 0x3f, 0x0f, 0x0f, 0x7, 0x7, 0x3, 0x3, 0x3, 0x3,
0x1, 0x1, 0x1, 0x1, 0x1, 0x1, 0x1, 0x1, 0x1, 0x1, 0x1, 0x1};
/**
* @brief Variable-length encode an integer
*/
inline __device__ uint8_t* VlqEncode(uint8_t* p, uint32_t v)
{
while (v > 0x7f) {
*p++ = (v | 0x80);
v >>= 7;
}
*p++ = v;
return p;
}
/**
* @brief Pack literal values in output bitstream (1,2,3,4,5,6,8,10,12,16,20 or 24 bits per value)
*/
inline __device__ void PackLiteralsShuffle(
uint8_t* dst, uint32_t v, uint32_t count, uint32_t w, uint32_t t)
{
constexpr uint32_t MASK2T = 1; // mask for 2 thread leader
constexpr uint32_t MASK4T = 3; // mask for 4 thread leader
constexpr uint32_t MASK8T = 7; // mask for 8 thread leader
uint64_t v64;
if (t > (count | 0x1f)) { return; }
switch (w) {
case 1:
v |= shuffle_xor(v, 1) << 1; // grab bit 1 from neighbor
v |= shuffle_xor(v, 2) << 2; // grab bits 2-3 from 2 lanes over
v |= shuffle_xor(v, 4) << 4; // grab bits 4-7 from 4 lanes over
// sub-warp leader writes the combined bits
if (t < count && !(t & MASK8T)) { dst[(t * w) >> 3] = v; }
return;
case 2:
v |= shuffle_xor(v, 1) << 2;
v |= shuffle_xor(v, 2) << 4;
if (t < count && !(t & MASK4T)) { dst[(t * w) >> 3] = v; }
return;
case 3:
v |= shuffle_xor(v, 1) << 3;
v |= shuffle_xor(v, 2) << 6;
v |= shuffle_xor(v, 4) << 12;
if (t < count && !(t & MASK8T)) {
dst[(t >> 3) * 3 + 0] = v;
dst[(t >> 3) * 3 + 1] = v >> 8;
dst[(t >> 3) * 3 + 2] = v >> 16;
}
return;
case 4:
v |= shuffle_xor(v, 1) << 4;
if (t < count && !(t & MASK2T)) { dst[(t * w) >> 3] = v; }
return;
case 5:
v |= shuffle_xor(v, 1) << 5;
v |= shuffle_xor(v, 2) << 10;
v64 = static_cast<uint64_t>(shuffle_xor(v, 4)) << 20 | v;
if (t < count && !(t & MASK8T)) {
dst[(t >> 3) * 5 + 0] = v64;
dst[(t >> 3) * 5 + 1] = v64 >> 8;
dst[(t >> 3) * 5 + 2] = v64 >> 16;
dst[(t >> 3) * 5 + 3] = v64 >> 24;
dst[(t >> 3) * 5 + 4] = v64 >> 32;
}
return;
case 6:
v |= shuffle_xor(v, 1) << 6;
v |= shuffle_xor(v, 2) << 12;
if (t < count && !(t & MASK4T)) {
dst[(t >> 2) * 3 + 0] = v;
dst[(t >> 2) * 3 + 1] = v >> 8;
dst[(t >> 2) * 3 + 2] = v >> 16;