-
Notifications
You must be signed in to change notification settings - Fork 114
/
alex_nodes.h
2330 lines (2099 loc) · 81.3 KB
/
alex_nodes.h
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) Microsoft Corporation.
// Licensed under the MIT license.
/*
* This file contains code for ALEX nodes. There are two types of nodes in ALEX:
* - Model nodes (equivalent to internal/inner nodes of a B+ Tree)
* - Data nodes, sometimes referred to as leaf nodes (equivalent to leaf nodes
* of a B+ Tree)
*/
#pragma once
#include "alex_base.h"
// Whether we store key and payload arrays separately in data nodes
// By default, we store them separately
#define ALEX_DATA_NODE_SEP_ARRAYS 1
#if ALEX_DATA_NODE_SEP_ARRAYS
#define ALEX_DATA_NODE_KEY_AT(i) key_slots_[i]
#define ALEX_DATA_NODE_PAYLOAD_AT(i) payload_slots_[i]
#else
#define ALEX_DATA_NODE_KEY_AT(i) data_slots_[i].first
#define ALEX_DATA_NODE_PAYLOAD_AT(i) data_slots_[i].second
#endif
// Whether we use lzcnt and tzcnt when manipulating a bitmap (e.g., when finding
// the closest gap).
// If your hardware does not support lzcnt/tzcnt (e.g., your Intel CPU is
// pre-Haswell), set this to 0.
#define ALEX_USE_LZCNT 1
namespace alex {
// A parent class for both types of ALEX nodes
template <class T, class P>
class AlexNode {
public:
// Whether this node is a leaf (data) node
bool is_leaf_ = false;
// Power of 2 to which the pointer to this node is duplicated in its parent
// model node
// For example, if duplication_factor_ is 3, then there are 8 redundant
// pointers to this node in its parent
uint8_t duplication_factor_ = 0;
// Node's level in the RMI. Root node is level 0
short level_ = 0;
// Both model nodes and data nodes nodes use models
LinearModel<T> model_;
// Could be either the expected or empirical cost, depending on how this field
// is used
double cost_ = 0.0;
AlexNode() = default;
explicit AlexNode(short level) : level_(level) {}
AlexNode(short level, bool is_leaf) : is_leaf_(is_leaf), level_(level) {}
virtual ~AlexNode() = default;
// The size in bytes of all member variables in this class
virtual long long node_size() const = 0;
};
template <class T, class P, class Alloc = std::allocator<std::pair<T, P>>>
class AlexModelNode : public AlexNode<T, P> {
public:
typedef AlexModelNode<T, P, Alloc> self_type;
typedef typename Alloc::template rebind<self_type>::other alloc_type;
typedef typename Alloc::template rebind<AlexNode<T, P>*>::other
pointer_alloc_type;
const Alloc& allocator_;
// Number of logical children. Must be a power of 2
int num_children_ = 0;
// Array of pointers to children
AlexNode<T, P>** children_ = nullptr;
explicit AlexModelNode(const Alloc& alloc = Alloc())
: AlexNode<T, P>(0, false), allocator_(alloc) {}
explicit AlexModelNode(short level, const Alloc& alloc = Alloc())
: AlexNode<T, P>(level, false), allocator_(alloc) {}
~AlexModelNode() {
if (children_ == nullptr) {
return;
}
pointer_allocator().deallocate(children_, num_children_);
}
AlexModelNode(const self_type& other)
: AlexNode<T, P>(other),
allocator_(other.allocator_),
num_children_(other.num_children_) {
children_ = new (pointer_allocator().allocate(other.num_children_))
AlexNode<T, P>*[other.num_children_];
std::copy(other.children_, other.children_ + other.num_children_,
children_);
}
// Given a key, traverses to the child node responsible for that key
inline AlexNode<T, P>* get_child_node(const T& key) {
int bucketID = this->model_.predict(key);
bucketID = std::min<int>(std::max<int>(bucketID, 0), num_children_ - 1);
return children_[bucketID];
}
// Expand by a power of 2 by creating duplicates of all existing child
// pointers.
// Input is the base 2 log of the expansion factor, in order to guarantee
// expanding by a power of 2.
// Returns the expansion factor.
int expand(int log2_expansion_factor) {
assert(log2_expansion_factor >= 0);
int expansion_factor = 1 << log2_expansion_factor;
int num_new_children = num_children_ * expansion_factor;
auto new_children = new (pointer_allocator().allocate(num_new_children))
AlexNode<T, P>*[num_new_children];
int cur = 0;
while (cur < num_children_) {
AlexNode<T, P>* cur_child = children_[cur];
int cur_child_repeats = 1 << cur_child->duplication_factor_;
for (int i = expansion_factor * cur;
i < expansion_factor * (cur + cur_child_repeats); i++) {
new_children[i] = cur_child;
}
cur_child->duplication_factor_ += log2_expansion_factor;
cur += cur_child_repeats;
}
pointer_allocator().deallocate(children_, num_children_);
children_ = new_children;
num_children_ = num_new_children;
this->model_.expand(expansion_factor);
return expansion_factor;
}
pointer_alloc_type pointer_allocator() {
return pointer_alloc_type(allocator_);
}
long long node_size() const override {
long long size = sizeof(self_type);
size += num_children_ * sizeof(AlexNode<T, P>*); // pointers to children
return size;
}
// Helpful for debugging
bool validate_structure(bool verbose = false) const {
if (num_children_ == 0) {
if (verbose) {
std::cout << "[Childless node] addr: " << this << ", level "
<< this->level_ << std::endl;
}
return false;
}
if (num_children_ == 1) {
if (verbose) {
std::cout << "[Single child node] addr: " << this << ", level "
<< this->level_ << std::endl;
}
return false;
}
if (std::ceil(std::log2(num_children_)) !=
std::floor(std::log2(num_children_))) {
if (verbose) {
std::cout << "[Num children not a power of 2] num children: "
<< num_children_ << std::endl;
}
return false;
}
if (this->model_.a_ == 0) {
if (verbose) {
std::cout << "[Model node with zero slope] addr: " << this << ", level "
<< this->level_ << std::endl;
}
return false;
}
AlexNode<T, P>* cur_child = children_[0];
int cur_repeats = 1;
int i;
for (i = 1; i < num_children_; i++) {
if (children_[i] == cur_child) {
cur_repeats++;
} else {
if (cur_repeats != (1 << cur_child->duplication_factor_)) {
if (verbose) {
std::cout << "[Incorrect duplication factor] num actual repeats: "
<< cur_repeats << ", num dup_factor repeats: "
<< (1 << cur_child->duplication_factor_)
<< ", parent addr: " << this
<< ", parent level: " << this->level_
<< ", parent num children: " << num_children_
<< ", child addr: " << children_[i - cur_repeats]
<< ", child pointer indexes: [" << i - cur_repeats << ", "
<< i << ")" << std::endl;
}
return false;
}
if (std::ceil(std::log2(cur_repeats)) !=
std::floor(std::log2(cur_repeats))) {
if (verbose) {
std::cout
<< "[Num duplicates not a power of 2] num actual repeats: "
<< cur_repeats << std::endl;
}
return false;
}
if (i % cur_repeats != 0) {
if (verbose) {
std::cout
<< "[Duplicate region incorrectly aligned] num actual repeats: "
<< cur_repeats << ", num dup_factor repeats: "
<< (1 << cur_child->duplication_factor_)
<< ", child pointer indexes: [" << i - cur_repeats << ", " << i
<< ")" << std::endl;
}
return false;
}
cur_child = children_[i];
cur_repeats = 1;
}
}
if (cur_repeats != (1 << cur_child->duplication_factor_)) {
if (verbose) {
std::cout << "[Incorrect duplication factor] num actual repeats: "
<< cur_repeats << ", num dup_factor repeats: "
<< (1 << cur_child->duplication_factor_)
<< ", parent addr: " << this
<< ", parent level: " << this->level_
<< ", parent num children: " << num_children_
<< ", child addr: " << children_[i - cur_repeats]
<< ", child pointer indexes: [" << i - cur_repeats << ", "
<< i << ")" << std::endl;
}
return false;
}
if (std::ceil(std::log2(cur_repeats)) !=
std::floor(std::log2(cur_repeats))) {
if (verbose) {
std::cout << "[Num duplicates not a power of 2] num actual repeats: "
<< cur_repeats << std::endl;
}
return false;
}
if (i % cur_repeats != 0) {
if (verbose) {
std::cout
<< "[Duplicate region incorrectly aligned] num actual repeats: "
<< cur_repeats << ", num dup_factor repeats: "
<< (1 << cur_child->duplication_factor_)
<< ", child pointer indexes: [" << i - cur_repeats << ", " << i
<< ")" << std::endl;
}
return false;
}
if (cur_repeats == num_children_) {
if (verbose) {
std::cout << "[All children are the same] num actual repeats: "
<< cur_repeats << ", parent addr: " << this
<< ", parent level: " << this->level_
<< ", parent num children: " << num_children_ << std::endl;
}
return false;
}
return true;
}
};
/*
* Functions are organized into different sections:
* - Constructors and destructors
* - General helper functions
* - Iterator
* - Cost model
* - Bulk loading and model building (e.g., bulk_load, bulk_load_from_existing)
* - Lookups (e.g., find_key, find_lower, find_upper, lower_bound, upper_bound)
* - Inserts and resizes (e.g, insert)
* - Deletes (e.g., erase, erase_one)
* - Stats
* - Debugging
*/
template <class T, class P, class Compare = AlexCompare,
class Alloc = std::allocator<std::pair<T, P>>,
bool allow_duplicates = true>
class AlexDataNode : public AlexNode<T, P> {
public:
typedef std::pair<T, P> V;
typedef AlexDataNode<T, P, Compare, Alloc, allow_duplicates> self_type;
typedef typename Alloc::template rebind<self_type>::other alloc_type;
typedef typename Alloc::template rebind<T>::other key_alloc_type;
typedef typename Alloc::template rebind<P>::other payload_alloc_type;
typedef typename Alloc::template rebind<V>::other value_alloc_type;
typedef typename Alloc::template rebind<uint64_t>::other bitmap_alloc_type;
const Compare& key_less_;
const Alloc& allocator_;
// Forward declaration
template <typename node_type = self_type, typename payload_return_type = P,
typename value_return_type = V>
class Iterator;
typedef Iterator<> iterator_type;
typedef Iterator<const self_type, const P, const V> const_iterator_type;
self_type* next_leaf_ = nullptr;
self_type* prev_leaf_ = nullptr;
#if ALEX_DATA_NODE_SEP_ARRAYS
T* key_slots_ = nullptr; // holds keys
P* payload_slots_ =
nullptr; // holds payloads, must be same size as key_slots
#else
V* data_slots_ = nullptr; // holds key-payload pairs
#endif
int data_capacity_ = 0; // size of key/data_slots array
int num_keys_ = 0; // number of filled key/data slots (as opposed to gaps)
// Bitmap: each uint64_t represents 64 positions in reverse order
// (i.e., each uint64_t is "read" from the right-most bit to the left-most
// bit)
uint64_t* bitmap_ = nullptr;
int bitmap_size_ = 0; // number of int64_t in bitmap
// Variables related to resizing (expansions and contractions)
static constexpr double kMaxDensity_ = 0.8; // density after contracting,
// also determines the expansion
// threshold
static constexpr double kInitDensity_ =
0.7; // density of data nodes after bulk loading
static constexpr double kMinDensity_ = 0.6; // density after expanding, also
// determines the contraction
// threshold
double expansion_threshold_ = 1; // expand after m_num_keys is >= this number
double contraction_threshold_ =
0; // contract after m_num_keys is < this number
static constexpr int kDefaultMaxDataNodeBytes_ =
1 << 24; // by default, maximum data node size is 16MB
int max_slots_ =
kDefaultMaxDataNodeBytes_ /
sizeof(V); // cannot expand beyond this number of key/data slots
// Counters used in cost models
long long num_shifts_ = 0; // does not reset after resizing
long long num_exp_search_iterations_ = 0; // does not reset after resizing
int num_lookups_ = 0; // does not reset after resizing
int num_inserts_ = 0; // does not reset after resizing
int num_resizes_ = 0; // technically not required, but nice to have
// Variables for determining append-mostly behavior
T max_key_ = std::numeric_limits<
T>::lowest(); // max key in node, updates after inserts but not erases
T min_key_ = std::numeric_limits<T>::max(); // min key in node, updates after
// inserts but not erases
int num_right_out_of_bounds_inserts_ =
0; // number of inserts that are larger than the max key
int num_left_out_of_bounds_inserts_ =
0; // number of inserts that are smaller than the min key
// Node is considered append-mostly if the fraction of inserts that are out of
// bounds is above this threshold
// Append-mostly nodes will expand in a manner that anticipates further
// appends
static constexpr double kAppendMostlyThreshold = 0.9;
// Purely for benchmark debugging purposes
double expected_avg_exp_search_iterations_ = 0;
double expected_avg_shifts_ = 0;
// Placed at the end of the key/data slots if there are gaps after the max key
static constexpr T kEndSentinel_ = std::numeric_limits<T>::max();
/*** Constructors and destructors ***/
explicit AlexDataNode(const Compare& comp = Compare(),
const Alloc& alloc = Alloc())
: AlexNode<T, P>(0, true), key_less_(comp), allocator_(alloc) {}
AlexDataNode(short level, int max_data_node_slots,
const Compare& comp = Compare(), const Alloc& alloc = Alloc())
: AlexNode<T, P>(level, true),
key_less_(comp),
allocator_(alloc),
max_slots_(max_data_node_slots) {}
~AlexDataNode() {
#if ALEX_DATA_NODE_SEP_ARRAYS
if (key_slots_ == nullptr) {
return;
}
key_allocator().deallocate(key_slots_, data_capacity_);
payload_allocator().deallocate(payload_slots_, data_capacity_);
#else
if (data_slots_ == nullptr) {
return;
}
value_allocator().deallocate(data_slots_, data_capacity_);
#endif
bitmap_allocator().deallocate(bitmap_, bitmap_size_);
}
AlexDataNode(const self_type& other)
: AlexNode<T, P>(other),
key_less_(other.key_less_),
allocator_(other.allocator_),
next_leaf_(other.next_leaf_),
prev_leaf_(other.prev_leaf_),
data_capacity_(other.data_capacity_),
num_keys_(other.num_keys_),
bitmap_size_(other.bitmap_size_),
expansion_threshold_(other.expansion_threshold_),
contraction_threshold_(other.contraction_threshold_),
max_slots_(other.max_slots_),
num_shifts_(other.num_shifts_),
num_exp_search_iterations_(other.num_exp_search_iterations_),
num_lookups_(other.num_lookups_),
num_inserts_(other.num_inserts_),
num_resizes_(other.num_resizes_),
max_key_(other.max_key_),
min_key_(other.min_key_),
num_right_out_of_bounds_inserts_(
other.num_right_out_of_bounds_inserts_),
num_left_out_of_bounds_inserts_(other.num_left_out_of_bounds_inserts_),
expected_avg_exp_search_iterations_(
other.expected_avg_exp_search_iterations_),
expected_avg_shifts_(other.expected_avg_shifts_) {
#if ALEX_DATA_NODE_SEP_ARRAYS
key_slots_ = new (key_allocator().allocate(other.data_capacity_))
T[other.data_capacity_];
std::copy(other.key_slots_, other.key_slots_ + other.data_capacity_,
key_slots_);
payload_slots_ = new (payload_allocator().allocate(other.data_capacity_))
P[other.data_capacity_];
std::copy(other.payload_slots_, other.payload_slots_ + other.data_capacity_,
payload_slots_);
#else
data_slots_ = new (value_allocator().allocate(other.data_capacity_))
V[other.data_capacity_];
std::copy(other.data_slots_, other.data_slots_ + other.data_capacity_,
data_slots_);
#endif
bitmap_ = new (bitmap_allocator().allocate(other.bitmap_size_))
uint64_t[other.bitmap_size_];
std::copy(other.bitmap_, other.bitmap_ + other.bitmap_size_, bitmap_);
}
/*** Allocators ***/
key_alloc_type key_allocator() { return key_alloc_type(allocator_); }
payload_alloc_type payload_allocator() {
return payload_alloc_type(allocator_);
}
value_alloc_type value_allocator() { return value_alloc_type(allocator_); }
bitmap_alloc_type bitmap_allocator() { return bitmap_alloc_type(allocator_); }
/*** General helper functions ***/
inline T& get_key(int pos) const { return ALEX_DATA_NODE_KEY_AT(pos); }
inline P& get_payload(int pos) const {
return ALEX_DATA_NODE_PAYLOAD_AT(pos);
}
// Check whether the position corresponds to a key (as opposed to a gap)
inline bool check_exists(int pos) const {
assert(pos >= 0 && pos < data_capacity_);
int bitmap_pos = pos >> 6;
int bit_pos = pos - (bitmap_pos << 6);
return static_cast<bool>(bitmap_[bitmap_pos] & (1ULL << bit_pos));
}
// Mark the entry for position in the bitmap
inline void set_bit(int pos) {
assert(pos >= 0 && pos < data_capacity_);
int bitmap_pos = pos >> 6;
int bit_pos = pos - (bitmap_pos << 6);
bitmap_[bitmap_pos] |= (1ULL << bit_pos);
}
// Mark the entry for position in the bitmap
inline void set_bit(uint64_t bitmap[], int pos) {
int bitmap_pos = pos >> 6;
int bit_pos = pos - (bitmap_pos << 6);
bitmap[bitmap_pos] |= (1ULL << bit_pos);
}
// Unmark the entry for position in the bitmap
inline void unset_bit(int pos) {
assert(pos >= 0 && pos < data_capacity_);
int bitmap_pos = pos >> 6;
int bit_pos = pos - (bitmap_pos << 6);
bitmap_[bitmap_pos] &= ~(1ULL << bit_pos);
}
// Value of first (i.e., min) key
T first_key() const {
for (int i = 0; i < data_capacity_; i++) {
if (check_exists(i)) return get_key(i);
}
return std::numeric_limits<T>::max();
}
// Value of last (i.e., max) key
T last_key() const {
for (int i = data_capacity_ - 1; i >= 0; i--) {
if (check_exists(i)) return get_key(i);
}
return std::numeric_limits<T>::lowest();
}
// Position in key/data_slots of first (i.e., min) key
int first_pos() const {
for (int i = 0; i < data_capacity_; i++) {
if (check_exists(i)) return i;
}
return 0;
}
// Position in key/data_slots of last (i.e., max) key
int last_pos() const {
for (int i = data_capacity_ - 1; i >= 0; i--) {
if (check_exists(i)) return i;
}
return 0;
}
// Number of keys between positions left and right (exclusive) in
// key/data_slots
int num_keys_in_range(int left, int right) const {
assert(left >= 0 && left <= right && right <= data_capacity_);
int num_keys = 0;
int left_bitmap_idx = left >> 6;
int right_bitmap_idx = right >> 6;
if (left_bitmap_idx == right_bitmap_idx) {
uint64_t bitmap_data = bitmap_[left_bitmap_idx];
int left_bit_pos = left - (left_bitmap_idx << 6);
bitmap_data &= ~((1ULL << left_bit_pos) - 1);
int right_bit_pos = right - (right_bitmap_idx << 6);
bitmap_data &= ((1ULL << right_bit_pos) - 1);
num_keys += _mm_popcnt_u64(bitmap_data);
} else {
uint64_t left_bitmap_data = bitmap_[left_bitmap_idx];
int bit_pos = left - (left_bitmap_idx << 6);
left_bitmap_data &= ~((1ULL << bit_pos) - 1);
num_keys += _mm_popcnt_u64(left_bitmap_data);
for (int i = left_bitmap_idx + 1; i < right_bitmap_idx; i++) {
num_keys += _mm_popcnt_u64(bitmap_[i]);
}
if (right_bitmap_idx != bitmap_size_) {
uint64_t right_bitmap_data = bitmap_[right_bitmap_idx];
bit_pos = right - (right_bitmap_idx << 6);
right_bitmap_data &= ((1ULL << bit_pos) - 1);
num_keys += _mm_popcnt_u64(right_bitmap_data);
}
}
return num_keys;
}
// True if a < b
template <class K>
forceinline bool key_less(const T& a, const K& b) const {
return key_less_(a, b);
}
// True if a <= b
template <class K>
forceinline bool key_lessequal(const T& a, const K& b) const {
return !key_less_(b, a);
}
// True if a > b
template <class K>
forceinline bool key_greater(const T& a, const K& b) const {
return key_less_(b, a);
}
// True if a >= b
template <class K>
forceinline bool key_greaterequal(const T& a, const K& b) const {
return !key_less_(a, b);
}
// True if a == b
template <class K>
forceinline bool key_equal(const T& a, const K& b) const {
return !key_less_(a, b) && !key_less_(b, a);
}
/*** Iterator ***/
// Forward iterator meant for iterating over a single data node.
// By default, it is a "normal" non-const iterator.
// Can be templated to be a const iterator.
template <typename node_type, typename payload_return_type,
typename value_return_type>
class Iterator {
public:
node_type* node_;
int cur_idx_ = 0; // current position in key/data_slots, -1 if at end
int cur_bitmap_idx_ = 0; // current position in bitmap
uint64_t cur_bitmap_data_ =
0; // caches the relevant data in the current bitmap position
explicit Iterator(node_type* node) : node_(node) {}
Iterator(node_type* node, int idx) : node_(node), cur_idx_(idx) {
initialize();
}
void initialize() {
cur_bitmap_idx_ = cur_idx_ >> 6;
cur_bitmap_data_ = node_->bitmap_[cur_bitmap_idx_];
// Zero out extra bits
int bit_pos = cur_idx_ - (cur_bitmap_idx_ << 6);
cur_bitmap_data_ &= ~((1ULL << bit_pos) - 1);
(*this)++;
}
void operator++(int) {
while (cur_bitmap_data_ == 0) {
cur_bitmap_idx_++;
if (cur_bitmap_idx_ >= node_->bitmap_size_) {
cur_idx_ = -1;
return;
}
cur_bitmap_data_ = node_->bitmap_[cur_bitmap_idx_];
}
uint64_t bit = extract_rightmost_one(cur_bitmap_data_);
cur_idx_ = get_offset(cur_bitmap_idx_, bit);
cur_bitmap_data_ = remove_rightmost_one(cur_bitmap_data_);
}
#if ALEX_DATA_NODE_SEP_ARRAYS
V operator*() const {
return std::make_pair(node_->key_slots_[cur_idx_],
node_->payload_slots_[cur_idx_]);
}
#else
value_return_type& operator*() const {
return node_->data_slots_[cur_idx_];
}
#endif
const T& key() const {
#if ALEX_DATA_NODE_SEP_ARRAYS
return node_->key_slots_[cur_idx_];
#else
return node_->data_slots_[cur_idx_].first;
#endif
}
payload_return_type& payload() const {
#if ALEX_DATA_NODE_SEP_ARRAYS
return node_->payload_slots_[cur_idx_];
#else
return node_->data_slots_[cur_idx_].second;
#endif
}
bool is_end() const { return cur_idx_ == -1; }
bool operator==(const Iterator& rhs) const {
return cur_idx_ == rhs.cur_idx_;
}
bool operator!=(const Iterator& rhs) const { return !(*this == rhs); };
};
iterator_type begin() { return iterator_type(this, 0); }
/*** Cost model ***/
// Empirical average number of shifts per insert
double shifts_per_insert() const {
if (num_inserts_ == 0) {
return 0;
}
return num_shifts_ / static_cast<double>(num_inserts_);
}
// Empirical average number of exponential search iterations per operation
// (either lookup or insert)
double exp_search_iterations_per_operation() const {
if (num_inserts_ + num_lookups_ == 0) {
return 0;
}
return num_exp_search_iterations_ /
static_cast<double>(num_inserts_ + num_lookups_);
}
double empirical_cost() const {
if (num_inserts_ + num_lookups_ == 0) {
return 0;
}
double frac_inserts =
static_cast<double>(num_inserts_) / (num_inserts_ + num_lookups_);
return kExpSearchIterationsWeight * exp_search_iterations_per_operation() +
kShiftsWeight * shifts_per_insert() * frac_inserts;
}
// Empirical fraction of operations (either lookup or insert) that are inserts
double frac_inserts() const {
int num_ops = num_inserts_ + num_lookups_;
if (num_ops == 0) {
return 0; // if no operations, assume no inserts
}
return static_cast<double>(num_inserts_) / (num_inserts_ + num_lookups_);
}
void reset_stats() {
num_shifts_ = 0;
num_exp_search_iterations_ = 0;
num_lookups_ = 0;
num_inserts_ = 0;
num_resizes_ = 0;
}
// Computes the expected cost of the current node
double compute_expected_cost(double frac_inserts = 0) {
if (num_keys_ == 0) {
return 0;
}
ExpectedSearchIterationsAccumulator search_iters_accumulator;
ExpectedShiftsAccumulator shifts_accumulator(data_capacity_);
const_iterator_type it(this, 0);
for (; !it.is_end(); it++) {
int predicted_position = std::max(
0, std::min(data_capacity_ - 1, this->model_.predict(it.key())));
search_iters_accumulator.accumulate(it.cur_idx_, predicted_position);
shifts_accumulator.accumulate(it.cur_idx_, predicted_position);
}
expected_avg_exp_search_iterations_ = search_iters_accumulator.get_stat();
expected_avg_shifts_ = shifts_accumulator.get_stat();
double cost =
kExpSearchIterationsWeight * expected_avg_exp_search_iterations_ +
kShiftsWeight * expected_avg_shifts_ * frac_inserts;
return cost;
}
// Computes the expected cost of a data node constructed using the input dense
// array of keys
// Assumes existing_model is trained on the dense array of keys
static double compute_expected_cost(
const V* values, int num_keys, double density,
double expected_insert_frac,
const LinearModel<T>* existing_model = nullptr, bool use_sampling = false,
DataNodeStats* stats = nullptr) {
if (use_sampling) {
return compute_expected_cost_sampling(values, num_keys, density,
expected_insert_frac,
existing_model, stats);
}
if (num_keys == 0) {
return 0;
}
int data_capacity =
std::max(static_cast<int>(num_keys / density), num_keys + 1);
// Compute what the node's model would be
LinearModel<T> model;
if (existing_model == nullptr) {
build_model(values, num_keys, &model);
} else {
model.a_ = existing_model->a_;
model.b_ = existing_model->b_;
}
model.expand(static_cast<double>(data_capacity) / num_keys);
// Compute expected stats in order to compute the expected cost
double cost = 0;
double expected_avg_exp_search_iterations = 0;
double expected_avg_shifts = 0;
if (expected_insert_frac == 0) {
ExpectedSearchIterationsAccumulator acc;
build_node_implicit(values, num_keys, data_capacity, &acc, &model);
expected_avg_exp_search_iterations = acc.get_stat();
} else {
ExpectedIterationsAndShiftsAccumulator acc(data_capacity);
build_node_implicit(values, num_keys, data_capacity, &acc, &model);
expected_avg_exp_search_iterations =
acc.get_expected_num_search_iterations();
expected_avg_shifts = acc.get_expected_num_shifts();
}
cost = kExpSearchIterationsWeight * expected_avg_exp_search_iterations +
kShiftsWeight * expected_avg_shifts * expected_insert_frac;
if (stats) {
stats->num_search_iterations = expected_avg_exp_search_iterations;
stats->num_shifts = expected_avg_shifts;
}
return cost;
}
// Helper function for compute_expected_cost
// Implicitly build the data node in order to collect the stats
static void build_node_implicit(const V* values, int num_keys,
int data_capacity, StatAccumulator* acc,
const LinearModel<T>* model) {
int last_position = -1;
int keys_remaining = num_keys;
for (int i = 0; i < num_keys; i++) {
int predicted_position = std::max(
0, std::min(data_capacity - 1, model->predict(values[i].first)));
int actual_position =
std::max<int>(predicted_position, last_position + 1);
int positions_remaining = data_capacity - actual_position;
if (positions_remaining < keys_remaining) {
actual_position = data_capacity - keys_remaining;
for (int j = i; j < num_keys; j++) {
predicted_position = std::max(
0, std::min(data_capacity - 1, model->predict(values[j].first)));
acc->accumulate(actual_position, predicted_position);
actual_position++;
}
break;
}
acc->accumulate(actual_position, predicted_position);
last_position = actual_position;
keys_remaining--;
}
}
// Using sampling, approximates the expected cost of a data node constructed
// using the input dense array of keys
// Assumes existing_model is trained on the dense array of keys
// Uses progressive sampling: keep increasing the sample size until the
// computed stats stop changing drastically
static double compute_expected_cost_sampling(
const V* values, int num_keys, double density,
double expected_insert_frac,
const LinearModel<T>* existing_model = nullptr,
DataNodeStats* stats = nullptr) {
const static int min_sample_size = 25;
// Stop increasing sample size if relative diff of stats between samples is
// less than this
const static double rel_diff_threshold = 0.2;
// Equivalent threshold in log2-space
const static double abs_log2_diff_threshold =
std::log2(1 + rel_diff_threshold);
// Increase sample size by this many times each iteration
const static int sample_size_multiplier = 2;
// If num_keys is below this threshold, we compute entropy exactly
const static int exact_computation_size_threshold =
(min_sample_size * sample_size_multiplier * sample_size_multiplier * 2);
// Target fraction of the keys to use in the initial sample
const static double init_sample_frac = 0.01;
// If the number of keys is sufficiently small, we do not sample
if (num_keys < exact_computation_size_threshold) {
return compute_expected_cost(values, num_keys, density,
expected_insert_frac, existing_model, false,
stats);
}
LinearModel<T> model; // trained for full dense array
if (existing_model == nullptr) {
build_model(values, num_keys, &model);
} else {
model.a_ = existing_model->a_;
model.b_ = existing_model->b_;
}
// Compute initial sample size and step size
// Right now, sample_num_keys holds the target sample num keys
int sample_num_keys = std::max(
static_cast<int>(num_keys * init_sample_frac), min_sample_size);
int step_size = 1;
double tmp_sample_size =
num_keys; // this helps us determine the right sample size
while (tmp_sample_size >= sample_num_keys) {
tmp_sample_size /= sample_size_multiplier;
step_size *= sample_size_multiplier;
}
step_size /= sample_size_multiplier;
sample_num_keys =
num_keys /
step_size; // now sample_num_keys is the actual sample num keys
std::vector<SampleDataNodeStats>
sample_stats; // stats computed usinig each sample
bool compute_shifts = expected_insert_frac !=
0; // whether we need to compute expected shifts
double log2_num_keys = std::log2(num_keys);
double expected_full_search_iters =
0; // extrapolated estimate for search iters on the full array
double expected_full_shifts =
0; // extrapolated estimate shifts on the full array
bool search_iters_computed =
false; // set to true when search iters is accurately computed
bool shifts_computed =
false; // set to true when shifts is accurately computed
// Progressively increase sample size
while (true) {
int sample_data_capacity = std::max(
static_cast<int>(sample_num_keys / density), sample_num_keys + 1);
LinearModel<T> sample_model(model.a_, model.b_);
sample_model.expand(static_cast<double>(sample_data_capacity) / num_keys);
// Compute stats using the sample
if (expected_insert_frac == 0) {
ExpectedSearchIterationsAccumulator acc;
build_node_implicit_sampling(values, num_keys, sample_num_keys,
sample_data_capacity, step_size, &acc,
&sample_model);
sample_stats.push_back({std::log2(sample_num_keys), acc.get_stat(), 0});
} else {
ExpectedIterationsAndShiftsAccumulator acc(sample_data_capacity);
build_node_implicit_sampling(values, num_keys, sample_num_keys,
sample_data_capacity, step_size, &acc,
&sample_model);
sample_stats.push_back({std::log2(sample_num_keys),
acc.get_expected_num_search_iterations(),
std::log2(acc.get_expected_num_shifts())});
}
if (sample_stats.size() >= 3) {
// Check if the diff in stats is sufficiently small
SampleDataNodeStats& s0 = sample_stats[sample_stats.size() - 3];
SampleDataNodeStats& s1 = sample_stats[sample_stats.size() - 2];
SampleDataNodeStats& s2 = sample_stats[sample_stats.size() - 1];
// (y1 - y0) / (x1 - x0) = (y2 - y1) / (x2 - x1) --> y2 = (y1 - y0) /
// (x1 - x0) * (x2 - x1) + y1
double expected_s2_search_iters =
(s1.num_search_iterations - s0.num_search_iterations) /
(s1.log2_sample_size - s0.log2_sample_size) *
(s2.log2_sample_size - s1.log2_sample_size) +
s1.num_search_iterations;
double rel_diff =
std::abs((s2.num_search_iterations - expected_s2_search_iters) /
s2.num_search_iterations);
if (rel_diff <= rel_diff_threshold || num_keys <= 2 * sample_num_keys) {
search_iters_computed = true;
expected_full_search_iters =
(s2.num_search_iterations - s1.num_search_iterations) /
(s2.log2_sample_size - s1.log2_sample_size) *
(log2_num_keys - s2.log2_sample_size) +
s2.num_search_iterations;
}
if (compute_shifts) {
double expected_s2_log2_shifts =
(s1.log2_num_shifts - s0.log2_num_shifts) /
(s1.log2_sample_size - s0.log2_sample_size) *
(s2.log2_sample_size - s1.log2_sample_size) +
s1.log2_num_shifts;
double abs_diff =
std::abs((s2.log2_num_shifts - expected_s2_log2_shifts) /
s2.log2_num_shifts);
if (abs_diff <= abs_log2_diff_threshold ||
num_keys <= 2 * sample_num_keys) {
shifts_computed = true;
double expected_full_log2_shifts =
(s2.log2_num_shifts - s1.log2_num_shifts) /
(s2.log2_sample_size - s1.log2_sample_size) *
(log2_num_keys - s2.log2_sample_size) +
s2.log2_num_shifts;
expected_full_shifts = std::pow(2, expected_full_log2_shifts);
}
}
// If diff in stats is sufficiently small, return the approximate
// expected cost
if ((expected_insert_frac == 0 && search_iters_computed) ||
(expected_insert_frac > 0 && search_iters_computed &&
shifts_computed)) {
double cost =
kExpSearchIterationsWeight * expected_full_search_iters +
kShiftsWeight * expected_full_shifts * expected_insert_frac;
if (stats) {
stats->num_search_iterations = expected_full_search_iters;
stats->num_shifts = expected_full_shifts;
}
return cost;
}
}
step_size /= sample_size_multiplier;
sample_num_keys = num_keys / step_size;
}