faiss 0.6.5 → 0.6.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (157) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +5 -0
  3. data/ext/faiss/extconf.rb +1 -0
  4. data/ext/faiss/index.cpp +42 -0
  5. data/lib/faiss/version.rb +1 -1
  6. data/vendor/faiss/faiss/IVFlib.cpp +48 -51
  7. data/vendor/faiss/faiss/IVFlib.h +6 -2
  8. data/vendor/faiss/faiss/Index.cpp +2 -2
  9. data/vendor/faiss/faiss/Index.h +3 -3
  10. data/vendor/faiss/faiss/IndexBinary.cpp +2 -2
  11. data/vendor/faiss/faiss/IndexBinary.h +2 -2
  12. data/vendor/faiss/faiss/IndexBinaryFlat.cpp +1 -0
  13. data/vendor/faiss/faiss/IndexBinaryHNSW.cpp +6 -3
  14. data/vendor/faiss/faiss/IndexBinaryIVF.cpp +6 -11
  15. data/vendor/faiss/faiss/IndexFastScan.cpp +1 -1
  16. data/vendor/faiss/faiss/IndexFlat.cpp +1 -1
  17. data/vendor/faiss/faiss/IndexHNSW.cpp +12 -10
  18. data/vendor/faiss/faiss/IndexHNSW.h +2 -5
  19. data/vendor/faiss/faiss/IndexIDMap.cpp +17 -4
  20. data/vendor/faiss/faiss/IndexIDMap.h +10 -5
  21. data/vendor/faiss/faiss/IndexIVF.cpp +68 -37
  22. data/vendor/faiss/faiss/IndexIVF.h +37 -1
  23. data/vendor/faiss/faiss/IndexIVFFastScan.cpp +5 -15
  24. data/vendor/faiss/faiss/IndexIVFFlat.h +6 -6
  25. data/vendor/faiss/faiss/IndexIVFPQFastScan.cpp +1 -1
  26. data/vendor/faiss/faiss/IndexIVFRaBitQFastScan.cpp +28 -44
  27. data/vendor/faiss/faiss/IndexIVFRaBitQFastScan.h +2 -11
  28. data/vendor/faiss/faiss/IndexIVFRaBitQSSD.cpp +1694 -0
  29. data/vendor/faiss/faiss/IndexIVFRaBitQSSD.h +288 -0
  30. data/vendor/faiss/faiss/IndexIVFSQFastScan.cpp +7 -2
  31. data/vendor/faiss/faiss/IndexNNDescent.cpp +21 -0
  32. data/vendor/faiss/faiss/IndexRaBitQ.cpp +189 -41
  33. data/vendor/faiss/faiss/IndexRaBitQ.h +5 -0
  34. data/vendor/faiss/faiss/IndexRaBitQFastScan.cpp +1 -1
  35. data/vendor/faiss/faiss/IndexRaBitQFastScan.h +2 -2
  36. data/vendor/faiss/faiss/SuperKMeans.cpp +2 -2
  37. data/vendor/faiss/faiss/VectorTransform.cpp +156 -9
  38. data/vendor/faiss/faiss/VectorTransform.h +24 -1
  39. data/vendor/faiss/faiss/factory_tools.cpp +19 -1
  40. data/vendor/faiss/faiss/gpu/Dataset.h +66 -14
  41. data/vendor/faiss/faiss/gpu/GpuIndexBinaryCagra.h +8 -2
  42. data/vendor/faiss/faiss/gpu/GpuIndexCagra.h +8 -2
  43. data/vendor/faiss/faiss/gpu/impl/optimal_kmeans/GpuOptimalKMeans.h +184 -0
  44. data/vendor/faiss/faiss/gpu/test/TestCodePacking.cpp +12 -4
  45. data/vendor/faiss/faiss/gpu/test/TestUtils.cpp +6 -5
  46. data/vendor/faiss/faiss/gpu_metal/GpuIndexFlat.h +1 -1
  47. data/vendor/faiss/faiss/gpu_metal/MetalCloner.h +1 -1
  48. data/vendor/faiss/faiss/gpu_metal/MetalDistance.h +1 -1
  49. data/vendor/faiss/faiss/gpu_metal/MetalFlatKernels.h +1 -1
  50. data/vendor/faiss/faiss/gpu_metal/MetalIndex.h +1 -1
  51. data/vendor/faiss/faiss/gpu_metal/MetalIndexBinaryFlat.h +1 -1
  52. data/vendor/faiss/faiss/gpu_metal/MetalIndexFlat.h +1 -1
  53. data/vendor/faiss/faiss/gpu_metal/MetalIndexIVFFlat.h +1 -1
  54. data/vendor/faiss/faiss/gpu_metal/MetalIndexIVFPQ.h +1 -1
  55. data/vendor/faiss/faiss/gpu_metal/MetalKernels.h +1 -1
  56. data/vendor/faiss/faiss/gpu_metal/MetalPythonBridge.h +1 -1
  57. data/vendor/faiss/faiss/gpu_metal/MetalResources.h +1 -1
  58. data/vendor/faiss/faiss/gpu_metal/StandardMetalResources.h +1 -1
  59. data/vendor/faiss/faiss/gpu_metal/impl/MetalIVFFlat.h +1 -1
  60. data/vendor/faiss/faiss/gpu_metal/impl/MetalIVFPQ.h +1 -1
  61. data/vendor/faiss/faiss/impl/AuxIndexStructures.cpp +1 -1
  62. data/vendor/faiss/faiss/impl/ClusteringInitialization.cpp +31 -50
  63. data/vendor/faiss/faiss/impl/ClusteringInitialization.h +0 -15
  64. data/vendor/faiss/faiss/impl/CodePacker.cpp +2 -2
  65. data/vendor/faiss/faiss/impl/CodePackerRaBitQ.cpp +2 -2
  66. data/vendor/faiss/faiss/impl/DeterministicNNDescent.cpp +2167 -0
  67. data/vendor/faiss/faiss/impl/DeterministicNNDescent.h +301 -0
  68. data/vendor/faiss/faiss/impl/HNSW.cpp +2 -2
  69. data/vendor/faiss/faiss/impl/HNSW.h +2 -2
  70. data/vendor/faiss/faiss/impl/IDSelector.h +5 -4
  71. data/vendor/faiss/faiss/impl/NNDescent.h +4 -0
  72. data/vendor/faiss/faiss/impl/PiPNN.cpp +4 -2
  73. data/vendor/faiss/faiss/impl/PiPNN.h +1 -1
  74. data/vendor/faiss/faiss/impl/PolysemousTraining.cpp +1 -1
  75. data/vendor/faiss/faiss/impl/RaBitQUtils.cpp +0 -2
  76. data/vendor/faiss/faiss/impl/RaBitQUtils.h +29 -0
  77. data/vendor/faiss/faiss/impl/RaBitQuantizer.cpp +14 -13
  78. data/vendor/faiss/faiss/impl/ResultHandler.h +116 -0
  79. data/vendor/faiss/faiss/impl/binary_hamming/IndexBinaryIVF_impl.h +1 -3
  80. data/vendor/faiss/faiss/impl/expanded_scanners.h +29 -24
  81. data/vendor/faiss/faiss/impl/fast_scan/fast_scan.cpp +68 -6
  82. data/vendor/faiss/faiss/impl/fast_scan/fast_scan.h +43 -0
  83. data/vendor/faiss/faiss/impl/fast_scan/impl-avx2.cpp +15 -0
  84. data/vendor/faiss/faiss/impl/fast_scan/impl-avx512.cpp +115 -0
  85. data/vendor/faiss/faiss/impl/fast_scan/impl-neon.cpp +13 -0
  86. data/vendor/faiss/faiss/impl/fast_scan/kernels_simd256.h +84 -0
  87. data/vendor/faiss/faiss/impl/fast_scan/kernels_simd512.h +0 -4
  88. data/vendor/faiss/faiss/impl/fast_scan/rabitq_result_handler.h +0 -1
  89. data/vendor/faiss/faiss/impl/fast_scan/simd_result_handlers.h +64 -55
  90. data/vendor/faiss/faiss/impl/hnsw/LockVector.h +1 -2
  91. data/vendor/faiss/faiss/impl/index_read.cpp +146 -9
  92. data/vendor/faiss/faiss/impl/index_write.cpp +29 -5
  93. data/vendor/faiss/faiss/impl/io.cpp +1 -0
  94. data/vendor/faiss/faiss/impl/io_macros.h +2 -2
  95. data/vendor/faiss/faiss/impl/mapped_io.cpp +3 -1
  96. data/vendor/faiss/faiss/impl/maybe_owned_vector.h +78 -41
  97. data/vendor/faiss/faiss/impl/nndescent/gram-avx2.cpp +121 -0
  98. data/vendor/faiss/faiss/impl/nndescent/gram-avx512.cpp +124 -0
  99. data/vendor/faiss/faiss/impl/nndescent/gram-neon.cpp +114 -0
  100. data/vendor/faiss/faiss/impl/nndescent/gram.h +66 -0
  101. data/vendor/faiss/faiss/impl/optimal_kmeans/BlockCombiner-avx512.cpp +431 -0
  102. data/vendor/faiss/faiss/impl/optimal_kmeans/BlockCombiner-inl.h +1157 -0
  103. data/vendor/faiss/faiss/impl/optimal_kmeans/OptimalKMeans.cpp +282 -0
  104. data/vendor/faiss/faiss/impl/optimal_kmeans/OptimalKMeans.h +226 -0
  105. data/vendor/faiss/faiss/impl/optimal_kmeans/OptimalKMeansCompressed.cpp +1567 -0
  106. data/vendor/faiss/faiss/impl/optimal_kmeans/OptimalKMeansCompressed.h +281 -0
  107. data/vendor/faiss/faiss/impl/pipnn/HashPrune.cpp +1 -1
  108. data/vendor/faiss/faiss/impl/platform_macros.h +47 -28
  109. data/vendor/faiss/faiss/impl/pq_code_distance/IVFPQScanner_impl.h +6 -1
  110. data/vendor/faiss/faiss/impl/pq_code_distance/IVFPQ_QueryTables.cpp +17 -17
  111. data/vendor/faiss/faiss/impl/result_handler/ResultHandler.cpp +68 -1
  112. data/vendor/faiss/faiss/impl/result_handler/avx2.cpp +70 -2
  113. data/vendor/faiss/faiss/impl/result_handler/avx512.cpp +2 -1
  114. data/vendor/faiss/faiss/impl/scalar_quantizer/EDENQuantizer.cpp +1 -1
  115. data/vendor/faiss/faiss/impl/scalar_quantizer/scanners.h +26 -26
  116. data/vendor/faiss/faiss/impl/scalar_quantizer/sq-avx2.cpp +48 -45
  117. data/vendor/faiss/faiss/impl/scalar_quantizer/sq-avx512-impl.h +34 -32
  118. data/vendor/faiss/faiss/impl/scalar_quantizer/sq-avx512-spr.cpp +8 -6
  119. data/vendor/faiss/faiss/impl/scalar_quantizer/sq-avx512.cpp +4 -3
  120. data/vendor/faiss/faiss/impl/scalar_quantizer/sq-neon.cpp +34 -33
  121. data/vendor/faiss/faiss/impl/simdlib/simdlib_avx512.h +20 -20
  122. data/vendor/faiss/faiss/impl/simdlib/simdlib_neon.h +4 -4
  123. data/vendor/faiss/faiss/impl/zerocopy_io.cpp +2 -1
  124. data/vendor/faiss/faiss/index_factory.cpp +30 -6
  125. data/vendor/faiss/faiss/invlists/DirectMap.cpp +1 -1
  126. data/vendor/faiss/faiss/invlists/DiskIOBackend.cpp +121 -0
  127. data/vendor/faiss/faiss/invlists/DiskIOBackend.h +71 -0
  128. data/vendor/faiss/faiss/invlists/InvertedLists.cpp +12 -9
  129. data/vendor/faiss/faiss/invlists/InvertedListsIOHook.cpp +26 -0
  130. data/vendor/faiss/faiss/invlists/InvertedListsIOHook.h +5 -0
  131. data/vendor/faiss/faiss/invlists/OnDiskInvertedLists.cpp +9 -24
  132. data/vendor/faiss/faiss/invlists/RaBitQSSDInvertedLists.cpp +751 -0
  133. data/vendor/faiss/faiss/invlists/RaBitQSSDInvertedLists.h +224 -0
  134. data/vendor/faiss/faiss/svs/IndexSVSFaissUtils.h +2 -7
  135. data/vendor/faiss/faiss/svs/IndexSVSFlat.cpp +1 -1
  136. data/vendor/faiss/faiss/svs/IndexSVSIVF.cpp +2 -2
  137. data/vendor/faiss/faiss/svs/IndexSVSVamana.cpp +4 -4
  138. data/vendor/faiss/faiss/utils/WorkerThread.h +0 -1
  139. data/vendor/faiss/faiss/utils/distances.cpp +246 -34
  140. data/vendor/faiss/faiss/utils/distances.h +145 -2
  141. data/vendor/faiss/faiss/utils/extra_distances.h +2 -1
  142. data/vendor/faiss/faiss/utils/hamming-inl.h +3 -0
  143. data/vendor/faiss/faiss/utils/partitioning.cpp +2 -2
  144. data/vendor/faiss/faiss/utils/rabitq_simd.h +120 -6
  145. data/vendor/faiss/faiss/utils/simd_impl/distances_arm_sve.cpp +47 -7
  146. data/vendor/faiss/faiss/utils/simd_impl/distances_autovec-inl.h +7 -3
  147. data/vendor/faiss/faiss/utils/simd_impl/distances_avx2.cpp +47 -7
  148. data/vendor/faiss/faiss/utils/simd_impl/distances_avx512.cpp +50 -10
  149. data/vendor/faiss/faiss/utils/simd_impl/distances_simdlib256.h +3 -3
  150. data/vendor/faiss/faiss/utils/simd_impl/exhaustive_L2sqr_blas_cmax.h +13 -0
  151. data/vendor/faiss/faiss/utils/simd_impl/partitioning_simdlib256.h +16 -15
  152. data/vendor/faiss/faiss/utils/simd_impl/rabitq_avx2.cpp +131 -36
  153. data/vendor/faiss/faiss/utils/simd_impl/rabitq_avx512.cpp +156 -45
  154. data/vendor/faiss/faiss/utils/simd_levels.cpp +3 -3
  155. data/vendor/faiss/faiss/utils/sorting.cpp +6 -5
  156. data/vendor/faiss/faiss/utils/utils.cpp +4 -0
  157. metadata +20 -1
