-
Notifications
You must be signed in to change notification settings - Fork 108
Expand file tree
/
Copy pathopen_addressing_ref_impl.cuh
More file actions
1817 lines (1650 loc) · 68.6 KB
/
open_addressing_ref_impl.cuh
File metadata and controls
1817 lines (1650 loc) · 68.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (c) 2023-2024, NVIDIA CORPORATION.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#pragma once
#include <cuco/detail/equal_wrapper.cuh>
#include <cuco/detail/probing_scheme/probing_scheme_base.cuh>
#include <cuco/detail/utility/cuda.cuh>
#include <cuco/extent.cuh>
#include <cuco/pair.cuh>
#include <cuco/probing_scheme.cuh>
#include <cuda/atomic>
#include <cuda/std/type_traits>
#include <thrust/distance.h>
#include <thrust/execution_policy.h>
#include <thrust/logical.h>
#include <thrust/reduce.h>
#include <thrust/tuple.h>
#if defined(CUCO_HAS_CUDA_BARRIER)
#include <cuda/barrier>
#endif
#include <cooperative_groups.h>
#include <cstdint>
#include <type_traits>
namespace cuco {
namespace detail {
/// Three-way insert result enum
enum class insert_result : int32_t { CONTINUE = 0, SUCCESS = 1, DUPLICATE = 2 };
/**
* @brief Helper struct to store intermediate bucket probing results.
*/
struct bucket_probing_results {
detail::equal_result state_; ///< Equal result
int32_t intra_bucket_index_; ///< Intra-bucket index
/**
* @brief Constructs bucket_probing_results.
*
* @param state The three way equality result
* @param index Intra-bucket index
*/
__device__ explicit constexpr bucket_probing_results(detail::equal_result state,
int32_t index) noexcept
: state_{state}, intra_bucket_index_{index}
{
}
};
/**
* @brief Common device non-owning "ref" implementation class.
*
* @note This class should NOT be used directly.
*
* @throw If the size of the given key type is larger than 8 bytes
* @throw If the given key type doesn't have unique object representations, i.e.,
* `cuco::bitwise_comparable_v<Key> == false`
* @throw If the probing scheme type is not inherited from `cuco::detail::probing_scheme_base`
*
* @tparam Key Type used for keys. Requires `cuco::is_bitwise_comparable_v<Key>` returning true
* @tparam Scope The scope in which operations will be performed by individual threads.
* @tparam KeyEqual Binary callable type used to compare two keys for equality
* @tparam ProbingScheme Probing scheme (see `include/cuco/probing_scheme.cuh` for options)
* @tparam StorageRef Storage ref type
* @tparam AllowsDuplicates Flag indicating whether duplicate keys are allowed or not
*/
template <typename Key,
cuda::thread_scope Scope,
typename KeyEqual,
typename ProbingScheme,
typename StorageRef,
bool AllowsDuplicates>
class open_addressing_ref_impl {
static_assert(sizeof(Key) <= 8, "Container does not support key types larger than 8 bytes.");
static_assert(
cuco::is_bitwise_comparable_v<Key>,
"Key type must have unique object representations or have been explicitly declared as safe for "
"bitwise comparison via specialization of cuco::is_bitwise_comparable_v<Key>.");
static_assert(
std::is_base_of_v<cuco::detail::probing_scheme_base<ProbingScheme::cg_size>, ProbingScheme>,
"ProbingScheme must inherit from cuco::detail::probing_scheme_base");
/// Determines if the container is a key/value or key-only store
static constexpr auto has_payload = not std::is_same_v<Key, typename StorageRef::value_type>;
/// Flag indicating whether duplicate keys are allowed or not
static constexpr auto allows_duplicates = AllowsDuplicates;
// TODO: how to re-enable this check?
// static_assert(is_bucket_extent_v<typename StorageRef::extent_type>,
// "Extent is not a valid cuco::bucket_extent");
public:
using key_type = Key; ///< Key type
using probing_scheme_type = ProbingScheme; ///< Type of probing scheme
using hasher = typename probing_scheme_type::hasher; ///< Hash function type
using storage_ref_type = StorageRef; ///< Type of storage ref
using bucket_type = typename storage_ref_type::bucket_type; ///< Bucket type
using value_type = typename storage_ref_type::value_type; ///< Storage element type
using extent_type = typename storage_ref_type::extent_type; ///< Extent type
using size_type = typename storage_ref_type::size_type; ///< Probing scheme size type
using key_equal = KeyEqual; ///< Type of key equality binary callable
using iterator = typename storage_ref_type::iterator; ///< Slot iterator type
using const_iterator = typename storage_ref_type::const_iterator; ///< Const slot iterator type
static constexpr auto cg_size = probing_scheme_type::cg_size; ///< Cooperative group size
static constexpr auto bucket_size =
storage_ref_type::bucket_size; ///< Number of elements handled per bucket
static constexpr auto thread_scope = Scope; ///< CUDA thread scope
/**
* @brief Constructs open_addressing_ref_impl.
*
* @param empty_slot_sentinel Sentinel indicating an empty slot
* @param predicate Key equality binary callable
* @param probing_scheme Probing scheme
* @param storage_ref Non-owning ref of slot storage
*/
__host__ __device__ explicit constexpr open_addressing_ref_impl(
value_type empty_slot_sentinel,
key_equal const& predicate,
probing_scheme_type const& probing_scheme,
storage_ref_type storage_ref) noexcept
: empty_slot_sentinel_{empty_slot_sentinel},
predicate_{
this->extract_key(empty_slot_sentinel), this->extract_key(empty_slot_sentinel), predicate},
probing_scheme_{probing_scheme},
storage_ref_{storage_ref}
{
}
/**
* @brief Constructs open_addressing_ref_impl.
*
* @param empty_slot_sentinel Sentinel indicating an empty slot
* @param erased_key_sentinel Sentinel indicating an erased key
* @param predicate Key equality binary callable
* @param probing_scheme Probing scheme
* @param storage_ref Non-owning ref of slot storage
*/
__host__ __device__ explicit constexpr open_addressing_ref_impl(
value_type empty_slot_sentinel,
key_type erased_key_sentinel,
key_equal const& predicate,
probing_scheme_type const& probing_scheme,
storage_ref_type storage_ref) noexcept
: empty_slot_sentinel_{empty_slot_sentinel},
predicate_{this->extract_key(empty_slot_sentinel), erased_key_sentinel, predicate},
probing_scheme_{probing_scheme},
storage_ref_{storage_ref}
{
}
/**
* @brief Gets the sentinel value used to represent an empty key slot.
*
* @return The sentinel value used to represent an empty key slot
*/
[[nodiscard]] __host__ __device__ constexpr key_type const& empty_key_sentinel() const noexcept
{
return this->predicate_.empty_sentinel_;
}
/**
* @brief Gets the sentinel value used to represent an empty payload slot.
*
* @return The sentinel value used to represent an empty payload slot
*/
template <bool Dummy = true, typename Enable = std::enable_if_t<has_payload and Dummy>>
[[nodiscard]] __host__ __device__ constexpr auto const& empty_value_sentinel() const noexcept
{
return this->extract_payload(this->empty_slot_sentinel());
}
/**
* @brief Gets the sentinel value used to represent an erased key slot.
*
* @return The sentinel value used to represent an erased key slot
*/
[[nodiscard]] __host__ __device__ constexpr key_type const& erased_key_sentinel() const noexcept
{
return this->predicate_.erased_sentinel_;
}
/**
* @brief Gets the sentinel used to represent an empty slot.
*
* @return The sentinel value used to represent an empty slot
*/
[[nodiscard]] __host__ __device__ constexpr value_type const& empty_slot_sentinel() const noexcept
{
return empty_slot_sentinel_;
}
/**
* @brief Returns the function that compares keys for equality.
*
* @return The key equality predicate
*/
[[nodiscard]] __host__ __device__ constexpr detail::equal_wrapper<key_type, key_equal> const&
predicate() const noexcept
{
return this->predicate_;
}
/**
* @brief Gets the key comparator.
*
* @return The comparator used to compare keys
*/
[[nodiscard]] __host__ __device__ constexpr key_equal key_eq() const noexcept
{
return this->predicate().equal_;
}
/**
* @brief Gets the probing scheme.
*
* @return The probing scheme used for the container
*/
[[nodiscard]] __host__ __device__ constexpr probing_scheme_type const& probing_scheme()
const noexcept
{
return probing_scheme_;
}
/**
* @brief Gets the function(s) used to hash keys
*
* @return The function(s) used to hash keys
*/
[[nodiscard]] __host__ __device__ constexpr hasher hash_function() const noexcept
{
return this->probing_scheme().hash_function();
}
/**
* @brief Gets the non-owning storage ref.
*
* @return The non-owning storage ref of the container
*/
[[nodiscard]] __host__ __device__ constexpr storage_ref_type const& storage_ref() const noexcept
{
return storage_ref_;
}
/**
* @brief Gets the maximum number of elements the container can hold.
*
* @return The maximum number of elements the container can hold
*/
[[nodiscard]] __host__ __device__ constexpr auto capacity() const noexcept
{
return storage_ref_.capacity();
}
/**
* @brief Gets the bucket extent of the current storage.
*
* @return The bucket extent.
*/
[[nodiscard]] __host__ __device__ constexpr extent_type bucket_extent() const noexcept
{
return storage_ref_.bucket_extent();
}
/**
* @brief Returns a const_iterator to one past the last slot.
*
* @return A const_iterator to one past the last slot
*/
[[nodiscard]] __host__ __device__ constexpr const_iterator end() const noexcept
{
return storage_ref_.end();
}
/**
* @brief Returns an iterator to one past the last slot.
*
* @return An iterator to one past the last slot
*/
[[nodiscard]] __host__ __device__ constexpr iterator end() noexcept { return storage_ref_.end(); }
/**
* @brief Makes a copy of the current device reference using non-owned memory.
*
* This function is intended to be used to create shared memory copies of small static data
* structures, although global memory can be used as well.
*
* @tparam CG The type of the cooperative thread group
*
* @param g The ooperative thread group used to copy the data structure
* @param memory_to_use Array large enough to support `capacity` elements. Object does not take
* the ownership of the memory
*/
template <typename CG>
__device__ void make_copy(CG const& g, bucket_type* const memory_to_use) const noexcept
{
auto const num_buckets = static_cast<size_type>(this->bucket_extent());
#if defined(CUCO_HAS_CUDA_BARRIER)
#pragma nv_diagnostic push
// Disables `barrier` initialization warning.
#pragma nv_diag_suppress static_var_with_dynamic_init
__shared__ cuda::barrier<cuda::thread_scope::thread_scope_block> barrier;
#pragma nv_diagnostic pop
if (g.thread_rank() == 0) { init(&barrier, g.size()); }
g.sync();
cuda::memcpy_async(
g, memory_to_use, this->storage_ref().data(), sizeof(bucket_type) * num_buckets, barrier);
barrier.arrive_and_wait();
#else
bucket_type const* const buckets_ptr = this->storage_ref().data();
for (size_type i = g.thread_rank(); i < num_buckets; i += g.size()) {
memory_to_use[i] = buckets_ptr[i];
}
g.sync();
#endif
}
/**
* @brief Initializes the container storage.
*
* @note This function synchronizes the group `tile`.
*
* @tparam CG The type of the cooperative thread group
*
* @param tile The cooperative thread group used to initialize the container
*/
template <typename CG>
__device__ constexpr void initialize(CG const& tile) noexcept
{
auto tid = tile.thread_rank();
auto* const buckets_ptr = this->storage_ref().data();
while (tid < static_cast<size_type>(this->bucket_extent())) {
auto& bucket = *(buckets_ptr + tid);
#pragma unroll
for (auto& slot : bucket) {
slot = this->empty_slot_sentinel();
}
tid += tile.size();
}
tile.sync();
}
/**
* @brief Inserts an element.
*
* @tparam Value Input type which is convertible to 'value_type'
*
* @param value The element to insert
*
* @return True if the given element is successfully inserted
*/
template <typename Value>
__device__ bool insert(Value const& value) noexcept
{
static_assert(cg_size == 1, "Non-CG operation is incompatible with the current probing scheme");
auto const val = this->heterogeneous_value(value);
auto const key = this->extract_key(val);
auto probing_iter = probing_scheme_(key, storage_ref_.bucket_extent());
auto const init_idx = *probing_iter;
[[maybe_unused]] auto probing_iter_copy = probing_iter;
[[maybe_unused]] bool erased = false;
[[maybe_unused]] bool empty_after_erased = false;
while (true) {
[[maybe_unused]] continue_after_erased:
auto const bucket_slots = storage_ref_[*probing_iter];
for (auto& slot_content : bucket_slots) {
auto const eq_res =
this->predicate_.operator()<is_insert::YES>(key, this->extract_key(slot_content));
if constexpr (not allows_duplicates) {
// If the key is already in the container, return false
if (eq_res == detail::equal_result::EQUAL) { return false; }
if (eq_res == detail::equal_result::ERASED and not erased and not empty_after_erased) {
erased = true;
probing_iter_copy = probing_iter;
}
if (eq_res == detail::equal_result::EMPTY and erased and not empty_after_erased) {
empty_after_erased = true;
probing_iter = probing_iter_copy;
goto continue_after_erased;
}
}
if (not erased or empty_after_erased) {
if ((eq_res == detail::equal_result::EMPTY) or (eq_res == detail::equal_result::ERASED)) {
auto const intra_bucket_index = thrust::distance(bucket_slots.begin(), &slot_content);
switch (
attempt_insert((storage_ref_.data() + *probing_iter)->data() + intra_bucket_index,
slot_content,
val)) {
case insert_result::DUPLICATE: {
if constexpr (allows_duplicates) {
[[fallthrough]];
} else {
return false;
}
}
case insert_result::CONTINUE: continue;
case insert_result::SUCCESS: return true;
}
}
}
}
++probing_iter;
if (*probing_iter == init_idx) { return false; }
}
}
/**
* @brief Inserts an element.
*
* @tparam Value Input type which is convertible to 'value_type'
*
* @param group The Cooperative Group used to perform group insert
* @param value The element to insert
*
* @return True if the given element is successfully inserted
*/
template <typename Value>
__device__ bool insert(cooperative_groups::thread_block_tile<cg_size> const& group,
Value const& value) noexcept
{
auto const val = this->heterogeneous_value(value);
auto const key = this->extract_key(val);
auto probing_iter = probing_scheme_(group, key, storage_ref_.bucket_extent());
auto const init_idx = *probing_iter;
while (true) {
auto const bucket_slots = storage_ref_[*probing_iter];
auto const [state, intra_bucket_index] = [&]() {
for (auto i = 0; i < bucket_size; ++i) {
switch (
this->predicate_.operator()<is_insert::YES>(key, this->extract_key(bucket_slots[i]))) {
case detail::equal_result::EMPTY:
return bucket_probing_results{detail::equal_result::EMPTY, i};
case detail::equal_result::ERASED:
return bucket_probing_results{detail::equal_result::ERASED, i};
case detail::equal_result::EQUAL: {
if constexpr (allows_duplicates) {
continue;
} else {
return bucket_probing_results{detail::equal_result::EQUAL, i};
}
}
default: continue;
}
}
// returns dummy index `-1` for UNEQUAL
return bucket_probing_results{detail::equal_result::UNEQUAL, -1};
}();
if constexpr (not allows_duplicates) {
// If the key is already in the container, return false
if (group.any(state == detail::equal_result::EQUAL)) { return false; }
}
auto const group_contains_available = group.ballot((state == detail::equal_result::EMPTY) or
(state == detail::equal_result::ERASED));
if (group_contains_available) {
auto const src_lane = __ffs(group_contains_available) - 1;
auto const status =
(group.thread_rank() == src_lane)
? attempt_insert((storage_ref_.data() + *probing_iter)->data() + intra_bucket_index,
bucket_slots[intra_bucket_index],
val)
: insert_result::CONTINUE;
switch (group.shfl(status, src_lane)) {
case insert_result::SUCCESS: return true;
case insert_result::DUPLICATE: {
if constexpr (allows_duplicates) {
[[fallthrough]];
} else {
return false;
}
}
default: continue;
}
} else {
++probing_iter;
if (*probing_iter == init_idx) { return false; }
}
}
}
/**
* @brief Inserts the given element into the container.
*
* @note This API returns a pair consisting of an iterator to the inserted element (or to the
* element that prevented the insertion) and a `bool` denoting whether the insertion took place or
* not.
*
* @tparam Value Input type which is convertible to 'value_type'
*
* @param value The element to insert
*
* @return a pair consisting of an iterator to the element and a bool indicating whether the
* insertion is successful or not.
*/
template <typename Value>
__device__ thrust::pair<iterator, bool> insert_and_find(Value const& value) noexcept
{
static_assert(cg_size == 1, "Non-CG operation is incompatible with the current probing scheme");
#if __CUDA_ARCH__ < 700
// Spinning to ensure that the write to the value part took place requires
// independent thread scheduling introduced with the Volta architecture.
static_assert(
cuco::detail::is_packable<value_type>(),
"insert_and_find is not supported for pair types larger than 8 bytes on pre-Volta GPUs.");
#endif
auto const val = this->heterogeneous_value(value);
auto const key = this->extract_key(val);
auto probing_iter = probing_scheme_(key, storage_ref_.bucket_extent());
auto const init_idx = *probing_iter;
while (true) {
auto const bucket_slots = storage_ref_[*probing_iter];
for (auto i = 0; i < bucket_size; ++i) {
auto const eq_res =
this->predicate_.operator()<is_insert::YES>(key, this->extract_key(bucket_slots[i]));
auto* bucket_ptr = (storage_ref_.data() + *probing_iter)->data();
// If the key is already in the container, return false
if (eq_res == detail::equal_result::EQUAL) {
if constexpr (has_payload) {
// wait to ensure that the write to the value part also took place
this->wait_for_payload((bucket_ptr + i)->second, this->empty_value_sentinel());
}
return {iterator{&bucket_ptr[i]}, false};
}
if ((eq_res == detail::equal_result::EMPTY) or (eq_res == detail::equal_result::ERASED)) {
switch (this->attempt_insert_stable(bucket_ptr + i, bucket_slots[i], val)) {
case insert_result::SUCCESS: {
if constexpr (has_payload) {
// wait to ensure that the write to the value part also took place
this->wait_for_payload((bucket_ptr + i)->second, this->empty_value_sentinel());
}
return {iterator{&bucket_ptr[i]}, true};
}
case insert_result::DUPLICATE: {
if constexpr (has_payload) {
// wait to ensure that the write to the value part also took place
this->wait_for_payload((bucket_ptr + i)->second, this->empty_value_sentinel());
}
return {iterator{&bucket_ptr[i]}, false};
}
default: continue;
}
}
}
++probing_iter;
if (*probing_iter == init_idx) { return {this->end(), false}; }
};
}
/**
* @brief Inserts the given element into the container.
*
* @note This API returns a pair consisting of an iterator to the inserted element (or to the
* element that prevented the insertion) and a `bool` denoting whether the insertion took place or
* not.
*
* @tparam Value Input type which is convertible to 'value_type'
*
* @param group The Cooperative Group used to perform group insert_and_find
* @param value The element to insert
*
* @return a pair consisting of an iterator to the element and a bool indicating whether the
* insertion is successful or not.
*/
template <typename Value>
__device__ thrust::pair<iterator, bool> insert_and_find(
cooperative_groups::thread_block_tile<cg_size> const& group, Value const& value) noexcept
{
#if __CUDA_ARCH__ < 700
// Spinning to ensure that the write to the value part took place requires
// independent thread scheduling introduced with the Volta architecture.
static_assert(
cuco::detail::is_packable<value_type>(),
"insert_and_find is not supported for pair types larger than 8 bytes on pre-Volta GPUs.");
#endif
auto const val = this->heterogeneous_value(value);
auto const key = this->extract_key(val);
auto probing_iter = probing_scheme_(group, key, storage_ref_.bucket_extent());
auto const init_idx = *probing_iter;
while (true) {
auto const bucket_slots = storage_ref_[*probing_iter];
auto const [state, intra_bucket_index] = [&]() {
auto res = detail::equal_result::UNEQUAL;
for (auto i = 0; i < bucket_size; ++i) {
res =
this->predicate_.operator()<is_insert::YES>(key, this->extract_key(bucket_slots[i]));
if (res != detail::equal_result::UNEQUAL) { return bucket_probing_results{res, i}; }
}
// returns dummy index `-1` for UNEQUAL
return bucket_probing_results{res, -1};
}();
auto* slot_ptr = (storage_ref_.data() + *probing_iter)->data() + intra_bucket_index;
// If the key is already in the container, return false
auto const group_finds_equal = group.ballot(state == detail::equal_result::EQUAL);
if (group_finds_equal) {
auto const src_lane = __ffs(group_finds_equal) - 1;
auto const res = group.shfl(reinterpret_cast<intptr_t>(slot_ptr), src_lane);
if (group.thread_rank() == src_lane) {
if constexpr (has_payload) {
// wait to ensure that the write to the value part also took place
this->wait_for_payload(slot_ptr->second, this->empty_value_sentinel());
}
}
group.sync();
return {iterator{reinterpret_cast<value_type*>(res)}, false};
}
auto const group_contains_available = group.ballot((state == detail::equal_result::EMPTY) or
(state == detail::equal_result::ERASED));
if (group_contains_available) {
auto const src_lane = __ffs(group_contains_available) - 1;
auto const res = group.shfl(reinterpret_cast<intptr_t>(slot_ptr), src_lane);
auto const status = [&, target_idx = intra_bucket_index]() {
if (group.thread_rank() != src_lane) { return insert_result::CONTINUE; }
return this->attempt_insert_stable(slot_ptr, bucket_slots[target_idx], val);
}();
switch (group.shfl(status, src_lane)) {
case insert_result::SUCCESS: {
if (group.thread_rank() == src_lane) {
if constexpr (has_payload) {
// wait to ensure that the write to the value part also took place
this->wait_for_payload(slot_ptr->second, this->empty_value_sentinel());
}
}
group.sync();
return {iterator{reinterpret_cast<value_type*>(res)}, true};
}
case insert_result::DUPLICATE: {
if (group.thread_rank() == src_lane) {
if constexpr (has_payload) {
// wait to ensure that the write to the value part also took place
this->wait_for_payload(slot_ptr->second, this->empty_value_sentinel());
}
}
group.sync();
return {iterator{reinterpret_cast<value_type*>(res)}, false};
}
default: continue;
}
} else {
++probing_iter;
if (*probing_iter == init_idx) { return {this->end(), false}; }
}
}
}
/**
* @brief Erases an element.
*
* @tparam ProbeKey Input type which is convertible to 'key_type'
*
* @param value The element to erase
*
* @return True if the given element is successfully erased
*/
template <typename ProbeKey>
__device__ bool erase(ProbeKey const& key) noexcept
{
static_assert(cg_size == 1, "Non-CG operation is incompatible with the current probing scheme");
auto probing_iter = probing_scheme_(key, storage_ref_.bucket_extent());
auto const init_idx = *probing_iter;
while (true) {
auto const bucket_slots = storage_ref_[*probing_iter];
for (auto& slot_content : bucket_slots) {
auto const eq_res =
this->predicate_.operator()<is_insert::NO>(key, this->extract_key(slot_content));
// Key doesn't exist, return false
if (eq_res == detail::equal_result::EMPTY) { return false; }
// Key exists, return true if successfully deleted
if (eq_res == detail::equal_result::EQUAL) {
auto const intra_bucket_index = thrust::distance(bucket_slots.begin(), &slot_content);
switch (attempt_insert_stable(
(storage_ref_.data() + *probing_iter)->data() + intra_bucket_index,
slot_content,
this->erased_slot_sentinel())) {
case insert_result::SUCCESS: return true;
case insert_result::DUPLICATE: return false;
default: continue;
}
}
}
++probing_iter;
if (*probing_iter == init_idx) { return false; }
}
}
/**
* @brief Erases an element.
*
* @tparam ProbeKey Input type which is convertible to 'key_type'
*
* @param group The Cooperative Group used to perform group erase
* @param value The element to erase
*
* @return True if the given element is successfully erased
*/
template <typename ProbeKey>
__device__ bool erase(cooperative_groups::thread_block_tile<cg_size> const& group,
ProbeKey const& key) noexcept
{
auto probing_iter = probing_scheme_(group, key, storage_ref_.bucket_extent());
auto const init_idx = *probing_iter;
while (true) {
auto const bucket_slots = storage_ref_[*probing_iter];
auto const [state, intra_bucket_index] = [&]() {
auto res = detail::equal_result::UNEQUAL;
for (auto i = 0; i < bucket_size; ++i) {
res = this->predicate_.operator()<is_insert::NO>(key, this->extract_key(bucket_slots[i]));
if (res != detail::equal_result::UNEQUAL) { return bucket_probing_results{res, i}; }
}
// returns dummy index `-1` for UNEQUAL
return bucket_probing_results{res, -1};
}();
auto const group_contains_equal = group.ballot(state == detail::equal_result::EQUAL);
if (group_contains_equal) {
auto const src_lane = __ffs(group_contains_equal) - 1;
auto const status =
(group.thread_rank() == src_lane)
? attempt_insert_stable(
(storage_ref_.data() + *probing_iter)->data() + intra_bucket_index,
bucket_slots[intra_bucket_index],
this->erased_slot_sentinel())
: insert_result::CONTINUE;
switch (group.shfl(status, src_lane)) {
case insert_result::SUCCESS: return true;
case insert_result::DUPLICATE: return false;
default: continue;
}
}
// Key doesn't exist, return false
if (group.any(state == detail::equal_result::EMPTY)) { return false; }
++probing_iter;
if (*probing_iter == init_idx) { return false; }
}
}
/**
* @brief Indicates whether the probe key `key` was inserted into the container.
*
* @note If the probe key `key` was inserted into the container, returns true. Otherwise, returns
* false.
*
* @tparam ProbeKey Probe key type
*
* @param key The key to search for
*
* @return A boolean indicating whether the probe key is present
*/
template <typename ProbeKey>
[[nodiscard]] __device__ bool contains(ProbeKey const& key) const noexcept
{
static_assert(cg_size == 1, "Non-CG operation is incompatible with the current probing scheme");
auto probing_iter = probing_scheme_(key, storage_ref_.bucket_extent());
auto const init_idx = *probing_iter;
while (true) {
// TODO atomic_ref::load if insert operator is present
auto const bucket_slots = storage_ref_[*probing_iter];
for (auto& slot_content : bucket_slots) {
switch (this->predicate_.operator()<is_insert::NO>(key, this->extract_key(slot_content))) {
case detail::equal_result::UNEQUAL: continue;
case detail::equal_result::EMPTY: return false;
case detail::equal_result::EQUAL: return true;
}
}
++probing_iter;
if (*probing_iter == init_idx) { return false; }
}
}
/**
* @brief Indicates whether the probe key `key` was inserted into the container.
*
* @note If the probe key `key` was inserted into the container, returns true. Otherwise, returns
* false.
*
* @tparam ProbeKey Probe key type
*
* @param group The Cooperative Group used to perform group contains
* @param key The key to search for
*
* @return A boolean indicating whether the probe key is present
*/
template <typename ProbeKey>
[[nodiscard]] __device__ bool contains(
cooperative_groups::thread_block_tile<cg_size> const& group, ProbeKey const& key) const noexcept
{
auto probing_iter = probing_scheme_(group, key, storage_ref_.bucket_extent());
auto const init_idx = *probing_iter;
while (true) {
auto const bucket_slots = storage_ref_[*probing_iter];
auto const state = [&]() {
auto res = detail::equal_result::UNEQUAL;
for (auto& slot : bucket_slots) {
res = this->predicate_.operator()<is_insert::NO>(key, this->extract_key(slot));
if (res != detail::equal_result::UNEQUAL) { return res; }
}
return res;
}();
if (group.any(state == detail::equal_result::EQUAL)) { return true; }
if (group.any(state == detail::equal_result::EMPTY)) { return false; }
++probing_iter;
if (*probing_iter == init_idx) { return false; }
}
}
/**
* @brief Finds an element in the container with key equivalent to the probe key.
*
* @note Returns a un-incrementable input iterator to the element whose key is equivalent to
* `key`. If no such element exists, returns `end()`.
*
* @tparam ProbeKey Probe key type
*
* @param key The key to search for
*
* @return An iterator to the position at which the equivalent key is stored
*/
template <typename ProbeKey>
[[nodiscard]] __device__ const_iterator find(ProbeKey const& key) const noexcept
{
static_assert(cg_size == 1, "Non-CG operation is incompatible with the current probing scheme");
auto probing_iter = probing_scheme_(key, storage_ref_.bucket_extent());
auto const init_idx = *probing_iter;
while (true) {
// TODO atomic_ref::load if insert operator is present
auto const bucket_slots = storage_ref_[*probing_iter];
for (auto i = 0; i < bucket_size; ++i) {
switch (
this->predicate_.operator()<is_insert::NO>(key, this->extract_key(bucket_slots[i]))) {
case detail::equal_result::EMPTY: {
return this->end();
}
case detail::equal_result::EQUAL: {
return const_iterator{&(*(storage_ref_.data() + *probing_iter))[i]};
}
default: continue;
}
}
++probing_iter;
if (*probing_iter == init_idx) { return this->end(); }
}
}
/**
* @brief Finds an element in the container with key equivalent to the probe key.
*
* @note Returns a un-incrementable input iterator to the element whose key is equivalent to
* `key`. If no such element exists, returns `end()`.
*
* @tparam ProbeKey Probe key type
*
* @param group The Cooperative Group used to perform this operation
* @param key The key to search for
*
* @return An iterator to the position at which the equivalent key is stored
*/
template <typename ProbeKey>
[[nodiscard]] __device__ const_iterator find(
cooperative_groups::thread_block_tile<cg_size> const& group, ProbeKey const& key) const noexcept
{
auto probing_iter = probing_scheme_(group, key, storage_ref_.bucket_extent());
auto const init_idx = *probing_iter;
while (true) {
auto const bucket_slots = storage_ref_[*probing_iter];
auto const [state, intra_bucket_index] = [&]() {
auto res = detail::equal_result::UNEQUAL;
for (auto i = 0; i < bucket_size; ++i) {
res = this->predicate_.operator()<is_insert::NO>(key, this->extract_key(bucket_slots[i]));
if (res != detail::equal_result::UNEQUAL) { return bucket_probing_results{res, i}; }
}
// returns dummy index `-1` for UNEQUAL
return bucket_probing_results{res, -1};
}();
// Find a match for the probe key, thus return an iterator to the entry
auto const group_finds_match = group.ballot(state == detail::equal_result::EQUAL);
if (group_finds_match) {
auto const src_lane = __ffs(group_finds_match) - 1;
auto const res = group.shfl(
reinterpret_cast<intptr_t>(&(*(storage_ref_.data() + *probing_iter))[intra_bucket_index]),
src_lane);
return const_iterator{reinterpret_cast<value_type*>(res)};
}
// Find an empty slot, meaning that the probe key isn't present in the container
if (group.any(state == detail::equal_result::EMPTY)) { return this->end(); }
++probing_iter;
if (*probing_iter == init_idx) { return this->end(); }
}
}
/**
* @brief Counts the occurrence of a given key contained in the container
*
* @tparam ProbeKey Probe key type
*
* @param key The key to count for
*
* @return Number of occurrences found by the current thread
*/
template <typename ProbeKey>
[[nodiscard]] __device__ size_type count(ProbeKey const& key) const noexcept
{
if constexpr (not allows_duplicates) {
return static_cast<size_type>(this->contains(key));
} else {
auto probing_iter = probing_scheme_(key, storage_ref_.bucket_extent());
auto const init_idx = *probing_iter;
size_type count = 0;
while (true) {
// TODO atomic_ref::load if insert operator is present
auto const bucket_slots = storage_ref_[*probing_iter];
for (auto& slot_content : bucket_slots) {
switch (
this->predicate_.operator()<is_insert::NO>(key, this->extract_key(slot_content))) {
case detail::equal_result::EMPTY: return count;
case detail::equal_result::EQUAL: ++count; break;
default: continue;
}
}
++probing_iter;
if (*probing_iter == init_idx) { return count; }
}
}
}
/**
* @brief Counts the occurrence of a given key contained in the container
*
* @tparam ProbeKey Probe key type
*
* @param group The Cooperative Group used to perform group count
* @param key The key to count for
*