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,1567 @@
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
+ // Compressed levels of the optimal k-means (contrib/optimal_kmeans/
9
+ // 07_compressed.md). Compiled with -ffp-contract=off (faiss/CMakeLists.txt):
10
+ // the lower bounds are computed with the same double operations here and in
11
+ // the CUDA decoder.
12
+
13
+ #include <faiss/impl/optimal_kmeans/OptimalKMeansCompressed.h>
14
+
15
+ #include <faiss/impl/FaissAssert.h>
16
+ #include <faiss/impl/io.h>
17
+ #include <faiss/impl/io_macros.h>
18
+ #include <faiss/impl/platform_macros.h>
19
+ #include <faiss/impl/zerocopy_io.h>
20
+ #include <faiss/utils/popcount.h>
21
+
22
+ #include <omp.h>
23
+
24
+ #include <algorithm>
25
+ #include <atomic>
26
+ #include <cmath>
27
+ #include <cstring>
28
+ #include <future>
29
+ #include <limits>
30
+ #include <list>
31
+ #include <mutex>
32
+ #include <shared_mutex>
33
+ #include <unordered_map>
34
+
35
+ namespace faiss {
36
+
37
+ namespace {
38
+
39
+ constexpr float F_INF = std::numeric_limits<float>::infinity();
40
+
41
+ inline int popc(uint64_t x) {
42
+ return popcount64(x);
43
+ }
44
+
45
+ inline int get_code(const uint8_t* codes, int q, uint32_t z) {
46
+ if (!q) {
47
+ return 0;
48
+ }
49
+ const int per = 8 / q;
50
+ return (codes[z / per] >> (q * (z % per))) & ((1 << q) - 1);
51
+ }
52
+
53
+ /// group of the entries of a block visited in increasing order
54
+ struct GroupIterator {
55
+ const OptimalKMeansCodec& c;
56
+ uint32_t cnt[33];
57
+
58
+ explicit GroupIterator(const OptimalKMeansCodec& c_in) : c(c_in) {}
59
+
60
+ uint32_t next(uint32_t z) {
61
+ const uint32_t submask = (uint32_t(1) << c.sb) - 1;
62
+ if ((z & submask) == 0) {
63
+ memset(cnt, 0, sizeof(cnt));
64
+ }
65
+ const int j = popc(z & submask);
66
+ return uint32_t((z >> c.sb) * c.groups_per_sub) + c.class_off[j] +
67
+ cnt[j]++ / uint32_t(c.g);
68
+ }
69
+ };
70
+
71
+ /*********************************************************
72
+ * Elias-Fano code of the sorted offsets of the exact entries
73
+ *********************************************************/
74
+
75
+ int ef_lbits(uint64_t k, int L) {
76
+ int lbits = 0;
77
+ if (k > 0) {
78
+ const double u = std::ldexp(1.0, L) / double(k);
79
+ while (lbits < L && std::ldexp(1.0, lbits + 1) <= u) {
80
+ lbits++;
81
+ }
82
+ }
83
+ return lbits;
84
+ }
85
+
86
+ // number of bits of the unary array
87
+ uint64_t ef_nbits(uint64_t k, int L, int lbits) {
88
+ return k + (uint64_t(1) << (L - lbits)) + 1;
89
+ }
90
+
91
+ // bits q .. q + 63 of the unary array
92
+ inline uint64_t get64(const std::vector<uint64_t>& hi, uint64_t q) {
93
+ const uint64_t w = q >> 6;
94
+ const int sh = int(q & 63);
95
+ if (w >= hi.size()) {
96
+ return 0;
97
+ }
98
+ uint64_t x = hi[w] >> sh;
99
+ if (sh && w + 1 < hi.size()) {
100
+ x |= hi[w + 1] << (64 - sh);
101
+ }
102
+ return x;
103
+ }
104
+
105
+ // position of the r-th set bit of w (r >= 1)
106
+ inline int select_in_word(uint64_t w, int r) {
107
+ for (int i = 1; i < r; i++) {
108
+ w &= w - 1;
109
+ }
110
+ return __builtin_ctzll(w);
111
+ }
112
+
113
+ inline uint32_t ef_low(const std::vector<uint32_t>& lo, uint64_t i, int lbits) {
114
+ if (!lbits) {
115
+ return 0;
116
+ }
117
+ const uint64_t off = i * lbits, w = off >> 5, sh = off & 31;
118
+ uint64_t x = lo[w] >> sh;
119
+ if (sh + lbits > 32) {
120
+ x |= uint64_t(lo[w + 1]) << (32 - sh);
121
+ }
122
+ return uint32_t(x) & ((uint32_t(1) << lbits) - 1);
123
+ }
124
+
125
+ void ef_encode(
126
+ const std::vector<uint32_t>& v,
127
+ int L,
128
+ OptimalKMeansCompressedBlock& b) {
129
+ const uint64_t k = v.size();
130
+ const int lbits = ef_lbits(k, L);
131
+ b.k = k;
132
+ b.ef_lbits = lbits;
133
+ b.ef_lo.assign((k * lbits + 31) / 32 + 1, 0);
134
+ const uint64_t nbits = ef_nbits(k, L, lbits);
135
+ b.ef_hi.assign((nbits + 63) / 64 + 1, 0);
136
+ const uint32_t mask = lbits ? (uint32_t(1) << lbits) - 1 : 0;
137
+ for (uint64_t i = 0; i < k; i++) {
138
+ if (lbits) {
139
+ const uint64_t off = i * lbits, w = off >> 5, sh = off & 31;
140
+ const uint64_t low = v[i] & mask;
141
+ b.ef_lo[w] |= uint32_t(low << sh);
142
+ if (sh + lbits > 32) {
143
+ b.ef_lo[w + 1] |= uint32_t(low >> (32 - sh));
144
+ }
145
+ }
146
+ const uint64_t p = (uint64_t(v[i]) >> lbits) + i;
147
+ b.ef_hi[p >> 6] |= uint64_t(1) << (p & 63);
148
+ }
149
+ // samples: bucket h starts right after the h-th zero of the unary array
150
+ b.ef_samples.assign(1, 0);
151
+ uint64_t zeros = 0, next = 64;
152
+ for (uint64_t q = 0; q < nbits; q += 64) {
153
+ uint64_t z = ~get64(b.ef_hi, q);
154
+ if (nbits - q < 64) {
155
+ z &= (uint64_t(1) << (nbits - q)) - 1;
156
+ }
157
+ const uint64_t c = popc(z);
158
+ while (zeros + c >= next) {
159
+ b.ef_samples.push_back(
160
+ uint32_t(q + select_in_word(z, int(next - zeros)) + 1));
161
+ next += 64;
162
+ }
163
+ zeros += c;
164
+ }
165
+ }
166
+
167
+ } // namespace
168
+
169
+ /*********************************************************
170
+ * Codec
171
+ *********************************************************/
172
+
173
+ OptimalKMeansCodec::OptimalKMeansCodec(
174
+ int L_in,
175
+ int g_in,
176
+ int q_in,
177
+ int sub_bits_in)
178
+ : L(L_in), g(g_in), q(q_in), sub_bits(sub_bits_in) {
179
+ FAISS_THROW_IF_NOT_FMT(L >= 3 && L <= 30, "L = %d out of range", L);
180
+ FAISS_THROW_IF_NOT_FMT(g >= 1, "g = %d out of range", g);
181
+ FAISS_THROW_IF_NOT_FMT(
182
+ q == 0 || q == 1 || q == 2 || q == 4 || q == 8,
183
+ "q = %d: must be 0, 1, 2, 4 or 8",
184
+ q);
185
+ FAISS_THROW_IF_NOT(sub_bits >= 1);
186
+ sb = std::min(sub_bits, L);
187
+ L1 = L / 2;
188
+ binom.assign(33 * 33, 0);
189
+ for (int i = 0; i <= 32; i++) {
190
+ for (int j = 0; j <= 32; j++) {
191
+ binom[i * 33 + j] = j == 0 ? 1
192
+ : i == 0
193
+ ? 0
194
+ : binom[(i - 1) * 33 + j - 1] + binom[(i - 1) * 33 + j];
195
+ }
196
+ }
197
+ class_off.assign(sb + 2, 0);
198
+ uint64_t acc = 0;
199
+ for (int j = 0; j <= sb; j++) {
200
+ class_off[j] = uint32_t(acc);
201
+ acc += (uint64_t(binom[sb * 33 + j]) + g - 1) / g;
202
+ }
203
+ class_off[sb + 1] = uint32_t(acc);
204
+ groups_per_sub = acc;
205
+ ngroups = groups_per_sub << (L - sb);
206
+ }
207
+
208
+ uint32_t OptimalKMeansCodec::group(uint32_t z) const {
209
+ const uint32_t w = z & ((uint32_t(1) << sb) - 1);
210
+ // rank of w among the sb-bit words of the same popcount (increasing
211
+ // order): sum of C(position, i) over its i-th set bit
212
+ uint32_t rank = 0, m = w;
213
+ int j = 0;
214
+ while (m) {
215
+ const int p = __builtin_ctz(m);
216
+ m &= m - 1;
217
+ j++;
218
+ rank += binom[p * 33 + j];
219
+ }
220
+ return uint32_t((z >> sb) * groups_per_sub) + class_off[j] +
221
+ rank / uint32_t(g);
222
+ }
223
+
224
+ size_t OptimalKMeansCodec::code_bytes() const {
225
+ return (size_t(1) << L) * q / 8;
226
+ }
227
+
228
+ /*********************************************************
229
+ * Blocks and levels
230
+ *********************************************************/
231
+
232
+ int64_t OptimalKMeansCompressedBlock::find(uint32_t z) const {
233
+ if (!k) {
234
+ return -1;
235
+ }
236
+ const int lbits = ef_lbits;
237
+ const uint64_t h = z >> lbits;
238
+ const uint32_t zl = lbits ? z & ((uint32_t(1) << lbits) - 1) : 0;
239
+ if ((h >> 6) >= ef_samples.size()) {
240
+ return -1;
241
+ }
242
+ uint64_t q = ef_samples[h >> 6];
243
+ int need = int(h & 63); // zeros to skip
244
+ while (need > 0) {
245
+ const uint64_t w = ~get64(ef_hi, q);
246
+ const int c = popc(w);
247
+ if (c >= need) {
248
+ q += select_in_word(w, need) + 1;
249
+ break;
250
+ }
251
+ need -= c;
252
+ q += 64;
253
+ }
254
+ // the elements of bucket h, in increasing order
255
+ for (uint64_t i = q - h; i < k; i++, q++) {
256
+ if (!(get64(ef_hi, q) & 1)) {
257
+ return -1;
258
+ }
259
+ const uint32_t lw = ef_low(ef_lo, i, lbits);
260
+ if (lw == zl) {
261
+ return int64_t(i);
262
+ }
263
+ if (lw > zl) {
264
+ return -1;
265
+ }
266
+ }
267
+ return -1;
268
+ }
269
+
270
+ std::vector<uint32_t> OptimalKMeansCompressedBlock::exact_offsets() const {
271
+ std::vector<uint32_t> out(k);
272
+ uint64_t i = 0;
273
+ for (size_t w = 0; w < ef_hi.size() && i < k; w++) {
274
+ uint64_t bits = ef_hi[w];
275
+ while (bits && i < k) {
276
+ const uint64_t p = w * 64 + __builtin_ctzll(bits);
277
+ bits &= bits - 1;
278
+ out[i] = uint32_t(
279
+ ((p - i) << ef_lbits) | ef_low(ef_lo, i, ef_lbits));
280
+ i++;
281
+ }
282
+ }
283
+ return out;
284
+ }
285
+
286
+ size_t OptimalKMeansCompressedBlock::nbytes() const {
287
+ return C.size() * 8 + gmin.size() * 4 + step.size() * 4 + codes.size() +
288
+ ef_lo.size() * 4 + ef_hi.size() * 8 + ef_samples.size() * 4 +
289
+ e_cost.size() * 4 + e_split.size() * 8;
290
+ }
291
+
292
+ void OptimalKMeansCompressedBlock::write(IOWriter* f) const {
293
+ uint32_t magic = 0x424d4b4f; // "OKMB"
294
+ WRITE1(magic);
295
+ WRITEVECTOR(C);
296
+ WRITEVECTOR(gmin);
297
+ WRITEVECTOR(step);
298
+ WRITEVECTOR(codes);
299
+ WRITE1(k);
300
+ WRITE1(ef_lbits);
301
+ WRITEVECTOR(ef_lo);
302
+ WRITEVECTOR(ef_hi);
303
+ WRITEVECTOR(ef_samples);
304
+ WRITEVECTOR(e_cost);
305
+ uint8_t cl = clamp;
306
+ WRITE1(cl);
307
+ WRITE1(ncert);
308
+ }
309
+
310
+ void OptimalKMeansCompressedBlock::read(IOReader* f) {
311
+ uint32_t magic;
312
+ READ1(magic);
313
+ FAISS_THROW_IF_NOT_MSG(magic == 0x424d4b4f, "not a compressed block");
314
+ READVECTOR(C);
315
+ READVECTOR(gmin);
316
+ READVECTOR(step);
317
+ READVECTOR(codes);
318
+ READ1(k);
319
+ READ1(ef_lbits);
320
+ READVECTOR(ef_lo);
321
+ READVECTOR(ef_hi);
322
+ READVECTOR(ef_samples);
323
+ READVECTOR(e_cost);
324
+ READ1_BOOL(clamp);
325
+ READ1(ncert);
326
+ e_split.clear();
327
+ }
328
+
329
+ /*********************************************************
330
+ * Levels on disk
331
+ *********************************************************/
332
+
333
+ struct OptimalKMeansDiskCacheState {
334
+ std::mutex mu;
335
+ size_t bytes = 0, peak = 0;
336
+ uint64_t loads = 0;
337
+ struct Entry {
338
+ std::weak_ptr<OptimalKMeansLevelStorage> storage;
339
+ uint64_t s;
340
+ size_t nbytes;
341
+ };
342
+ std::list<Entry> fifo; // blocks in memory, oldest first
343
+ };
344
+
345
+ /// the blocks of a level in memory (disk mode)
346
+ struct OptimalKMeansLevelStorage {
347
+ std::string dir;
348
+ OptimalKMeansDiskCache* cache = nullptr;
349
+ std::vector<std::shared_ptr<const OptimalKMeansCompressedBlock>> resident;
350
+ /// entry of block s in the FIFO of the cache, if queued[s] (both under
351
+ /// the mutex of the cache)
352
+ std::vector<std::list<OptimalKMeansDiskCacheState::Entry>::iterator>
353
+ fifo_pos;
354
+ std::vector<uint8_t> queued;
355
+ std::mutex stripes[256];
356
+
357
+ std::mutex& stripe(uint64_t s) {
358
+ return stripes[s & 255];
359
+ }
360
+ std::string path(uint64_t s, const char* ext) const {
361
+ return dir + "/b" + std::to_string(s) + ext;
362
+ }
363
+ };
364
+
365
+ namespace {
366
+
367
+ // block s of the storage is in memory: count it in the cache and release the
368
+ // oldest blocks beyond the budget (their readers keep them alive)
369
+ void cache_insert(
370
+ const std::shared_ptr<OptimalKMeansLevelStorage>& st,
371
+ uint64_t s,
372
+ size_t nbytes) {
373
+ OptimalKMeansDiskCacheState& cs = *st->cache->state;
374
+ std::vector<std::pair<std::shared_ptr<OptimalKMeansLevelStorage>, uint64_t>>
375
+ evict;
376
+ {
377
+ std::lock_guard<std::mutex> g(cs.mu);
378
+ st->fifo_pos[s] = cs.fifo.insert(cs.fifo.end(), {st, s, nbytes});
379
+ st->queued[s] = 1;
380
+ cs.bytes += nbytes;
381
+ cs.peak = std::max(cs.peak, cs.bytes);
382
+ while (cs.bytes > st->cache->max_bytes && cs.fifo.size() > 1) {
383
+ auto e = cs.fifo.front();
384
+ cs.fifo.pop_front();
385
+ cs.bytes -= e.nbytes;
386
+ if (auto st2 = e.storage.lock()) {
387
+ st2->queued[e.s] = 0;
388
+ evict.emplace_back(st2, e.s);
389
+ }
390
+ }
391
+ }
392
+ for (auto& [st2, s2] : evict) {
393
+ std::shared_ptr<const OptimalKMeansCompressedBlock> old;
394
+ std::lock_guard<std::mutex> g(st2->stripe(s2));
395
+ old.swap(st2->resident[s2]); // freed when the last reader is done
396
+ }
397
+ }
398
+
399
+ } // namespace
400
+
401
+ OptimalKMeansDiskCache::OptimalKMeansDiskCache(size_t max_bytes_in)
402
+ : max_bytes(max_bytes_in),
403
+ state(std::make_shared<OptimalKMeansDiskCacheState>()) {}
404
+
405
+ size_t OptimalKMeansDiskCache::bytes() const {
406
+ std::lock_guard<std::mutex> g(state->mu);
407
+ return state->bytes;
408
+ }
409
+
410
+ size_t OptimalKMeansDiskCache::peak_bytes() const {
411
+ std::lock_guard<std::mutex> g(state->mu);
412
+ return state->peak;
413
+ }
414
+
415
+ uint64_t OptimalKMeansDiskCache::loads() const {
416
+ std::lock_guard<std::mutex> g(state->mu);
417
+ return state->loads;
418
+ }
419
+
420
+ OptimalKMeansCompressedLevel::OptimalKMeansCompressedLevel(
421
+ int c_in,
422
+ int a_in,
423
+ int b_in,
424
+ int n_in,
425
+ const OptimalKMeansCodec& codec_in)
426
+ : c(c_in), a(a_in), b(b_in), n(n_in), L(codec_in.L), codec(codec_in) {
427
+ FAISS_THROW_IF_NOT_FMT(
428
+ n >= L && n <= 40, "n = %d out of range (L = %d)", n, L);
429
+ const size_t nb = size_t(1) << (n - L);
430
+ blocks.resize(nb);
431
+ block_k.assign(nb, 0);
432
+ block_ncert.assign(nb, 0);
433
+ block_nbytes.assign(nb, 0);
434
+ block_clamp.assign(nb, 1);
435
+ }
436
+
437
+ void OptimalKMeansCompressedLevel::set_offsets(const double* o_in) {
438
+ o.assign(o_in, o_in + L);
439
+ const int L1 = codec.L1, L2 = L - L1;
440
+ tlo.assign(size_t(1) << L1, 0.0);
441
+ thi.assign(size_t(1) << L2, 0.0);
442
+ // sums over the bits in increasing order
443
+ for (int j = 0; j < L1; j++) {
444
+ for (size_t i = 0; i < (size_t(1) << j); i++) {
445
+ tlo[(size_t(1) << j) + i] = tlo[i] + o[j];
446
+ }
447
+ }
448
+ for (int j = 0; j < L2; j++) {
449
+ for (size_t i = 0; i < (size_t(1) << j); i++) {
450
+ thi[(size_t(1) << j) + i] = thi[i] + o[L1 + j];
451
+ }
452
+ }
453
+ }
454
+
455
+ void OptimalKMeansCompressedLevel::set_disk_cache(
456
+ const char* dir_in,
457
+ OptimalKMeansDiskCache* cache) {
458
+ FAISS_THROW_IF_NOT(dir_in && cache);
459
+ dir = dir_in;
460
+ storage = std::make_shared<OptimalKMeansLevelStorage>();
461
+ storage->dir = dir;
462
+ storage->cache = cache;
463
+ storage->resident.resize(block_k.size());
464
+ storage->fifo_pos.resize(block_k.size());
465
+ storage->queued.assign(block_k.size(), 0);
466
+ blocks.clear();
467
+ blocks.shrink_to_fit();
468
+ }
469
+
470
+ void OptimalKMeansCompressedLevel::store_block(
471
+ uint64_t s,
472
+ OptimalKMeansCompressedBlock& blk) {
473
+ FAISS_THROW_IF_NOT(s < block_k.size());
474
+ block_k[s] = blk.k;
475
+ block_ncert[s] = blk.ncert;
476
+ block_clamp[s] = blk.clamp;
477
+ if (!storage) {
478
+ block_nbytes[s] = blk.nbytes();
479
+ blocks[s] = std::move(blk);
480
+ return;
481
+ }
482
+ {
483
+ FileIOWriter fw(storage->path(s, ".spl").c_str());
484
+ IOWriter* f = &fw;
485
+ WRITEANDCHECK(blk.e_split.data(), blk.e_split.size());
486
+ }
487
+ blk.e_split.clear();
488
+ blk.e_split.shrink_to_fit();
489
+ {
490
+ FileIOWriter fw(storage->path(s, ".blk").c_str());
491
+ blk.write(&fw);
492
+ }
493
+ block_nbytes[s] = blk.nbytes();
494
+ auto p = std::make_shared<const OptimalKMeansCompressedBlock>(
495
+ std::move(blk));
496
+ {
497
+ std::lock_guard<std::mutex> g(storage->stripe(s));
498
+ storage->resident[s] = p;
499
+ }
500
+ cache_insert(storage, s, block_nbytes[s]);
501
+ }
502
+
503
+ void OptimalKMeansCompressedLevel::drop_block(uint64_t s) {
504
+ FAISS_THROW_IF_NOT(s < block_k.size());
505
+ if (!storage) {
506
+ return;
507
+ }
508
+ OptimalKMeansDiskCacheState& cs = *storage->cache->state;
509
+ {
510
+ std::lock_guard<std::mutex> g(cs.mu);
511
+ if (storage->queued[s]) {
512
+ cs.bytes -= storage->fifo_pos[s]->nbytes;
513
+ cs.fifo.erase(storage->fifo_pos[s]);
514
+ storage->queued[s] = 0;
515
+ }
516
+ }
517
+ std::shared_ptr<const OptimalKMeansCompressedBlock> old;
518
+ std::lock_guard<std::mutex> g(storage->stripe(s));
519
+ old.swap(storage->resident[s]); // freed when the last reader is done
520
+ }
521
+
522
+ std::shared_ptr<const OptimalKMeansCompressedBlock>
523
+ OptimalKMeansCompressedLevel::get_block(uint64_t s) const {
524
+ if (!storage) {
525
+ // aliasing pointer without ownership: no reference counting
526
+ return std::shared_ptr<const OptimalKMeansCompressedBlock>(
527
+ std::shared_ptr<const OptimalKMeansCompressedBlock>(),
528
+ &blocks[s]);
529
+ }
530
+ OptimalKMeansLevelStorage& st = *storage;
531
+ {
532
+ std::lock_guard<std::mutex> g(st.stripe(s));
533
+ if (st.resident[s]) {
534
+ return st.resident[s];
535
+ }
536
+ }
537
+ auto blk = std::make_shared<OptimalKMeansCompressedBlock>();
538
+ {
539
+ FileIOReader fr(st.path(s, ".blk").c_str());
540
+ blk->read(&fr);
541
+ }
542
+ std::shared_ptr<const OptimalKMeansCompressedBlock> p = blk;
543
+ {
544
+ std::lock_guard<std::mutex> g(st.stripe(s));
545
+ if (st.resident[s]) { // loaded by another thread in the meantime
546
+ return st.resident[s];
547
+ }
548
+ st.resident[s] = p;
549
+ }
550
+ {
551
+ std::lock_guard<std::mutex> g(st.cache->state->mu);
552
+ st.cache->state->loads++;
553
+ }
554
+ cache_insert(storage, s, p->nbytes());
555
+ return p;
556
+ }
557
+
558
+ uint64_t OptimalKMeansCompressedLevel::exact_split(uint64_t s, int64_t i)
559
+ const {
560
+ if (!storage) {
561
+ return blocks[s].e_split.at(i);
562
+ }
563
+ FileIOReader fr(storage->path(s, ".spl").c_str());
564
+ FAISS_THROW_IF_NOT(fseek(fr.f, long(i) * 8, SEEK_SET) == 0);
565
+ uint64_t v;
566
+ IOReader* f = &fr;
567
+ READ1(v);
568
+ return v;
569
+ }
570
+
571
+ void OptimalKMeansCompressedLevel::serialize_block(
572
+ uint64_t s,
573
+ std::vector<uint8_t>& data) const {
574
+ FAISS_THROW_IF_NOT(s < block_k.size());
575
+ VectorIOWriter vw;
576
+ IOWriter* f = &vw;
577
+ const auto blk = get_block(s);
578
+ blk->write(f);
579
+ if (!storage) {
580
+ WRITEVECTOR(blk->e_split);
581
+ } else {
582
+ std::vector<uint64_t> e_split(blk->k);
583
+ FileIOReader fr(storage->path(s, ".spl").c_str());
584
+ IOReader* r = &fr;
585
+ if (blk->k) {
586
+ size_t ret = (*r)(e_split.data(), 8, blk->k);
587
+ FAISS_THROW_IF_NOT_FMT(
588
+ ret == blk->k, "cannot read the splits of block %zd", s);
589
+ }
590
+ WRITEVECTOR(e_split);
591
+ }
592
+ data.swap(vw.data);
593
+ }
594
+
595
+ void OptimalKMeansCompressedLevel::store_serialized_block(
596
+ uint64_t s,
597
+ size_t nbytes,
598
+ const uint8_t* data) {
599
+ ZeroCopyIOReader zr(data, nbytes);
600
+ IOReader* f = &zr;
601
+ OptimalKMeansCompressedBlock blk;
602
+ blk.read(f);
603
+ READVECTOR(blk.e_split);
604
+ FAISS_THROW_IF_NOT(blk.e_split.size() == blk.k);
605
+ store_block(s, blk);
606
+ }
607
+
608
+ double OptimalKMeansCompressedLevel::low_sum(uint32_t z) const {
609
+ return tlo[z & ((uint32_t(1) << codec.L1) - 1)] + thi[z >> codec.L1];
610
+ }
611
+
612
+ float OptimalKMeansCompressedLevel::lower(uint64_t Y, bool* exact) const {
613
+ const auto p = get_block(Y >> L);
614
+ const OptimalKMeansCompressedBlock& blk = *p;
615
+ const uint32_t z = uint32_t(Y & ((uint64_t(1) << L) - 1));
616
+ const int64_t ix = blk.find(z);
617
+ if (exact) {
618
+ *exact = ix >= 0;
619
+ }
620
+ if (ix >= 0) {
621
+ return blk.e_cost[ix];
622
+ }
623
+ const uint32_t g = codec.group(z);
624
+ return optimal_kmeans_lower_bound(
625
+ blk.C[popc(z)] + low_sum(z),
626
+ blk.gmin[g],
627
+ codec.q ? blk.step[g] : 0.f,
628
+ get_code(blk.codes.data(), codec.q, z),
629
+ codec.q,
630
+ blk.clamp);
631
+ }
632
+
633
+ bool OptimalKMeansCompressedLevel::is_exact(uint64_t Y) const {
634
+ return get_block(Y >> L)->find(uint32_t(Y & ((uint64_t(1) << L) - 1))) >= 0;
635
+ }
636
+
637
+ size_t OptimalKMeansCompressedLevel::nbytes() const {
638
+ size_t s = 0;
639
+ for (auto v : block_nbytes) {
640
+ s += v;
641
+ }
642
+ return s;
643
+ }
644
+
645
+ uint64_t OptimalKMeansCompressedLevel::nexact() const {
646
+ uint64_t s = 0;
647
+ for (auto v : block_k) {
648
+ s += v;
649
+ }
650
+ return s;
651
+ }
652
+
653
+ uint64_t OptimalKMeansCompressedLevel::ncert() const {
654
+ uint64_t s = 0;
655
+ for (auto v : block_ncert) {
656
+ s += v;
657
+ }
658
+ return s;
659
+ }
660
+
661
+ bool OptimalKMeansCompressedLevel::nonneg() const {
662
+ for (auto v : block_clamp) {
663
+ if (!v) {
664
+ return false;
665
+ }
666
+ }
667
+ return true;
668
+ }
669
+
670
+ float optimal_kmeans_lower_bound(
671
+ double off,
672
+ float gmin,
673
+ float step,
674
+ int code,
675
+ int q,
676
+ bool clamp) {
677
+ double lb = off + double(gmin);
678
+ if (q) {
679
+ lb = lb + double(code) * double(step);
680
+ }
681
+ float f = float(lb); // rounded down below
682
+ if (double(f) > lb) {
683
+ f = std::nextafter(f, -F_INF);
684
+ }
685
+ if (clamp) {
686
+ f = f > 0 ? f : 0.0f;
687
+ }
688
+ return f;
689
+ }
690
+
691
+ /*********************************************************
692
+ * Encoding and decoding
693
+ *********************************************************/
694
+
695
+ void optimal_kmeans_encode_block(
696
+ OptimalKMeansCompressedLevel* level,
697
+ uint64_t s,
698
+ const float* cost,
699
+ const uint64_t* split,
700
+ const OptimalKMeansCompressedLevel* in_a,
701
+ const OptimalKMeansCompressedLevel* in_b,
702
+ double f,
703
+ const float* final_other) {
704
+ const OptimalKMeansCodec& c = level->codec;
705
+ const int L = c.L, q = c.q;
706
+ const uint32_t S = uint32_t(1) << L;
707
+ FAISS_THROW_IF_NOT_MSG(
708
+ level->o.size() == size_t(L), "set_offsets was not called");
709
+ FAISS_THROW_IF_NOT(s < level->block_k.size());
710
+ OptimalKMeansCompressedBlock blk;
711
+
712
+ // certification: the winning split uses two exact entries. The input
713
+ // blocks are taken once per block (they may be loaded from disk).
714
+ std::vector<uint8_t> cert(S);
715
+ uint64_t ncert = 0;
716
+ {
717
+ using BlockPtr = std::shared_ptr<const OptimalKMeansCompressedBlock>;
718
+ std::unordered_map<uint64_t, BlockPtr> ba, bb;
719
+ auto exact = [&](const OptimalKMeansCompressedLevel* lv,
720
+ std::unordered_map<uint64_t, BlockPtr>& m,
721
+ uint64_t Y) {
722
+ if (!lv) {
723
+ return true;
724
+ }
725
+ auto it = m.find(Y >> L);
726
+ if (it == m.end()) {
727
+ it = m.emplace(Y >> L, lv->get_block(Y >> L)).first;
728
+ }
729
+ return it->second->find(uint32_t(Y & (S - 1))) >= 0;
730
+ };
731
+ for (uint32_t z = 0; z < S; z++) {
732
+ const uint64_t Sx = (s << L) | z, l = split[z];
733
+ const bool ok = exact(in_a, ba, l) && exact(in_b, bb, Sx ^ l);
734
+ cert[z] = ok;
735
+ ncert += ok;
736
+ }
737
+ }
738
+ blk.ncert = ncert;
739
+
740
+ // offsets: C per popcount = mean of (cost - low sum) over the finite
741
+ // costs (+inf if there are none)
742
+ std::vector<double> sum(L + 1, 0.0), cnt(L + 1, 0.0), r(S);
743
+ for (uint32_t z = 0; z < S; z++) {
744
+ const double low = level->low_sum(z);
745
+ r[z] = low;
746
+ if (std::isfinite(cost[z])) {
747
+ sum[popc(z)] += double(cost[z]) - low;
748
+ cnt[popc(z)] += 1;
749
+ }
750
+ }
751
+ blk.C.resize(L + 1);
752
+ for (int p = 0; p <= L; p++) {
753
+ blk.C[p] = cnt[p] > 0 ? sum[p] / cnt[p]
754
+ : std::numeric_limits<double>::infinity();
755
+ }
756
+ // residuals (NaN for infinite costs)
757
+ for (uint32_t z = 0; z < S; z++) {
758
+ r[z] = std::isfinite(cost[z])
759
+ ? double(cost[z]) - (blk.C[popc(z)] + r[z])
760
+ : std::numeric_limits<double>::quiet_NaN();
761
+ }
762
+
763
+ // exact subset, among the certified entries
764
+ std::vector<uint8_t> E(S, 0);
765
+ if (f > 0 && !final_other) {
766
+ // per popcount class: the smallest residuals
767
+ std::vector<std::vector<uint32_t>> cand(L + 1);
768
+ for (uint32_t z = 0; z < S; z++) {
769
+ if (cert[z] && !std::isnan(r[z])) {
770
+ cand[popc(z)].push_back(z);
771
+ }
772
+ }
773
+ for (int p = 0; p <= L; p++) {
774
+ const uint64_t size = c.binom[L * 33 + p];
775
+ const uint64_t kq =
776
+ std::min<uint64_t>(size, uint64_t(std::ceil(f * size)));
777
+ auto& v = cand[p];
778
+ if (v.size() > kq) {
779
+ std::nth_element(
780
+ v.begin(),
781
+ v.begin() + kq,
782
+ v.end(),
783
+ [&](uint32_t x, uint32_t y) {
784
+ return r[x] < r[y] || (r[x] == r[y] && x < y);
785
+ });
786
+ v.resize(kq);
787
+ }
788
+ for (uint32_t z : v) {
789
+ E[z] = 1;
790
+ }
791
+ }
792
+ } else if (f > 0) {
793
+ // smallest final candidate values
794
+ std::vector<double> score(S);
795
+ std::vector<uint32_t> cand;
796
+ for (uint32_t z = 0; z < S; z++) {
797
+ score[z] = double(cost[z]) + double(final_other[z]);
798
+ if (cert[z] && std::isfinite(score[z])) {
799
+ cand.push_back(z);
800
+ }
801
+ }
802
+ const uint64_t kq =
803
+ std::min<uint64_t>(S, uint64_t(std::ceil(f * double(S))));
804
+ if (cand.size() > kq) {
805
+ std::nth_element(
806
+ cand.begin(),
807
+ cand.begin() + kq,
808
+ cand.end(),
809
+ [&](uint32_t x, uint32_t y) {
810
+ return score[x] < score[y] ||
811
+ (score[x] == score[y] && x < y);
812
+ });
813
+ cand.resize(kq);
814
+ }
815
+ for (uint32_t z : cand) {
816
+ E[z] = 1;
817
+ }
818
+ }
819
+
820
+ // group bounds of the other entries
821
+ const size_t G = c.ngroups;
822
+ std::vector<double> mn(G, std::numeric_limits<double>::infinity()),
823
+ mx(G, -std::numeric_limits<double>::infinity());
824
+ {
825
+ GroupIterator gi(c);
826
+ for (uint32_t z = 0; z < S; z++) {
827
+ const uint32_t g = gi.next(z);
828
+ if (!E[z] && !std::isnan(r[z])) {
829
+ mn[g] = std::min(mn[g], r[z]);
830
+ mx[g] = std::max(mx[g], r[z]);
831
+ }
832
+ }
833
+ }
834
+ blk.gmin.resize(G);
835
+ if (q) {
836
+ blk.step.resize(G);
837
+ }
838
+ for (size_t g = 0; g < G; g++) {
839
+ if (!std::isfinite(mn[g])) { // no entry
840
+ mn[g] = mx[g] = 0;
841
+ }
842
+ float g32 = float(mn[g]);
843
+ if (double(g32) > mn[g]) {
844
+ g32 = std::nextafter(g32, -F_INF);
845
+ }
846
+ blk.gmin[g] = g32;
847
+ if (q) {
848
+ const double st = (mx[g] - double(g32)) / double((1 << q) - 1);
849
+ float s32 = float(st);
850
+ if (double(s32) > st) {
851
+ s32 = std::nextafter(s32, -F_INF);
852
+ }
853
+ blk.step[g] = s32 > 0 ? s32 : 0.f;
854
+ }
855
+ }
856
+ std::vector<uint8_t> code(S, 0);
857
+ if (q) {
858
+ GroupIterator gi(c);
859
+ for (uint32_t z = 0; z < S; z++) {
860
+ const uint32_t g = gi.next(z);
861
+ if (E[z] || std::isnan(r[z])) {
862
+ continue;
863
+ }
864
+ const double sg = double(blk.step[g]);
865
+ if (sg > 0) {
866
+ const double cd = std::floor((r[z] - double(blk.gmin[g])) / sg);
867
+ if (std::isfinite(cd)) {
868
+ code[z] =
869
+ uint8_t(std::min<double>(
870
+ std::max<double>(cd, 0), (1 << q) - 1));
871
+ }
872
+ }
873
+ }
874
+ }
875
+ blk.clamp = true;
876
+ for (uint32_t z = 0; z < S; z++) {
877
+ if (std::signbit(cost[z])) {
878
+ blk.clamp = false;
879
+ break;
880
+ }
881
+ }
882
+ // rounding safety: every bound <= the cost it replaces
883
+ for (int it = 0;; it++) {
884
+ FAISS_THROW_IF_NOT_MSG(it < 256, "could not round the bounds");
885
+ bool bad_any = false;
886
+ std::vector<uint8_t> gbad(G, 0);
887
+ GroupIterator gi(c);
888
+ for (uint32_t z = 0; z < S; z++) {
889
+ const uint32_t g = gi.next(z);
890
+ if (E[z]) {
891
+ continue;
892
+ }
893
+ const float lb = optimal_kmeans_lower_bound(
894
+ blk.C[popc(z)] + level->low_sum(z),
895
+ blk.gmin[g],
896
+ q ? blk.step[g] : 0.f,
897
+ code[z],
898
+ q,
899
+ blk.clamp);
900
+ if (lb > cost[z]) {
901
+ bad_any = true;
902
+ if (q && code[z] > 0) {
903
+ code[z]--;
904
+ } else {
905
+ gbad[g] = 1;
906
+ }
907
+ }
908
+ }
909
+ if (!bad_any) {
910
+ break;
911
+ }
912
+ for (size_t g = 0; g < G; g++) {
913
+ if (gbad[g]) {
914
+ blk.gmin[g] = std::nextafter(blk.gmin[g], -F_INF);
915
+ }
916
+ }
917
+ }
918
+ if (q) {
919
+ const int per = 8 / q;
920
+ blk.codes.assign(c.code_bytes(), 0);
921
+ for (uint32_t z = 0; z < S; z++) {
922
+ blk.codes[z / per] |= uint8_t(code[z] << (q * (z % per)));
923
+ }
924
+ }
925
+ std::vector<uint32_t> e_off;
926
+ for (uint32_t z = 0; z < S; z++) {
927
+ if (E[z]) {
928
+ e_off.push_back(z);
929
+ blk.e_cost.push_back(cost[z]);
930
+ blk.e_split.push_back(split[z]);
931
+ }
932
+ }
933
+ ef_encode(e_off, L, blk);
934
+ level->store_block(s, blk);
935
+ }
936
+
937
+ void optimal_kmeans_decode_block(
938
+ const OptimalKMeansCompressedLevel& level,
939
+ uint64_t s,
940
+ float* out,
941
+ uint8_t* exact) {
942
+ const OptimalKMeansCodec& c = level.codec;
943
+ FAISS_THROW_IF_NOT(s < level.block_k.size());
944
+ const auto p = level.get_block(s);
945
+ const OptimalKMeansCompressedBlock& blk = *p;
946
+ const uint32_t S = uint32_t(1) << c.L;
947
+ FAISS_THROW_IF_NOT_MSG(blk.C.size() == size_t(c.L + 1), "empty block");
948
+ GroupIterator gi(c);
949
+ for (uint32_t z = 0; z < S; z++) {
950
+ const uint32_t g = gi.next(z);
951
+ out[z] = optimal_kmeans_lower_bound(
952
+ blk.C[popc(z)] + level.low_sum(z),
953
+ blk.gmin[g],
954
+ c.q ? blk.step[g] : 0.f,
955
+ get_code(blk.codes.data(), c.q, z),
956
+ c.q,
957
+ blk.clamp);
958
+ }
959
+ if (exact) {
960
+ memset(exact, 0, S);
961
+ }
962
+ const std::vector<uint32_t> eo = blk.exact_offsets();
963
+ for (uint64_t i = 0; i < blk.k; i++) {
964
+ out[eo[i]] = blk.e_cost[i];
965
+ if (exact) {
966
+ exact[eo[i]] = 1;
967
+ }
968
+ }
969
+ }
970
+
971
+ /*********************************************************
972
+ * Exact recomputation
973
+ *********************************************************/
974
+
975
+ namespace {
976
+
977
+ constexpr int MEMO_SHARDS = 256;
978
+ constexpr int PAR_BITS = 16; // rows with >= 2^PAR_BITS candidates use tasks
979
+ constexpr int MAX_LEVEL = 65;
980
+
981
+ /** parallel loop over [0, n) as OpenMP tasks (nested loops are balanced
982
+ * over the threads of the enclosing parallel region); serial without
983
+ * OpenMP 4.5 */
984
+ template <class F>
985
+ void parallel_for(size_t n, F& f) {
986
+ #if defined(_OPENMP) && _OPENMP >= 201511
987
+ #pragma omp taskloop grainsize(1) shared(f)
988
+ for (size_t i = 0; i < n; i++) {
989
+ f(i);
990
+ }
991
+ #else
992
+ for (size_t i = 0; i < n; i++) {
993
+ f(i);
994
+ }
995
+ #endif
996
+ }
997
+
998
+ struct Memo {
999
+ struct Shard {
1000
+ std::unordered_map<uint64_t, std::pair<float, uint64_t>> m;
1001
+ std::shared_mutex mu;
1002
+ };
1003
+ Shard shards[MEMO_SHARDS];
1004
+ // lock-free filter of the memoized entries (one bit per hash): most
1005
+ // lookups are misses
1006
+ static constexpr int FILT_BITS = 26;
1007
+ std::unique_ptr<std::atomic<uint64_t>[]> filt{
1008
+ new std::atomic<uint64_t>[size_t(1) << (FILT_BITS - 6)]()};
1009
+ std::atomic<uint64_t> rows{0};
1010
+
1011
+ Shard& shard(uint64_t Y) {
1012
+ return shards[(Y * 0x9E3779B97F4A7C15ull) >> 56];
1013
+ }
1014
+ static uint64_t fh(uint64_t Y) {
1015
+ return (Y * 0xD6E8FEB86659FD93ull) >> (64 - FILT_BITS);
1016
+ }
1017
+ bool maybe(uint64_t Y) const {
1018
+ const uint64_t h = fh(Y);
1019
+ return (filt[h >> 6].load(std::memory_order_acquire) >> (h & 63)) & 1;
1020
+ }
1021
+ void mark(uint64_t Y) {
1022
+ const uint64_t h = fh(Y);
1023
+ filt[h >> 6].fetch_or(
1024
+ uint64_t(1) << (h & 63), std::memory_order_release);
1025
+ }
1026
+ bool get(uint64_t Y, std::pair<float, uint64_t>& v) {
1027
+ if (!maybe(Y)) {
1028
+ return false;
1029
+ }
1030
+ Shard& sh = shard(Y);
1031
+ std::shared_lock<std::shared_mutex> g(sh.mu);
1032
+ auto it = sh.m.find(Y);
1033
+ if (it == sh.m.end()) {
1034
+ return false;
1035
+ }
1036
+ v = it->second;
1037
+ return true;
1038
+ }
1039
+ void put(uint64_t Y, std::pair<float, uint64_t> v) {
1040
+ Shard& sh = shard(Y);
1041
+ std::unique_lock<std::shared_mutex> g(sh.mu);
1042
+ sh.m[Y] = v;
1043
+ mark(Y); // after the insertion: a reader that sees the bit finds it
1044
+ }
1045
+ };
1046
+
1047
+ /// a decoded block
1048
+ struct Dense {
1049
+ std::vector<float> v;
1050
+ std::vector<uint8_t> ex; // empty: every entry exact
1051
+ size_t bytes() const {
1052
+ return 4 * v.size() + ex.size();
1053
+ }
1054
+ };
1055
+
1056
+ bool lex_less(float c1, uint64_t l1, float c2, uint64_t l2) {
1057
+ return c1 < c2 || (c1 == c2 && l1 < l2);
1058
+ }
1059
+
1060
+ } // namespace
1061
+
1062
+ struct OptimalKMeansExactEngineState {
1063
+ const OptimalKMeansCost1* t1 = nullptr;
1064
+ int n = 0, L = 0, nthreads = 1;
1065
+ size_t max_candidates = 0, cache_max = 4;
1066
+ const OptimalKMeansCompressedLevel* levels[MAX_LEVEL] = {};
1067
+ std::unique_ptr<Memo> memo[MAX_LEVEL];
1068
+
1069
+ // LRU cache of decoded blocks
1070
+ std::mutex cache_mutex;
1071
+ using LruList = std::list<std::pair<uint64_t, std::shared_ptr<Dense>>>;
1072
+ LruList lru;
1073
+ std::unordered_map<uint64_t, LruList::iterator> where;
1074
+ std::unordered_map<uint64_t, std::shared_future<std::shared_ptr<Dense>>>
1075
+ inflight;
1076
+
1077
+ uint64_t mask() const {
1078
+ return (uint64_t(1) << L) - 1;
1079
+ }
1080
+
1081
+ const OptimalKMeansCompressedLevel& level(int c) const {
1082
+ FAISS_THROW_IF_NOT_FMT(
1083
+ c > 1 && c < MAX_LEVEL && levels[c],
1084
+ "level %d not registered",
1085
+ c);
1086
+ return *levels[c];
1087
+ }
1088
+
1089
+ // block blk of level c, decoded (one decoder per block)
1090
+ std::shared_ptr<Dense> dense(int c, uint64_t blk) {
1091
+ const uint64_t key = (uint64_t(c) << 48) | blk;
1092
+ std::promise<std::shared_ptr<Dense>> prom;
1093
+ {
1094
+ std::unique_lock<std::mutex> g(cache_mutex);
1095
+ auto it = where.find(key);
1096
+ if (it != where.end()) {
1097
+ lru.splice(lru.begin(), lru, it->second);
1098
+ return it->second->second;
1099
+ }
1100
+ auto fi = inflight.find(key);
1101
+ if (fi != inflight.end()) {
1102
+ auto fut = fi->second;
1103
+ g.unlock();
1104
+ return fut.get();
1105
+ }
1106
+ inflight[key] = prom.get_future().share();
1107
+ }
1108
+ auto d = std::make_shared<Dense>();
1109
+ const size_t size = size_t(1) << L;
1110
+ d->v.resize(size);
1111
+ if (c == 1) {
1112
+ // 64 sub-ranges in parallel
1113
+ const int sub = L >= 12 ? 6 : 0;
1114
+ const size_t len = size >> sub;
1115
+ auto part = [&](size_t i) {
1116
+ const uint64_t lo = (blk << L) + i * len;
1117
+ t1->range(lo, lo + len, d->v.data() + i * len);
1118
+ };
1119
+ parallel_for(size_t(1) << sub, part);
1120
+ } else {
1121
+ d->ex.resize(size);
1122
+ optimal_kmeans_decode_block(
1123
+ level(c), blk, d->v.data(), d->ex.data());
1124
+ }
1125
+ std::lock_guard<std::mutex> g(cache_mutex);
1126
+ lru.emplace_front(key, d);
1127
+ where[key] = lru.begin();
1128
+ while (lru.size() > cache_max) {
1129
+ where.erase(lru.back().first);
1130
+ lru.pop_back();
1131
+ }
1132
+ inflight.erase(key);
1133
+ prom.set_value(d);
1134
+ return d;
1135
+ }
1136
+
1137
+ // stored value of entry Y of level c and whether it is exact
1138
+ std::pair<float, bool> lower(int c, uint64_t Y) {
1139
+ if (c == 1) {
1140
+ return {t1->entry(Y), true};
1141
+ }
1142
+ bool ex;
1143
+ const float v = level(c).lower(Y, &ex);
1144
+ if (ex) {
1145
+ return {v, true};
1146
+ }
1147
+ std::pair<float, uint64_t> m;
1148
+ if (memo[c]->get(Y, m)) {
1149
+ return {m.first, true};
1150
+ }
1151
+ return {v, false};
1152
+ }
1153
+
1154
+ // exact (cost, split) of entry Y of level c
1155
+ std::pair<float, uint64_t> value(int c, uint64_t Y) {
1156
+ if (c == 1) {
1157
+ return {t1->entry(Y), 0};
1158
+ }
1159
+ const OptimalKMeansCompressedLevel& lv = level(c);
1160
+ {
1161
+ const auto b = lv.get_block(Y >> L);
1162
+ const int64_t ix = b->find(uint32_t(Y & mask()));
1163
+ if (ix >= 0) { // (the split is only needed by the backtracking)
1164
+ return {b->e_cost[ix], lv.exact_split(Y >> L, ix)};
1165
+ }
1166
+ }
1167
+ std::pair<float, uint64_t> r;
1168
+ if (memo[c]->get(Y, r)) {
1169
+ return r;
1170
+ }
1171
+ memo[c]->rows++;
1172
+ // large rows use the threads
1173
+ r = row(Y, lv.a, lv.b, popc(Y) >= PAR_BITS);
1174
+ memo[c]->put(Y, r);
1175
+ return r;
1176
+ }
1177
+
1178
+ struct Cand {
1179
+ float c;
1180
+ uint64_t l;
1181
+ };
1182
+
1183
+ // enumerate the candidates l = P | x of row Y (A = level a, B = level b),
1184
+ // x subset of free (low bits of Y), P fixed: fn(cost, l, exact)
1185
+ template <class F>
1186
+ void chunk(uint64_t Y, int a, int b, uint64_t P, uint64_t free, F&& fn) {
1187
+ const uint64_t Ylo = Y & mask();
1188
+ if (popc(Ylo) >= L - 6) { // large: decode both blocks
1189
+ auto A = dense(a, P >> L), B = dense(b, (Y ^ P) >> L);
1190
+ const uint64_t plo = P & mask();
1191
+ for (uint64_t x = 0;;) {
1192
+ const uint64_t la = plo | x, r = Ylo ^ la;
1193
+ const float cv = A->v[la] + B->v[r];
1194
+ const bool ex = (A->ex.empty() || A->ex[la]) &&
1195
+ (B->ex.empty() || B->ex[r]);
1196
+ fn(cv, P | x, ex);
1197
+ if (x == free) {
1198
+ break;
1199
+ }
1200
+ x = (x - free) & free;
1201
+ }
1202
+ } else {
1203
+ for (uint64_t x = 0;;) {
1204
+ const uint64_t l = P | x;
1205
+ auto va = lower(a, l), vb = lower(b, Y ^ l);
1206
+ fn(va.first + vb.first, l, va.second && vb.second);
1207
+ if (x == free) {
1208
+ break;
1209
+ }
1210
+ x = (x - free) & free;
1211
+ }
1212
+ }
1213
+ }
1214
+
1215
+ // the chunks of row Y are the subsets P of Y minus free: the high bits,
1216
+ // plus top low bits when parallel, for enough chunks (of at least
1217
+ // 2^CHUNK_BITS candidates: smaller tasks cost more than they run)
1218
+ uint64_t free_bits(uint64_t Y, bool parallel) const {
1219
+ constexpr int CHUNK_BITS = 12;
1220
+ uint64_t free = Y & mask();
1221
+ if (parallel && nthreads > 1) {
1222
+ int nch = popc(Y >> L);
1223
+ while (nch < 63 && (uint64_t(1) << nch) < uint64_t(8 * nthreads) &&
1224
+ popc(free) > CHUNK_BITS) {
1225
+ free &= ~(uint64_t(1) << (63 - __builtin_clzll(free)));
1226
+ nch++;
1227
+ }
1228
+ }
1229
+ return free;
1230
+ }
1231
+
1232
+ template <class F>
1233
+ void for_chunks(uint64_t Y, uint64_t free, bool parallel, F&& per_chunk) {
1234
+ const uint64_t fixed = Y & ~free;
1235
+ std::vector<uint64_t> ps;
1236
+ for (uint64_t x = 0;;) {
1237
+ ps.push_back(x);
1238
+ if (x == fixed) {
1239
+ break;
1240
+ }
1241
+ x = (x - fixed) & fixed;
1242
+ }
1243
+ auto fn = [&](size_t i) { per_chunk(i, ps[i]); };
1244
+ if (!parallel || ps.size() == 1 || nthreads <= 1) {
1245
+ for (size_t i = 0; i < ps.size(); i++) {
1246
+ fn(i);
1247
+ }
1248
+ } else {
1249
+ parallel_for(ps.size(), fn);
1250
+ }
1251
+ }
1252
+
1253
+ // exact value of candidate cd of row Y, refined one side at a time (the
1254
+ // other stored value is a lower bound); +inf if it cannot beat (pc, pl)
1255
+ float refine(
1256
+ uint64_t Y,
1257
+ int a,
1258
+ int b,
1259
+ const Cand& cd,
1260
+ bool phave,
1261
+ float pc,
1262
+ uint64_t pl) {
1263
+ auto la = lower(a, cd.l), lb = lower(b, Y ^ cd.l);
1264
+ const float va = la.second ? la.first : value(a, cd.l).first;
1265
+ if (phave && !lb.second && !lex_less(va + lb.first, cd.l, pc, pl)) {
1266
+ return F_INF;
1267
+ }
1268
+ const float vb = lb.second ? lb.first : value(b, Y ^ cd.l).first;
1269
+ return va + vb;
1270
+ }
1271
+
1272
+ std::pair<float, uint64_t> row(uint64_t Y, int a, int b, bool parallel) {
1273
+ const uint64_t NONE = ~uint64_t(0);
1274
+ // pass 1: best exact candidate
1275
+ const uint64_t free = free_bits(Y, parallel);
1276
+ const size_t nch = size_t(1) << popc(Y & ~free);
1277
+ std::vector<Cand> best1(nch, Cand{F_INF, NONE});
1278
+ for_chunks(Y, free, parallel, [&](size_t i, uint64_t P) {
1279
+ Cand bc{F_INF, NONE};
1280
+ chunk(Y, a, b, P, free, [&](float cv, uint64_t l, bool ex) {
1281
+ if (ex && lex_less(cv, l, bc.c, bc.l)) {
1282
+ bc = Cand{cv, l};
1283
+ }
1284
+ });
1285
+ best1[i] = bc;
1286
+ });
1287
+ float bc = F_INF;
1288
+ uint64_t bl = NONE;
1289
+ for (auto& cd : best1) {
1290
+ if (lex_less(cd.c, cd.l, bc, bl)) {
1291
+ bc = cd.c;
1292
+ bl = cd.l;
1293
+ }
1294
+ }
1295
+ bool have = bl != NONE;
1296
+ auto cmp = [](const Cand& x, const Cand& y) {
1297
+ return lex_less(x.c, x.l, y.c, y.l);
1298
+ };
1299
+ // next passes: the non-exact candidates below the best value, by
1300
+ // increasing lower bound, at most max_candidates per pass
1301
+ bool lower_set = false;
1302
+ Cand low{0, 0};
1303
+ while (true) {
1304
+ const float bc0 = bc;
1305
+ const uint64_t bl0 = bl;
1306
+ const bool have0 = have;
1307
+ // a chunk that keeps too many candidates is cut at a threshold;
1308
+ // the pass handles the candidates below the smallest threshold
1309
+ // and the next pass starts there
1310
+ std::vector<std::vector<Cand>> parts(nch);
1311
+ const size_t ccap = std::min<size_t>(
1312
+ max_candidates,
1313
+ std::max<size_t>(
1314
+ 4 * max_candidates / nch,
1315
+ std::min<size_t>(32768, max_candidates)));
1316
+ std::vector<Cand> cuts(nch, Cand{F_INF, NONE});
1317
+ std::vector<uint8_t> was_cut(nch, 0);
1318
+ for_chunks(Y, free, parallel, [&](size_t i, uint64_t P) {
1319
+ auto& v = parts[i];
1320
+ chunk(Y, a, b, P, free, [&](float cv, uint64_t l, bool ex) {
1321
+ if (ex || (have0 && !lex_less(cv, l, bc0, bl0)) ||
1322
+ (lower_set && lex_less(cv, l, low.c, low.l)) ||
1323
+ (was_cut[i] &&
1324
+ !lex_less(cv, l, cuts[i].c, cuts[i].l))) {
1325
+ return;
1326
+ }
1327
+ v.push_back(Cand{cv, l});
1328
+ if (v.size() > 2 * ccap) {
1329
+ std::nth_element(
1330
+ v.begin(), v.begin() + ccap, v.end(), cmp);
1331
+ cuts[i] = v[ccap];
1332
+ was_cut[i] = 1;
1333
+ v.resize(ccap);
1334
+ }
1335
+ });
1336
+ });
1337
+ bool truncated = false;
1338
+ Cand thr{F_INF, NONE};
1339
+ for (size_t i = 0; i < nch; i++) {
1340
+ if (was_cut[i] && (!truncated || cmp(cuts[i], thr))) {
1341
+ thr = cuts[i];
1342
+ truncated = true;
1343
+ }
1344
+ }
1345
+ std::vector<Cand> all;
1346
+ for (auto& p : parts) {
1347
+ for (auto& cd : p) {
1348
+ if (!truncated || cmp(cd, thr)) {
1349
+ all.push_back(cd);
1350
+ }
1351
+ }
1352
+ }
1353
+ parts.clear();
1354
+ if (all.size() > max_candidates) {
1355
+ std::nth_element(
1356
+ all.begin(),
1357
+ all.begin() + max_candidates,
1358
+ all.end(),
1359
+ cmp);
1360
+ thr = all[max_candidates];
1361
+ truncated = true;
1362
+ all.resize(max_candidates);
1363
+ }
1364
+ std::sort(all.begin(), all.end(), cmp);
1365
+ auto update = [&](float v, uint64_t l) {
1366
+ if (v != F_INF && (!have || lex_less(v, l, bc, bl))) {
1367
+ bc = v;
1368
+ bl = l;
1369
+ have = true;
1370
+ }
1371
+ };
1372
+ if (!parallel || nthreads <= 1) {
1373
+ for (auto& cd : all) {
1374
+ if (have && !lex_less(cd.c, cd.l, bc, bl)) {
1375
+ break;
1376
+ }
1377
+ update(refine(Y, a, b, cd, have, bc, bl), cd.l);
1378
+ }
1379
+ } else {
1380
+ refine_parallel(Y, a, b, all, have, bc, bl, update);
1381
+ }
1382
+ if (!truncated) {
1383
+ break;
1384
+ }
1385
+ lower_set = true;
1386
+ low = thr;
1387
+ if (have && !lex_less(low.c, low.l, bc, bl)) {
1388
+ break;
1389
+ }
1390
+ }
1391
+ return {bc, bl};
1392
+ }
1393
+
1394
+ // the sorted candidates refined by batches in parallel, against the best
1395
+ // value at the start of the batch
1396
+ template <class U>
1397
+ void refine_parallel(
1398
+ uint64_t Y,
1399
+ int a,
1400
+ int b,
1401
+ const std::vector<Cand>& all,
1402
+ bool& have,
1403
+ float& bc,
1404
+ uint64_t& bl,
1405
+ U& update) {
1406
+ size_t pos = 0, B = size_t(nthreads);
1407
+ // a candidate with a large sub-row is refined alone (its row uses
1408
+ // the threads)
1409
+ auto big = [&](const Cand& cd) {
1410
+ return (popc(cd.l) >= PAR_BITS && !lower(a, cd.l).second) ||
1411
+ (popc(Y ^ cd.l) >= PAR_BITS && !lower(b, Y ^ cd.l).second);
1412
+ };
1413
+ while (pos < all.size()) {
1414
+ if (have && !lex_less(all[pos].c, all[pos].l, bc, bl)) {
1415
+ break;
1416
+ }
1417
+ if (big(all[pos])) {
1418
+ update(refine(Y, a, b, all[pos], have, bc, bl), all[pos].l);
1419
+ pos++;
1420
+ continue;
1421
+ }
1422
+ size_t end = pos;
1423
+ while (end < all.size() && end < pos + B && !big(all[end])) {
1424
+ end++;
1425
+ }
1426
+ // small total work (sum of the sub-row sizes): serially, with
1427
+ // the current best value
1428
+ double work = 0;
1429
+ for (size_t j = pos; j < end; j++) {
1430
+ const Cand& cd = all[j];
1431
+ if (!lower(a, cd.l).second) {
1432
+ work += std::ldexp(1.0, popc(cd.l));
1433
+ }
1434
+ if (!lower(b, Y ^ cd.l).second) {
1435
+ work += std::ldexp(1.0, popc(Y ^ cd.l));
1436
+ }
1437
+ }
1438
+ if (work < double(1 << 17)) {
1439
+ for (; pos < end; pos++) {
1440
+ const Cand& cd = all[pos];
1441
+ if (have && !lex_less(cd.c, cd.l, bc, bl)) {
1442
+ break;
1443
+ }
1444
+ update(refine(Y, a, b, cd, have, bc, bl), cd.l);
1445
+ }
1446
+ continue;
1447
+ }
1448
+ std::vector<float> res(end - pos, F_INF);
1449
+ const bool phave = have;
1450
+ const float pc = bc;
1451
+ const uint64_t pl = bl;
1452
+ auto fn = [&](size_t jj) {
1453
+ const Cand& cd = all[pos + jj];
1454
+ if (phave && !lex_less(cd.c, cd.l, pc, pl)) {
1455
+ return;
1456
+ }
1457
+ res[jj] = refine(Y, a, b, cd, phave, pc, pl);
1458
+ };
1459
+ parallel_for(end - pos, fn);
1460
+ for (size_t j = pos; j < end; j++) {
1461
+ const Cand& cd = all[j];
1462
+ if (have && !lex_less(cd.c, cd.l, bc, bl)) {
1463
+ break;
1464
+ }
1465
+ update(res[j - pos], cd.l);
1466
+ }
1467
+ pos = end;
1468
+ B = std::min<size_t>(B * 2, 16 * size_t(nthreads));
1469
+ }
1470
+ }
1471
+ };
1472
+
1473
+ OptimalKMeansExactEngine::OptimalKMeansExactEngine(
1474
+ const OptimalKMeansCost1* t1,
1475
+ int n,
1476
+ int L,
1477
+ const OptimalKMeansExactEngineParams& params_in)
1478
+ : params(params_in) {
1479
+ FAISS_THROW_IF_NOT(t1 && t1->n == n);
1480
+ FAISS_THROW_IF_NOT_FMT(
1481
+ L >= 1 && L <= n && n <= 40, "n = %d, L = %d out of range", n, L);
1482
+ state = std::make_shared<OptimalKMeansExactEngineState>();
1483
+ OptimalKMeansExactEngineState& s = *state;
1484
+ s.t1 = t1;
1485
+ s.n = n;
1486
+ s.L = L;
1487
+ s.nthreads = params.nthreads > 0 ? params.nthreads : omp_get_max_threads();
1488
+ s.max_candidates = std::max<size_t>(params.max_candidates, 1);
1489
+ s.cache_max = std::max<size_t>(4, params.cache_bytes / ((size_t(5) << L)));
1490
+ }
1491
+
1492
+ OptimalKMeansExactEngine::~OptimalKMeansExactEngine() {}
1493
+
1494
+ void OptimalKMeansExactEngine::add_level(
1495
+ const OptimalKMeansCompressedLevel* level) {
1496
+ FAISS_THROW_IF_NOT(level);
1497
+ FAISS_THROW_IF_NOT_FMT(
1498
+ level->c > 1 && level->c < MAX_LEVEL, "level %d", level->c);
1499
+ FAISS_THROW_IF_NOT(level->n == state->n && level->L == state->L);
1500
+ state->levels[level->c] = level;
1501
+ state->memo[level->c].reset(new Memo());
1502
+ }
1503
+
1504
+ namespace {
1505
+
1506
+ // run fn in a parallel region of nthreads threads, from one thread (the
1507
+ // others run the tasks)
1508
+ template <class F>
1509
+ void run_parallel(int nthreads, F&& fn) {
1510
+ #if defined(_OPENMP) && _OPENMP >= 201511
1511
+ #pragma omp parallel num_threads(nthreads)
1512
+ #pragma omp single
1513
+ fn();
1514
+ #else
1515
+ (void)nthreads;
1516
+ fn();
1517
+ #endif
1518
+ }
1519
+
1520
+ // level c and the levels below it are registered (exceptions cannot leave
1521
+ // the OpenMP tasks)
1522
+ void check_levels(const OptimalKMeansExactEngineState& s, int c) {
1523
+ if (c == 1) {
1524
+ return;
1525
+ }
1526
+ const OptimalKMeansCompressedLevel& lv = s.level(c);
1527
+ check_levels(s, lv.a);
1528
+ check_levels(s, lv.b);
1529
+ }
1530
+
1531
+ } // namespace
1532
+
1533
+ void OptimalKMeansExactEngine::row(
1534
+ uint64_t Y,
1535
+ int a,
1536
+ int b,
1537
+ float* cost,
1538
+ uint64_t* split) {
1539
+ check_levels(*state, a);
1540
+ check_levels(*state, b);
1541
+ FAISS_THROW_IF_NOT((Y >> state->n) == 0);
1542
+ std::pair<float, uint64_t> r;
1543
+ run_parallel(state->nthreads, [&]() { r = state->row(Y, a, b, true); });
1544
+ *cost = r.first;
1545
+ *split = r.second;
1546
+ }
1547
+
1548
+ void OptimalKMeansExactEngine::value(
1549
+ int c,
1550
+ uint64_t Y,
1551
+ float* cost,
1552
+ uint64_t* split) {
1553
+ check_levels(*state, c);
1554
+ FAISS_THROW_IF_NOT((Y >> state->n) == 0);
1555
+ std::pair<float, uint64_t> r;
1556
+ run_parallel(state->nthreads, [&]() { r = state->value(c, Y); });
1557
+ *cost = r.first;
1558
+ *split = r.second;
1559
+ }
1560
+
1561
+ uint64_t OptimalKMeansExactEngine::rows(int c) const {
1562
+ return c > 1 && c < MAX_LEVEL && state->memo[c]
1563
+ ? state->memo[c]->rows.load()
1564
+ : 0;
1565
+ }
1566
+
1567
+ } // namespace faiss