-
Notifications
You must be signed in to change notification settings - Fork 115
/
alex.h
3018 lines (2741 loc) · 113 KB
/
alex.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.
/*
* ALEX with key type T and payload type P, combined type V=std::pair<T, P>.
* Iterating through keys is done using an "Iterator".
* Iterating through tree nodes is done using a "NodeIterator".
*
* Core user-facing API of Alex:
* - Alex()
* - void bulk_load(V values[], int num_keys)
* - void insert(T key, P payload)
* - int erase_one(T key)
* - int erase(T key)
* - Iterator find(T key) // for exact match
* - Iterator begin()
* - Iterator end()
* - Iterator lower_bound(T key)
* - Iterator upper_bound(T key)
*
* User-facing API of Iterator:
* - void operator ++ () // post increment
* - V operator * () // does not return reference to V by default
* - const T& key ()
* - P& payload ()
* - bool is_end()
* - bool operator == (const Iterator & rhs)
* - bool operator != (const Iterator & rhs)
*/
#pragma once
#include <fstream>
#include <iostream>
#include <stack>
#include <type_traits>
#include "alex_base.h"
#include "alex_fanout_tree.h"
#include "alex_nodes.h"
// Whether we account for floating-point precision issues when traversing down
// ALEX.
// These issues rarely occur in practice but can cause incorrect behavior.
// Turning this on will cause slight performance overhead due to extra
// computation and possibly accessing two data nodes to perform a lookup.
#define ALEX_SAFE_LOOKUP 1
namespace alex {
template <class T, class P, class Compare = AlexCompare,
class Alloc = std::allocator<std::pair<T, P>>,
bool allow_duplicates = true>
class Alex {
static_assert(std::is_arithmetic<T>::value, "ALEX key type must be numeric.");
static_assert(std::is_same<Compare, AlexCompare>::value,
"Must use AlexCompare.");
public:
// Value type, returned by dereferencing an iterator
typedef std::pair<T, P> V;
// ALEX class aliases
typedef Alex<T, P, Compare, Alloc, allow_duplicates> self_type;
typedef AlexModelNode<T, P, Alloc> model_node_type;
typedef AlexDataNode<T, P, Compare, Alloc, allow_duplicates> data_node_type;
// Forward declaration for iterators
class Iterator;
class ConstIterator;
class ReverseIterator;
class ConstReverseIterator;
class NodeIterator; // Iterates through all nodes with pre-order traversal
AlexNode<T, P>* root_node_ = nullptr;
model_node_type* superroot_ =
nullptr; // phantom node that is the root's parent
/* User-changeable parameters */
struct Params {
// When bulk loading, Alex can use provided knowledge of the expected
// fraction of operations that will be inserts
// For simplicity, operations are either point lookups ("reads") or inserts
// ("writes)
// i.e., 0 means we expect a read-only workload, 1 means write-only
double expected_insert_frac = 1;
// Maximum node size, in bytes. By default, 16MB.
// Higher values result in better average throughput, but worse tail/max
// insert latency
int max_node_size = 1 << 24;
// Approximate model computation: bulk load faster by using sampling to
// train models
bool approximate_model_computation = true;
// Approximate cost computation: bulk load faster by using sampling to
// compute cost
bool approximate_cost_computation = false;
};
Params params_;
/* Setting max node size automatically changes these parameters */
struct DerivedParams {
// The defaults here assume the default max node size of 16MB
int max_fanout = 1 << 21; // assumes 8-byte pointers
int max_data_node_slots = (1 << 24) / sizeof(V);
};
DerivedParams derived_params_;
/* Counters, useful for benchmarking and profiling */
struct Stats {
int num_keys = 0;
int num_model_nodes = 0; // num model nodes
int num_data_nodes = 0; // num data nodes
int num_expand_and_scales = 0;
int num_expand_and_retrains = 0;
int num_downward_splits = 0;
int num_sideways_splits = 0;
int num_model_node_expansions = 0;
int num_model_node_splits = 0;
long long num_downward_split_keys = 0;
long long num_sideways_split_keys = 0;
long long num_model_node_expansion_pointers = 0;
long long num_model_node_split_pointers = 0;
mutable long long num_node_lookups = 0;
mutable long long num_lookups = 0;
long long num_inserts = 0;
double splitting_time = 0;
double cost_computation_time = 0;
};
Stats stats_;
/* These are for research purposes, a user should not change these */
struct ExperimentalParams {
// Fanout selection method used during bulk loading: 0 means use bottom-up
// fanout tree, 1 means top-down
int fanout_selection_method = 0;
// Policy when a data node experiences significant cost deviation.
// 0 means always split node in 2
// 1 means decide between no splitting or splitting in 2
// 2 means use a full fanout tree to decide the splitting strategy
int splitting_policy_method = 1;
// Splitting upwards means that a split can propagate all the way up to the
// root, like a B+ tree
// Splitting upwards can result in a better RMI, but has much more overhead
// than splitting sideways
bool allow_splitting_upwards = false;
};
ExperimentalParams experimental_params_;
/* Structs used internally */
private:
/* Statistics related to the key domain.
* The index can hold keys outside the domain, but lookups/inserts on those
* keys will be inefficient.
* If enough keys fall outside the key domain, then we expand the key domain.
*/
struct InternalStats {
T key_domain_min_ = std::numeric_limits<T>::max();
T key_domain_max_ = std::numeric_limits<T>::lowest();
int num_keys_above_key_domain = 0;
int num_keys_below_key_domain = 0;
int num_keys_at_last_right_domain_resize = 0;
int num_keys_at_last_left_domain_resize = 0;
};
InternalStats istats_;
/* Save the traversal path down the RMI by having a linked list of these
* structs. */
struct TraversalNode {
model_node_type* node = nullptr;
int bucketID = -1;
};
/* Used when finding the best way to propagate up the RMI when splitting
* upwards.
* Cost is in terms of additional model size created through splitting
* upwards, measured in units of pointers.
* One instance of this struct is created for each node on the traversal path.
* User should take into account the cost of metadata for new model nodes
* (base_cost). */
struct SplitDecisionCosts {
static constexpr double base_cost =
static_cast<double>(sizeof(model_node_type)) / sizeof(void*);
// Additional cost due to this node if propagation stops at this node.
// Equal to 0 if redundant slot exists, otherwise number of new pointers due
// to node expansion.
double stop_cost = 0;
// Additional cost due to this node if propagation continues past this node.
// Equal to number of new pointers due to node splitting, plus size of
// metadata of new model node.
double split_cost = 0;
};
// At least this many keys must be outside the domain before a domain
// expansion is triggered.
static const int kMinOutOfDomainKeys = 5;
// After this many keys are outside the domain, a domain expansion must be
// triggered.
static const int kMaxOutOfDomainKeys = 1000;
// When the number of max out-of-domain (OOD) keys is between the min and
// max, expand the domain if the number of OOD keys is greater than the
// expected number of OOD due to randomness by greater than the tolereance
// factor.
static const int kOutOfDomainToleranceFactor = 2;
Compare key_less_ = Compare();
Alloc allocator_ = Alloc();
/*** Constructors and setters ***/
public:
Alex() {
// Set up root as empty data node
auto empty_data_node = new (data_node_allocator().allocate(1))
data_node_type(key_less_, allocator_);
empty_data_node->bulk_load(nullptr, 0);
root_node_ = empty_data_node;
stats_.num_data_nodes++;
create_superroot();
}
Alex(const Compare& comp, const Alloc& alloc = Alloc())
: key_less_(comp), allocator_(alloc) {
// Set up root as empty data node
auto empty_data_node = new (data_node_allocator().allocate(1))
data_node_type(key_less_, allocator_);
empty_data_node->bulk_load(nullptr, 0);
root_node_ = empty_data_node;
stats_.num_data_nodes++;
create_superroot();
}
Alex(const Alloc& alloc) : allocator_(alloc) {
// Set up root as empty data node
auto empty_data_node = new (data_node_allocator().allocate(1))
data_node_type(key_less_, allocator_);
empty_data_node->bulk_load(nullptr, 0);
root_node_ = empty_data_node;
stats_.num_data_nodes++;
create_superroot();
}
~Alex() {
for (NodeIterator node_it = NodeIterator(this); !node_it.is_end();
node_it.next()) {
delete_node(node_it.current());
}
delete_node(superroot_);
}
// Initializes with range [first, last). The range does not need to be
// sorted. This creates a temporary copy of the data. If possible, we
// recommend directly using bulk_load() instead.
template <class InputIterator>
explicit Alex(InputIterator first, InputIterator last, const Compare& comp,
const Alloc& alloc = Alloc())
: key_less_(comp), allocator_(alloc) {
std::vector<V> values;
for (auto it = first; it != last; ++it) {
values.push_back(*it);
}
std::sort(values.begin(), values.end(),
[this](auto const& a, auto const& b) {
return key_less_(a.first, b.first);
});
bulk_load(values.data(), static_cast<int>(values.size()));
}
// Initializes with range [first, last). The range does not need to be
// sorted. This creates a temporary copy of the data. If possible, we
// recommend directly using bulk_load() instead.
template <class InputIterator>
explicit Alex(InputIterator first, InputIterator last,
const Alloc& alloc = Alloc())
: allocator_(alloc) {
std::vector<V> values;
for (auto it = first; it != last; ++it) {
values.push_back(*it);
}
std::sort(values.begin(), values.end(),
[this](auto const& a, auto const& b) {
return key_less_(a.first, b.first);
});
bulk_load(values.data(), static_cast<int>(values.size()));
}
explicit Alex(const self_type& other)
: params_(other.params_),
derived_params_(other.derived_params_),
stats_(other.stats_),
experimental_params_(other.experimental_params_),
istats_(other.istats_),
key_less_(other.key_less_),
allocator_(other.allocator_) {
superroot_ =
static_cast<model_node_type*>(copy_tree_recursive(other.superroot_));
root_node_ = superroot_->children_[0];
}
Alex& operator=(const self_type& other) {
if (this != &other) {
for (NodeIterator node_it = NodeIterator(this); !node_it.is_end();
node_it.next()) {
delete_node(node_it.current());
}
delete_node(superroot_);
params_ = other.params_;
derived_params_ = other.derived_params_;
experimental_params_ = other.experimental_params_;
istats_ = other.istats_;
stats_ = other.stats_;
key_less_ = other.key_less_;
allocator_ = other.allocator_;
superroot_ =
static_cast<model_node_type*>(copy_tree_recursive(other.superroot_));
root_node_ = superroot_->children_[0];
}
return *this;
}
void swap(const self_type& other) {
std::swap(params_, other.params_);
std::swap(derived_params_, other.derived_params_);
std::swap(experimental_params_, other.experimental_params_);
std::swap(istats_, other.istats_);
std::swap(stats_, other.stats_);
std::swap(key_less_, other.key_less_);
std::swap(allocator_, other.allocator_);
std::swap(superroot_, other.superroot_);
std::swap(root_node_, other.root_node_);
}
private:
// Deep copy of tree starting at given node
AlexNode<T, P>* copy_tree_recursive(const AlexNode<T, P>* node) {
if (!node) return nullptr;
if (node->is_leaf_) {
return new (data_node_allocator().allocate(1))
data_node_type(*static_cast<const data_node_type*>(node));
} else {
auto node_copy = new (model_node_allocator().allocate(1))
model_node_type(*static_cast<const model_node_type*>(node));
int cur = 0;
while (cur < node_copy->num_children_) {
AlexNode<T, P>* child_node = node_copy->children_[cur];
AlexNode<T, P>* child_node_copy = copy_tree_recursive(child_node);
int repeats = 1 << child_node_copy->duplication_factor_;
for (int i = cur; i < cur + repeats; i++) {
node_copy->children_[i] = child_node_copy;
}
cur += repeats;
}
return node_copy;
}
}
public:
// When bulk loading, Alex can use provided knowledge of the expected fraction
// of operations that will be inserts
// For simplicity, operations are either point lookups ("reads") or inserts
// ("writes)
// i.e., 0 means we expect a read-only workload, 1 means write-only
// This is only useful if you set it before bulk loading
void set_expected_insert_frac(double expected_insert_frac) {
assert(expected_insert_frac >= 0 && expected_insert_frac <= 1);
params_.expected_insert_frac = expected_insert_frac;
}
// Maximum node size, in bytes.
// Higher values result in better average throughput, but worse tail/max
// insert latency.
void set_max_node_size(int max_node_size) {
assert(max_node_size >= sizeof(V));
params_.max_node_size = max_node_size;
derived_params_.max_fanout = params_.max_node_size / sizeof(void*);
derived_params_.max_data_node_slots = params_.max_node_size / sizeof(V);
}
// Bulk load faster by using sampling to train models.
// This is only useful if you set it before bulk loading.
void set_approximate_model_computation(bool approximate_model_computation) {
params_.approximate_model_computation = approximate_model_computation;
}
// Bulk load faster by using sampling to compute cost.
// This is only useful if you set it before bulk loading.
void set_approximate_cost_computation(bool approximate_cost_computation) {
params_.approximate_cost_computation = approximate_cost_computation;
}
/*** General helpers ***/
public:
// Return the data node that contains the key (if it exists).
// Also optionally return the traversal path to the data node.
// traversal_path should be empty when calling this function.
// The returned traversal path begins with superroot and ends with the data
// node's parent.
#if ALEX_SAFE_LOOKUP
forceinline data_node_type* get_leaf(
T key, std::vector<TraversalNode>* traversal_path = nullptr) const {
if (traversal_path) {
traversal_path->push_back({superroot_, 0});
}
AlexNode<T, P>* cur = root_node_;
if (cur->is_leaf_) {
return static_cast<data_node_type*>(cur);
}
while (true) {
auto node = static_cast<model_node_type*>(cur);
double bucketID_prediction = node->model_.predict_double(key);
int bucketID = static_cast<int>(bucketID_prediction);
bucketID =
std::min<int>(std::max<int>(bucketID, 0), node->num_children_ - 1);
if (traversal_path) {
traversal_path->push_back({node, bucketID});
}
cur = node->children_[bucketID];
if (cur->is_leaf_) {
stats_.num_node_lookups += cur->level_;
auto leaf = static_cast<data_node_type*>(cur);
// Doesn't really matter if rounding is incorrect, we just want it to be
// fast.
// So we don't need to use std::round or std::lround.
int bucketID_prediction_rounded =
static_cast<int>(bucketID_prediction + 0.5);
double tolerance =
10 * std::numeric_limits<double>::epsilon() * bucketID_prediction;
// https://stackoverflow.com/questions/17333/what-is-the-most-effective-way-for-float-and-double-comparison
if (std::abs(bucketID_prediction - bucketID_prediction_rounded) <=
tolerance) {
if (bucketID_prediction_rounded <= bucketID_prediction) {
if (leaf->prev_leaf_ && leaf->prev_leaf_->last_key() >= key) {
if (traversal_path) {
// Correct the traversal path
correct_traversal_path(leaf, *traversal_path, true);
}
return leaf->prev_leaf_;
}
} else {
if (leaf->next_leaf_ && leaf->next_leaf_->first_key() <= key) {
if (traversal_path) {
// Correct the traversal path
correct_traversal_path(leaf, *traversal_path, false);
}
return leaf->next_leaf_;
}
}
}
return leaf;
}
}
}
#else
data_node_type* get_leaf(
T key, std::vector<TraversalNode>* traversal_path = nullptr) const {
if (traversal_path) {
traversal_path->push_back({superroot_, 0});
}
AlexNode<T, P>* cur = root_node_;
while (!cur->is_leaf_) {
auto node = static_cast<model_node_type*>(cur);
int bucketID = node->model_.predict(key);
bucketID =
std::min<int>(std::max<int>(bucketID, 0), node->num_children_ - 1);
if (traversal_path) {
traversal_path->push_back({node, bucketID});
}
cur = node->children_[bucketID];
}
stats_.num_node_lookups += cur->level_;
return static_cast<data_node_type*>(cur);
}
#endif
private:
// Make a correction to the traversal path to instead point to the leaf node
// that is to the left or right of the current leaf node.
inline void correct_traversal_path(data_node_type* leaf,
std::vector<TraversalNode>& traversal_path,
bool left) const {
if (left) {
int repeats = 1 << leaf->duplication_factor_;
TraversalNode& tn = traversal_path.back();
model_node_type* parent = tn.node;
// First bucket whose pointer is to leaf
int start_bucketID = tn.bucketID - (tn.bucketID % repeats);
if (start_bucketID == 0) {
// Traverse back up the traversal path to make correction
while (start_bucketID == 0) {
traversal_path.pop_back();
repeats = 1 << parent->duplication_factor_;
tn = traversal_path.back();
parent = tn.node;
start_bucketID = tn.bucketID - (tn.bucketID % repeats);
}
int correct_bucketID = start_bucketID - 1;
tn.bucketID = correct_bucketID;
AlexNode<T, P>* cur = parent->children_[correct_bucketID];
while (!cur->is_leaf_) {
auto node = static_cast<model_node_type*>(cur);
traversal_path.push_back({node, node->num_children_ - 1});
cur = node->children_[node->num_children_ - 1];
}
assert(cur == leaf->prev_leaf_);
} else {
tn.bucketID = start_bucketID - 1;
}
} else {
int repeats = 1 << leaf->duplication_factor_;
TraversalNode& tn = traversal_path.back();
model_node_type* parent = tn.node;
// First bucket whose pointer is not to leaf
int end_bucketID = tn.bucketID - (tn.bucketID % repeats) + repeats;
if (end_bucketID == parent->num_children_) {
// Traverse back up the traversal path to make correction
while (end_bucketID == parent->num_children_) {
traversal_path.pop_back();
repeats = 1 << parent->duplication_factor_;
tn = traversal_path.back();
parent = tn.node;
end_bucketID = tn.bucketID - (tn.bucketID % repeats) + repeats;
}
int correct_bucketID = end_bucketID;
tn.bucketID = correct_bucketID;
AlexNode<T, P>* cur = parent->children_[correct_bucketID];
while (!cur->is_leaf_) {
auto node = static_cast<model_node_type*>(cur);
traversal_path.push_back({node, 0});
cur = node->children_[0];
}
assert(cur == leaf->next_leaf_);
} else {
tn.bucketID = end_bucketID;
}
}
}
// Return left-most data node
data_node_type* first_data_node() const {
AlexNode<T, P>* cur = root_node_;
while (!cur->is_leaf_) {
cur = static_cast<model_node_type*>(cur)->children_[0];
}
return static_cast<data_node_type*>(cur);
}
// Return right-most data node
data_node_type* last_data_node() const {
AlexNode<T, P>* cur = root_node_;
while (!cur->is_leaf_) {
auto node = static_cast<model_node_type*>(cur);
cur = node->children_[node->num_children_ - 1];
}
return static_cast<data_node_type*>(cur);
}
// Returns minimum key in the index
T get_min_key() const { return first_data_node()->first_key(); }
// Returns maximum key in the index
T get_max_key() const { return last_data_node()->last_key(); }
// Link all data nodes together. Used after bulk loading.
void link_all_data_nodes() {
data_node_type* prev_leaf = nullptr;
for (NodeIterator node_it = NodeIterator(this); !node_it.is_end();
node_it.next()) {
AlexNode<T, P>* cur = node_it.current();
if (cur->is_leaf_) {
auto node = static_cast<data_node_type*>(cur);
if (prev_leaf != nullptr) {
prev_leaf->next_leaf_ = node;
node->prev_leaf_ = prev_leaf;
}
prev_leaf = node;
}
}
}
// Link the new data nodes together when old data node is replaced by two new
// data nodes.
void link_data_nodes(const data_node_type* old_leaf,
data_node_type* left_leaf, data_node_type* right_leaf) {
if (old_leaf->prev_leaf_ != nullptr) {
old_leaf->prev_leaf_->next_leaf_ = left_leaf;
}
left_leaf->prev_leaf_ = old_leaf->prev_leaf_;
left_leaf->next_leaf_ = right_leaf;
right_leaf->prev_leaf_ = left_leaf;
right_leaf->next_leaf_ = old_leaf->next_leaf_;
if (old_leaf->next_leaf_ != nullptr) {
old_leaf->next_leaf_->prev_leaf_ = right_leaf;
}
}
/*** Allocators and comparators ***/
public:
Alloc get_allocator() const { return allocator_; }
Compare key_comp() const { return key_less_; }
private:
typename model_node_type::alloc_type model_node_allocator() {
return typename model_node_type::alloc_type(allocator_);
}
typename data_node_type::alloc_type data_node_allocator() {
return typename data_node_type::alloc_type(allocator_);
}
typename model_node_type::pointer_alloc_type pointer_allocator() {
return typename model_node_type::pointer_alloc_type(allocator_);
}
void delete_node(AlexNode<T, P>* node) {
if (node == nullptr) {
return;
} else if (node->is_leaf_) {
data_node_allocator().destroy(static_cast<data_node_type*>(node));
data_node_allocator().deallocate(static_cast<data_node_type*>(node), 1);
} else {
model_node_allocator().destroy(static_cast<model_node_type*>(node));
model_node_allocator().deallocate(static_cast<model_node_type*>(node), 1);
}
}
// 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);
}
/*** Bulk loading ***/
public:
// values should be the sorted array of key-payload pairs.
// The number of elements should be num_keys.
// The index must be empty when calling this method.
void bulk_load(const V values[], int num_keys) {
if (stats_.num_keys > 0 || num_keys <= 0) {
return;
}
delete_node(root_node_); // delete the empty root node from constructor
stats_.num_keys = num_keys;
// Build temporary root model, which outputs a CDF in the range [0, 1]
root_node_ =
new (model_node_allocator().allocate(1)) model_node_type(0, allocator_);
T min_key = values[0].first;
T max_key = values[num_keys - 1].first;
root_node_->model_.a_ = 1.0 / (max_key - min_key);
root_node_->model_.b_ = -1.0 * min_key * root_node_->model_.a_;
// Compute cost of root node
LinearModel<T> root_data_node_model;
data_node_type::build_model(values, num_keys, &root_data_node_model,
params_.approximate_model_computation);
DataNodeStats stats;
root_node_->cost_ = data_node_type::compute_expected_cost(
values, num_keys, data_node_type::kInitDensity_,
params_.expected_insert_frac, &root_data_node_model,
params_.approximate_cost_computation, &stats);
// Recursively bulk load
bulk_load_node(values, num_keys, root_node_, num_keys,
&root_data_node_model);
if (root_node_->is_leaf_) {
static_cast<data_node_type*>(root_node_)
->expected_avg_exp_search_iterations_ = stats.num_search_iterations;
static_cast<data_node_type*>(root_node_)->expected_avg_shifts_ =
stats.num_shifts;
}
create_superroot();
update_superroot_key_domain();
link_all_data_nodes();
}
private:
// Only call this after creating a root node
void create_superroot() {
if (!root_node_) return;
delete_node(superroot_);
superroot_ = new (model_node_allocator().allocate(1))
model_node_type(static_cast<short>(root_node_->level_ - 1), allocator_);
superroot_->num_children_ = 1;
superroot_->children_ =
new (pointer_allocator().allocate(1)) AlexNode<T, P>*[1];
update_superroot_pointer();
}
// Updates the key domain based on the min/max keys and retrains the model.
// Should only be called immediately after bulk loading or when the root node
// is a data node.
void update_superroot_key_domain() {
assert(stats_.num_inserts == 0 || root_node_->is_leaf_);
istats_.key_domain_min_ = get_min_key();
istats_.key_domain_max_ = get_max_key();
istats_.num_keys_at_last_right_domain_resize = stats_.num_keys;
istats_.num_keys_at_last_left_domain_resize = stats_.num_keys;
istats_.num_keys_above_key_domain = 0;
istats_.num_keys_below_key_domain = 0;
superroot_->model_.a_ =
1.0 / (istats_.key_domain_max_ - istats_.key_domain_min_);
superroot_->model_.b_ =
-1.0 * istats_.key_domain_min_ * superroot_->model_.a_;
}
void update_superroot_pointer() {
superroot_->children_[0] = root_node_;
superroot_->level_ = static_cast<short>(root_node_->level_ - 1);
}
// Recursively bulk load a single node.
// Assumes node has already been trained to output [0, 1), has cost.
// Figures out the optimal partitioning of children.
// node is trained as if it's a model node.
// data_node_model is what the node's model would be if it were a data node of
// dense keys.
void bulk_load_node(const V values[], int num_keys, AlexNode<T, P>*& node,
int total_keys,
const LinearModel<T>* data_node_model = nullptr) {
// Automatically convert to data node when it is impossible to be better
// than current cost
if (num_keys <= derived_params_.max_data_node_slots *
data_node_type::kInitDensity_ &&
(node->cost_ < kNodeLookupsWeight || node->model_.a_ == 0)) {
stats_.num_data_nodes++;
auto data_node = new (data_node_allocator().allocate(1))
data_node_type(node->level_, derived_params_.max_data_node_slots,
key_less_, allocator_);
data_node->bulk_load(values, num_keys, data_node_model,
params_.approximate_model_computation);
data_node->cost_ = node->cost_;
delete_node(node);
node = data_node;
return;
}
// Use a fanout tree to determine the best way to divide the key space into
// child nodes
std::vector<fanout_tree::FTNode> used_fanout_tree_nodes;
std::pair<int, double> best_fanout_stats;
if (experimental_params_.fanout_selection_method == 0) {
int max_data_node_keys = static_cast<int>(
derived_params_.max_data_node_slots * data_node_type::kInitDensity_);
best_fanout_stats = fanout_tree::find_best_fanout_bottom_up<T, P>(
values, num_keys, node, total_keys, used_fanout_tree_nodes,
derived_params_.max_fanout, max_data_node_keys,
params_.expected_insert_frac, params_.approximate_model_computation,
params_.approximate_cost_computation, key_less_);
} else if (experimental_params_.fanout_selection_method == 1) {
best_fanout_stats = fanout_tree::find_best_fanout_top_down<T, P>(
values, num_keys, node, total_keys, used_fanout_tree_nodes,
derived_params_.max_fanout, params_.expected_insert_frac,
params_.approximate_model_computation,
params_.approximate_cost_computation, key_less_);
}
int best_fanout_tree_depth = best_fanout_stats.first;
double best_fanout_tree_cost = best_fanout_stats.second;
// Decide whether this node should be a model node or data node
if (best_fanout_tree_cost < node->cost_ ||
num_keys > derived_params_.max_data_node_slots *
data_node_type::kInitDensity_) {
// Convert to model node based on the output of the fanout tree
stats_.num_model_nodes++;
auto model_node = new (model_node_allocator().allocate(1))
model_node_type(node->level_, allocator_);
if (best_fanout_tree_depth == 0) {
// slightly hacky: we assume this means that the node is relatively
// uniform but we need to split in
// order to satisfy the max node size, so we compute the fanout that
// would satisfy that condition
// in expectation
best_fanout_tree_depth =
static_cast<int>(std::log2(static_cast<double>(num_keys) /
derived_params_.max_data_node_slots)) +
1;
used_fanout_tree_nodes.clear();
int max_data_node_keys = static_cast<int>(
derived_params_.max_data_node_slots * data_node_type::kInitDensity_);
fanout_tree::compute_level<T, P>(
values, num_keys, node, total_keys, used_fanout_tree_nodes,
best_fanout_tree_depth, max_data_node_keys,
params_.expected_insert_frac, params_.approximate_model_computation,
params_.approximate_cost_computation);
}
int fanout = 1 << best_fanout_tree_depth;
model_node->model_.a_ = node->model_.a_ * fanout;
model_node->model_.b_ = node->model_.b_ * fanout;
model_node->num_children_ = fanout;
model_node->children_ =
new (pointer_allocator().allocate(fanout)) AlexNode<T, P>*[fanout];
// Instantiate all the child nodes and recurse
int cur = 0;
for (fanout_tree::FTNode& tree_node : used_fanout_tree_nodes) {
auto child_node = new (model_node_allocator().allocate(1))
model_node_type(static_cast<short>(node->level_ + 1), allocator_);
child_node->cost_ = tree_node.cost;
child_node->duplication_factor_ =
static_cast<uint8_t>(best_fanout_tree_depth - tree_node.level);
int repeats = 1 << child_node->duplication_factor_;
double left_value = static_cast<double>(cur) / fanout;
double right_value = static_cast<double>(cur + repeats) / fanout;
double left_boundary = (left_value - node->model_.b_) / node->model_.a_;
double right_boundary =
(right_value - node->model_.b_) / node->model_.a_;
child_node->model_.a_ = 1.0 / (right_boundary - left_boundary);
child_node->model_.b_ = -child_node->model_.a_ * left_boundary;
model_node->children_[cur] = child_node;
LinearModel<T> child_data_node_model(tree_node.a, tree_node.b);
bulk_load_node(values + tree_node.left_boundary,
tree_node.right_boundary - tree_node.left_boundary,
model_node->children_[cur], total_keys,
&child_data_node_model);
model_node->children_[cur]->duplication_factor_ =
static_cast<uint8_t>(best_fanout_tree_depth - tree_node.level);
if (model_node->children_[cur]->is_leaf_) {
static_cast<data_node_type*>(model_node->children_[cur])
->expected_avg_exp_search_iterations_ =
tree_node.expected_avg_search_iterations;
static_cast<data_node_type*>(model_node->children_[cur])
->expected_avg_shifts_ = tree_node.expected_avg_shifts;
}
for (int i = cur + 1; i < cur + repeats; i++) {
model_node->children_[i] = model_node->children_[cur];
}
cur += repeats;
}
delete_node(node);
node = model_node;
} else {
// Convert to data node
stats_.num_data_nodes++;
auto data_node = new (data_node_allocator().allocate(1))
data_node_type(node->level_, derived_params_.max_data_node_slots,
key_less_, allocator_);
data_node->bulk_load(values, num_keys, data_node_model,
params_.approximate_model_computation);
data_node->cost_ = node->cost_;
delete_node(node);
node = data_node;
}
}
// Caller needs to set the level, duplication factor, and neighbor pointers of
// the returned data node
data_node_type* bulk_load_leaf_node_from_existing(
const data_node_type* existing_node, int left, int right,
bool compute_cost = true, const fanout_tree::FTNode* tree_node = nullptr,
bool reuse_model = false, bool keep_left = false,
bool keep_right = false) {
auto node = new (data_node_allocator().allocate(1))
data_node_type(key_less_, allocator_);
stats_.num_data_nodes++;
if (tree_node) {
// Use the model and num_keys saved in the tree node so we don't have to
// recompute it
LinearModel<T> precomputed_model(tree_node->a, tree_node->b);
node->bulk_load_from_existing(existing_node, left, right, keep_left,
keep_right, &precomputed_model,
tree_node->num_keys);
} else if (reuse_model) {
// Use the model from the existing node
// Assumes the model is accurate
int num_actual_keys = existing_node->num_keys_in_range(left, right);
LinearModel<T> precomputed_model(existing_node->model_);
precomputed_model.b_ -= left;
precomputed_model.expand(static_cast<double>(num_actual_keys) /
(right - left));
node->bulk_load_from_existing(existing_node, left, right, keep_left,
keep_right, &precomputed_model,
num_actual_keys);
} else {
node->bulk_load_from_existing(existing_node, left, right, keep_left,
keep_right);
}
node->max_slots_ = derived_params_.max_data_node_slots;
if (compute_cost) {
node->cost_ = node->compute_expected_cost(existing_node->frac_inserts());
}
return node;
}
/*** Lookup ***/
public:
// Looks for an exact match of the key
// If the key does not exist, returns an end iterator
// If there are multiple keys with the same value, returns an iterator to the
// right-most key
// If you instead want an iterator to the left-most key with the input value,
// use lower_bound()
typename self_type::Iterator find(const T& key) {
stats_.num_lookups++;
data_node_type* leaf = get_leaf(key);
int idx = leaf->find_key(key);
if (idx < 0) {
return end();
} else {
return Iterator(leaf, idx);
}
}
typename self_type::ConstIterator find(const T& key) const {
stats_.num_lookups++;
data_node_type* leaf = get_leaf(key);
int idx = leaf->find_key(key);
if (idx < 0) {
return cend();
} else {
return ConstIterator(leaf, idx);
}
}
size_t count(const T& key) {
ConstIterator it = lower_bound(key);
size_t num_equal = 0;
while (!it.is_end() && key_equal(it.key(), key)) {
num_equal++;
++it;
}
return num_equal;
}
// Returns an iterator to the first key no less than the input value
typename self_type::Iterator lower_bound(const T& key) {
stats_.num_lookups++;
data_node_type* leaf = get_leaf(key);
int idx = leaf->find_lower(key);
return Iterator(leaf, idx); // automatically handles the case where idx ==
// leaf->data_capacity
}
typename self_type::ConstIterator lower_bound(const T& key) const {
stats_.num_lookups++;
data_node_type* leaf = get_leaf(key);
int idx = leaf->find_lower(key);
return ConstIterator(leaf, idx); // automatically handles the case where
// idx == leaf->data_capacity
}
// Returns an iterator to the first key greater than the input value
typename self_type::Iterator upper_bound(const T& key) {
stats_.num_lookups++;
data_node_type* leaf = get_leaf(key);
int idx = leaf->find_upper(key);
return Iterator(leaf, idx); // automatically handles the case where idx ==
// leaf->data_capacity
}
typename self_type::ConstIterator upper_bound(const T& key) const {
stats_.num_lookups++;
data_node_type* leaf = get_leaf(key);
int idx = leaf->find_upper(key);
return ConstIterator(leaf, idx); // automatically handles the case where
// idx == leaf->data_capacity
}
std::pair<Iterator, Iterator> equal_range(const T& key) {
return std::pair<Iterator, Iterator>(lower_bound(key), upper_bound(key));
}
std::pair<ConstIterator, ConstIterator> equal_range(const T& key) const {
return std::pair<ConstIterator, ConstIterator>(lower_bound(key),
upper_bound(key));
}
// Directly returns a pointer to the payload found through find(key)
// This avoids the overhead of creating an iterator
// Returns null pointer if there is no exact match of the key
P* get_payload(const T& key) const {
stats_.num_lookups++;
data_node_type* leaf = get_leaf(key);
int idx = leaf->find_key(key);
if (idx < 0) {
return nullptr;
} else {
return &(leaf->get_payload(idx));
}
}
// Looks for the last key no greater than the input value
// Conceptually, this is equal to the last key before upper_bound()
typename self_type::Iterator find_last_no_greater_than(const T& key) {
stats_.num_lookups++;
data_node_type* leaf = get_leaf(key);
const int idx = leaf->upper_bound(key) - 1;