@@ -0,0 +1,2167 @@
1
+ /*
2
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
3
+ *
4
+ * This source code is licensed under the MIT license found in the
5
+ * LICENSE file in the root directory of this source tree.
6
+ */
7
+
8
+ #include <faiss/impl/DeterministicNNDescent.h>
9
+
10
+ #include <omp.h>
11
+ #include <algorithm>
12
+ #include <cinttypes>
13
+ #include <cstdio>
14
+ #include <limits>
15
+ #include <memory>
16
+ #include <numeric>
17
+ #include <typeinfo>
18
+ #include <utility>
19
+
20
+ #include <atomic>
21
+
22
+ #include <faiss/IndexFlat.h>
23
+ #include <faiss/IndexScalarQuantizer.h>
24
+ #include <faiss/impl/FaissAssert.h>
25
+ #include <faiss/impl/nndescent/gram.h>
26
+ #include <faiss/impl/pipnn/kernels.h>
27
+ #include <faiss/impl/simd_dispatch.h>
28
+ #include <faiss/utils/AlignedTable.h>
29
+ #include <faiss/utils/distances.h>
30
+ #include <faiss/utils/fp16.h>
31
+ #include <faiss/utils/prefetch.h>
32
+ #include <faiss/utils/random.h>
33
+ #include <faiss/utils/utils.h>
34
+
35
+ extern "C" {
36
+
37
+ #ifndef FINTEGER
38
+ #define FINTEGER long
39
+ #endif
40
+
41
+ int sgemm_(
42
+ const char* transa,
43
+ const char* transb,
44
+ FINTEGER* m,
45
+ FINTEGER* n,
46
+ FINTEGER* k,
47
+ const float* alpha,
48
+ const float* a,
49
+ FINTEGER* lda,
50
+ const float* b,
51
+ FINTEGER* ldb,
52
+ float* beta,
53
+ float* c,
54
+ FINTEGER* ldc);
55
+
56
+ int ssyrk_(
57
+ const char* uplo,
58
+ const char* trans,
59
+ FINTEGER* n,
60
+ FINTEGER* k,
61
+ float* alpha,
62
+ float* a,
63
+ FINTEGER* lda,
64
+ float* beta,
65
+ float* c,
66
+ FINTEGER* ldc);
67
+ }
68
+
69
+ namespace faiss {
70
+
71
+ namespace {
72
+
73
+ constexpr float kInf = std::numeric_limits<float>::infinity();
74
+
75
+ /// (distance, id); operator< orders by (distance, id)
76
+ using DisId = std::pair<float, int32_t>;
77
+ using DisId64 = std::pair<float, int64_t>;
78
+
79
+ /// a hash of x: the first output of SplitMix64 seeded with x
80
+ uint64_t mix64(uint64_t x) {
81
+ return SplitMix64RandomGenerator(int64_t(x)).next();
82
+ }
83
+
84
+ /// open-addressing map from ids to 0, 1, 2, ... in insertion order;
85
+ /// cleared in O(size)
86
+ struct IdMap {
87
+ std::vector<int32_t> keys; // -1: empty
88
+ std::vector<int32_t> vals;
89
+ std::vector<uint32_t> used;
90
+ uint32_t mask = 0;
91
+
92
+ IdMap() {
93
+ rehash(1024);
94
+ }
95
+
96
+ void rehash(size_t size) {
97
+ std::vector<int32_t> ok = std::move(keys), ov = std::move(vals);
98
+ std::vector<uint32_t> ou = std::move(used);
99
+ keys.assign(size, -1);
100
+ vals.assign(size, 0);
101
+ used.clear();
102
+ mask = uint32_t(size - 1);
103
+ for (uint32_t h : ou) {
104
+ insert_new(ok[h], ov[h]);
105
+ }
106
+ }
107
+
108
+ void clear() {
109
+ for (uint32_t h : used) {
110
+ keys[h] = -1;
111
+ }
112
+ used.clear();
113
+ }
114
+
115
+ uint32_t slot(int32_t id) const {
116
+ // high bits of a multiplicative hash: ids that share low bits spread
117
+ uint32_t h = uint32_t(
118
+ (uint64_t(uint32_t(id)) * 0x9e3779b97f4a7c15ULL) >>
119
+ 32) &
120
+ mask;
121
+ while (keys[h] >= 0 && keys[h] != id) {
122
+ h = (h + 1) & mask;
123
+ }
124
+ return h;
125
+ }
126
+
127
+ void insert_new(int32_t id, int32_t val) {
128
+ const uint32_t h = slot(id);
129
+ keys[h] = id;
130
+ vals[h] = val;
131
+ used.push_back(h);
132
+ }
133
+
134
+ /// value of id, inserting size() if absent; sets is_new
135
+ int32_t find_or_insert(int32_t id, bool& is_new) {
136
+ uint32_t h = slot(id);
137
+ if (keys[h] >= 0) {
138
+ is_new = false;
139
+ return vals[h];
140
+ }
141
+ is_new = true;
142
+ const int32_t v = int32_t(used.size());
143
+ keys[h] = id;
144
+ vals[h] = v;
145
+ used.push_back(h);
146
+ if (2 * used.size() > keys.size()) {
147
+ rehash(2 * keys.size());
148
+ }
149
+ return v;
150
+ }
151
+ };
152
+
153
+ /** Per-thread read access to the float vectors of the storage. IndexFlat is
154
+ * read in place and IndexScalarQuantizer is decoded directly:
155
+ * Index::reconstruct of IndexScalarQuantizer opens a nested OpenMP region and
156
+ * allocates for each call. The pointer that get() returns is valid until the
157
+ * next get(). */
158
+ struct VectorReader {
159
+ const Index& storage;
160
+ const size_t d;
161
+ const float* flat = nullptr;
162
+ const IndexScalarQuantizer* sq = nullptr;
163
+ std::unique_ptr<ScalarQuantizer::SQuantizer> squant;
164
+ std::vector<float> buf;
165
+
166
+ explicit VectorReader(const Index& s) : storage(s), d(s.d), buf(s.d) {
167
+ // exact types: subclasses such as IndexFlatPanorama change the layout
168
+ const std::type_info& t = typeid(s);
169
+ if (t == typeid(IndexFlat) || t == typeid(IndexFlatL2) ||
170
+ t == typeid(IndexFlatIP)) {
171
+ flat = static_cast<const IndexFlat&>(s).get_xb();
172
+ } else if (auto* q = dynamic_cast<const IndexScalarQuantizer*>(&s)) {
173
+ // throws for a quantizer without a decoder, such as QT_0bit
174
+ sq = q;
175
+ squant.reset(q->sq.select_quantizer());
176
+ }
177
+ }
178
+
179
+ const float* get(idx_t i) {
180
+ if (flat) {
181
+ return flat + i * d;
182
+ }
183
+ decode(i, buf.data());
184
+ return buf.data();
185
+ }
186
+
187
+ void decode(idx_t i, float* out) {
188
+ if (flat) {
189
+ std::copy_n(flat + i * d, d, out);
190
+ } else if (squant) {
191
+ squant->decode_vector(sq->codes.data() + i * sq->code_size, out);
192
+ } else {
193
+ storage.reconstruct(i, out);
194
+ }
195
+ }
196
+
197
+ void prefetch(idx_t i) const {
198
+ const uint8_t* p;
199
+ size_t nbytes;
200
+ if (flat) {
201
+ p = reinterpret_cast<const uint8_t*>(flat + i * d);
202
+ nbytes = d * sizeof(float);
203
+ } else if (squant) {
204
+ p = sq->codes.data() + i * sq->code_size;
205
+ nbytes = sq->code_size;
206
+ } else {
207
+ return;
208
+ }
209
+ for (size_t o = 0; o < std::min(nbytes, size_t(4096)); o += 64) {
210
+ prefetch_L1(p + o);
211
+ }
212
+ }
213
+ };
214
+
215
+ /// one smaller-is-better distance: L2, or the negated inner product. NaN
216
+ /// (overflow) becomes +inf and -0 becomes +0, as in products_to_distances()
217
+ float pair_distance(
218
+ MetricType metric_type,
219
+ const float* x,
220
+ const float* y,
221
+ size_t d) {
222
+ const float v = metric_type == METRIC_INNER_PRODUCT
223
+ ? -fvec_inner_product(x, y, d)
224
+ : fvec_L2sqr(x, y, d);
225
+ return std::isnan(v) ? kInf : v + 0.0f;
226
+ }
227
+
228
+ /** Rows [0, r) of the upper triangle of the Gram matrix of the m rows of x
229
+ * into out (row-major, m columns): the entries i < r, j > i, by ssyrk
230
+ * (new x new) and sgemm (new x old); the other entries are not set. */
231
+ void gram_upper_rows_blas(
232
+ const float* x,
233
+ size_t r,
234
+ size_t m,
235
+ size_t d,
236
+ float* out) {
237
+ FINTEGER ri = FINTEGER(r), di = FINTEGER(d), mi = FINTEGER(m);
238
+ float alpha = 1, beta = 0;
239
+ // column-major lower triangle = row-major upper triangle (j >= i)
240
+ ssyrk_("L",
241
+ "T",
242
+ &ri,
243
+ &di,
244
+ &alpha,
245
+ const_cast<float*>(x),
246
+ &di,
247
+ &beta,
248
+ out,
249
+ &mi);
250
+ if (m > r) {
251
+ FINTEGER oi = FINTEGER(m - r);
252
+ sgemm_("T",
253
+ "N",
254
+ &oi,
255
+ &ri,
256
+ &di,
257
+ &alpha,
258
+ x + r * d,
259
+ &di,
260
+ x,
261
+ &di,
262
+ &beta,
263
+ out + r,
264
+ &mi);
265
+ }
266
+ }
267
+
268
+ /// levels with the nndescent::gram_upper_rows kernel: the higher AVX-512
269
+ /// levels fall back to AVX512, and ARM_SVE to ARM_NEON. The others use BLAS.
270
+ constexpr int kGramLevels =
271
+ AVAILABLE_SIMD_LEVELS_AVX2_NEON | (1 << int(SIMDLevel::AVX512));
272
+
273
+ using GramKernel = void (*)(
274
+ const float* const* rows,
275
+ size_t r,
276
+ size_t m,
277
+ size_t d,
278
+ float* out);
279
+
280
+ /// the kernel of the SIMD level, or null for BLAS. The kernel reads the rows
281
+ /// through pointers, in place for flat storage, without the gather copy and
282
+ /// BLAS. BLAS called from an OpenMP region can open a nested region, so the
283
+ /// kernel is also the safer path.
284
+ GramKernel gram_kernel() {
285
+ GramKernel kernel = nullptr;
286
+ with_selected_simd_levels<kGramLevels>([&]<SIMDLevel SL>() {
287
+ if constexpr (SL != SIMDLevel::NONE) {
288
+ kernel = &nndescent::gram_upper_rows<SL>;
289
+ }
290
+ });
291
+ return kernel;
292
+ }
293
+
294
+ /** Turns the inner products of gram_upper_rows_*() into distances, in place:
295
+ * negated for IP; for L2 from the squared norms, clamped at 0. Scaling by -1
296
+ * or -2 is exact. A NaN (overflow) becomes +inf as in
297
+ * pipnn::gram_to_distance, and -0 becomes +0 so that a value has one bit
298
+ * pattern. A pair can get a different value in another join; the rounds do
299
+ * not depend on it (see drop_old_ids()). */
300
+ void products_to_distances(
301
+ MetricType metric_type,
302
+ const float* norms,
303
+ size_t r,
304
+ size_t m,
305
+ float* out) {
306
+ const bool ip = metric_type == METRIC_INNER_PRODUCT;
307
+ for (size_t i = 0; i < r; i++) {
308
+ float* oi = out + i * m;
309
+ for (size_t j = i + 1; j < m; j++) {
310
+ float v = ip ? -oi[j] : norms[i] + norms[j] - 2 * oi[j];
311
+ if (std::isnan(v)) {
312
+ v = kInf;
313
+ } else if (!ip) {
314
+ v = std::max(0.0f, v);
315
+ }
316
+ oi[j] = v + 0.0f; // -0 + 0 = +0
317
+ }
318
+ }
319
+ }
320
+
321
+ /// keeps the k smallest of cand by (dis, id), in any order
322
+ void keep_best(std::vector<DisId>& cand, size_t k) {
323
+ if (cand.size() > k) {
324
+ std::nth_element(cand.begin(), cand.begin() + k, cand.end());
325
+ cand.resize(k);
326
+ }
327
+ }
328
+
329
+ struct Segment {
330
+ size_t begin, end;
331
+ uint64_t hash;
332
+ };
333
+
334
+ bool any_nonempty(const std::vector<std::vector<Segment>>& work) {
335
+ for (const std::vector<Segment>& w : work) {
336
+ if (!w.empty()) {
337
+ return true;
338
+ }
339
+ }
340
+ return false;
341
+ }
342
+
343
+ /// whether vector v is on the side of pivot a
344
+ struct OnPivotASide {
345
+ const uint8_t* side;
346
+
347
+ bool operator()(int32_t v) const {
348
+ return side[v] == 0;
349
+ }
350
+ };
351
+
352
+ /// maximum points in a cluster tree leaf
353
+ constexpr size_t kLeafSize = 512;
354
+
355
+ /** Splits the points of perms[t] by random cluster tree t, for all trees at
356
+ * once, and returns the leaves of each tree. Each level reads each vector
357
+ * once for all trees. The pivots of a segment come from its hash, so the
358
+ * trees do not depend on the thread count. */
359
+ std::vector<std::vector<Segment>> cluster_trees(
360
+ const Index& storage,
361
+ std::vector<std::vector<int32_t>>& perms,
362
+ uint64_t seed) {
363
+ const int T = int(perms.size());
364
+ const size_t n = storage.ntotal;
365
+ const size_t d = storage.d;
366
+ const bool ip = storage.metric_type == METRIC_INNER_PRODUCT;
367
+ std::vector<std::vector<Segment>> work(T), leaves(T);
368
+ for (int t = 0; t < T; t++) {
369
+ const Segment root = {0, n, mix64(seed + t)};
370
+ (n <= kLeafSize ? leaves[t] : work[t]).push_back(root);
371
+ }
372
+ // segment of each vector in the current level (-1: in a leaf), and side
373
+ std::vector<int32_t> segv(size_t(T) * n);
374
+ std::vector<uint8_t> sidev(size_t(T) * n);
375
+ std::vector<std::vector<float>> w(T), c(T);
376
+ while (any_nonempty(work)) {
377
+ for (int t = 0; t < T; t++) {
378
+ // side test: nearer to pivot a than to pivot b, as one dot
379
+ // product: <x, b - a> <= (|b|^2 - |a|^2) / 2 for L2, <= 0 for IP
380
+ const std::vector<int32_t>& perm = perms[t];
381
+ const size_t ns = work[t].size();
382
+ w[t].resize(ns * d);
383
+ c[t].resize(ns);
384
+ VectorReader vr(storage);
385
+ std::vector<float> pa(d), pb(d);
386
+ for (size_t s = 0; s < ns; s++) {
387
+ const Segment& sg = work[t][s];
388
+ const size_t size = sg.end - sg.begin;
389
+ const uint64_t r = mix64(sg.hash);
390
+ const size_t a = r % size;
391
+ const size_t b = (a + 1 + mix64(r) % (size - 1)) % size;
392
+ vr.decode(perm[sg.begin + a], pa.data());
393
+ vr.decode(perm[sg.begin + b], pb.data());
394
+ for (size_t k = 0; k < d; k++) {
395
+ w[t][s * d + k] = pb[k] - pa[k];
396
+ }
397
+ c[t][s] = ip ? 0
398
+ : (fvec_norm_L2sqr(pb.data(), d) -
399
+ fvec_norm_L2sqr(pa.data(), d)) /
400
+ 2;
401
+ }
402
+ int32_t* sv = segv.data() + size_t(t) * n;
403
+ std::fill(sv, sv + n, -1);
404
+ #pragma omp parallel for schedule(dynamic)
405
+ for (int64_t s = 0; s < int64_t(ns); s++) {
406
+ for (size_t i = work[t][s].begin; i < work[t][s].end; i++) {
407
+ sv[perm[i]] = int32_t(s);
408
+ }
409
+ }
410
+ }
411
+ #pragma omp parallel
412
+ {
413
+ VectorReader vr(storage);
414
+ #pragma omp for schedule(static)
415
+ for (int64_t v = 0; v < int64_t(n); v++) {
416
+ const float* x = nullptr;
417
+ for (int t = 0; t < T; t++) {
418
+ const int32_t q = segv[size_t(t) * n + v];
419
+ if (q < 0) {
420
+ continue;
421
+ }
422
+ if (!x) {
423
+ x = vr.get(v);
424
+ }
425
+ sidev[size_t(t) * n + v] =
426
+ fvec_inner_product(x, w[t].data() + q * d, d) <=
427
+ c[t][q]
428
+ ? 0
429
+ : 1;
430
+ }
431
+ }
432
+ }
433
+ for (int t = 0; t < T; t++) {
434
+ std::vector<int32_t>& perm = perms[t];
435
+ const uint8_t* side = sidev.data() + size_t(t) * n;
436
+ const size_t ns = work[t].size();
437
+ std::vector<Segment> children(2 * ns);
438
+ #pragma omp parallel for schedule(dynamic)
439
+ for (int64_t s = 0; s < int64_t(ns); s++) {
440
+ const Segment sg = work[t][s];
441
+ const auto first = perm.begin() + sg.begin;
442
+ size_t mid = sg.begin +
443
+ (std::stable_partition(
444
+ first,
445
+ perm.begin() + sg.end,
446
+ OnPivotASide{side}) -
447
+ first);
448
+ if (mid == sg.begin || mid == sg.end) {
449
+ // copies of one vector: split by position
450
+ mid = sg.begin + (sg.end - sg.begin) / 2;
451
+ }
452
+ children[2 * s] = {sg.begin, mid, mix64(sg.hash ^ 1)};
453
+ children[2 * s + 1] = {mid, sg.end, mix64(sg.hash ^ 2)};
454
+ }
455
+ std::vector<Segment> next;
456
+ for (const Segment& cs : children) {
457
+ (cs.end - cs.begin <= kLeafSize ? leaves[t] : next)
458
+ .push_back(cs);
459
+ }
460
+ work[t].swap(next);
461
+ }
462
+ }
463
+ return leaves;
464
+ }
465
+
466
+ } // namespace
467
+
468
+ namespace {
469
+
470
+ /// whether id is in the K slots of row; no early exit, so that the loop
471
+ /// vectorizes
472
+ template <class Id>
473
+ inline bool row_contains(const Id* row, int K, Id id) {
474
+ int hit = 0;
475
+ for (int i = 0; i < K; i++) {
476
+ hit |= row[i] == id;
477
+ }
478
+ return hit != 0;
479
+ }
480
+
481
+ /** Merges the candidates c[0..m) into the sorted row of K slots. The
482
+ * candidates are sorted by (distance, id) and have distinct ids. The row
483
+ * keeps the K best entries by (distance, id), with the smallest distance of
484
+ * each id. An entry from a candidate is new. The result does not depend on
485
+ * the order of the candidates. buf holds K entries and K flags. */
486
+ template <class Id>
487
+ void merge_into_row(
488
+ int K,
489
+ Id* ids,
490
+ float* dis,
491
+ uint8_t* is_new,
492
+ std::pair<float, Id>* c,
493
+ size_t m,
494
+ std::vector<std::pair<float, Id>>& buf,
495
+ std::vector<uint8_t>& buf_new) {
496
+ // a candidate with an id of the row replaces the entry if it is better,
497
+ // else it is dropped
498
+ size_t mk = 0;
499
+ for (size_t j = 0; j < m; j++) {
500
+ if (row_contains(ids, K, c[j].second)) {
501
+ int pos = 0;
502
+ while (ids[pos] != c[j].second) {
503
+ pos++;
504
+ }
505
+ if (!(c[j] < std::make_pair(dis[pos], ids[pos]))) {
506
+ continue;
507
+ }
508
+ ids[pos] = -2; // removed
509
+ }
510
+ c[mk++] = c[j];
511
+ }
512
+ if (mk == 0) {
513
+ return;
514
+ }
515
+ buf.resize(K);
516
+ buf_new.resize(K);
517
+ int i = 0, k = 0;
518
+ size_t j = 0;
519
+ while (k < K) {
520
+ while (i < K && ids[i] == -2) {
521
+ i++;
522
+ }
523
+ const bool has_row = i < K && ids[i] >= 0;
524
+ const bool has_cand = j < mk;
525
+ if (!has_row && !has_cand) {
526
+ break;
527
+ }
528
+ if (has_cand && (!has_row || c[j] < std::make_pair(dis[i], ids[i]))) {
529
+ buf[k] = c[j++];
530
+ buf_new[k++] = 1;
531
+ } else {
532
+ buf[k] = {dis[i], ids[i]};
533
+ buf_new[k++] = is_new[i++];
534
+ }
535
+ }
536
+ for (int t = 0; t < k; t++) {
537
+ ids[t] = buf[t].second;
538
+ dis[t] = buf[t].first;
539
+ is_new[t] = buf_new[t];
540
+ }
541
+ for (int t = k; t < K; t++) {
542
+ ids[t] = -1;
543
+ dis[t] = kInf;
544
+ is_new[t] = 0;
545
+ }
546
+ }
547
+
548
+ /** Keeps at the front of cand the candidates that can enter the row: by
549
+ * (distance, id), better than the K-th entry of a full row (its distance is
550
+ * kth), and with an id that is not in the old row orow. Returns the number
551
+ * kept. An id of the old row keeps
552
+ * its old entry. If the id could leave the row and come back, the row would
553
+ * depend on the order of the candidates when one pair gets two distances. */
554
+ template <class Id>
555
+ size_t drop_old_ids(
556
+ const Id* orow,
557
+ float kth,
558
+ int K,
559
+ std::vector<std::pair<float, Id>>& cand) {
560
+ const bool full = orow[K - 1] >= 0;
561
+ const std::pair<float, Id> worst = {kth, orow[K - 1]};
562
+ size_t m = 0;
563
+ for (const std::pair<float, Id>& c : cand) {
564
+ if ((full && !(c < worst)) || row_contains(orow, K, c.second)) {
565
+ continue;
566
+ }
567
+ cand[m++] = c;
568
+ }
569
+ return m;
570
+ }
571
+
572
+ struct LeafScratch {
573
+ AlignedTable<float, 64> xl, dis;
574
+ std::vector<float> norms;
575
+ std::vector<const float*> rows;
576
+ };
577
+
578
+ /// all distances between the m points lp of a leaf, into ls.dis (m x m)
579
+ void leaf_distances(
580
+ MetricType metric_type,
581
+ GramKernel kernel,
582
+ const int32_t* lp,
583
+ size_t m,
584
+ VectorReader& vr,
585
+ LeafScratch& ls) {
586
+ const size_t d = vr.d;
587
+ // the kernel reads flat storage in place; BLAS reads one matrix
588
+ const bool in_place = kernel && vr.flat;
589
+ if (!in_place) {
590
+ pipnn::ensure_size(ls.xl, m * d);
591
+ }
592
+ ls.rows.resize(m);
593
+ ls.norms.resize(m);
594
+ for (size_t p = 0; p < m; p++) {
595
+ if (in_place) {
596
+ ls.rows[p] = vr.flat + size_t(lp[p]) * d;
597
+ } else {
598
+ vr.decode(lp[p], ls.xl.data() + p * d);
599
+ ls.rows[p] = ls.xl.data() + p * d;
600
+ }
601
+ ls.norms[p] = fvec_norm_L2sqr(ls.rows[p], d);
602
+ }
603
+ pipnn::ensure_size(ls.dis, m * m);
604
+ float* leaf_dis = ls.dis.data();
605
+ if (kernel) {
606
+ kernel(ls.rows.data(), m, m, d, leaf_dis);
607
+ products_to_distances(metric_type, ls.norms.data(), m, m, leaf_dis);
608
+ for (size_t p = 0; p < m; p++) {
609
+ for (size_t q = p + 1; q < m; q++) {
610
+ leaf_dis[q * m + p] = leaf_dis[p * m + q];
611
+ }
612
+ }
613
+ return;
614
+ }
615
+ pipnn::pairwise_distances(
616
+ ls.xl.data(), ls.norms.data(), m, d, metric_type, leaf_dis);
617
+ for (size_t e = 0; e < m * m; e++) {
618
+ leaf_dis[e] += 0.0f; // -0 + 0 = +0, as in products_to_distances
619
+ }
620
+ }
621
+
622
+ /// merges the candidates into the row v of init(), as round() does
623
+ void add_to_row(
624
+ int K,
625
+ int32_t* ids,
626
+ float* dis,
627
+ uint8_t* is_new,
628
+ idx_t v,
629
+ std::vector<DisId>& cand,
630
+ std::vector<DisId>& buf,
631
+ std::vector<uint8_t>& buf_new) {
632
+ const size_t o = size_t(v) * K;
633
+ const size_t m = drop_old_ids(ids + o, dis[o + K - 1], K, cand);
634
+ if (m == 0) {
635
+ return;
636
+ }
637
+ std::sort(cand.begin(), cand.begin() + m);
638
+ merge_into_row(
639
+ K, ids + o, dis + o, is_new + o, cand.data(), m, buf, buf_new);
640
+ }
641
+
642
+ /// appends 2K random ids of [0, n) for node v, then the next ids, so that a
643
+ /// row of n - 1 >= K fills
644
+ void random_ids(
645
+ idx_t v,
646
+ idx_t n,
647
+ int K,
648
+ int64_t seed,
649
+ std::vector<int32_t>& c) {
650
+ const int want = int(std::min<idx_t>(K, n - 1));
651
+ uint64_t r = mix64(uint64_t(seed) ^ mix64(v) ^ 0x5bd1e995);
652
+ for (int j = 0; j < 2 * want; j++) {
653
+ r = mix64(r);
654
+ c.push_back(int32_t(r % n));
655
+ }
656
+ for (int j = 1; j <= want; j++) {
657
+ c.push_back(int32_t((v + j) % n));
658
+ }
659
+ }
660
+
661
+ } // namespace
662
+
663
+ void DeterministicNNDescent::init(const Index& storage) {
664
+ check_params();
665
+ FAISS_THROW_IF_NOT_MSG(
666
+ storage.metric_type == METRIC_L2 ||
667
+ storage.metric_type == METRIC_INNER_PRODUCT,
668
+ "DeterministicNNDescent: only METRIC_L2 and METRIC_INNER_PRODUCT");
669
+ FAISS_THROW_IF_NOT_MSG(
670
+ storage.d > 0, "DeterministicNNDescent: d must be > 0");
671
+ FAISS_THROW_IF_NOT_MSG(
672
+ storage.ntotal < (idx_t(1) << 31),
673
+ "DeterministicNNDescent: at most 2^31 - 1 vectors");
674
+ n = storage.ntotal;
675
+ d = storage.d;
676
+ metric_type = storage.metric_type;
677
+ const size_t nK = size_t(n) * K;
678
+ if (n > 0) {
679
+ // a storage that cannot reconstruct throws here, not inside OpenMP
680
+ VectorReader(storage).get(0);
681
+ }
682
+ ids.assign(nK, -1);
683
+ dis.assign(nK, kInf);
684
+ is_new.assign(nK, 1);
685
+ order.resize(n);
686
+ std::iota(order.begin(), order.end(), 0);
687
+ ndis = 0;
688
+ if (n <= 1) {
689
+ return;
690
+ }
691
+ const double t0 = getmillisecs();
692
+
693
+ size_t nd_total = 0;
694
+ if (ntrees > 0) {
695
+ std::vector<std::vector<int32_t>> perms(
696
+ ntrees, std::vector<int32_t>(n));
697
+ for (auto& perm : perms) {
698
+ std::iota(perm.begin(), perm.end(), 0);
699
+ }
700
+ const std::vector<std::vector<Segment>> all_leaves =
701
+ cluster_trees(storage, perms, uint64_t(seed));
702
+ order = perms[0];
703
+ const GramKernel kernel = gram_kernel();
704
+ for (int t = 0; t < ntrees; t++) {
705
+ const std::vector<int32_t>& perm = perms[t];
706
+ const std::vector<Segment>& leaves = all_leaves[t];
707
+ #pragma omp parallel reduction(+ : nd_total)
708
+ {
709
+ VectorReader vr(storage);
710
+ LeafScratch ls;
711
+ std::vector<DisId> cand, buf;
712
+ std::vector<uint8_t> buf_new;
713
+ #pragma omp for schedule(dynamic)
714
+ for (int64_t l = 0; l < int64_t(leaves.size()); l++) {
715
+ const int32_t* lp = perm.data() + leaves[l].begin;
716
+ const size_t m = leaves[l].end - leaves[l].begin;
717
+ leaf_distances(metric_type, kernel, lp, m, vr, ls);
718
+ const auto& leaf_dis = ls.dis;
719
+ nd_total += m * (m - 1) / 2;
720
+ for (size_t p = 0; p < m; p++) {
721
+ const float* ld = leaf_dis.data() + p * m;
722
+ // what cannot beat the K-th of the row cannot enter
723
+ const size_t ro = size_t(lp[p]) * K + K - 1;
724
+ const float rw = ids[ro] >= 0 ? dis[ro] : kInf;
725
+ cand.clear();
726
+ for (size_t q = 0; q < m; q++) {
727
+ if (q != p && ld[q] <= rw) {
728
+ cand.push_back({ld[q], lp[q]});
729
+ }
730
+ }
731
+ keep_best(cand, K);
732
+ add_to_row(
733
+ K,
734
+ ids.data(),
735
+ dis.data(),
736
+ is_new.data(),
737
+ lp[p],
738
+ cand,
739
+ buf,
740
+ buf_new);
741
+ }
742
+ }
743
+ }
744
+ }
745
+ }
746
+ // rows that the leaves left short, and all rows with ntrees = 0, get
747
+ // random neighbors
748
+ #pragma omp parallel reduction(+ : nd_total)
749
+ {
750
+ VectorReader rv(storage), rc(storage);
751
+ IdMap seen;
752
+ std::vector<int32_t> c;
753
+ std::vector<DisId> cand, buf;
754
+ std::vector<uint8_t> buf_new;
755
+ #pragma omp for schedule(dynamic, 256)
756
+ for (idx_t v = 0; v < n; v++) {
757
+ const int want = int(std::min<idx_t>(K, n - 1));
758
+ if (ids[size_t(v) * K + want - 1] >= 0) {
759
+ continue;
760
+ }
761
+ c.clear();
762
+ random_ids(v, n, K, seed, c);
763
+ // the ids of c that are not v and not in the row
764
+ seen.clear();
765
+ bool is_new_id;
766
+ seen.find_or_insert(int32_t(v), is_new_id);
767
+ for (int j = 0; j < K && ids[size_t(v) * K + j] >= 0; j++) {
768
+ seen.find_or_insert(ids[size_t(v) * K + j], is_new_id);
769
+ }
770
+ const float* xv = rv.get(v);
771
+ cand.clear();
772
+ for (int32_t id : c) {
773
+ seen.find_or_insert(id, is_new_id);
774
+ if (is_new_id) {
775
+ cand.push_back(
776
+ {pair_distance(metric_type, xv, rc.get(id), d),
777
+ id});
778
+ }
779
+ }
780
+ nd_total += cand.size();
781
+ keep_best(cand, K);
782
+ add_to_row(
783
+ K,
784
+ ids.data(),
785
+ dis.data(),
786
+ is_new.data(),
787
+ v,
788
+ cand,
789
+ buf,
790
+ buf_new);
791
+ }
792
+ }
793
+ // every entry is new for the first round, as in NNDescentShard::set_rows()
794
+ #pragma omp parallel for schedule(static)
795
+ for (int64_t e = 0; e < int64_t(nK); e++) {
796
+ is_new[e] = ids[e] >= 0;
797
+ }
798
+ ndis = nd_total;
799
+ if (verbose) {
800
+ printf("DeterministicNNDescent: init n=%" PRId64
801
+ " K=%d in %.1f s, %.0f distances per node\n",
802
+ n,
803
+ K,
804
+ (getmillisecs() - t0) / 1000,
805
+ double(ndis) / n);
806
+ }
807
+ }
808
+
809
+ namespace {
810
+
811
+ struct SpinLock {
812
+ std::atomic_flag& flag;
813
+ explicit SpinLock(std::atomic_flag& f) : flag(f) {
814
+ while (flag.test_and_set(std::memory_order_acquire)) {
815
+ }
816
+ }
817
+ SpinLock(const SpinLock&) = delete;
818
+ SpinLock& operator=(const SpinLock&) = delete;
819
+ ~SpinLock() {
820
+ flag.clear(std::memory_order_release);
821
+ }
822
+ };
823
+
824
+ /// merge_into_row() of the sorted c[0..m) under the lock of the row; lowers
825
+ /// the K-th distance worst of the row
826
+ template <class Id>
827
+ void merge_into_row_locked(
828
+ int K,
829
+ std::atomic_flag& lock,
830
+ std::atomic<float>& worst,
831
+ Id* ids,
832
+ float* dis,
833
+ uint8_t* is_new,
834
+ std::pair<float, Id>* c,
835
+ size_t m,
836
+ std::vector<std::pair<float, Id>>& buf,
837
+ std::vector<uint8_t>& buf_new) {
838
+ SpinLock guard(lock);
839
+ merge_into_row(K, ids, dis, is_new, c, m, buf, buf_new);
840
+ if (ids[K - 1] >= 0) {
841
+ worst.store(dis[K - 1], std::memory_order_relaxed);
842
+ }
843
+ }
844
+
845
+ /** The flags of the next rows at the start of a round: the local joins use
846
+ * the first S new entries of each row, and the other new entries stay new
847
+ * for the next round. */
848
+ void unsampled_new(
849
+ const std::vector<uint8_t>& is_new,
850
+ idx_t n,
851
+ int K,
852
+ int S,
853
+ std::vector<uint8_t>& next_new) {
854
+ next_new.assign(is_new.size(), 0);
855
+ #pragma omp parallel for schedule(static)
856
+ for (idx_t v = 0; v < n; v++) {
857
+ int taken = 0;
858
+ for (int j = 0; j < K; j++) {
859
+ const size_t e = size_t(v) * K + j;
860
+ if (is_new[e] && taken++ >= S) {
861
+ next_new[e] = 1;
862
+ }
863
+ }
864
+ }
865
+ }
866
+
867
+ /// number of rows with a new entry
868
+ idx_t count_rows_with_new(const std::vector<uint8_t>& is_new, idx_t n, int K) {
869
+ idx_t changed = 0;
870
+ #pragma omp parallel for reduction(+ : changed)
871
+ for (idx_t v = 0; v < n; v++) {
872
+ const auto row = is_new.begin() + size_t(v) * K;
873
+ changed += std::find(row, row + K, 1) != row + K;
874
+ }
875
+ return changed;
876
+ }
877
+
878
+ /// per-thread scratch of local_join()
879
+ template <class Id>
880
+ struct JoinScratch {
881
+ IdMap seen;
882
+ std::vector<int32_t> nbr; ///< the new members, then the old ones
883
+ std::vector<std::pair<int32_t, uint8_t>> lst; ///< (member, is new)
884
+ AlignedTable<float, 64> xs, out;
885
+ std::vector<const float*> rows;
886
+ std::vector<float> nrm, thr;
887
+ std::vector<std::vector<std::pair<float, Id>>> bk;
888
+ std::vector<std::pair<float, Id>> mbuf;
889
+ std::vector<uint8_t> mbuf_new;
890
+
891
+ /// adds the members of the list l (len slots, -1 padded, with the flags
892
+ /// f) to lst. An id is new if one of its edges is new, and up to S
893
+ /// members of the list are new.
894
+ void collect(const int32_t* l, const uint8_t* f, int len, int S) {
895
+ int taken = 0;
896
+ for (int i = 0; i < len && l[i] >= 0; i++) {
897
+ bool fresh;
898
+ const bool want_new = f[i] && taken < S;
899
+ const int32_t k = seen.find_or_insert(l[i], fresh);
900
+ if (fresh) {
901
+ lst.push_back({l[i], uint8_t(want_new)});
902
+ taken += want_new;
903
+ } else if (want_new && !lst[k].second) {
904
+ lst[k].second = 1;
905
+ taken++;
906
+ }
907
+ }
908
+ }
909
+ };
910
+
911
+ /** The local join of one neighborhood, for DeterministicNNDescent::round()
912
+ * and NNDescentShard::join_impl(). The members are storage indices: the
913
+ * out-list out_l (K slots) and the in-list in_l (Rr slots), -1 padded, with
914
+ * their new flags. Up to S new members of each list are new. For the pairs
915
+ * (new, new) and (new, old), each distance that can beat the K-th distance
916
+ * nworst[] of a member goes to acc.flush(member, cand, buf, buf_new) as
917
+ * (distance, acc.gid(other member)).
918
+ *
919
+ * acc.row(s, buf) returns the vector of member s, or decodes it into buf (d
920
+ * floats) and returns buf. acc.prefetch(s) is called two members ahead. The
921
+ * products come from kernel, or from BLAS if it is null. Adds the distance
922
+ * computations to ndis. Access is RoundAccess or ShardAccess. */
923
+ template <class Id, class Access>
924
+ void local_join(
925
+ const int32_t* out_l,
926
+ const uint8_t* out_f,
927
+ int K,
928
+ const int32_t* in_l,
929
+ const uint8_t* in_f,
930
+ int Rr,
931
+ int S,
932
+ GramKernel kernel,
933
+ MetricType metric_type,
934
+ size_t d,
935
+ const float* norms,
936
+ const std::vector<std::atomic<float>>& nworst,
937
+ JoinScratch<Id>& js,
938
+ size_t& ndis,
939
+ const Access& acc) {
940
+ js.seen.clear();
941
+ js.nbr.clear();
942
+ js.lst.clear();
943
+ js.collect(out_l, out_f, K, S);
944
+ js.collect(in_l, in_f, Rr, S);
945
+ int r = 0;
946
+ for (auto& p : js.lst) {
947
+ r += p.second;
948
+ }
949
+ if (r == 0) {
950
+ return;
951
+ }
952
+ for (auto& p : js.lst) {
953
+ if (p.second) {
954
+ js.nbr.push_back(p.first);
955
+ }
956
+ }
957
+ for (auto& p : js.lst) {
958
+ if (!p.second) {
959
+ js.nbr.push_back(p.first);
960
+ }
961
+ }
962
+ const size_t m = js.nbr.size();
963
+ pipnn::ensure_size(js.out, r * m);
964
+ pipnn::ensure_size(js.xs, m * d);
965
+ js.nrm.resize(m);
966
+ js.thr.resize(m);
967
+ js.rows.resize(m);
968
+ if (js.bk.size() < m) {
969
+ js.bk.resize(m);
970
+ }
971
+ for (size_t i = 0; i < m; i++) {
972
+ if (i + 2 < m) {
973
+ acc.prefetch(js.nbr[i + 2]);
974
+ }
975
+ float* buf = js.xs.data() + i * d;
976
+ const float* x = acc.row(js.nbr[i], buf);
977
+ if (!kernel && x != buf) {
978
+ std::copy_n(x, d, buf); // BLAS reads one matrix
979
+ }
980
+ js.rows[i] = kernel ? x : buf;
981
+ js.nrm[i] = norms[js.nbr[i]];
982
+ // nworst starts at the K-th distance of the old row and only goes
983
+ // down
984
+ js.thr[i] = nworst[js.nbr[i]].load(std::memory_order_relaxed);
985
+ js.bk[i].clear();
986
+ }
987
+ if (kernel) {
988
+ kernel(js.rows.data(), r, m, d, js.out.data());
989
+ } else {
990
+ gram_upper_rows_blas(js.xs.data(), r, m, d, js.out.data());
991
+ }
992
+ products_to_distances(metric_type, js.nrm.data(), r, m, js.out.data());
993
+ for (int i = 0; i < r; i++) {
994
+ const float* oi = js.out.data() + size_t(i) * m;
995
+ ndis += m - i - 1;
996
+ for (size_t j = i + 1; j < m; j++) {
997
+ const float v = oi[j];
998
+ if (v <= js.thr[i]) {
999
+ js.bk[i].push_back({v, acc.gid(js.nbr[j])});
1000
+ }
1001
+ if (v <= js.thr[j]) {
1002
+ js.bk[j].push_back({v, acc.gid(js.nbr[i])});
1003
+ }
1004
+ }
1005
+ }
1006
+ for (size_t i = 0; i < m; i++) {
1007
+ if (!js.bk[i].empty()) {
1008
+ acc.flush(js.nbr[i], js.bk[i], js.mbuf, js.mbuf_new);
1009
+ }
1010
+ }
1011
+ }
1012
+
1013
+ /** local_join() access of DeterministicNNDescent::round(), one per thread.
1014
+ * The storage indices are the graph ids. flush() merges the candidates into
1015
+ * the next rows under the lock of the row. */
1016
+ struct RoundAccess {
1017
+ VectorReader& vr;
1018
+ int K;
1019
+ /// the rows at the start of the round
1020
+ const int32_t* ids;
1021
+ const float* dis;
1022
+ int32_t* next_ids;
1023
+ float* next_dis;
1024
+ uint8_t* next_new;
1025
+ std::atomic_flag* locks;
1026
+ std::atomic<float>* nworst;
1027
+
1028
+ const float* row(int32_t s, float* buf) const {
1029
+ if (vr.flat) {
1030
+ return vr.flat + size_t(s) * vr.d;
1031
+ }
1032
+ vr.decode(s, buf);
1033
+ return buf;
1034
+ }
1035
+
1036
+ void prefetch(int32_t s) const {
1037
+ vr.prefetch(s);
1038
+ }
1039
+
1040
+ int32_t gid(int32_t s) const {
1041
+ return s;
1042
+ }
1043
+
1044
+ void flush(
1045
+ int32_t a,
1046
+ std::vector<DisId>& cand,
1047
+ std::vector<DisId>& buf,
1048
+ std::vector<uint8_t>& buf_new) const {
1049
+ const size_t o = size_t(a) * K;
1050
+ const size_t m = drop_old_ids(ids + o, dis[o + K - 1], K, cand);
1051
+ if (m == 0) {
1052
+ return;
1053
+ }
1054
+ std::sort(cand.begin(), cand.begin() + m);
1055
+ merge_into_row_locked(
1056
+ K,
1057
+ locks[a],
1058
+ nworst[a],
1059
+ next_ids + o,
1060
+ next_dis + o,
1061
+ next_new + o,
1062
+ cand.data(),
1063
+ m,
1064
+ buf,
1065
+ buf_new);
1066
+ }
1067
+ };
1068
+
1069
+ } // namespace
1070
+
1071
+ idx_t DeterministicNNDescent::round(const Index& storage) {
1072
+ FAISS_THROW_IF_NOT_MSG(
1073
+ storage.ntotal == n && ids.size() == size_t(n) * K &&
1074
+ order.size() == size_t(n),
1075
+ "DeterministicNNDescent: init() before round()");
1076
+ check_params();
1077
+ FAISS_THROW_IF_NOT_MSG(
1078
+ size_t(storage.d) == d && storage.metric_type == metric_type,
1079
+ "DeterministicNNDescent: round() needs the storage of init()");
1080
+ if (n > 0) {
1081
+ // a storage that cannot reconstruct throws here, not inside OpenMP
1082
+ VectorReader(storage).get(0);
1083
+ }
1084
+ const int Rr = nreverse();
1085
+ const int S = nsample();
1086
+ const double t0 = getmillisecs();
1087
+
1088
+ // reverse neighbors: the Rr nearest of each node, by (distance, source).
1089
+ // The edges are counted and placed in parallel; each list is sorted after.
1090
+ // rpos[t + 1] counts the edges to t, then rpos[t] is the next free slot of
1091
+ // list t; after the placement, list t is [rpos[t - 1], rpos[t]).
1092
+ std::vector<std::atomic<int64_t>> rpos(n + 1);
1093
+ for (idx_t i = 0; i <= n; i++) {
1094
+ rpos[i].store(0, std::memory_order_relaxed);
1095
+ }
1096
+ #pragma omp parallel for schedule(static)
1097
+ for (idx_t s = 0; s < n; s++) {
1098
+ for (int j = 0; j < K; j++) {
1099
+ const int32_t t = ids[size_t(s) * K + j];
1100
+ if (t >= 0) {
1101
+ rpos[t + 1].fetch_add(1, std::memory_order_relaxed);
1102
+ }
1103
+ }
1104
+ }
1105
+ for (idx_t i = 0; i < n; i++) {
1106
+ rpos[i + 1].store(
1107
+ rpos[i + 1].load(std::memory_order_relaxed) +
1108
+ rpos[i].load(std::memory_order_relaxed),
1109
+ std::memory_order_relaxed);
1110
+ }
1111
+ const int64_t nedges = rpos[n].load(std::memory_order_relaxed);
1112
+ std::vector<DisId> redges(nedges);
1113
+ std::vector<uint8_t> rnew(nedges);
1114
+ #pragma omp parallel for schedule(static)
1115
+ for (idx_t s = 0; s < n; s++) {
1116
+ for (int j = 0; j < K; j++) {
1117
+ const size_t e = size_t(s) * K + j;
1118
+ const int32_t t = ids[e];
1119
+ if (t >= 0) {
1120
+ const int64_t p =
1121
+ rpos[t].fetch_add(1, std::memory_order_relaxed);
1122
+ redges[p] = {dis[e], int32_t(s)};
1123
+ rnew[p] = is_new[e];
1124
+ }
1125
+ }
1126
+ }
1127
+ std::vector<int32_t> rev(size_t(n) * Rr, -1);
1128
+ std::vector<uint8_t> rev_new(size_t(n) * Rr, 0);
1129
+ #pragma omp parallel
1130
+ {
1131
+ // a source is in a list at most once, so the pairs compare as their
1132
+ // (distance, source)
1133
+ std::vector<std::pair<DisId, uint8_t>> sel;
1134
+ #pragma omp for schedule(dynamic, 1024)
1135
+ for (idx_t t = 0; t < n; t++) {
1136
+ const int64_t b =
1137
+ t == 0 ? 0 : rpos[t - 1].load(std::memory_order_relaxed);
1138
+ const int64_t e = rpos[t].load(std::memory_order_relaxed);
1139
+ sel.resize(e - b);
1140
+ for (int64_t p = b; p < e; p++) {
1141
+ sel[p - b] = {redges[p], rnew[p]};
1142
+ }
1143
+ const size_t m = std::min<size_t>(sel.size(), Rr);
1144
+ std::partial_sort(sel.begin(), sel.begin() + m, sel.end());
1145
+ for (size_t j = 0; j < m; j++) {
1146
+ rev[size_t(t) * Rr + j] = sel[j].first.second;
1147
+ rev_new[size_t(t) * Rr + j] = sel[j].second;
1148
+ }
1149
+ }
1150
+ }
1151
+ redges = std::vector<DisId>();
1152
+ rnew = std::vector<uint8_t>();
1153
+
1154
+ // the next rows start as the current rows; the local joins insert the
1155
+ // candidates under a lock per row
1156
+ std::vector<int32_t> nids = ids;
1157
+ std::vector<float> ndis_ = dis;
1158
+ std::vector<uint8_t> nnew;
1159
+ unsampled_new(is_new, n, K, S, nnew);
1160
+ std::vector<std::atomic_flag> locks(n);
1161
+ // K-th distance of each next row, read without the lock: it can only go
1162
+ // down, so a candidate above it cannot enter the final row
1163
+ std::vector<std::atomic<float>> nworst(n);
1164
+ for (idx_t v = 0; v < n; v++) {
1165
+ const size_t e = size_t(v) * K + K - 1;
1166
+ nworst[v].store(ids[e] >= 0 ? dis[e] : kInf, std::memory_order_relaxed);
1167
+ }
1168
+
1169
+ // squared norms, once per round
1170
+ std::vector<float> gnorms(n);
1171
+ #pragma omp parallel
1172
+ {
1173
+ VectorReader vr(storage);
1174
+ #pragma omp for schedule(static)
1175
+ for (idx_t v = 0; v < n; v++) {
1176
+ gnorms[v] = fvec_norm_L2sqr(vr.get(v), d);
1177
+ }
1178
+ }
1179
+
1180
+ const GramKernel kernel = gram_kernel();
1181
+ size_t nd_total = 0;
1182
+ #pragma omp parallel reduction(+ : nd_total)
1183
+ {
1184
+ VectorReader vr(storage);
1185
+ JoinScratch<int32_t> js;
1186
+ const RoundAccess acc{
1187
+ vr,
1188
+ K,
1189
+ ids.data(),
1190
+ dis.data(),
1191
+ nids.data(),
1192
+ ndis_.data(),
1193
+ nnew.data(),
1194
+ locks.data(),
1195
+ nworst.data()};
1196
+ #pragma omp for schedule(dynamic, 64)
1197
+ for (idx_t pos = 0; pos < n; pos++) {
1198
+ const idx_t u = order[pos];
1199
+ local_join(
1200
+ ids.data() + size_t(u) * K,
1201
+ is_new.data() + size_t(u) * K,
1202
+ K,
1203
+ rev.data() + size_t(u) * Rr,
1204
+ rev_new.data() + size_t(u) * Rr,
1205
+ Rr,
1206
+ S,
1207
+ kernel,
1208
+ metric_type,
1209
+ d,
1210
+ gnorms.data(),
1211
+ nworst,
1212
+ js,
1213
+ nd_total,
1214
+ acc);
1215
+ }
1216
+ }
1217
+ const idx_t changed = count_rows_with_new(nnew, n, K);
1218
+ ids.swap(nids);
1219
+ dis.swap(ndis_);
1220
+ is_new.swap(nnew);
1221
+ ndis = nd_total;
1222
+ if (verbose) {
1223
+ printf("DeterministicNNDescent: round in %.1f s, %" PRId64
1224
+ " nodes changed, %.0f distances per node\n",
1225
+ (getmillisecs() - t0) / 1000,
1226
+ changed,
1227
+ double(ndis) / n);
1228
+ }
1229
+ return changed;
1230
+ }
1231
+
1232
+ void DeterministicNNDescent::check_params() const {
1233
+ FAISS_THROW_IF_NOT_FMT(
1234
+ K >= 1 && K <= 4096,
1235
+ "DeterministicNNDescent: K must be in [1, 4096], got %d",
1236
+ K);
1237
+ FAISS_THROW_IF_NOT_FMT(
1238
+ R >= 0 && R <= 4096,
1239
+ "DeterministicNNDescent: R must be in [0, 4096], got %d",
1240
+ R);
1241
+ FAISS_THROW_IF_NOT_FMT(
1242
+ sample >= 0,
1243
+ "DeterministicNNDescent: sample must be >= 0, got %d",
1244
+ sample);
1245
+ FAISS_THROW_IF_NOT_FMT(
1246
+ ntrees >= 0,
1247
+ "DeterministicNNDescent: ntrees must be >= 0, got %d",
1248
+ ntrees);
1249
+ }
1250
+
1251
+ void DeterministicNNDescent::build(const Index& storage) {
1252
+ init(storage);
1253
+ for (int r = 0; r < max_rounds; r++) {
1254
+ if (round(storage) < delta * n) {
1255
+ break;
1256
+ }
1257
+ }
1258
+ }
1259
+
1260
+ /*************************************************************
1261
+ * NNDescentShard
1262
+ *************************************************************/
1263
+
1264
+ namespace {
1265
+
1266
+ /// owner process of graph id v
1267
+ inline int owner_of(const std::vector<int64_t>& owner_begin, int64_t v) {
1268
+ return int(std::upper_bound(owner_begin.begin(), owner_begin.end(), v) -
1269
+ owner_begin.begin()) -
1270
+ 1;
1271
+ }
1272
+
1273
+ /// throws msg if one of the n ids is not in [lo, hi), or -1 with allow_none.
1274
+ /// An id out of range would index past the end of per-owner arrays.
1275
+ void check_graph_ids(
1276
+ const int64_t* v,
1277
+ size_t n,
1278
+ int64_t lo,
1279
+ int64_t hi,
1280
+ bool allow_none,
1281
+ const char* msg) {
1282
+ int bad = 0;
1283
+ #pragma omp parallel for schedule(static) reduction(| : bad)
1284
+ for (int64_t e = 0; e < int64_t(n); e++) {
1285
+ const bool ok = (allow_none && v[e] == -1) || (v[e] >= lo && v[e] < hi);
1286
+ bad |= ok ? 0 : 1;
1287
+ }
1288
+ if (bad) {
1289
+ FAISS_THROW_MSG(msg);
1290
+ }
1291
+ }
1292
+
1293
+ /// counts of a list grouped by owner, from the owner of each item
1294
+ void group_counts(
1295
+ const std::vector<int64_t>& owner_begin,
1296
+ const std::vector<int64_t>& sorted_ids,
1297
+ std::vector<int64_t>& counts) {
1298
+ const int world = int(owner_begin.size()) - 1;
1299
+ counts.assign(world, 0);
1300
+ for (int p = 0; p < world; p++) {
1301
+ counts[p] =
1302
+ std::lower_bound(
1303
+ sorted_ids.begin(),
1304
+ sorted_ids.end(),
1305
+ owner_begin[p + 1]) -
1306
+ std::lower_bound(
1307
+ sorted_ids.begin(), sorted_ids.end(), owner_begin[p]);
1308
+ }
1309
+ }
1310
+
1311
+ /// appends the remote ids of the list v (len slots, -1 padded) to the
1312
+ /// buckets of their owners; the home ids are [hb, hb + nh)
1313
+ void bucket_remote_ids(
1314
+ const int64_t* v,
1315
+ int len,
1316
+ int64_t hb,
1317
+ idx_t nh,
1318
+ const std::vector<int64_t>& owner_begin,
1319
+ std::vector<std::vector<int64_t>>& buckets) {
1320
+ for (int j = 0; j < len; j++) {
1321
+ if (v[j] >= 0 && (v[j] < hb || v[j] >= hb + nh)) {
1322
+ buckets[owner_of(owner_begin, v[j])].push_back(v[j]);
1323
+ }
1324
+ }
1325
+ }
1326
+
1327
+ } // namespace
1328
+
1329
+ void NNDescentShard::set_rows(
1330
+ int K_in,
1331
+ MetricType metric_type_in,
1332
+ size_t d_in,
1333
+ int rank_in,
1334
+ int world,
1335
+ const int64_t* owner_begin_in,
1336
+ const float* x_in,
1337
+ const int64_t* ids_in,
1338
+ const float* dis_in) {
1339
+ FAISS_THROW_IF_NOT_FMT(
1340
+ K_in >= 1 && K_in <= 4096,
1341
+ "NNDescentShard: K must be in [1, 4096], got %d",
1342
+ K_in);
1343
+ FAISS_THROW_IF_NOT_MSG(
1344
+ metric_type_in == METRIC_L2 ||
1345
+ metric_type_in == METRIC_INNER_PRODUCT,
1346
+ "NNDescentShard: only METRIC_L2 and METRIC_INNER_PRODUCT");
1347
+ FAISS_THROW_IF_NOT_MSG(d_in > 0, "NNDescentShard: d must be > 0");
1348
+ FAISS_THROW_IF_NOT(world >= 1 && rank_in >= 0 && rank_in < world);
1349
+ for (int p = 0; p < world; p++) {
1350
+ FAISS_THROW_IF_NOT_MSG(
1351
+ owner_begin_in[p] <= owner_begin_in[p + 1],
1352
+ "NNDescentShard: owner_begin must be non-decreasing");
1353
+ }
1354
+ const size_t nK =
1355
+ size_t(owner_begin_in[rank_in + 1] - owner_begin_in[rank_in]) *
1356
+ K_in;
1357
+ check_graph_ids(
1358
+ ids_in,
1359
+ nK,
1360
+ owner_begin_in[0],
1361
+ owner_begin_in[world],
1362
+ true,
1363
+ "NNDescentShard: row id out of range");
1364
+ K = K_in;
1365
+ metric_type = metric_type_in;
1366
+ d = d_in;
1367
+ rank = rank_in;
1368
+ owner_begin.assign(owner_begin_in, owner_begin_in + world + 1);
1369
+ x = x_in;
1370
+ ids.assign(ids_in, ids_in + nK);
1371
+ dis.assign(dis_in, dis_in + nK);
1372
+ is_new.resize(nK);
1373
+ for (size_t e = 0; e < nK; e++) {
1374
+ is_new[e] = ids[e] >= 0;
1375
+ }
1376
+ remote_ids.clear();
1377
+ reverse_ids.clear();
1378
+ reverse_new.clear();
1379
+ }
1380
+
1381
+ idx_t NNDescentShard::nhome() const {
1382
+ return owner_begin.empty() ? 0 : owner_begin[rank + 1] - owner_begin[rank];
1383
+ }
1384
+
1385
+ void NNDescentShard::reverse_edges(
1386
+ std::vector<int64_t>& counts,
1387
+ std::vector<int64_t>& target,
1388
+ std::vector<int64_t>& source,
1389
+ std::vector<float>& edge_dis,
1390
+ std::vector<uint8_t>& edge_new) const {
1391
+ const int world = int(owner_begin.size()) - 1;
1392
+ const idx_t nh = nhome();
1393
+ const size_t nK = size_t(nh) * K;
1394
+ std::vector<int32_t> owner(nK, -1);
1395
+ #pragma omp parallel for schedule(static)
1396
+ for (int64_t e = 0; e < int64_t(nK); e++) {
1397
+ if (ids[e] >= 0) {
1398
+ owner[e] = owner_of(owner_begin, ids[e]);
1399
+ }
1400
+ }
1401
+ const int nt = omp_get_max_threads();
1402
+ // pos[c * world + p]: the edges of row chunk c to owner p, then the
1403
+ // position of the next one
1404
+ std::vector<int64_t> pos(size_t(nt) * world, 0);
1405
+ #pragma omp parallel for schedule(static)
1406
+ for (int c = 0; c < nt; c++) {
1407
+ int64_t* mine = pos.data() + size_t(c) * world;
1408
+ for (size_t e = nK * c / nt; e < nK * (c + 1) / nt; e++) {
1409
+ if (owner[e] >= 0) {
1410
+ mine[owner[e]]++;
1411
+ }
1412
+ }
1413
+ }
1414
+ counts.assign(world, 0);
1415
+ int64_t total = 0;
1416
+ for (int p = 0; p < world; p++) {
1417
+ for (int c = 0; c < nt; c++) {
1418
+ const int64_t m = pos[size_t(c) * world + p];
1419
+ pos[size_t(c) * world + p] = total;
1420
+ total += m;
1421
+ counts[p] += m;
1422
+ }
1423
+ }
1424
+ target.resize(total);
1425
+ source.resize(total);
1426
+ edge_dis.resize(total);
1427
+ edge_new.resize(total);
1428
+ #pragma omp parallel for schedule(static)
1429
+ for (int c = 0; c < nt; c++) {
1430
+ int64_t* cur = pos.data() + size_t(c) * world;
1431
+ for (size_t e = nK * c / nt; e < nK * (c + 1) / nt; e++) {
1432
+ if (owner[e] < 0) {
1433
+ continue;
1434
+ }
1435
+ const int64_t q = cur[owner[e]]++;
1436
+ target[q] = ids[e];
1437
+ source[q] = owner_begin[rank] + int64_t(e / K);
1438
+ edge_dis[q] = dis[e];
1439
+ edge_new[q] = is_new[e];
1440
+ }
1441
+ }
1442
+ }
1443
+
1444
+ namespace {
1445
+
1446
+ /// Groups the n items by their home row target[e] - hb, and calls
1447
+ /// rows.row(t, begin, end) on the items [begin, end) of each home row t. The
1448
+ /// items of a row keep their input order. rows.make(e) builds item e of type
1449
+ /// Rows::Item; the function sets its field row. Threads process disjoint
1450
+ /// ranges of rows. Rows is ReverseEdgeRows or CandidateRows.
1451
+ template <class Rows>
1452
+ void group_by_home_row(
1453
+ size_t n,
1454
+ const int64_t* target,
1455
+ int64_t hb,
1456
+ idx_t nh,
1457
+ const char* msg,
1458
+ const Rows& rows) {
1459
+ using Item = typename Rows::Item;
1460
+ const int nt = omp_get_max_threads();
1461
+ // bucket b holds the rows [b * rows_per, (b + 1) * rows_per)
1462
+ const idx_t nchunks = 16 * idx_t(nt);
1463
+ const idx_t rows_per = std::max<idx_t>(1, (nh + nchunks - 1) / nchunks);
1464
+ const idx_t nb = (nh + rows_per - 1) / rows_per;
1465
+ // pos[c * nb + b]: the items of input chunk c in bucket b, then the
1466
+ // position of the next one
1467
+ std::vector<size_t> pos(size_t(nt) * nb, 0);
1468
+ std::vector<uint8_t> bad(nt, 0);
1469
+ #pragma omp parallel for schedule(static)
1470
+ for (int c = 0; c < nt; c++) {
1471
+ size_t* mine = pos.data() + size_t(c) * nb;
1472
+ for (size_t e = n * c / nt; e < n * (c + 1) / nt; e++) {
1473
+ const int64_t r = target[e] - hb;
1474
+ if (r < 0 || r >= nh) {
1475
+ bad[c] = 1;
1476
+ break;
1477
+ }
1478
+ mine[r / rows_per]++;
1479
+ }
1480
+ }
1481
+ FAISS_THROW_IF_NOT_FMT(
1482
+ std::find(bad.begin(), bad.end(), 1) == bad.end(), "%s", msg);
1483
+ std::vector<size_t> bucket_begin(nb + 1);
1484
+ size_t acc = 0;
1485
+ for (idx_t b = 0; b < nb; b++) {
1486
+ bucket_begin[b] = acc;
1487
+ for (int c = 0; c < nt; c++) {
1488
+ const size_t m = pos[size_t(c) * nb + b];
1489
+ pos[size_t(c) * nb + b] = acc;
1490
+ acc += m;
1491
+ }
1492
+ }
1493
+ bucket_begin[nb] = acc;
1494
+ std::vector<Item> items(n);
1495
+ #pragma omp parallel for schedule(static)
1496
+ for (int c = 0; c < nt; c++) {
1497
+ size_t* cur = pos.data() + size_t(c) * nb;
1498
+ for (size_t e = n * c / nt; e < n * (c + 1) / nt; e++) {
1499
+ const idx_t r = target[e] - hb;
1500
+ Item& it = items[cur[r / rows_per]++];
1501
+ it = rows.make(e);
1502
+ it.row = uint32_t(r);
1503
+ }
1504
+ }
1505
+ #pragma omp parallel
1506
+ {
1507
+ std::vector<Item> tmp;
1508
+ std::vector<size_t> off;
1509
+ #pragma omp for schedule(dynamic)
1510
+ for (idx_t b = 0; b < nb; b++) {
1511
+ const idx_t r0 = b * rows_per;
1512
+ const idx_t r1 = std::min(nh, r0 + rows_per);
1513
+ const Item* in = items.data() + bucket_begin[b];
1514
+ const size_t m = bucket_begin[b + 1] - bucket_begin[b];
1515
+ off.assign(r1 - r0 + 1, 0);
1516
+ for (size_t i = 0; i < m; i++) {
1517
+ off[in[i].row - r0 + 1]++;
1518
+ }
1519
+ for (idx_t t = r0; t < r1; t++) {
1520
+ off[t - r0 + 1] += off[t - r0];
1521
+ }
1522
+ tmp.resize(m);
1523
+ for (size_t i = 0; i < m; i++) {
1524
+ tmp[off[in[i].row - r0]++] = in[i];
1525
+ }
1526
+ for (idx_t t = r1; t > r0; t--) {
1527
+ off[t - r0] = off[t - r0 - 1];
1528
+ }
1529
+ off[0] = 0;
1530
+ for (idx_t t = r0; t < r1; t++) {
1531
+ rows.row(
1532
+ t,
1533
+ tmp.data() + off[t - r0],
1534
+ tmp.data() + off[t - r0 + 1]);
1535
+ }
1536
+ }
1537
+ }
1538
+ }
1539
+
1540
+ /// group_by_home_row() items of NNDescentShard::set_reverse_edges(): each
1541
+ /// home row keeps its Rr nearest reverse edges by (distance, source)
1542
+ struct ReverseEdgeRows {
1543
+ struct Item {
1544
+ float dis;
1545
+ uint32_t row;
1546
+ int64_t id;
1547
+ uint8_t is_new;
1548
+
1549
+ bool operator<(const Item& other) const {
1550
+ return dis < other.dis || (dis == other.dis && id < other.id);
1551
+ }
1552
+ };
1553
+
1554
+ const int64_t* source;
1555
+ const float* edge_dis;
1556
+ const uint8_t* edge_new;
1557
+ int Rr;
1558
+ int64_t* reverse_ids;
1559
+ uint8_t* reverse_new;
1560
+
1561
+ Item make(size_t e) const {
1562
+ return Item{edge_dis[e], 0, source[e], edge_new[e]};
1563
+ }
1564
+
1565
+ void row(idx_t t, Item* b, Item* e) const {
1566
+ const size_t m = std::min<size_t>(e - b, Rr);
1567
+ std::partial_sort(b, b + m, e);
1568
+ for (size_t j = 0; j < m; j++) {
1569
+ reverse_ids[size_t(t) * Rr + j] = b[j].id;
1570
+ reverse_new[size_t(t) * Rr + j] = b[j].is_new;
1571
+ }
1572
+ }
1573
+ };
1574
+
1575
+ /// group_by_home_row() items of NNDescentShard::insert_candidates(): each
1576
+ /// home row merges its candidates into its next row, one entry per
1577
+ /// candidate with its smallest distance
1578
+ struct CandidateRows {
1579
+ struct Item {
1580
+ float dis;
1581
+ uint32_t row;
1582
+ int64_t id;
1583
+ };
1584
+
1585
+ /// order by (id, distance), so that the best entry of an id comes first
1586
+ struct IdThenDis {
1587
+ bool operator()(const Item& p, const Item& q) const {
1588
+ return p.id < q.id || (p.id == q.id && p.dis < q.dis);
1589
+ }
1590
+ };
1591
+
1592
+ const int64_t* candidate;
1593
+ const float* candidate_dis;
1594
+ int K;
1595
+ /// the rows at the start of the round
1596
+ const int64_t* ids;
1597
+ const float* dis;
1598
+ int64_t* next_ids;
1599
+ float* next_dis;
1600
+ uint8_t* next_new;
1601
+ /// per-thread buffers
1602
+ std::vector<DisId64>* cand;
1603
+ std::vector<DisId64>* mbuf;
1604
+ std::vector<uint8_t>* mbuf_new;
1605
+
1606
+ Item make(size_t e) const {
1607
+ return Item{candidate_dis[e], 0, candidate[e]};
1608
+ }
1609
+
1610
+ void row(idx_t t, Item* b, Item* e) const {
1611
+ const int th = omp_get_thread_num();
1612
+ const size_t o = size_t(t) * K;
1613
+ std::sort(b, e, IdThenDis());
1614
+ std::vector<DisId64>& c = cand[th];
1615
+ c.clear();
1616
+ for (Item* it = b; it != e; ++it) {
1617
+ if (it == b || it->id != it[-1].id) {
1618
+ c.push_back({it->dis, it->id});
1619
+ }
1620
+ }
1621
+ const size_t m = drop_old_ids(ids + o, dis[o + K - 1], K, c);
1622
+ if (m == 0) {
1623
+ return;
1624
+ }
1625
+ std::sort(c.begin(), c.begin() + m);
1626
+ merge_into_row(
1627
+ K,
1628
+ next_ids + o,
1629
+ next_dis + o,
1630
+ next_new + o,
1631
+ c.data(),
1632
+ m,
1633
+ mbuf[th],
1634
+ mbuf_new[th]);
1635
+ }
1636
+ };
1637
+
1638
+ } // namespace
1639
+
1640
+ void NNDescentShard::set_reverse_edges(
1641
+ size_t n,
1642
+ const int64_t* target,
1643
+ const int64_t* source,
1644
+ const float* edge_dis,
1645
+ const uint8_t* edge_new) {
1646
+ const idx_t nh = nhome();
1647
+ const int64_t hb = owner_begin[rank];
1648
+ const int Rr = nreverse();
1649
+ check_graph_ids(
1650
+ source,
1651
+ n,
1652
+ owner_begin.front(),
1653
+ owner_begin.back(),
1654
+ false,
1655
+ "NNDescentShard: reverse edge source out of range");
1656
+ reverse_ids.assign(size_t(nh) * Rr, -1);
1657
+ reverse_new.assign(size_t(nh) * Rr, 0);
1658
+ group_by_home_row(
1659
+ n,
1660
+ target,
1661
+ hb,
1662
+ nh,
1663
+ "NNDescentShard: reverse edge to an id of another process",
1664
+ ReverseEdgeRows{
1665
+ source,
1666
+ edge_dis,
1667
+ edge_new,
1668
+ Rr,
1669
+ reverse_ids.data(),
1670
+ reverse_new.data()});
1671
+
1672
+ select_rows(0, nh);
1673
+ }
1674
+
1675
+ void NNDescentShard::select_rows(idx_t begin, idx_t end) {
1676
+ FAISS_THROW_IF_NOT_MSG(
1677
+ begin >= 0 && begin <= end && end <= nhome(),
1678
+ "NNDescentShard: invalid row range");
1679
+ FAISS_THROW_IF_NOT_MSG(
1680
+ reverse_ids.size() == size_t(nhome()) * nreverse(),
1681
+ "NNDescentShard: set_reverse_edges() before select_rows()");
1682
+ selected_begin = begin;
1683
+ selected_end = end;
1684
+ collect_remote_ids(true, begin, end);
1685
+ }
1686
+
1687
+ bool NNDescentShard::has_new_member(idx_t t) const {
1688
+ const int Rr = nreverse();
1689
+ for (int j = 0; j < K && ids[size_t(t) * K + j] >= 0; j++) {
1690
+ if (is_new[size_t(t) * K + j]) {
1691
+ return true;
1692
+ }
1693
+ }
1694
+ for (int j = 0; j < Rr && reverse_ids[size_t(t) * Rr + j] >= 0; j++) {
1695
+ if (reverse_new[size_t(t) * Rr + j]) {
1696
+ return true;
1697
+ }
1698
+ }
1699
+ return false;
1700
+ }
1701
+
1702
+ // the ids are bucketed by owner, then sorted and unique in each bucket
1703
+ void NNDescentShard::collect_remote_ids(
1704
+ bool with_reverse,
1705
+ idx_t begin,
1706
+ idx_t end) {
1707
+ const int Rr = with_reverse ? nreverse() : 0;
1708
+ const idx_t nh = nhome();
1709
+ const int64_t hb = owner_begin[rank];
1710
+ const int world = int(owner_begin.size()) - 1;
1711
+ const int nt = omp_get_max_threads();
1712
+ std::vector<std::vector<std::vector<int64_t>>> buckets(
1713
+ nt, std::vector<std::vector<int64_t>>(world));
1714
+ #pragma omp parallel
1715
+ {
1716
+ auto& mine = buckets[omp_get_thread_num()];
1717
+ #pragma omp for schedule(static)
1718
+ for (idx_t t = begin; t < end; t++) {
1719
+ if (with_reverse && !has_new_member(t)) {
1720
+ continue;
1721
+ }
1722
+ bucket_remote_ids(
1723
+ ids.data() + size_t(t) * K, K, hb, nh, owner_begin, mine);
1724
+ if (Rr > 0) {
1725
+ bucket_remote_ids(
1726
+ reverse_ids.data() + size_t(t) * Rr,
1727
+ Rr,
1728
+ hb,
1729
+ nh,
1730
+ owner_begin,
1731
+ mine);
1732
+ }
1733
+ }
1734
+ }
1735
+ std::vector<std::vector<int64_t>> per_owner(world);
1736
+ #pragma omp parallel for schedule(dynamic)
1737
+ for (int p = 0; p < world; p++) {
1738
+ auto& v = per_owner[p];
1739
+ for (int t = 0; t < nt; t++) {
1740
+ v.insert(v.end(), buckets[t][p].begin(), buckets[t][p].end());
1741
+ buckets[t][p] = std::vector<int64_t>();
1742
+ }
1743
+ std::sort(v.begin(), v.end());
1744
+ v.erase(std::unique(v.begin(), v.end()), v.end());
1745
+ }
1746
+ remote_ids.clear();
1747
+ for (auto& v : per_owner) {
1748
+ remote_ids.insert(remote_ids.end(), v.begin(), v.end());
1749
+ }
1750
+ }
1751
+
1752
+ void NNDescentShard::set_remote_ids_of_rows() {
1753
+ collect_remote_ids(false, 0, nhome());
1754
+ }
1755
+
1756
+ void NNDescentShard::original_ids(
1757
+ const int64_t* home_original,
1758
+ const int64_t* remote_original,
1759
+ int64_t* out) const {
1760
+ const idx_t nh = nhome();
1761
+ const int64_t hb = owner_begin[rank];
1762
+ int missing = 0;
1763
+ #pragma omp parallel for schedule(static) reduction(| : missing)
1764
+ for (int64_t e = 0; e < int64_t(size_t(nh) * K); e++) {
1765
+ const int64_t v = ids[e];
1766
+ if (v < 0) {
1767
+ out[e] = -1;
1768
+ } else if (v >= hb && v < hb + nh) {
1769
+ out[e] = home_original[v - hb];
1770
+ } else {
1771
+ const auto it =
1772
+ std::lower_bound(remote_ids.begin(), remote_ids.end(), v);
1773
+ if (it != remote_ids.end() && *it == v) {
1774
+ out[e] = remote_original[it - remote_ids.begin()];
1775
+ } else {
1776
+ out[e] = -1;
1777
+ missing = 1;
1778
+ }
1779
+ }
1780
+ }
1781
+ // throw outside the OpenMP region, where the caller can catch it
1782
+ FAISS_THROW_IF_MSG(
1783
+ missing,
1784
+ "NNDescentShard: row id not in remote_ids; call set_remote_ids_of_rows()");
1785
+ }
1786
+
1787
+ void NNDescentShard::remote_counts(std::vector<int64_t>& counts) const {
1788
+ group_counts(owner_begin, remote_ids, counts);
1789
+ }
1790
+
1791
+ void NNDescentShard::join(
1792
+ const float* remote_x,
1793
+ const float* remote_kth,
1794
+ std::vector<int64_t>& counts,
1795
+ std::vector<int64_t>& target,
1796
+ std::vector<int64_t>& candidate,
1797
+ std::vector<float>& candidate_dis) {
1798
+ RemoteVectors rv;
1799
+ rv.x = remote_x;
1800
+ join_impl(rv, remote_kth, counts, target, candidate, candidate_dis);
1801
+ }
1802
+
1803
+ void NNDescentShard::join_fp16(
1804
+ const uint16_t* remote_x,
1805
+ const float* remote_kth,
1806
+ std::vector<int64_t>& counts,
1807
+ std::vector<int64_t>& target,
1808
+ std::vector<int64_t>& candidate,
1809
+ std::vector<float>& candidate_dis) {
1810
+ RemoteVectors rv;
1811
+ rv.x16 = remote_x;
1812
+ join_impl(rv, remote_kth, counts, target, candidate, candidate_dis);
1813
+ }
1814
+
1815
+ void NNDescentShard::join_sq8(
1816
+ const uint8_t* remote_codes,
1817
+ const float* vmin,
1818
+ const float* vdiff,
1819
+ const float* remote_kth,
1820
+ std::vector<int64_t>& counts,
1821
+ std::vector<int64_t>& target,
1822
+ std::vector<int64_t>& candidate,
1823
+ std::vector<float>& candidate_dis) {
1824
+ RemoteVectors rv;
1825
+ rv.codes = remote_codes;
1826
+ rv.vmin = vmin;
1827
+ rv.vdiff = vdiff;
1828
+ join_impl(rv, remote_kth, counts, target, candidate, candidate_dis);
1829
+ }
1830
+
1831
+ namespace {
1832
+
1833
+ /** local_join() access of NNDescentShard::join_impl(). Storage index s < nh
1834
+ * is home row s, and s >= nh is remote id s - nh. flush() merges the
1835
+ * candidates for a home row into its next row under the lock of the row,
1836
+ * and keeps the candidates for a remote row in hbuf. */
1837
+ struct ShardAccess {
1838
+ NNDescentShard& shard;
1839
+ idx_t nh;
1840
+ int64_t hb;
1841
+ const NNDescentShard::RemoteVectors& rv;
1842
+ const float* remote_kth;
1843
+ std::atomic_flag* locks;
1844
+ std::atomic<float>* nworst;
1845
+ /// candidates for each remote row: the K best by (distance, candidate),
1846
+ /// one per id
1847
+ std::vector<DisId64>* hbuf;
1848
+
1849
+ /// storage index of graph id v: home ids first, then the remote ids; -1
1850
+ /// if v is not a home id or in remote_ids
1851
+ int32_t sidx(int64_t v) const {
1852
+ if (v >= hb && v < hb + nh) {
1853
+ return int32_t(v - hb);
1854
+ }
1855
+ const std::vector<int64_t>& rid = shard.remote_ids;
1856
+ const auto it = std::lower_bound(rid.begin(), rid.end(), v);
1857
+ return it != rid.end() && *it == v ? int32_t(nh + (it - rid.begin()))
1858
+ : -1;
1859
+ }
1860
+
1861
+ int64_t gid(int32_t s) const {
1862
+ return s < nh ? hb + s : shard.remote_ids[s - nh];
1863
+ }
1864
+
1865
+ /// the vector of storage index s; a coded remote vector is decoded into
1866
+ /// buf
1867
+ const float* row(int32_t s, float* buf) const {
1868
+ const size_t d = shard.d;
1869
+ if (s < nh) {
1870
+ return shard.x + size_t(s) * d;
1871
+ }
1872
+ const size_t o = size_t(s - nh) * d;
1873
+ if (rv.x) {
1874
+ return rv.x + o;
1875
+ }
1876
+ if (rv.x16) {
1877
+ for (size_t j = 0; j < d; j++) {
1878
+ buf[j] = decode_fp16(rv.x16[o + j]);
1879
+ }
1880
+ return buf;
1881
+ }
1882
+ // two loops: a fused multiply-add would round differently from the
1883
+ // encoder's float32 decode
1884
+ for (size_t j = 0; j < d; j++) {
1885
+ buf[j] = (rv.codes[o + j] + 0.5f) / 255.f * rv.vdiff[j];
1886
+ }
1887
+ for (size_t j = 0; j < d; j++) {
1888
+ buf[j] += rv.vmin[j];
1889
+ }
1890
+ return buf;
1891
+ }
1892
+
1893
+ void prefetch(int32_t) const {}
1894
+
1895
+ void flush(
1896
+ int32_t a,
1897
+ std::vector<DisId64>& cand,
1898
+ std::vector<DisId64>& buf,
1899
+ std::vector<uint8_t>& buf_new) const {
1900
+ const int K = shard.K;
1901
+ size_t m = 0;
1902
+ if (a < nh) {
1903
+ const size_t o = size_t(a) * K;
1904
+ m = drop_old_ids(
1905
+ shard.ids.data() + o, shard.dis[o + K - 1], K, cand);
1906
+ } else {
1907
+ // the owner drops the ids of its row in insert_candidates()
1908
+ const float kth = remote_kth[a - nh];
1909
+ for (const DisId64& c : cand) {
1910
+ if (c.first <= kth) {
1911
+ cand[m++] = c;
1912
+ }
1913
+ }
1914
+ }
1915
+ if (m == 0) {
1916
+ return;
1917
+ }
1918
+ std::sort(cand.begin(), cand.begin() + m);
1919
+ if (a < nh) {
1920
+ const size_t o = size_t(a) * K;
1921
+ merge_into_row_locked(
1922
+ K,
1923
+ locks[a],
1924
+ nworst[a],
1925
+ shard.next_ids.data() + o,
1926
+ shard.next_dis.data() + o,
1927
+ shard.next_new.data() + o,
1928
+ cand.data(),
1929
+ m,
1930
+ buf,
1931
+ buf_new);
1932
+ return;
1933
+ }
1934
+ insert_remote(a, cand.data(), m);
1935
+ }
1936
+
1937
+ /// keeps in hbuf the K best distinct candidates of remote row a by their
1938
+ /// smallest distance, in any order of the candidates
1939
+ void insert_remote(int32_t a, const DisId64* cand, size_t m) const {
1940
+ const size_t K = shard.K;
1941
+ SpinLock lock(locks[a]);
1942
+ std::vector<DisId64>& h = hbuf[a - nh];
1943
+ for (size_t j = 0; j < m; j++) {
1944
+ const DisId64 c = cand[j];
1945
+ size_t k = 0;
1946
+ while (k < h.size() && h[k].second != c.second) {
1947
+ k++;
1948
+ }
1949
+ if (k < h.size()) {
1950
+ if (c < h[k]) {
1951
+ h[k] = c;
1952
+ }
1953
+ } else if (h.size() < K) {
1954
+ h.push_back(c);
1955
+ } else {
1956
+ auto w = std::max_element(h.begin(), h.end());
1957
+ if (c < *w) {
1958
+ *w = c;
1959
+ }
1960
+ }
1961
+ }
1962
+ if (h.size() == K) {
1963
+ const auto w = std::max_element(h.begin(), h.end());
1964
+ if (w->first < nworst[a].load(std::memory_order_relaxed)) {
1965
+ nworst[a].store(w->first, std::memory_order_relaxed);
1966
+ }
1967
+ }
1968
+ }
1969
+ };
1970
+
1971
+ } // namespace
1972
+
1973
+ void NNDescentShard::join_impl(
1974
+ const RemoteVectors& rv,
1975
+ const float* remote_kth,
1976
+ std::vector<int64_t>& counts,
1977
+ std::vector<int64_t>& target,
1978
+ std::vector<int64_t>& candidate,
1979
+ std::vector<float>& candidate_dis) {
1980
+ const idx_t nh = nhome();
1981
+ const size_t nr = remote_ids.size();
1982
+ const int64_t hb = owner_begin[rank];
1983
+ const int Rr = nreverse();
1984
+ const int S = nsample();
1985
+ FAISS_THROW_IF_NOT_MSG(
1986
+ reverse_ids.size() == size_t(nh) * Rr,
1987
+ "NNDescentShard: set_reverse_edges() before join()");
1988
+ FAISS_THROW_IF_NOT_MSG(
1989
+ size_t(nh) + nr < (size_t(1) << 31),
1990
+ "NNDescentShard: at most 2^31 - 1 home and remote ids");
1991
+
1992
+ std::vector<std::atomic_flag> locks(nh + nr);
1993
+ std::vector<std::atomic<float>> nworst(nh + nr);
1994
+ std::vector<std::vector<DisId64>> hbuf(nr);
1995
+ const ShardAccess acc{
1996
+ *this,
1997
+ nh,
1998
+ hb,
1999
+ rv,
2000
+ remote_kth,
2001
+ locks.data(),
2002
+ nworst.data(),
2003
+ hbuf.data()};
2004
+ // remote_ids has only the members of the neighborhoods with a new member;
2005
+ // the other rows stay -1 and their local joins are empty
2006
+ std::vector<int32_t> out_s(size_t(nh) * K, -1), in_s(size_t(nh) * Rr, -1);
2007
+ std::vector<float> norms(nh + nr);
2008
+ int missing = 0;
2009
+ #pragma omp parallel for schedule(static) reduction(| : missing)
2010
+ for (idx_t t = selected_begin; t < selected_end; t++) {
2011
+ if (!has_new_member(t)) {
2012
+ continue;
2013
+ }
2014
+ for (int j = 0; j < K; j++) {
2015
+ const int64_t v = ids[size_t(t) * K + j];
2016
+ if (v >= 0) {
2017
+ out_s[size_t(t) * K + j] = acc.sidx(v);
2018
+ missing |= out_s[size_t(t) * K + j] < 0;
2019
+ }
2020
+ }
2021
+ for (int j = 0; j < Rr; j++) {
2022
+ const int64_t v = reverse_ids[size_t(t) * Rr + j];
2023
+ if (v >= 0) {
2024
+ in_s[size_t(t) * Rr + j] = acc.sidx(v);
2025
+ missing |= in_s[size_t(t) * Rr + j] < 0;
2026
+ }
2027
+ }
2028
+ }
2029
+ FAISS_THROW_IF_MSG(
2030
+ missing,
2031
+ "NNDescentShard: a neighborhood id is not in remote_ids; "
2032
+ "call select_rows() before join()");
2033
+ #pragma omp parallel
2034
+ {
2035
+ std::vector<float> buf(d);
2036
+ #pragma omp for schedule(static)
2037
+ for (int64_t s = 0; s < int64_t(nh + nr); s++) {
2038
+ norms[s] = fvec_norm_L2sqr(acc.row(int32_t(s), buf.data()), d);
2039
+ }
2040
+ }
2041
+
2042
+ // next rows, as in round(), at the first join() of the round
2043
+ if (next_ids.size() != ids.size()) {
2044
+ next_ids = ids;
2045
+ next_dis = dis;
2046
+ unsampled_new(is_new, nh, K, S, next_new);
2047
+ ndis = 0;
2048
+ }
2049
+ for (idx_t v = 0; v < nh; v++) {
2050
+ const size_t e = size_t(v) * K + K - 1;
2051
+ nworst[v].store(
2052
+ next_ids[e] >= 0 ? next_dis[e] : kInf,
2053
+ std::memory_order_relaxed);
2054
+ }
2055
+ for (size_t i = 0; i < nr; i++) {
2056
+ nworst[nh + i].store(remote_kth[i], std::memory_order_relaxed);
2057
+ }
2058
+ const GramKernel kernel = gram_kernel();
2059
+ size_t nd_total = 0;
2060
+ #pragma omp parallel reduction(+ : nd_total)
2061
+ {
2062
+ JoinScratch<int64_t> js;
2063
+ #pragma omp for schedule(dynamic, 64)
2064
+ for (idx_t u = selected_begin; u < selected_end; u++) {
2065
+ local_join(
2066
+ out_s.data() + size_t(u) * K,
2067
+ is_new.data() + size_t(u) * K,
2068
+ K,
2069
+ in_s.data() + size_t(u) * Rr,
2070
+ reverse_new.data() + size_t(u) * Rr,
2071
+ Rr,
2072
+ S,
2073
+ kernel,
2074
+ metric_type,
2075
+ d,
2076
+ norms.data(),
2077
+ nworst,
2078
+ js,
2079
+ nd_total,
2080
+ acc);
2081
+ }
2082
+ }
2083
+ ndis += nd_total;
2084
+
2085
+ // candidates for remote rows, grouped by owner because remote_ids is
2086
+ // sorted
2087
+ size_t total = 0;
2088
+ std::vector<size_t> start(nr + 1, 0);
2089
+ for (size_t i = 0; i < nr; i++) {
2090
+ start[i + 1] = start[i] + hbuf[i].size();
2091
+ }
2092
+ total = start[nr];
2093
+ target.resize(total);
2094
+ candidate.resize(total);
2095
+ candidate_dis.resize(total);
2096
+ #pragma omp parallel for schedule(dynamic, 1024)
2097
+ for (int64_t i = 0; i < int64_t(nr); i++) {
2098
+ auto& b = hbuf[i];
2099
+ std::sort(b.begin(), b.end());
2100
+ for (size_t j = 0; j < b.size(); j++) {
2101
+ target[start[i] + j] = remote_ids[i];
2102
+ candidate[start[i] + j] = b[j].second;
2103
+ candidate_dis[start[i] + j] = b[j].first;
2104
+ }
2105
+ }
2106
+ group_counts(owner_begin, target, counts);
2107
+ }
2108
+
2109
+ void NNDescentShard::insert_candidates(
2110
+ size_t n,
2111
+ const int64_t* target,
2112
+ const int64_t* candidate,
2113
+ const float* candidate_dis) {
2114
+ const idx_t nh = nhome();
2115
+ const int64_t hb = owner_begin[rank];
2116
+ FAISS_THROW_IF_NOT_MSG(
2117
+ next_ids.size() == ids.size(),
2118
+ "NNDescentShard: join() before insert_candidates()");
2119
+ check_graph_ids(
2120
+ candidate,
2121
+ n,
2122
+ owner_begin.front(),
2123
+ owner_begin.back(),
2124
+ false,
2125
+ "NNDescentShard: candidate out of range");
2126
+ std::vector<std::vector<DisId64>> cand(omp_get_max_threads());
2127
+ std::vector<std::vector<DisId64>> mbuf(cand.size());
2128
+ std::vector<std::vector<uint8_t>> mbuf_new(cand.size());
2129
+ group_by_home_row(
2130
+ n,
2131
+ target,
2132
+ hb,
2133
+ nh,
2134
+ "NNDescentShard: candidate for an id of another process",
2135
+ CandidateRows{
2136
+ candidate,
2137
+ candidate_dis,
2138
+ K,
2139
+ ids.data(),
2140
+ dis.data(),
2141
+ next_ids.data(),
2142
+ next_dis.data(),
2143
+ next_new.data(),
2144
+ cand.data(),
2145
+ mbuf.data(),
2146
+ mbuf_new.data()});
2147
+ }
2148
+
2149
+ idx_t NNDescentShard::end_round() {
2150
+ const idx_t nh = nhome();
2151
+ FAISS_THROW_IF_NOT_MSG(
2152
+ next_ids.size() == ids.size(),
2153
+ "NNDescentShard: join() before end_round()");
2154
+ const idx_t changed = count_rows_with_new(next_new, nh, K);
2155
+ ids.swap(next_ids);
2156
+ dis.swap(next_dis);
2157
+ is_new.swap(next_new);
2158
+ next_ids.clear();
2159
+ next_dis.clear();
2160
+ next_new.clear();
2161
+ reverse_ids.clear();
2162
+ reverse_new.clear();
2163
+ remote_ids.clear();
2164
+ return changed;
2165
+ }
2166
+
2167
+ } // namespace faiss