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,282 @@
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
+ // Compiled with -ffp-contract=off (faiss/CMakeLists.txt): the T1 formulas
9
+ // must not be contracted into fused multiply-adds.
10
+
11
+ #include <faiss/impl/optimal_kmeans/OptimalKMeans.h>
12
+
13
+ #include <faiss/impl/FaissAssert.h>
14
+ #include <faiss/impl/optimal_kmeans/BlockCombiner-inl.h>
15
+ #include <faiss/impl/simd_dispatch.h>
16
+
17
+ #include <cstring>
18
+ #include <limits>
19
+ #include <memory>
20
+
21
+ namespace faiss {
22
+
23
+ using optimal_kmeans::kInf;
24
+ using optimal_kmeans::lex_update;
25
+
26
+ /*********************************************************
27
+ * T1
28
+ *********************************************************/
29
+
30
+ OptimalKMeansCost1::OptimalKMeansCost1(int n_in, int d, const float* x)
31
+ : n(n_in) {
32
+ FAISS_THROW_IF_NOT_FMT(n >= 0 && n <= 64, "n = %d out of range", n);
33
+ gram.assign(size_t(n) * n, 0.0);
34
+ // each term accumulated over the dimensions in increasing order
35
+ for (int a = 0; a < n; a++) {
36
+ for (int b = a; b < n; b++) {
37
+ double s = 0;
38
+ for (int l = 0; l < d; l++) {
39
+ s = s +
40
+ double(x[size_t(a) * d + l]) *
41
+ double(x[size_t(b) * d + l]);
42
+ }
43
+ gram[size_t(a) * n + b] = gram[size_t(b) * n + a] = s;
44
+ }
45
+ }
46
+ }
47
+
48
+ float OptimalKMeansCost1::entry(uint64_t S) const {
49
+ double s2 = 0, sg = 0;
50
+ int ns = 0, sel[64];
51
+ for (int b = n - 1; b >= 0; b--) {
52
+ if (!((S >> b) & 1)) {
53
+ continue;
54
+ }
55
+ double cross = 0;
56
+ for (int t = 0; t < ns; t++) {
57
+ cross = cross + gram[size_t(b) * n + sel[t]];
58
+ }
59
+ double nb = gram[size_t(b) * n + b];
60
+ sg = (sg + nb) + 2.0 * cross;
61
+ s2 = s2 + nb;
62
+ sel[ns++] = b;
63
+ }
64
+ return ns ? float(s2 - sg / double(ns)) : 0.f;
65
+ }
66
+
67
+ // the fixed high bits as in entry(), then a recursion over the nbits low bits
68
+ // in which cross[j] holds the sum of gram[j, k] over the points k added so far
69
+ void OptimalKMeansCost1::range_rec(
70
+ int nbits,
71
+ uint64_t i,
72
+ int ns,
73
+ double s2,
74
+ double sg,
75
+ const double* cross,
76
+ float* out) const {
77
+ if (nbits == 0) {
78
+ out[i] = ns ? float(s2 - sg / double(ns)) : 0.f;
79
+ return;
80
+ }
81
+ int b = nbits - 1;
82
+ range_rec(b, i, ns, s2, sg, cross, out);
83
+ double c2[64];
84
+ for (int j = 0; j < b; j++) {
85
+ c2[j] = cross[j] + gram[size_t(j) * n + b];
86
+ }
87
+ double nb = gram[size_t(b) * n + b];
88
+ range_rec(
89
+ b,
90
+ i | (uint64_t(1) << b),
91
+ ns + 1,
92
+ s2 + nb,
93
+ (sg + nb) + 2.0 * cross[b],
94
+ c2,
95
+ out);
96
+ }
97
+
98
+ void OptimalKMeansCost1::range(uint64_t lo, uint64_t hi, float* out) const {
99
+ FAISS_THROW_IF_NOT(lo <= hi);
100
+ uint64_t i = lo;
101
+ while (i < hi) {
102
+ // largest aligned power-of-two piece starting at i that fits
103
+ int nfree = 0;
104
+ while (nfree < n && (i & ((uint64_t(2) << nfree) - 1)) == 0 &&
105
+ i + (uint64_t(2) << nfree) <= hi) {
106
+ nfree++;
107
+ }
108
+ if (nfree < 4) {
109
+ out[i - lo] = entry(i);
110
+ i++;
111
+ continue;
112
+ }
113
+ uint64_t prefix = i >> nfree;
114
+ double s2 = 0, sg = 0;
115
+ int ns = 0;
116
+ double cross[64] = {0};
117
+ for (int b = n - 1; b >= nfree; b--) {
118
+ if (!((prefix >> (b - nfree)) & 1)) {
119
+ continue;
120
+ }
121
+ double cb = 0;
122
+ for (int k = n - 1; k > b; k--) {
123
+ if ((prefix >> (k - nfree)) & 1) {
124
+ cb = cb + gram[size_t(b) * n + k];
125
+ }
126
+ }
127
+ double nb = gram[size_t(b) * n + b];
128
+ sg = (sg + nb) + 2.0 * cb;
129
+ s2 = s2 + nb;
130
+ ns++;
131
+ for (int j = 0; j < nfree; j++) {
132
+ cross[j] = cross[j] + gram[size_t(j) * n + b];
133
+ }
134
+ }
135
+ range_rec(nfree, 0, ns, s2, sg, cross, out + (i - lo));
136
+ i += uint64_t(1) << nfree;
137
+ }
138
+ }
139
+
140
+ /*********************************************************
141
+ * Stats
142
+ *********************************************************/
143
+
144
+ void OptimalKMeansStats::reset() {
145
+ *this = OptimalKMeansStats();
146
+ }
147
+
148
+ void OptimalKMeansStats::add(const OptimalKMeansStats& o) {
149
+ pairs_total += o.pairs_total;
150
+ candidates_total += o.candidates_total;
151
+ candidates_evaluated += o.candidates_evaluated;
152
+ entries_improved += o.entries_improved;
153
+ pairs_skipped += o.pairs_skipped;
154
+ pairs_dense += o.pairs_dense;
155
+ pairs_pruned += o.pairs_pruned;
156
+ guess_candidates += o.guess_candidates;
157
+ guess_improved += o.guess_improved;
158
+ nodes_tested += o.nodes_tested;
159
+ nodes_kept += o.nodes_kept;
160
+ bottom_nodes += o.bottom_nodes;
161
+ bottom_passes += o.bottom_passes;
162
+ items += o.items;
163
+ roots_tested += o.roots_tested;
164
+ roots_kept += o.roots_kept;
165
+ leaf_hits += o.leaf_hits;
166
+ samples += o.samples;
167
+ samples_kept += o.samples_kept;
168
+ }
169
+
170
+ /*********************************************************
171
+ * Combination
172
+ *********************************************************/
173
+
174
+ namespace optimal_kmeans {
175
+
176
+ template <>
177
+ OptimalKMeansBlockCombiner* make_block_combiner<SIMDLevel::NONE>(
178
+ int n,
179
+ int L,
180
+ uint64_t s_hi,
181
+ const float* A,
182
+ const float* B,
183
+ bool sym,
184
+ float* acc_cost,
185
+ uint64_t* acc_split,
186
+ const OptimalKMeansCombineParams& params) {
187
+ return new BlockCombiner<SIMDLevel::NONE>(
188
+ n, L, s_hi, A, B, sym, acc_cost, acc_split, params);
189
+ }
190
+
191
+ } // namespace optimal_kmeans
192
+
193
+ OptimalKMeansBlockCombiner* optimal_kmeans_block_combiner(
194
+ int n,
195
+ int L,
196
+ uint64_t s_hi,
197
+ const float* A,
198
+ const float* B,
199
+ bool sym,
200
+ float* acc_cost,
201
+ uint64_t* acc_split,
202
+ const OptimalKMeansCombineParams& params) {
203
+ FAISS_THROW_IF_NOT_FMT(n >= 1 && n <= 40, "n = %d out of range", n);
204
+ FAISS_THROW_IF_NOT_FMT(L >= 1 && L <= n, "L = %d out of range", L);
205
+ FAISS_THROW_IF_NOT_FMT(
206
+ s_hi < (uint64_t(1) << (n - L)),
207
+ "s_hi = %zd out of range",
208
+ size_t(s_hi));
209
+ // kernels of the SIMD level of the library; AVX512_SPR uses AVX512,
210
+ // AVX2 uses NONE
211
+ constexpr int levels =
212
+ (1 << int(SIMDLevel::NONE)) | (1 << int(SIMDLevel::AVX512));
213
+ return with_selected_simd_levels<levels>(
214
+ [&]<SIMDLevel SL>() -> OptimalKMeansBlockCombiner* {
215
+ return optimal_kmeans::make_block_combiner<SL>(
216
+ n, L, s_hi, A, B, sym, acc_cost, acc_split, params);
217
+ });
218
+ }
219
+
220
+ void optimal_kmeans_combine_block(
221
+ int n,
222
+ int L,
223
+ uint64_t s_hi,
224
+ const float* A,
225
+ const float* B,
226
+ bool sym,
227
+ float* acc_cost,
228
+ uint64_t* acc_split,
229
+ const OptimalKMeansCombineParams& params,
230
+ OptimalKMeansStats* stats) {
231
+ std::unique_ptr<OptimalKMeansBlockCombiner> bc(
232
+ optimal_kmeans_block_combiner(
233
+ n, L, s_hi, A, B, sym, acc_cost, acc_split, params));
234
+ OptimalKMeansStats st;
235
+ bc->setup();
236
+ while (size_t ni = bc->next_phase()) {
237
+ bc->run_items(0, ni, &st);
238
+ }
239
+ bc->finish(&st);
240
+ if (stats) {
241
+ stats->add(st);
242
+ }
243
+ }
244
+
245
+ void optimal_kmeans_combine(
246
+ int n,
247
+ const float* A,
248
+ const float* B,
249
+ bool sym,
250
+ float* C,
251
+ uint64_t* split,
252
+ const OptimalKMeansCombineParams& params,
253
+ OptimalKMeansStats* stats) {
254
+ const uint64_t N = uint64_t(1) << n;
255
+ for (uint64_t i = 0; i < N; i++) {
256
+ C[i] = kInf;
257
+ split[i] = 0;
258
+ }
259
+ optimal_kmeans_combine_block(n, n, 0, A, B, sym, C, split, params, stats);
260
+ }
261
+
262
+ void optimal_kmeans_full_set_row(
263
+ int n,
264
+ const float* A,
265
+ const float* B,
266
+ uint64_t lo,
267
+ uint64_t hi,
268
+ float* cost,
269
+ uint64_t* split) {
270
+ FAISS_THROW_IF_NOT_FMT(n >= 1 && n <= 40, "n = %d out of range", n);
271
+ const uint64_t U = (uint64_t(1) << n) - 1;
272
+ FAISS_THROW_IF_NOT(lo <= hi && hi <= U + 1);
273
+ float bc = *cost;
274
+ uint64_t bs = *split;
275
+ for (uint64_t l = lo; l < hi; l++) {
276
+ lex_update(A[l - lo] + B[U ^ l], l, &bc, &bs);
277
+ }
278
+ *cost = bc;
279
+ *split = bs;
280
+ }
281
+
282
+ } // namespace faiss
@@ -0,0 +1,226 @@
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
+ #pragma once
9
+
10
+ #include <cstdint>
11
+ #include <vector>
12
+
13
+ /** Exact k-means by dynamic programming over the subsets of the points.
14
+ *
15
+ * The Python driver is contrib/optimal_kmeans (documentation: README.md
16
+ * there). A group of n <= 40 points is an n-bit integer S (bit b set if point
17
+ * b is in the group). A cost table has 2^n float32 entries indexed by the
18
+ * group. Splits (the A part of the best division of a group) are uint64.
19
+ */
20
+
21
+ namespace faiss {
22
+
23
+ /** Single-cluster costs T1[S] of all the groups of n points.
24
+ *
25
+ * T1[S] = float(s2 - sg / |S|) with s2 = sum of |x_b|^2 and sg = |sum of x_b|^2
26
+ * over the points b of S, both accumulated in double with a fixed order of
27
+ * operations (see 01_reference.md), so that the NumPy, C++ and CUDA tables
28
+ * are the same. T1[0] = 0.
29
+ */
30
+ struct OptimalKMeansCost1 {
31
+ int n = 0;
32
+ /// Gram matrix of the points in double (n x n, row-major)
33
+ std::vector<double> gram;
34
+
35
+ OptimalKMeansCost1() = default;
36
+
37
+ /// @param x points, size (n, d)
38
+ OptimalKMeansCost1(int n, int d, const float* x);
39
+
40
+ /// T1 of one group
41
+ float entry(uint64_t S) const;
42
+
43
+ /** out[i - lo] = T1[i] for lo <= i < hi.
44
+ * Aligned power-of-two pieces cost O(1) per entry. */
45
+ void range(uint64_t lo, uint64_t hi, float* out) const;
46
+
47
+ /// recursion of range() over the nbits low points
48
+ void range_rec(
49
+ int nbits,
50
+ uint64_t i,
51
+ int ns,
52
+ double s2,
53
+ double sg,
54
+ const double* cross,
55
+ float* out) const;
56
+ };
57
+
58
+ /** Parameters of a combination (see the chapters of the documentation). */
59
+ struct OptimalKMeansCombineParams {
60
+ /// skip the candidates that cannot win (03_pruned.md)
61
+ bool pruned = false;
62
+ /// guess pass: leave out each of the guess_bits highest points of a group
63
+ int guess_bits = 3;
64
+ /// ... guess_bits_ctx instead for the blocks with >= 2 context points
65
+ /// when their context is given (OptimalKMeansBlockCombiner::set_context)
66
+ int guess_bits_ctx = 2;
67
+ /// a pair is evaluated densely if the sampled fraction of its candidates
68
+ /// that are below the accumulator exceeds dense_rate (>= 1: never)
69
+ double dense_rate = 0.3;
70
+ /// level-4 nodes sampled per pair to measure that fraction
71
+ int samples = 32;
72
+ /// rebuild the region trees after 2^(Lp - rebuild_shift) updates
73
+ int rebuild_shift = 3;
74
+ /// outputs are processed by regions of 2^region_level entries (rounded
75
+ /// down to a multiple of 4); 0: the whole block is one region
76
+ int region_level = 0;
77
+ /// expected number of threads that run the items of a block
78
+ int nthreads_hint = 1;
79
+
80
+ OptimalKMeansCombineParams() {}
81
+ };
82
+
83
+ /** Counters of the combination of one or several blocks. */
84
+ struct OptimalKMeansStats {
85
+ uint64_t pairs_total = 0; ///< upper divisions processed
86
+ uint64_t candidates_total = 0; ///< 3^L per pair
87
+ uint64_t candidates_evaluated = 0; ///< by the dense and bottom tests
88
+ uint64_t entries_improved = 0; ///< accumulator entries changed
89
+ // pruning (03_pruned.md)
90
+ uint64_t pairs_skipped = 0; ///< removed by the pair test (or mirrored)
91
+ uint64_t pairs_dense = 0; ///< evaluated without pruning
92
+ uint64_t pairs_pruned = 0; ///< evaluated with the depth-first search
93
+ uint64_t guess_candidates = 0; ///< candidates of the guess pass
94
+ uint64_t guess_improved = 0; ///< accumulator updates of the guess pass
95
+ uint64_t nodes_tested = 0; ///< nodes of the search that were tested
96
+ uint64_t nodes_kept = 0; ///< ... and not skipped
97
+ uint64_t bottom_nodes = 0; ///< level-4 nodes evaluated
98
+ uint64_t bottom_passes = 0; ///< their candidates <= accumulator
99
+ uint64_t items = 0; ///< work items
100
+ // GPU engine (06_gpu.md)
101
+ uint64_t roots_tested = 0; ///< pruned engine: roots (level 11) tested
102
+ uint64_t roots_kept = 0; ///< ... and kept
103
+ uint64_t leaf_hits = 0; ///< level-3 candidates <= threshold
104
+ uint64_t samples = 0; ///< nodes sampled to classify the pairs
105
+ uint64_t samples_kept = 0; ///< ... that survived the bound test
106
+
107
+ void reset();
108
+ void add(const OptimalKMeansStats& other);
109
+ };
110
+
111
+ /** Combine the block s_hi of two cost tables into its accumulator.
112
+ *
113
+ * The block holds the 2^L groups S = (s_hi << L) | z. A pair (l_hi, r_hi)
114
+ * with l_hi | r_hi = s_hi, l_hi & r_hi = 0 fixes the context points of the
115
+ * divisions; its 3^L candidates are (L, S ^ L) with L = (l_hi << L) | x,
116
+ * x subset of z. On return, for every z:
117
+ *
118
+ * (acc_cost[z], acc_split[z]) = lexicographic minimum of the entry value
119
+ * and of (A[L] + B[S ^ L], L) over all candidates of all pairs
120
+ *
121
+ * (float32 sums rounded to nearest; smallest cost, then smallest split).
122
+ *
123
+ * @param n number of points (n <= 40)
124
+ * @param L block bits (1 <= L <= n); L = n: the whole table
125
+ * @param s_hi block number, < 2^(n - L)
126
+ * @param A, B cost tables of 2^n entries (only the blocks that are
127
+ * sub-groups of s_hi are read)
128
+ * @param sym A and B are the same table (may skip mirrored candidates)
129
+ * @param acc_cost in/out, 2^L entries
130
+ * @param acc_split in/out, 2^L entries (full n-bit splits)
131
+ */
132
+ void optimal_kmeans_combine_block(
133
+ int n,
134
+ int L,
135
+ uint64_t s_hi,
136
+ const float* A,
137
+ const float* B,
138
+ bool sym,
139
+ float* acc_cost,
140
+ uint64_t* acc_split,
141
+ const OptimalKMeansCombineParams& params,
142
+ OptimalKMeansStats* stats = nullptr);
143
+
144
+ /** The combination of one block, in steps, so that the work items can be run
145
+ * by several threads (05_threads.md). Usage:
146
+ *
147
+ * c->setup();
148
+ * while (size_t n = c->next_phase()) {
149
+ * c->run_items(i0, i1, stats) for ranges covering [0, n), or
150
+ * c->run_pending_items(stats), from one or several threads at the
151
+ * same time
152
+ * }
153
+ * c->finish(stats);
154
+ *
155
+ * The items of a phase can run in any order; a phase must be finished before
156
+ * next_phase() is called. The stats objects passed to concurrent calls must
157
+ * be different. */
158
+ struct OptimalKMeansBlockCombiner {
159
+ /** Optional, before setup(): the split table of the whole output
160
+ * (2^n entries). For each context point b of the block, the entries of
161
+ * the block s_hi ^ (1 << (b - L)) must be final; they are used as
162
+ * guesses. */
163
+ virtual void set_context(const uint64_t* split) = 0;
164
+ /// guess pass, offsets, trees, list of pairs
165
+ virtual void setup() = 0;
166
+ /// start the next phase, return its number of items (0: done)
167
+ virtual size_t next_phase() = 0;
168
+ /// run the items [i0, i1) of the current phase
169
+ virtual void run_items(
170
+ size_t i0,
171
+ size_t i1,
172
+ OptimalKMeansStats* stats = nullptr) = 0;
173
+ /** run the items of the current phase that no other call has claimed
174
+ * (items are claimed one by one, from an atomic counter), until there
175
+ * are none left. Several threads can call it at the same time; do not
176
+ * mix with run_items in the same phase. Returns the number of items
177
+ * run. */
178
+ virtual size_t run_pending_items(OptimalKMeansStats* stats = nullptr) = 0;
179
+ /// add the counters of the setup and of the result to stats
180
+ virtual void finish(OptimalKMeansStats* stats = nullptr) = 0;
181
+ virtual ~OptimalKMeansBlockCombiner() {}
182
+ };
183
+
184
+ /** Engine for the block combination (same arguments as
185
+ * optimal_kmeans_combine_block, which it implements); the arrays must stay
186
+ * valid until finish(). The caller owns the returned object. The kernels
187
+ * are those of the current SIMD level of Faiss (SIMDConfig, 04_simd.md). */
188
+ OptimalKMeansBlockCombiner* optimal_kmeans_block_combiner(
189
+ int n,
190
+ int L,
191
+ uint64_t s_hi,
192
+ const float* A,
193
+ const float* B,
194
+ bool sym,
195
+ float* acc_cost,
196
+ uint64_t* acc_split,
197
+ const OptimalKMeansCombineParams& params);
198
+
199
+ /** Combine two whole tables: C[S], split[S] for all 2^n groups (the block
200
+ * combination with L = n, starting from (+inf, 0)). */
201
+ void optimal_kmeans_combine(
202
+ int n,
203
+ const float* A,
204
+ const float* B,
205
+ bool sym,
206
+ float* C,
207
+ uint64_t* split,
208
+ const OptimalKMeansCombineParams& params,
209
+ OptimalKMeansStats* stats = nullptr);
210
+
211
+ /** Row of the full set U = 2^n - 1, restricted to lo <= L < hi:
212
+ * the lexicographic minimum of (A[L] + B[U ^ L], L), merged into
213
+ * (*cost, *split). Used for the last combination, by chunks.
214
+ * @param A entries lo..hi-1 of the first table (A[0] is entry lo), so that
215
+ * a chunk of T1 can be generated just before the call
216
+ * @param B the whole second table */
217
+ void optimal_kmeans_full_set_row(
218
+ int n,
219
+ const float* A,
220
+ const float* B,
221
+ uint64_t lo,
222
+ uint64_t hi,
223
+ float* cost,
224
+ uint64_t* split);
225
+
226
+ } // namespace faiss