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,1694 @@
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/IndexIVFRaBitQSSD.h>
9
+
10
+ #include <omp.h>
11
+
12
+ #include <algorithm>
13
+ #include <array>
14
+ #include <atomic>
15
+ #include <cinttypes>
16
+ #include <cmath>
17
+ #include <cstring>
18
+ #include <exception>
19
+ #include <limits>
20
+ #include <memory>
21
+ #include <numeric>
22
+ #include <vector>
23
+
24
+ #include <faiss/impl/FaissAssert.h>
25
+ #include <faiss/impl/FaissException.h>
26
+ #include <faiss/impl/IDSelector.h>
27
+ #include <faiss/impl/RaBitQUtils.h>
28
+ #include <faiss/impl/fast_scan/fast_scan.h>
29
+ #include <faiss/impl/platform_macros.h>
30
+ #include <faiss/impl/simd_dispatch.h>
31
+ #include <faiss/invlists/DirectMap.h>
32
+ #include <faiss/invlists/DiskIOBackend.h>
33
+ #include <faiss/invlists/RaBitQSSDInvertedLists.h>
34
+ #include <faiss/utils/AlignedTable.h>
35
+ #include <faiss/utils/distances.h>
36
+ #include <faiss/utils/rabitq_simd.h>
37
+ #include <faiss/utils/utils.h>
38
+
39
+ namespace faiss {
40
+
41
+ /* Distance estimates. For a vector o in a list of center c, with
42
+ * residual r = o - c and sign bits x_u[i] = (r[i] > 0), the RaBitQ estimator
43
+ * of <q - c, r> uses the code vector xb[i] = x_u[i] * 2^ex_bits + ex[i] + cb
44
+ * with cb = -(2^ex_bits - 1/2):
45
+ *
46
+ * <q - c, r> ~ |r|^2 <xb, q - c> / <xb, r>
47
+ *
48
+ * The terms that depend on c are folded into per-vector factors, so that the
49
+ * estimate is affine in <xb, q> and a query needs a single look-up table:
50
+ *
51
+ * dist(q, o) ~ g_add + f_add_ex + f_rescale_ex * <xb, q>
52
+ *
53
+ * L2: dist = |q - o|^2, g_add = |q - c|^2,
54
+ * f_add_ex = |r|^2 - f_rescale_ex * <xb, c>,
55
+ * f_rescale_ex = -2 |r|^2 / <xb, r>
56
+ * IP: dist = -<q, o>, g_add = -<q, c>,
57
+ * f_add_ex = -<r, c> - f_rescale_ex * <xb, c>,
58
+ * f_rescale_ex = -|r|^2 / <xb, r>
59
+ *
60
+ * The in-memory estimate uses the sign bits of dimensions [0, mem_dim) only:
61
+ * with x1 = x_u - 1/2, f_add, f_rescale and <x1, q> replace the above, with
62
+ * <x1, q> and <x1, c> summed over [0, mem_dim), <x1, r> over [0, d), and an
63
+ * extra factor d / mem_dim in f_rescale. Its error is bounded by
64
+ * f_error * |q - c|, with f_error = k * epsilon * |r| / sqrt(mem_dim) (k = 2
65
+ * for L2, 1 for IP, epsilon = 1.9).
66
+ */
67
+
68
+ IndexIVFRaBitQSSDStats indexIVFRaBitQSSD_stats;
69
+
70
+ void IndexIVFRaBitQSSDStats::reset() {
71
+ n_pages_read = 0;
72
+ n_reranked = 0;
73
+ }
74
+
75
+ void IndexIVFRaBitQSSDStats::add(const IndexIVFRaBitQSSDStats& other) {
76
+ n_pages_read += other.n_pages_read;
77
+ n_reranked += other.n_reranked;
78
+ }
79
+
80
+ namespace {
81
+
82
+ using Lists = RaBitQSSDInvertedLists;
83
+
84
+ constexpr size_t kBatchSize = Lists::kBatchSize;
85
+
86
+ /// vectors encoded at once when adding to a list
87
+ constexpr size_t kAddChunk = 4096;
88
+
89
+ /*********************************************************
90
+ * Encoding
91
+ *********************************************************/
92
+
93
+ /// Split the RaBitQuantizer code of one vector into its in-memory part (the
94
+ /// sign bits of [0, mem_dim) and kMemFactors factors) and its file record.
95
+ void split_code(
96
+ const Lists& il,
97
+ MetricType metric,
98
+ const float* x,
99
+ const float* centroid,
100
+ const uint8_t* code,
101
+ idx_t id,
102
+ uint8_t* mem_code,
103
+ float* mem_factors,
104
+ uint8_t* record) {
105
+ const size_t d = il.d;
106
+ const size_t mem_dim = il.mem_dim;
107
+ const size_t ex_bits = il.ex_bits;
108
+ // RaBitQuantizer code layout for nb_bits > 1:
109
+ // [sign bits][SignBitFactorsWithError][ex code][ExtraBitsFactors]
110
+ const uint8_t* sign_bits = code;
111
+ const uint8_t* ex_code =
112
+ code + d / 8 + sizeof(rabitq_utils::SignBitFactorsWithError);
113
+ const double cb = -(double(1 << ex_bits) - 0.5);
114
+
115
+ double r_norm2 = 0, ip_r_c = 0;
116
+ double ip_r_x1 = 0, ip_c_x1_mem = 0; // with the 1-bit code x_u - 1/2
117
+ double ip_r_xb = 0, ip_c_xb = 0; // with the full code xb
118
+ for (size_t i = 0; i < d; i++) {
119
+ const double ci = centroid[i];
120
+ const double r = double(x[i]) - ci;
121
+ const int bit = (sign_bits[i / 8] >> (i % 8)) & 1;
122
+ r_norm2 += r * r;
123
+ ip_r_c += r * ci;
124
+ const double x1 = bit - 0.5;
125
+ ip_r_x1 += r * x1;
126
+ if (i < mem_dim) {
127
+ ip_c_x1_mem += ci * x1;
128
+ }
129
+ const int ex = rabitq_utils::extract_code_inline(ex_code, i, ex_bits);
130
+ const double xb = double((bit << ex_bits) + ex) + cb;
131
+ ip_r_xb += r * xb;
132
+ ip_c_xb += ci * xb;
133
+ }
134
+ const double k = metric == METRIC_L2 ? 2 : 1;
135
+ const double f_base = metric == METRIC_L2 ? r_norm2 : -ip_r_c;
136
+
137
+ // ip_r_x1 = sum |r[i]| / 2, and every term of ip_r_xb has the sign of
138
+ // r[i], so they are 0 only for r = 0
139
+ const double f_rescale =
140
+ ip_r_x1 > 0 ? -k * r_norm2 * (double(d) / mem_dim) / ip_r_x1 : 0;
141
+ mem_factors[0] = float(f_base - f_rescale * ip_c_x1_mem);
142
+ mem_factors[1] = float(f_rescale);
143
+ mem_factors[2] = float(
144
+ k * rabitq_utils::kConstEpsilon * std::sqrt(r_norm2 / mem_dim));
145
+ memcpy(mem_code, sign_bits, mem_dim / 8);
146
+
147
+ // record: [sign bits mem_dim..d) [ex code] [f_add_ex f_rescale_ex] [id]
148
+ uint8_t* p = record;
149
+ memcpy(p, sign_bits + mem_dim / 8, (d - mem_dim) / 8);
150
+ p += (d - mem_dim) / 8;
151
+ memcpy(p, ex_code, d * ex_bits / 8);
152
+ p += d * ex_bits / 8;
153
+ const double f_rescale_ex = ip_r_xb != 0 ? -k * r_norm2 / ip_r_xb : 0;
154
+ rabitq_utils::ExtraBitsFactors ex_factors;
155
+ ex_factors.f_add_ex = float(f_base - f_rescale_ex * ip_c_xb);
156
+ ex_factors.f_rescale_ex = float(f_rescale_ex);
157
+ memcpy(p, &ex_factors, sizeof(ex_factors));
158
+ p += sizeof(ex_factors);
159
+ memcpy(p, &id, sizeof(id));
160
+ }
161
+
162
+ /// Add the vectors x[members[i]] to list list_no, by increasing distance to
163
+ /// the center of the list, ties broken by id.
164
+ void add_to_list(
165
+ const IndexIVFRaBitQSSD& index,
166
+ Lists& il,
167
+ idx_t list_no,
168
+ const idx_t* members,
169
+ size_t n,
170
+ const float* x,
171
+ const idx_t* xids) {
172
+ const size_t d = index.d;
173
+ std::vector<float> centroid(d);
174
+ index.quantizer->reconstruct(list_no, centroid.data());
175
+ if (!index.centroid_scales.empty()) {
176
+ const float s = index.centroid_scales[list_no];
177
+ for (float& v : centroid) {
178
+ v *= s;
179
+ }
180
+ }
181
+
182
+ std::vector<idx_t> ids(n);
183
+ std::vector<double> key(n);
184
+ for (size_t i = 0; i < n; i++) {
185
+ const idx_t j = members[i];
186
+ ids[i] = xids ? xids[j] : index.ntotal + j;
187
+ const float* xj = x + j * d;
188
+ double acc = 0;
189
+ for (size_t t = 0; t < d; t++) {
190
+ if (index.metric_type == METRIC_L2) {
191
+ const double diff = double(xj[t]) - double(centroid[t]);
192
+ acc += diff * diff;
193
+ } else {
194
+ acc -= double(xj[t]) * double(centroid[t]);
195
+ }
196
+ }
197
+ key[i] = acc;
198
+ }
199
+ std::vector<size_t> order(n);
200
+ std::iota(order.begin(), order.end(), 0);
201
+ std::stable_sort(order.begin(), order.end(), [&](size_t a, size_t b) {
202
+ const bool a_nan = std::isnan(key[a]);
203
+ const bool b_nan = std::isnan(key[b]);
204
+ if (a_nan != b_nan) {
205
+ return !a_nan;
206
+ }
207
+ if (key[a] < key[b]) {
208
+ return true;
209
+ }
210
+ if (key[a] > key[b]) {
211
+ return false;
212
+ }
213
+ return ids[a] < ids[b];
214
+ });
215
+
216
+ il.reserve(list_no, n);
217
+ const size_t chunk = std::min(n, kAddChunk);
218
+ const size_t code_size = index.rabitq.code_size;
219
+ std::vector<float> xbuf(chunk * d);
220
+ std::vector<uint8_t> codes(chunk * code_size);
221
+ std::vector<uint8_t> mem_codes(chunk * il.mem_dim / 8);
222
+ std::vector<float> mem_factors(chunk * Lists::kMemFactors);
223
+ std::vector<uint8_t> records(chunk * il.record_size);
224
+
225
+ for (size_t i0 = 0; i0 < n; i0 += chunk) {
226
+ const size_t i1 = std::min(n, i0 + chunk);
227
+ for (size_t i = i0; i < i1; i++) {
228
+ memcpy(xbuf.data() + (i - i0) * d,
229
+ x + members[order[i]] * d,
230
+ sizeof(float) * d);
231
+ }
232
+ index.rabitq.compute_codes_core(
233
+ xbuf.data(), codes.data(), i1 - i0, centroid.data());
234
+ for (size_t i = i0; i < i1; i++) {
235
+ const size_t j = i - i0;
236
+ split_code(
237
+ il,
238
+ index.metric_type,
239
+ xbuf.data() + j * d,
240
+ centroid.data(),
241
+ codes.data() + j * code_size,
242
+ ids[order[i]],
243
+ mem_codes.data() + j * il.mem_dim / 8,
244
+ mem_factors.data() + j * Lists::kMemFactors,
245
+ records.data() + j * il.record_size);
246
+ }
247
+ il.append(
248
+ list_no,
249
+ i1 - i0,
250
+ mem_codes.data(),
251
+ mem_factors.data(),
252
+ records.data());
253
+ }
254
+ }
255
+
256
+ /*********************************************************
257
+ * Search
258
+ *********************************************************/
259
+
260
+ /// The k best results so far, sorted by increasing distance, so that
261
+ /// pruning_threshold reads the drain_alpha-quantile in O(1) at each read
262
+ /// decision of the drain. Against a heap of utils/Heap.h (vench, wiki-10M,
263
+ /// k = 10 to 1000): the same QPS, as the reads bound the search, and the same
264
+ /// CPU time up to k = 100. At k = 1000 the heap took up to 25% fewer cycles
265
+ /// with drain_alpha = 1 and up to 52% more with drain_alpha = 0.4, where it
266
+ /// recomputes the quantile after each change.
267
+ struct TopKBuffer {
268
+ struct Entry {
269
+ float distance;
270
+ idx_t id;
271
+ };
272
+ std::vector<Entry> data; // capacity + 1 entries
273
+ size_t size = 0;
274
+ size_t capacity = 0;
275
+
276
+ void reset(size_t k) {
277
+ capacity = k;
278
+ size = 0;
279
+ data.resize(k + 1);
280
+ }
281
+
282
+ bool is_full() const {
283
+ return size == capacity;
284
+ }
285
+
286
+ float top_dist() const {
287
+ return is_full() ? data[size - 1].distance
288
+ : std::numeric_limits<float>::max();
289
+ }
290
+
291
+ void insert(idx_t id, float dist) {
292
+ if (dist > top_dist()) {
293
+ return;
294
+ }
295
+ // before the entries with the same distance
296
+ const size_t lo = std::lower_bound(
297
+ data.begin(),
298
+ data.begin() + size,
299
+ dist,
300
+ [](const Entry& e, float v) {
301
+ return e.distance < v;
302
+ }) -
303
+ data.begin();
304
+ memmove(&data[lo + 1], &data[lo], (size - lo) * sizeof(Entry));
305
+ data[lo] = Entry{dist, id};
306
+ size += size < capacity;
307
+ }
308
+ };
309
+
310
+ /// The pruning threshold: the alpha-quantile of the results, e.g. the 90th
311
+ /// distance for k = 100 and alpha = 0.9. With alpha >= 1, or until there are
312
+ /// k results, the k-th distance.
313
+ float pruning_threshold(const TopKBuffer& results, float alpha) {
314
+ if (alpha >= 1.0f || !results.is_full()) {
315
+ return results.top_dist();
316
+ }
317
+ const long topk = long(results.capacity);
318
+ long rank = std::lround(alpha * double(topk));
319
+ rank = std::min(std::max(rank, 1L), topk);
320
+ return results.data[rank - 1].distance;
321
+ }
322
+
323
+ /// Per query: the look-up table of the in-memory scan, and sums of the query
324
+ /// components.
325
+ struct QueryLUT {
326
+ /// packed for FastScan; with 16-bit entries, the low bytes of the
327
+ /// table, then the high bytes (as expected by accumulate_hacc)
328
+ std::vector<uint8_t> table;
329
+ /// <x_u, q> over [0, mem_dim) = delta * (sum of entries) + sum_vl
330
+ float delta = 0;
331
+ float sum_vl = 0;
332
+ float k1xsumq = 0; ///< -1/2 sum of q over [0, mem_dim)
333
+ float q_sum = 0; ///< sum of q over [0, d)
334
+
335
+ void build(const float* q, size_t mem_dim, size_t d, bool use_hacc) {
336
+ const size_t nsq = mem_dim / 4;
337
+ // entry c of table t: the sum of q over the dimensions 4t..4t+3
338
+ // whose bit is set in c
339
+ std::vector<float> lut_float(nsq * 16);
340
+ for (size_t t = 0; t < nsq; t++) {
341
+ rabitq_utils::write_subset_sum_lut(
342
+ lut_float.data() + t * 16,
343
+ 0.0f,
344
+ q[4 * t],
345
+ q[4 * t + 1],
346
+ q[4 * t + 2],
347
+ q[4 * t + 3]);
348
+ }
349
+ const auto [vl_it, vr_it] =
350
+ std::minmax_element(lut_float.begin(), lut_float.end());
351
+ const float vl = *vl_it, vr = *vr_it;
352
+ const uint32_t max_entry = use_hacc ? 65535 : 255;
353
+ delta = (vr - vl) / max_entry;
354
+ if (delta == 0) { // all entries equal: they quantize to 0
355
+ delta = 1;
356
+ }
357
+ const float one_over_delta = 1.0f / delta;
358
+ std::vector<uint8_t> lo(nsq * 16), hi(use_hacc ? nsq * 16 : 0);
359
+ for (size_t i = 0; i < nsq * 16; i++) {
360
+ const long e = std::lrint((lut_float[i] - vl) * one_over_delta);
361
+ const uint32_t entry =
362
+ uint32_t(std::min(std::max(e, 0L), long(max_entry)));
363
+ lo[i] = entry & 0xff;
364
+ if (use_hacc) {
365
+ hi[i] = entry >> 8;
366
+ }
367
+ }
368
+ table.resize((use_hacc ? 2 : 1) * nsq * 16);
369
+ pq4_pack_LUT(1, nsq, lo.data(), table.data());
370
+ if (use_hacc) {
371
+ pq4_pack_LUT(1, nsq, hi.data(), table.data() + nsq * 16);
372
+ }
373
+ sum_vl = vl * float(nsq);
374
+
375
+ float q_sum_mem = 0;
376
+ for (size_t i = 0; i < mem_dim; i++) {
377
+ q_sum_mem += q[i];
378
+ }
379
+ k1xsumq = -0.5f * q_sum_mem;
380
+ q_sum = q_sum_mem;
381
+ for (size_t i = mem_dim; i < d; i++) {
382
+ q_sum += q[i];
383
+ }
384
+ }
385
+ };
386
+
387
+ /// a vector to re-rank, in a page to read
388
+ struct Candidate {
389
+ size_t offset; ///< in its list
390
+ int in_page_idx; ///< record number in the page
391
+ float mem_low_dist;
392
+ float mem_est_dist;
393
+ float mem_ip_x0_qr; ///< <x_u, q> over [0, mem_dim)
394
+ };
395
+
396
+ /// a page to read, with its candidates
397
+ struct CandidatePage {
398
+ float page_lower_bound = 0; ///< smallest lower bound of its candidates
399
+ size_t probe_idx = 0;
400
+ size_t page_no = 0; ///< in its list
401
+ uint16_t candidate_num = 0;
402
+ };
403
+
404
+ using SlotID = uint32_t;
405
+ constexpr SlotID kSlotMax = std::numeric_limits<SlotID>::max();
406
+
407
+ /// The pages waiting to be read, sorted by lower bound.
408
+ struct PendingPages {
409
+ struct Entry {
410
+ SlotID slot_id;
411
+ float key;
412
+ };
413
+ std::vector<Entry> entries;
414
+ size_t head = 0;
415
+
416
+ void reset() {
417
+ entries.clear();
418
+ head = 0;
419
+ }
420
+
421
+ bool empty() const {
422
+ return size() == 0;
423
+ }
424
+
425
+ size_t size() const {
426
+ return entries.size() - head;
427
+ }
428
+
429
+ void insert(SlotID slot_id, float key) {
430
+ compact_if_needed();
431
+ const auto it = std::lower_bound(
432
+ entries.begin() + head,
433
+ entries.end(),
434
+ key,
435
+ [](const Entry& e, float value) { return e.key < value; });
436
+ entries.insert(it, Entry{slot_id, key});
437
+ }
438
+
439
+ SlotID front_slot() const {
440
+ return entries[head].slot_id;
441
+ }
442
+
443
+ void pop_front() {
444
+ ++head;
445
+ compact_if_needed();
446
+ }
447
+
448
+ /// remove the entries with a key above threshold, appending them to pruned
449
+ void prune_greater(float threshold, std::vector<SlotID>& pruned) {
450
+ const auto it = std::upper_bound(
451
+ entries.begin() + head,
452
+ entries.end(),
453
+ threshold,
454
+ [](float value, const Entry& e) { return value < e.key; });
455
+ for (auto cur = it; cur != entries.end(); ++cur) {
456
+ pruned.push_back(cur->slot_id);
457
+ }
458
+ entries.erase(it, entries.end());
459
+ if (head == entries.size()) {
460
+ entries.clear();
461
+ head = 0;
462
+ return;
463
+ }
464
+ compact_if_needed();
465
+ }
466
+
467
+ void compact_if_needed() {
468
+ if (head >= 256 && head * 2 >= entries.size()) {
469
+ entries.erase(entries.begin(), entries.begin() + head);
470
+ head = 0;
471
+ }
472
+ }
473
+ };
474
+
475
+ /// Scan position in the list being scanned. A page can span several batches.
476
+ struct ListScanState {
477
+ int64_t last_page = -1;
478
+ SlotID cur_page_slot_id = kSlotMax;
479
+ int64_t cur_inner_pid = -1;
480
+ size_t cur_page = 0;
481
+ int in_page_idx = 0;
482
+ int remaining_in_page = 0;
483
+ const uint8_t* mem_data = nullptr;
484
+ };
485
+
486
+ /// Per-thread search state. Each query is searched by
487
+ /// search_one().
488
+ template <SIMDLevel SL>
489
+ struct RaBitQSSDSearcher {
490
+ static constexpr size_t kMaxReadsInFlight =
491
+ IndexIVFRaBitQSSD::kMaxReadsInFlight;
492
+ static constexpr size_t kInitialPageSlots = kMaxReadsInFlight + 1;
493
+
494
+ const IndexIVFRaBitQSSD& index;
495
+ const Lists& il;
496
+ const size_t d, mem_dim, ex_bits;
497
+ const bool is_ip; // metric of the index
498
+ const bool coarse_is_ip; // metric of the coarse distances
499
+ const bool has_scales; // centroid_scales is set
500
+ const bool use_hacc;
501
+ const float drain_alpha;
502
+ const size_t qd_cap;
503
+ const IDSelector* sel;
504
+ const bool store_pairs;
505
+ const int fd;
506
+ const float cb; // -(2^ex_bits - 1/2)
507
+ const size_t suffix_bytes;
508
+
509
+ // query
510
+ const float* q = nullptr;
511
+ QueryLUT lut;
512
+ std::vector<float> g_adds, g_errors; // per probe
513
+ std::vector<idx_t> probe_lists; // per probe
514
+ std::vector<float> centroid; // see set_list_terms
515
+ TopKBuffer results;
516
+
517
+ // estimates of one batch
518
+ int32_t accu_arr[kBatchSize];
519
+ uint16_t accu16[kBatchSize];
520
+ float est_distance[kBatchSize];
521
+ float low_distance[kBatchSize];
522
+ float ip_x0_qr[kBatchSize];
523
+
524
+ // pages to read, with their candidates
525
+ size_t page_candidate_capacity;
526
+ std::vector<CandidatePage> page_slots;
527
+ std::vector<Candidate> candidate_storage;
528
+ std::vector<SlotID> free_page_slots;
529
+
530
+ // read requests, one buffer of page_size bytes each
531
+ struct ReadRequest {
532
+ size_t offset = 0;
533
+ size_t len = 0;
534
+ uint8_t* buf = nullptr;
535
+ };
536
+ AlignedTableTightAlloc<uint8_t, 4096> read_buffers;
537
+ std::array<ReadRequest, kMaxReadsInFlight> requests;
538
+ std::array<SlotID, kMaxReadsInFlight> req_slot_owner;
539
+ std::vector<int> free_req_slots;
540
+ std::vector<SlotID> completed_slots;
541
+
542
+ // I/O queue
543
+ PendingPages pending;
544
+ /// 1 from the submission of a page slot's read to its completion
545
+ std::vector<uint8_t> slot_inflight;
546
+ std::vector<int> slot_req_slot;
547
+ size_t inflight_count = 0;
548
+ std::vector<SlotID> pruned_slots;
549
+ std::array<void*, kMaxReadsInFlight> io_ud;
550
+ std::array<long, kMaxReadsInFlight> io_res;
551
+ std::unique_ptr<DiskIOBackend> io;
552
+
553
+ // statistics
554
+ size_t n_lists = 0, n_codes = 0, n_knn_inserts = 0;
555
+ IndexIVFRaBitQSSDStats disk_stats;
556
+
557
+ RaBitQSSDSearcher(
558
+ const IndexIVFRaBitQSSD& index_in,
559
+ const Lists& il_in,
560
+ bool use_hacc_in,
561
+ float drain_alpha_in,
562
+ size_t qd_in,
563
+ const IDSelector* sel_in,
564
+ bool store_pairs_in)
565
+ : index(index_in),
566
+ il(il_in),
567
+ d(il_in.d),
568
+ mem_dim(il_in.mem_dim),
569
+ ex_bits(il_in.ex_bits),
570
+ is_ip(index_in.metric_type == METRIC_INNER_PRODUCT),
571
+ coarse_is_ip(
572
+ index_in.quantizer->metric_type == METRIC_INNER_PRODUCT),
573
+ has_scales(!index_in.centroid_scales.empty()),
574
+ use_hacc(use_hacc_in),
575
+ drain_alpha(drain_alpha_in),
576
+ qd_cap(qd_in),
577
+ sel(sel_in),
578
+ store_pairs(store_pairs_in),
579
+ fd(il_in.fd),
580
+ cb(-(float(1 << il_in.ex_bits) - 0.5f)),
581
+ suffix_bytes((il_in.d - il_in.mem_dim) / 8),
582
+ page_candidate_capacity(il_in.records_per_page),
583
+ read_buffers(qd_in * il_in.page_size) {
584
+ FAISS_THROW_IF_MSG(
585
+ fd < 0, "RaBitQSSDInvertedLists: the file is not open");
586
+ io = il_in.acquire_io(int(qd_in));
587
+ if (has_scales && !coarse_is_ip) {
588
+ centroid.resize(d);
589
+ }
590
+ reserve_page_slots(kInitialPageSlots);
591
+ reset();
592
+ }
593
+
594
+ ~RaBitQSSDSearcher() {
595
+ // after an exception, reads can still be in flight into
596
+ // read_buffers: wait for them before the buffers are freed, and
597
+ // give the context back for the next searches. If waiting fails, the
598
+ // destructor of the context waits instead.
599
+ if (io && io->wait_all()) {
600
+ il.release_io(std::move(io));
601
+ }
602
+ io.reset();
603
+ }
604
+
605
+ /*********** page slots and read requests ***********/
606
+
607
+ void reserve_page_slots(size_t target_slots) {
608
+ if (page_slots.size() >= target_slots) {
609
+ return;
610
+ }
611
+ const size_t old_size = page_slots.size();
612
+ page_slots.resize(target_slots);
613
+ candidate_storage.resize(target_slots * page_candidate_capacity);
614
+ for (size_t i = target_slots; i > old_size; --i) {
615
+ free_page_slots.push_back(SlotID(i - 1));
616
+ }
617
+ slot_inflight.resize(target_slots, 0);
618
+ slot_req_slot.resize(target_slots, -1);
619
+ }
620
+
621
+ void reset() {
622
+ free_page_slots.clear();
623
+ for (size_t i = page_slots.size(); i > 0; --i) {
624
+ page_slots[i - 1] = CandidatePage();
625
+ free_page_slots.push_back(SlotID(i - 1));
626
+ }
627
+ free_req_slots.clear();
628
+ completed_slots.clear();
629
+ for (int req_slot = int(qd_cap); req_slot > 0; --req_slot) {
630
+ requests[req_slot - 1] = ReadRequest();
631
+ req_slot_owner[req_slot - 1] = kSlotMax;
632
+ free_req_slots.push_back(req_slot - 1);
633
+ }
634
+ pending.reset();
635
+ inflight_count = 0;
636
+ std::fill(slot_inflight.begin(), slot_inflight.end(), 0);
637
+ std::fill(slot_req_slot.begin(), slot_req_slot.end(), -1);
638
+ }
639
+
640
+ uint8_t* read_buffer(int req_slot) {
641
+ return read_buffers.get() + size_t(req_slot) * il.page_size;
642
+ }
643
+
644
+ Candidate* page_candidates(SlotID slot_id) {
645
+ return candidate_storage.data() +
646
+ size_t(slot_id) * page_candidate_capacity;
647
+ }
648
+
649
+ /*********** pending pages and reads ***********/
650
+
651
+ bool reads_done() const {
652
+ return pending.empty() && inflight_count == 0;
653
+ }
654
+
655
+ SlotID acquire_page_slot() {
656
+ if (free_page_slots.empty()) {
657
+ const size_t old_size = page_slots.size();
658
+ reserve_page_slots(
659
+ old_size + std::max(old_size, kInitialPageSlots));
660
+ }
661
+ const SlotID slot_id = free_page_slots.back();
662
+ free_page_slots.pop_back();
663
+ page_slots[slot_id] = CandidatePage();
664
+ return slot_id;
665
+ }
666
+
667
+ void release_page_slot(SlotID slot_id) {
668
+ page_slots[slot_id] = CandidatePage();
669
+ slot_inflight[slot_id] = 0;
670
+ slot_req_slot[slot_id] = -1;
671
+ free_page_slots.push_back(slot_id);
672
+ }
673
+
674
+ void prune_pending(float threshold) {
675
+ if (pending.empty()) {
676
+ return;
677
+ }
678
+ pruned_slots.clear();
679
+ pending.prune_greater(threshold, pruned_slots);
680
+ for (SlotID slot_id : pruned_slots) {
681
+ release_page_slot(slot_id);
682
+ }
683
+ }
684
+
685
+ void enqueue_page(SlotID slot_id) {
686
+ pending.insert(slot_id, page_slots[slot_id].page_lower_bound);
687
+ }
688
+
689
+ void prepare_read(SlotID slot_id, int req_slot) {
690
+ CandidatePage& cand = page_slots[slot_id];
691
+ requests[req_slot] = ReadRequest{
692
+ il.page_offset(probe_lists[cand.probe_idx], cand.page_no),
693
+ il.page_size,
694
+ read_buffer(req_slot)};
695
+ req_slot_owner[req_slot] = slot_id;
696
+ slot_req_slot[slot_id] = req_slot;
697
+ }
698
+
699
+ /// submit up to budget pending pages, smallest lower bound first, after
700
+ /// dropping the pending pages whose lower bound exceeds threshold
701
+ void submit_reads(size_t budget, float threshold) {
702
+ if (budget == 0 || pending.empty()) {
703
+ return;
704
+ }
705
+ prune_pending(threshold);
706
+ int submitted = 0;
707
+ while (budget > 0 && !pending.empty() && !free_req_slots.empty()) {
708
+ const SlotID slot_id = pending.front_slot();
709
+ pending.pop_front();
710
+ const int req_slot = free_req_slots.back();
711
+ free_req_slots.pop_back();
712
+ prepare_read(slot_id, req_slot);
713
+ ReadRequest& req = requests[req_slot];
714
+ io->stage(fd, req.buf, req.len, req.offset, &req);
715
+ slot_inflight[slot_id] = 1;
716
+ inflight_count++;
717
+ submitted++;
718
+ disk_stats.n_pages_read++;
719
+ --budget;
720
+ }
721
+ if (submitted > 0) {
722
+ io->submit();
723
+ }
724
+ }
725
+
726
+ /// collect the completed reads into completed_slots, waiting for at
727
+ /// least min_nr of them
728
+ void poll_reads(int min_nr = 0) {
729
+ completed_slots.clear();
730
+ if (inflight_count == 0) {
731
+ return;
732
+ }
733
+ const int ret =
734
+ io->reap(io_ud.data(), io_res.data(), int(qd_cap), min_nr);
735
+ for (int i = 0; i < ret; ++i) {
736
+ // re-ranking the stale bytes of a failed or short read would
737
+ // silently return wrong results
738
+ FAISS_THROW_IF_NOT_FMT(
739
+ io_res[i] >= 0,
740
+ "read of %s failed: %s",
741
+ il.filename.c_str(),
742
+ strerror(-io_res[i]));
743
+ const ReadRequest* req = static_cast<const ReadRequest*>(io_ud[i]);
744
+ FAISS_THROW_IF_NOT_FMT(
745
+ size_t(io_res[i]) == req->len,
746
+ "short read of %s at offset %zu: %ld of %zu bytes",
747
+ il.filename.c_str(),
748
+ req->offset,
749
+ io_res[i],
750
+ req->len);
751
+ const int req_slot = int(req - requests.data());
752
+ const SlotID slot_id = req_slot_owner[req_slot];
753
+ if (slot_id == kSlotMax || !slot_inflight[slot_id]) {
754
+ continue;
755
+ }
756
+ slot_inflight[slot_id] = 0;
757
+ inflight_count--;
758
+ completed_slots.push_back(slot_id);
759
+ }
760
+ }
761
+
762
+ void release_read(SlotID slot_id) {
763
+ const int req_slot = slot_req_slot[slot_id];
764
+ if (req_slot != -1) {
765
+ requests[req_slot] = ReadRequest();
766
+ req_slot_owner[req_slot] = kSlotMax;
767
+ free_req_slots.push_back(req_slot);
768
+ }
769
+ release_page_slot(slot_id);
770
+ }
771
+
772
+ /*********** scan and re-rank ***********/
773
+
774
+ /// FastScan over the in-memory bits of one batch of a list
775
+ void estimate_batch(const uint8_t* batch, size_t probe_idx) {
776
+ const size_t nsq = mem_dim / 4;
777
+ if (use_hacc) {
778
+ // Reuse the search's SIMD level, with compile-time fallback.
779
+ dispatch_with_fallback<FAST_SCAN_HACC_SIMD_LEVELS, SL>(
780
+ [&]<SIMDLevel AccSL>() {
781
+ accumulate_hacc_impl<AccSL>(
782
+ 1,
783
+ kBatchSize,
784
+ nsq,
785
+ batch,
786
+ lut.table.data(),
787
+ accu_arr);
788
+ });
789
+ } else {
790
+ // a segment of D dimensions sums D / 4 entries of at most 255
791
+ // into a uint16, so (D / 4) * 255 must stay below 2^16
792
+ constexpr size_t kNoHaccSegmentSq = 256;
793
+ std::fill(accu_arr, accu_arr + kBatchSize, 0);
794
+ dispatch_with_fallback<AVAILABLE_SIMD_LEVELS_BASE, SL>(
795
+ [&]<SIMDLevel AccSL>() {
796
+ for (size_t sq0 = 0; sq0 < nsq;
797
+ sq0 += kNoHaccSegmentSq) {
798
+ const size_t nsq_s =
799
+ std::min(kNoHaccSegmentSq, nsq - sq0);
800
+ accumulate_to_mem_impl<AccSL>(
801
+ 1,
802
+ kBatchSize,
803
+ int(nsq_s),
804
+ batch + 16 * sq0,
805
+ lut.table.data() + 16 * sq0,
806
+ accu16);
807
+ for (size_t i = 0; i < kBatchSize; ++i) {
808
+ accu_arr[i] += accu16[i];
809
+ }
810
+ }
811
+ });
812
+ }
813
+
814
+ const float* f_add = reinterpret_cast<const float*>(
815
+ batch + kBatchSize * mem_dim / 8);
816
+ const float* f_rescale = f_add + kBatchSize;
817
+ const float* f_error = f_rescale + kBatchSize;
818
+ const float g_add = g_adds[probe_idx];
819
+ const float g_error = g_errors[probe_idx];
820
+ for (size_t i = 0; i < kBatchSize; ++i) {
821
+ ip_x0_qr[i] = lut.delta * float(accu_arr[i]) + lut.sum_vl;
822
+ est_distance[i] = f_add[i] + g_add +
823
+ f_rescale[i] * (ip_x0_qr[i] + lut.k1xsumq);
824
+ low_distance[i] = est_distance[i] - f_error[i] * g_error;
825
+ }
826
+ }
827
+
828
+ /// scan batch iter of a list of n vectors: the vectors whose lower bound
829
+ /// does not exceed threshold become candidates of their page, and each page
830
+ /// is queued once the scan has moved past it
831
+ void scan_batch(
832
+ size_t n,
833
+ size_t probe_idx,
834
+ float threshold,
835
+ ListScanState& state,
836
+ size_t iter) {
837
+ const size_t batch_size = std::min(kBatchSize, n - iter * kBatchSize);
838
+ estimate_batch(state.mem_data, probe_idx);
839
+
840
+ for (size_t idx = 0; idx < batch_size; ++idx) {
841
+ ++state.cur_inner_pid;
842
+ if (state.remaining_in_page == 0) {
843
+ state.cur_page += 1;
844
+ state.remaining_in_page = int(il.records_per_page);
845
+ state.in_page_idx = 0;
846
+ }
847
+ const size_t cur_page_id = state.cur_page;
848
+ const int cur_in_page_idx = state.in_page_idx;
849
+ --state.remaining_in_page;
850
+ ++state.in_page_idx;
851
+
852
+ if (low_distance[idx] > threshold) {
853
+ continue;
854
+ }
855
+
856
+ if (int64_t(cur_page_id) != state.last_page) {
857
+ if (state.last_page != -1) {
858
+ enqueue_page(state.cur_page_slot_id);
859
+ }
860
+ state.last_page = cur_page_id;
861
+ state.cur_page_slot_id = acquire_page_slot();
862
+ CandidatePage& page_cand = page_slots[state.cur_page_slot_id];
863
+ page_cand.probe_idx = probe_idx;
864
+ page_cand.page_no = cur_page_id;
865
+ page_cand.candidate_num = 0;
866
+ page_cand.page_lower_bound = low_distance[idx];
867
+ }
868
+
869
+ CandidatePage& page_cand = page_slots[state.cur_page_slot_id];
870
+ Candidate& cand = page_candidates(
871
+ state.cur_page_slot_id)[page_cand.candidate_num++];
872
+ cand.offset = size_t(state.cur_inner_pid);
873
+ cand.in_page_idx = cur_in_page_idx;
874
+ cand.mem_low_dist = low_distance[idx];
875
+ cand.mem_est_dist = est_distance[idx];
876
+ cand.mem_ip_x0_qr = ip_x0_qr[idx];
877
+ page_cand.page_lower_bound =
878
+ std::min(page_cand.page_lower_bound, low_distance[idx]);
879
+ }
880
+ state.mem_data += il.batch_bytes;
881
+ }
882
+
883
+ /// queue the last page of a list
884
+ void finish_list(ListScanState& state) {
885
+ if (state.last_page != -1) {
886
+ enqueue_page(state.cur_page_slot_id);
887
+ }
888
+ }
889
+
890
+ /// re-rank the candidates of a page whose read completed
891
+ void rerank_page(SlotID slot_id) {
892
+ const CandidatePage& page_cand = page_slots[slot_id];
893
+ const uint8_t* data = requests[slot_req_slot[slot_id]].buf;
894
+ const size_t probe_idx = page_cand.probe_idx;
895
+ const idx_t list_no = probe_lists[probe_idx];
896
+ const float g_add = g_adds[probe_idx];
897
+ const Candidate* candidates = page_candidates(slot_id);
898
+
899
+ float threshold = results.top_dist();
900
+ for (size_t cidx = 0; cidx < page_cand.candidate_num; ++cidx) {
901
+ const Candidate& cand = candidates[cidx];
902
+ if (cand.mem_low_dist > threshold) {
903
+ continue;
904
+ }
905
+ const uint8_t* rec = data + cand.in_page_idx * il.record_size;
906
+ idx_t id;
907
+ memcpy(&id, rec + il.record_size - sizeof(idx_t), sizeof(id));
908
+ if (sel && !sel->is_member(id)) {
909
+ continue;
910
+ }
911
+
912
+ float sign_ip = cand.mem_ip_x0_qr;
913
+ if (d > mem_dim) {
914
+ sign_ip += fvec_masked_sum<simd512_level_selector<SL>::value>(
915
+ q + mem_dim, rec, d - mem_dim);
916
+ }
917
+ const float ip = dispatch_with_fallback<
918
+ rabitq::multibit::RABITQ_SPLIT_IP_SIMD_LEVELS,
919
+ SL>([&]<SIMDLevel L>() {
920
+ return rabitq::multibit::compute_inner_product_with_sign_ip<L>(
921
+ rec + suffix_bytes,
922
+ q,
923
+ d,
924
+ ex_bits,
925
+ cb,
926
+ sign_ip,
927
+ lut.q_sum);
928
+ });
929
+ rabitq_utils::ExtraBitsFactors ex_factors;
930
+ memcpy(&ex_factors,
931
+ rec + suffix_bytes + d * ex_bits / 8,
932
+ sizeof(ex_factors));
933
+ const float full_dist =
934
+ ex_factors.f_add_ex + g_add + ex_factors.f_rescale_ex * ip;
935
+ disk_stats.n_reranked++;
936
+
937
+ if (full_dist > threshold) {
938
+ continue;
939
+ }
940
+ const idx_t label =
941
+ store_pairs ? idx_t(lo_build(list_no, cand.offset)) : id;
942
+ results.insert(label, full_dist);
943
+ n_knn_inserts++;
944
+ threshold = results.top_dist();
945
+ }
946
+ release_read(slot_id);
947
+ }
948
+
949
+ /// re-rank the pages read since the last call
950
+ void rerank_read_pages(int min_nr = 0) {
951
+ poll_reads(min_nr);
952
+ for (SlotID slot_id : completed_slots) {
953
+ rerank_page(slot_id);
954
+ }
955
+ }
956
+
957
+ /// <q, c> and |q - c|^2 for the center c of list_no
958
+ void set_list_terms(
959
+ size_t probe_idx,
960
+ idx_t list_no,
961
+ float coarse_dis,
962
+ float q_norm2) {
963
+ float qc_dist2, qc_ip = 0;
964
+ if (has_scales) {
965
+ // the center is s times the centroid u
966
+ const float s = index.centroid_scales[list_no];
967
+ float qu_ip = coarse_dis;
968
+ if (!coarse_is_ip) {
969
+ // not from the L2 coarse distance: s would amplify the
970
+ // rounding error of the difference of two large numbers
971
+ index.quantizer->reconstruct(list_no, centroid.data());
972
+ qu_ip = fvec_inner_product(q, centroid.data(), d);
973
+ }
974
+ qc_ip = s * qu_ip;
975
+ qc_dist2 =
976
+ q_norm2 + s * s * index.centroid_norms[list_no] - 2 * qc_ip;
977
+ } else if (!is_ip && !coarse_is_ip) {
978
+ qc_dist2 = coarse_dis;
979
+ } else {
980
+ const float c_norm2 = index.centroid_norms[list_no];
981
+ if (coarse_is_ip) {
982
+ qc_ip = coarse_dis;
983
+ qc_dist2 = q_norm2 + c_norm2 - 2 * coarse_dis;
984
+ } else {
985
+ qc_dist2 = coarse_dis;
986
+ qc_ip = 0.5f * (q_norm2 + c_norm2 - coarse_dis);
987
+ }
988
+ }
989
+ qc_dist2 = std::max(qc_dist2, 0.0f);
990
+ g_adds[probe_idx] = is_ip ? -qc_ip : qc_dist2;
991
+ g_errors[probe_idx] = std::sqrt(qc_dist2);
992
+ }
993
+
994
+ /// search one query
995
+ void search_one(
996
+ const float* query,
997
+ idx_t k,
998
+ size_t nprobe,
999
+ const idx_t* assign,
1000
+ const float* coarse_dis,
1001
+ float* distances,
1002
+ idx_t* labels) {
1003
+ reset();
1004
+ q = query;
1005
+ results.reset(k);
1006
+ lut.build(q, mem_dim, d, use_hacc);
1007
+ const float q_norm2 = (is_ip || coarse_is_ip || has_scales)
1008
+ ? fvec_norm_L2sqr(q, d)
1009
+ : 0.0f;
1010
+ g_adds.resize(nprobe);
1011
+ g_errors.resize(nprobe);
1012
+ probe_lists.assign(assign, assign + nprobe);
1013
+
1014
+ for (size_t i = 0; i < nprobe; ++i) {
1015
+ const idx_t list_no = assign[i];
1016
+ if (list_no < 0) {
1017
+ continue;
1018
+ }
1019
+ FAISS_THROW_IF_NOT_FMT(
1020
+ list_no < idx_t(index.nlist),
1021
+ "invalid list number %" PRId64,
1022
+ list_no);
1023
+ const size_t n = il.list_size(list_no);
1024
+ if (n == 0) {
1025
+ continue;
1026
+ }
1027
+ n_lists++;
1028
+ n_codes += n;
1029
+ set_list_terms(i, list_no, coarse_dis[i], q_norm2);
1030
+
1031
+ // for each batch: scan it, re-rank the pages read so far and
1032
+ // submit the best pending pages. The search over the lists does
1033
+ // not prune beyond the k-th distance (alpha = 1).
1034
+ const size_t n_iter = (n + kBatchSize - 1) / kBatchSize;
1035
+ ListScanState state;
1036
+ state.remaining_in_page = int(il.records_per_page);
1037
+ state.mem_data = il.mem_data[list_no].get();
1038
+ for (size_t iter = 0; iter < n_iter; ++iter) {
1039
+ scan_batch(n, i, pruning_threshold(results, 1.0f), state, iter);
1040
+ rerank_read_pages();
1041
+ if (inflight_count < qd_cap) {
1042
+ submit_reads(
1043
+ qd_cap - inflight_count,
1044
+ pruning_threshold(results, 1.0f));
1045
+ }
1046
+ }
1047
+ finish_list(state);
1048
+ }
1049
+
1050
+ // drain: read the remaining pages, pruning with the
1051
+ // drain_alpha-quantile of the results. When no page can be
1052
+ // submitted, there is nothing else to do until a read completes, so
1053
+ // wait instead of polling.
1054
+ while (!reads_done()) {
1055
+ rerank_read_pages(
1056
+ pending.empty() || inflight_count >= qd_cap ? 1 : 0);
1057
+ if (inflight_count < qd_cap) {
1058
+ submit_reads(
1059
+ qd_cap - inflight_count,
1060
+ pruning_threshold(results, drain_alpha));
1061
+ }
1062
+ }
1063
+
1064
+ for (size_t j = 0; j < size_t(k); j++) {
1065
+ if (j < results.size) {
1066
+ labels[j] = results.data[j].id;
1067
+ // the search uses -<q, o> for the inner product
1068
+ distances[j] = is_ip ? -results.data[j].distance
1069
+ : results.data[j].distance;
1070
+ } else {
1071
+ labels[j] = -1;
1072
+ distances[j] = is_ip ? std::numeric_limits<float>::lowest()
1073
+ : std::numeric_limits<float>::max();
1074
+ }
1075
+ }
1076
+ }
1077
+ };
1078
+
1079
+ /// settings of one search, from the index and the search parameters
1080
+ struct SearchSettings {
1081
+ size_t nprobe = 0;
1082
+ bool use_hacc = true;
1083
+ float drain_alpha = 1.0f;
1084
+ size_t qd = 0;
1085
+ const IDSelector* sel = nullptr;
1086
+ };
1087
+
1088
+ SearchSettings get_search_settings(
1089
+ const IndexIVFRaBitQSSD& index,
1090
+ const IVFSearchParameters* params,
1091
+ bool store_pairs) {
1092
+ FAISS_THROW_IF_NOT_MSG(index.quantizer, "IVF quantizer must not be null");
1093
+ FAISS_THROW_IF_NOT_MSG(index.is_trained, "IVF index is not trained");
1094
+ SearchSettings s;
1095
+ s.nprobe = std::min(index.nlist, params ? params->nprobe : index.nprobe);
1096
+ FAISS_THROW_IF_NOT(s.nprobe > 0);
1097
+ FAISS_THROW_IF_NOT_MSG(
1098
+ (params ? params->max_codes : index.max_codes) == 0,
1099
+ "IndexIVFRaBitQSSD: max_codes not supported");
1100
+ FAISS_THROW_IF_MSG(
1101
+ params && params->max_lists_num != 0,
1102
+ "IndexIVFRaBitQSSD: max_lists_num not supported");
1103
+ FAISS_THROW_IF_MSG(
1104
+ params && params->ensure_topk_full,
1105
+ "IndexIVFRaBitQSSD: ensure_topk_full not supported");
1106
+ FAISS_THROW_IF_MSG(
1107
+ params && params->max_empty_result_buckets != 0,
1108
+ "IndexIVFRaBitQSSD: max_empty_result_buckets not supported");
1109
+ s.sel = params ? params->sel : nullptr;
1110
+ FAISS_THROW_IF_MSG(
1111
+ s.sel && store_pairs,
1112
+ "selector and store_pairs cannot be combined");
1113
+ s.use_hacc = index.use_hacc;
1114
+ s.drain_alpha = index.drain_alpha;
1115
+ s.qd = index.qd_per_thread;
1116
+ if (auto p = dynamic_cast<const IVFRaBitQSSDSearchParameters*>(params)) {
1117
+ s.use_hacc = p->use_hacc;
1118
+ s.drain_alpha = p->drain_alpha;
1119
+ s.qd = p->qd_per_thread;
1120
+ }
1121
+ FAISS_THROW_IF_NOT_FMT(
1122
+ s.drain_alpha >= 0 && s.drain_alpha <= 1,
1123
+ "drain_alpha=%g must be in [0, 1]",
1124
+ s.drain_alpha);
1125
+ FAISS_THROW_IF_NOT_FMT(
1126
+ s.qd >= 1 && s.qd <= IndexIVFRaBitQSSD::kMaxReadsInFlight,
1127
+ "qd_per_thread=%zu must be in [1, %zu]",
1128
+ s.qd,
1129
+ IndexIVFRaBitQSSD::kMaxReadsInFlight);
1130
+ FAISS_THROW_IF_MSG(
1131
+ index.parallel_mode & index.PARALLEL_MODE_NO_HEAP_INIT,
1132
+ "IndexIVFRaBitQSSD: PARALLEL_MODE_NO_HEAP_INIT not supported");
1133
+ const MetricType coarse_metric = index.quantizer->metric_type;
1134
+ FAISS_THROW_IF_NOT_MSG(
1135
+ coarse_metric == METRIC_L2 || coarse_metric == METRIC_INNER_PRODUCT,
1136
+ "IndexIVFRaBitQSSD: the coarse quantizer must use METRIC_L2 or "
1137
+ "METRIC_INNER_PRODUCT");
1138
+ FAISS_THROW_IF_NOT_MSG(
1139
+ index.centroid_scales.empty() ||
1140
+ index.centroid_scales.size() == index.nlist,
1141
+ "IndexIVFRaBitQSSD: centroid_scales must be empty or have one "
1142
+ "entry per list");
1143
+ // the norms are needed to convert the coarse distances, except for L2
1144
+ // with an L2 quantizer and no scales
1145
+ FAISS_THROW_IF_NOT_MSG(
1146
+ (index.metric_type == METRIC_L2 && coarse_metric == METRIC_L2 &&
1147
+ index.centroid_scales.empty()) ||
1148
+ index.centroid_norms.size() == index.nlist ||
1149
+ index.ntotal == 0,
1150
+ "IndexIVFRaBitQSSD: centroid norms missing, call "
1151
+ "update_centroid_norms()");
1152
+ return s;
1153
+ }
1154
+
1155
+ /** Search n queries. Without assign and centroid_dis, the thread that
1156
+ * searches a query first runs the coarse quantizer on it, so that the coarse
1157
+ * search of one query overlaps the reads of the others. */
1158
+ template <SIMDLevel SL>
1159
+ void search_impl(
1160
+ const IndexIVFRaBitQSSD& index,
1161
+ const Lists& il,
1162
+ idx_t n,
1163
+ const float* x,
1164
+ idx_t k,
1165
+ const idx_t* assign,
1166
+ const float* centroid_dis,
1167
+ const SearchParameters* quantizer_params,
1168
+ float* distances,
1169
+ idx_t* labels,
1170
+ bool store_pairs,
1171
+ const SearchSettings& s,
1172
+ [[maybe_unused]] bool do_parallel,
1173
+ IndexIVFStats* ivf_stats) {
1174
+ if (n == 0) {
1175
+ return;
1176
+ }
1177
+ const size_t nprobe = s.nprobe;
1178
+ size_t nlistv = 0, ndis = 0, nheap = 0, npages = 0, nreranked = 0;
1179
+ double quantization_ms = 0, search_ms = 0;
1180
+ std::exception_ptr ex;
1181
+ std::atomic<bool> interrupt{false};
1182
+
1183
+ auto capture = [&]() {
1184
+ omp_capture_exception(ex, [&] { interrupt = true; });
1185
+ };
1186
+
1187
+ #pragma omp parallel if (do_parallel) \
1188
+ num_threads(int(std::min<idx_t>(n, omp_get_max_threads()))) \
1189
+ reduction(+ : nlistv, ndis, nheap, npages, nreranked) \
1190
+ reduction(+ : quantization_ms, search_ms)
1191
+ {
1192
+ // every thread must reach the omp for, even if its setup fails
1193
+ std::unique_ptr<RaBitQSSDSearcher<SL>> searcher;
1194
+ std::vector<idx_t> q_assign;
1195
+ std::vector<float> q_dis;
1196
+ try {
1197
+ searcher = std::make_unique<RaBitQSSDSearcher<SL>>(
1198
+ index,
1199
+ il,
1200
+ s.use_hacc,
1201
+ s.drain_alpha,
1202
+ s.qd,
1203
+ s.sel,
1204
+ store_pairs);
1205
+ if (!assign) {
1206
+ q_assign.resize(nprobe);
1207
+ q_dis.resize(nprobe);
1208
+ }
1209
+ } catch (...) {
1210
+ capture();
1211
+ }
1212
+
1213
+ #pragma omp for schedule(FAISS_OMP_DYNAMIC, 1)
1214
+ for (idx_t i = 0; i < n; i++) {
1215
+ if (interrupt) {
1216
+ continue;
1217
+ }
1218
+ try {
1219
+ const float* xi = x + i * index.d;
1220
+ if (assign) {
1221
+ searcher->search_one(
1222
+ xi,
1223
+ k,
1224
+ nprobe,
1225
+ assign + i * nprobe,
1226
+ centroid_dis + i * nprobe,
1227
+ distances + i * k,
1228
+ labels + i * k);
1229
+ } else {
1230
+ const double t0 = getmillisecs();
1231
+ index.quantizer->search(
1232
+ 1,
1233
+ xi,
1234
+ nprobe,
1235
+ q_dis.data(),
1236
+ q_assign.data(),
1237
+ quantizer_params);
1238
+ const double t1 = getmillisecs();
1239
+ searcher->search_one(
1240
+ xi,
1241
+ k,
1242
+ nprobe,
1243
+ q_assign.data(),
1244
+ q_dis.data(),
1245
+ distances + i * k,
1246
+ labels + i * k);
1247
+ quantization_ms += t1 - t0;
1248
+ search_ms += getmillisecs() - t0;
1249
+ }
1250
+ } catch (...) {
1251
+ capture();
1252
+ }
1253
+ }
1254
+ if (searcher) {
1255
+ nlistv += searcher->n_lists;
1256
+ ndis += searcher->n_codes;
1257
+ nheap += searcher->n_knn_inserts;
1258
+ npages += searcher->disk_stats.n_pages_read;
1259
+ nreranked += searcher->disk_stats.n_reranked;
1260
+ }
1261
+ }
1262
+ omp_rethrow_if_exception(ex);
1263
+
1264
+ add_search_stats(n, nlistv, ndis, nheap, ivf_stats);
1265
+ add_search_times(quantization_ms, search_ms, ivf_stats);
1266
+ detail::atomic_fetch_add_relaxed(
1267
+ indexIVFRaBitQSSD_stats.n_pages_read, npages);
1268
+ detail::atomic_fetch_add_relaxed(
1269
+ indexIVFRaBitQSSD_stats.n_reranked, nreranked);
1270
+ }
1271
+
1272
+ } // namespace
1273
+
1274
+ /*********************************************************
1275
+ * IndexIVFRaBitQSSD
1276
+ *********************************************************/
1277
+
1278
+ IndexIVFRaBitQSSD::IndexIVFRaBitQSSD(
1279
+ Index* quantizer_in,
1280
+ size_t d_in,
1281
+ size_t nlist_in,
1282
+ size_t mem_dim_in,
1283
+ uint8_t nb_bits,
1284
+ MetricType metric)
1285
+ : IndexIVF(quantizer_in, d_in, nlist_in, 0, metric, false),
1286
+ rabitq(d_in, metric, nb_bits),
1287
+ mem_dim(mem_dim_in) {
1288
+ FAISS_THROW_IF_NOT_FMT(
1289
+ d_in > 0 && d_in % 64 == 0 && d_in < (size_t(1) << 31),
1290
+ "d=%zu must be a positive multiple of 64",
1291
+ d_in);
1292
+ FAISS_THROW_IF_NOT_FMT(
1293
+ mem_dim >= 64 && mem_dim <= d_in && mem_dim % 64 == 0,
1294
+ "mem_dim=%zu must be a multiple of 64 in [64, d=%zu]",
1295
+ mem_dim,
1296
+ d_in);
1297
+ FAISS_THROW_IF_NOT_MSG(
1298
+ metric == METRIC_L2 || metric == METRIC_INNER_PRODUCT,
1299
+ "IndexIVFRaBitQSSD supports METRIC_L2 and "
1300
+ "METRIC_INNER_PRODUCT only");
1301
+ // with nb_bits = 1, either the file holds no code, or the in-memory
1302
+ // estimate has no extra bits to be refined with
1303
+ FAISS_THROW_IF_NOT_FMT(
1304
+ nb_bits >= 2 && nb_bits <= 9,
1305
+ "IndexIVFRaBitQSSD: nb_bits=%d must be in [2, 9]",
1306
+ int(nb_bits));
1307
+ code_size = rabitq.code_size;
1308
+ by_residual = true;
1309
+ if (metric == METRIC_INNER_PRODUCT) {
1310
+ // not trained until train() sets centroid_scales, even if the
1311
+ // quantizer is filled
1312
+ is_trained = false;
1313
+ }
1314
+ }
1315
+
1316
+ IndexIVFRaBitQSSD::IndexIVFRaBitQSSD() {
1317
+ by_residual = true;
1318
+ }
1319
+
1320
+ void IndexIVFRaBitQSSD::attach_file(const char* filename) {
1321
+ // the new file is empty: the vectors of the current lists would be lost
1322
+ FAISS_THROW_IF_MSG(
1323
+ ntotal > 0,
1324
+ "IndexIVFRaBitQSSD: attach_file() needs an empty index");
1325
+ replace_invlists(
1326
+ new RaBitQSSDInvertedLists(
1327
+ nlist, d, mem_dim, rabitq.nb_bits - 1, filename),
1328
+ true);
1329
+ }
1330
+
1331
+ RaBitQSSDInvertedLists* IndexIVFRaBitQSSD::get_ssd_invlists() const {
1332
+ FAISS_THROW_IF_NOT_MSG(
1333
+ invlists,
1334
+ "IndexIVFRaBitQSSD has no inverted lists: call attach_file()");
1335
+ auto* il = dynamic_cast<RaBitQSSDInvertedLists*>(invlists);
1336
+ FAISS_THROW_IF_NOT_MSG(
1337
+ il, "IndexIVFRaBitQSSD needs RaBitQSSDInvertedLists");
1338
+ FAISS_THROW_IF_NOT_MSG(
1339
+ il->d == size_t(d) && il->mem_dim == mem_dim &&
1340
+ il->ex_bits + 1 == rabitq.nb_bits,
1341
+ "IndexIVFRaBitQSSD: the inverted lists do not match the index");
1342
+ return il;
1343
+ }
1344
+
1345
+ void IndexIVFRaBitQSSD::reset() {
1346
+ if (invlists) {
1347
+ IndexIVF::reset();
1348
+ } else {
1349
+ direct_map.clear();
1350
+ ntotal = 0;
1351
+ }
1352
+ centroid_norms.clear();
1353
+ }
1354
+
1355
+ void IndexIVFRaBitQSSD::train_encoder(
1356
+ idx_t n,
1357
+ const float* x,
1358
+ const idx_t* assign) {
1359
+ update_centroid_norms();
1360
+ if (metric_type != METRIC_INNER_PRODUCT || ntotal > 0) {
1361
+ // the codes of a non-empty index are relative to the current centers
1362
+ return;
1363
+ }
1364
+ // x holds o - u, the training vectors minus their centroid u. The
1365
+ // multiple of u closest to the mean of the vectors of a list is s * u,
1366
+ // with s = 1 + <mean of x, u> / |u|^2.
1367
+ FAISS_THROW_IF_NOT_MSG(
1368
+ assign, "IndexIVFRaBitQSSD: by_residual must stay set");
1369
+ FAISS_THROW_IF_NOT_MSG(
1370
+ n > 0,
1371
+ "IndexIVFRaBitQSSD: training vectors are needed to set "
1372
+ "centroid_scales");
1373
+
1374
+ // training vectors of each list
1375
+ std::vector<size_t> list_begin(nlist + 1, 0);
1376
+ for (idx_t i = 0; i < n; i++) {
1377
+ FAISS_THROW_IF_NOT_FMT(
1378
+ assign[i] >= 0 && assign[i] < idx_t(nlist),
1379
+ "invalid list number %" PRId64,
1380
+ assign[i]);
1381
+ list_begin[assign[i] + 1]++;
1382
+ }
1383
+ for (size_t l = 0; l < nlist; l++) {
1384
+ list_begin[l + 1] += list_begin[l];
1385
+ }
1386
+ std::vector<idx_t> order(n);
1387
+ {
1388
+ std::vector<size_t> next(list_begin.begin(), list_begin.end() - 1);
1389
+ for (idx_t i = 0; i < n; i++) {
1390
+ order[next[assign[i]]++] = i;
1391
+ }
1392
+ }
1393
+
1394
+ std::vector<float> scales(nlist, 1.0f);
1395
+ const size_t bs = 4096;
1396
+ std::vector<float> centroids(std::min(nlist, bs) * d);
1397
+ for (size_t l0 = 0; l0 < nlist; l0 += bs) {
1398
+ const size_t l1 = std::min(nlist, l0 + bs);
1399
+ quantizer->reconstruct_n(l0, l1 - l0, centroids.data());
1400
+ #pragma omp parallel for schedule(FAISS_OMP_DYNAMIC)
1401
+ for (int64_t l = l0; l < int64_t(l1); l++) {
1402
+ const size_t n_l = list_begin[l + 1] - list_begin[l];
1403
+ if (n_l == 0 || centroid_norms[l] == 0) {
1404
+ continue;
1405
+ }
1406
+ const float* u = centroids.data() + (l - l0) * d;
1407
+ double ip = 0;
1408
+ for (size_t j = list_begin[l]; j < list_begin[l + 1]; j++) {
1409
+ ip += fvec_inner_product(x + order[j] * d, u, d);
1410
+ }
1411
+ scales[l] = float(1 + ip / (double(n_l) * centroid_norms[l]));
1412
+ }
1413
+ }
1414
+
1415
+ // lists without training vectors: the mean scale of the others
1416
+ double scale_sum = 0;
1417
+ size_t n_empty = 0;
1418
+ for (size_t l = 0; l < nlist; l++) {
1419
+ if (list_begin[l + 1] > list_begin[l]) {
1420
+ scale_sum += scales[l];
1421
+ } else {
1422
+ n_empty++;
1423
+ }
1424
+ }
1425
+ if (n_empty > 0) {
1426
+ const float fill = float(scale_sum / (nlist - n_empty));
1427
+ for (size_t l = 0; l < nlist; l++) {
1428
+ if (list_begin[l + 1] == list_begin[l]) {
1429
+ scales[l] = fill;
1430
+ }
1431
+ }
1432
+ }
1433
+ centroid_scales = std::move(scales);
1434
+ }
1435
+
1436
+ void IndexIVFRaBitQSSD::update_centroid_norms() {
1437
+ std::vector<float> norms(nlist);
1438
+ const size_t bs = 4096;
1439
+ std::vector<float> centroids(std::min(nlist, bs) * d);
1440
+ for (size_t i0 = 0; i0 < nlist; i0 += bs) {
1441
+ const size_t i1 = std::min(nlist, i0 + bs);
1442
+ quantizer->reconstruct_n(i0, i1 - i0, centroids.data());
1443
+ fvec_norms_L2sqr(norms.data() + i0, centroids.data(), d, i1 - i0);
1444
+ }
1445
+ centroid_norms = std::move(norms);
1446
+ }
1447
+
1448
+ void IndexIVFRaBitQSSD::add_core(
1449
+ idx_t n,
1450
+ const float* x,
1451
+ const idx_t* xids,
1452
+ const idx_t* coarse_idx,
1453
+ void* /*inverted_list_context*/) {
1454
+ FAISS_THROW_IF_NOT_MSG(
1455
+ is_trained || metric_type != METRIC_INNER_PRODUCT,
1456
+ "IndexIVFRaBitQSSD: an inner-product index must be trained even "
1457
+ "if its quantizer is filled: train() sets centroid_scales");
1458
+ FAISS_THROW_IF_NOT(is_trained);
1459
+ FAISS_THROW_IF_NOT(coarse_idx);
1460
+ FAISS_THROW_IF_NOT_MSG(quantizer, "IVF quantizer must not be null");
1461
+ FAISS_THROW_IF_NOT_MSG(
1462
+ direct_map.no(), "IndexIVFRaBitQSSD does not support direct maps");
1463
+ RaBitQSSDInvertedLists* il = get_ssd_invlists();
1464
+ FAISS_THROW_IF_NOT_MSG(
1465
+ centroid_scales.size() ==
1466
+ (metric_type == METRIC_INNER_PRODUCT ? nlist : 0),
1467
+ "IndexIVFRaBitQSSD: centroid_scales must have one entry per list "
1468
+ "with METRIC_INNER_PRODUCT and be empty otherwise");
1469
+ if (centroid_norms.size() != nlist) {
1470
+ update_centroid_norms();
1471
+ }
1472
+
1473
+ // vectors of each list, in input order
1474
+ std::vector<size_t> list_begin(nlist + 1, 0);
1475
+ for (idx_t i = 0; i < n; i++) {
1476
+ const idx_t list_no = coarse_idx[i];
1477
+ if (list_no >= 0) {
1478
+ FAISS_THROW_IF_NOT_FMT(
1479
+ list_no < idx_t(nlist),
1480
+ "invalid list number %" PRId64,
1481
+ list_no);
1482
+ list_begin[list_no + 1]++;
1483
+ }
1484
+ }
1485
+ std::vector<idx_t> lists;
1486
+ for (size_t l = 0; l < nlist; l++) {
1487
+ if (list_begin[l + 1] > 0) {
1488
+ lists.push_back(l);
1489
+ }
1490
+ list_begin[l + 1] += list_begin[l];
1491
+ }
1492
+ std::vector<idx_t> members(list_begin[nlist]);
1493
+ {
1494
+ std::vector<size_t> pos(list_begin.begin(), list_begin.end() - 1);
1495
+ for (idx_t i = 0; i < n; i++) {
1496
+ if (coarse_idx[i] >= 0) {
1497
+ members[pos[coarse_idx[i]]++] = i;
1498
+ }
1499
+ }
1500
+ }
1501
+
1502
+ std::exception_ptr ex;
1503
+ std::atomic<bool> interrupt{false};
1504
+ #pragma omp parallel for schedule(FAISS_OMP_DYNAMIC)
1505
+ for (idx_t j = 0; j < idx_t(lists.size()); j++) {
1506
+ if (interrupt) {
1507
+ continue;
1508
+ }
1509
+ const idx_t list_no = lists[j];
1510
+ try {
1511
+ add_to_list(
1512
+ *this,
1513
+ *il,
1514
+ list_no,
1515
+ members.data() + list_begin[list_no],
1516
+ list_begin[list_no + 1] - list_begin[list_no],
1517
+ x,
1518
+ xids);
1519
+ } catch (...) {
1520
+ omp_capture_exception(ex, [&] { interrupt = true; });
1521
+ }
1522
+ }
1523
+ omp_rethrow_if_exception(ex);
1524
+ ntotal += n;
1525
+ }
1526
+
1527
+ void IndexIVFRaBitQSSD::encode_vectors(
1528
+ idx_t,
1529
+ const float*,
1530
+ const idx_t*,
1531
+ uint8_t*,
1532
+ bool) const {
1533
+ FAISS_THROW_MSG("IndexIVFRaBitQSSD: encode_vectors not supported");
1534
+ }
1535
+
1536
+ void IndexIVFRaBitQSSD::search_preassigned(
1537
+ idx_t n,
1538
+ const float* x,
1539
+ idx_t k,
1540
+ const idx_t* assign,
1541
+ const float* centroid_dis,
1542
+ float* distances,
1543
+ idx_t* labels,
1544
+ bool store_pairs,
1545
+ const IVFSearchParameters* params,
1546
+ IndexIVFStats* stats) const {
1547
+ FAISS_THROW_IF_NOT(k > 0);
1548
+ const SearchSettings s = get_search_settings(*this, params, store_pairs);
1549
+ const RaBitQSSDInvertedLists* il = get_ssd_invlists();
1550
+
1551
+ // queries are processed in parallel, unless the caller already does it
1552
+ // (parallel_mode 0, as in IndexIVF::search)
1553
+ const bool do_parallel = omp_get_max_threads() >= 2 && n > 1 &&
1554
+ (parallel_mode & ~PARALLEL_MODE_NO_HEAP_INIT) != 0;
1555
+
1556
+ with_simd_level_with_vpopcnt([&]<SIMDLevel SL>() {
1557
+ search_impl<SL>(
1558
+ *this,
1559
+ *il,
1560
+ n,
1561
+ x,
1562
+ k,
1563
+ assign,
1564
+ centroid_dis,
1565
+ nullptr,
1566
+ distances,
1567
+ labels,
1568
+ store_pairs,
1569
+ s,
1570
+ do_parallel,
1571
+ stats);
1572
+ });
1573
+ }
1574
+
1575
+ void IndexIVFRaBitQSSD::search(
1576
+ idx_t n,
1577
+ const float* x,
1578
+ idx_t k,
1579
+ float* distances,
1580
+ idx_t* labels,
1581
+ const SearchParameters* params_in) const {
1582
+ FAISS_THROW_IF_NOT(k > 0);
1583
+ const IVFSearchParameters* params = nullptr;
1584
+ if (params_in) {
1585
+ params = dynamic_cast<const IVFSearchParameters*>(params_in);
1586
+ FAISS_THROW_IF_NOT_MSG(params, "IndexIVF params have incorrect type");
1587
+ }
1588
+ const SearchSettings s = get_search_settings(*this, params, false);
1589
+ const RaBitQSSDInvertedLists* il = get_ssd_invlists();
1590
+
1591
+ // IndexIVF::search runs the coarse quantizer on all the queries before
1592
+ // searching the lists, which leaves the SSD idle meanwhile. Here each
1593
+ // thread runs it on its own query, while the other threads read.
1594
+ const bool do_parallel = omp_get_max_threads() >= 2 && n > 1;
1595
+
1596
+ with_simd_level_with_vpopcnt([&]<SIMDLevel SL>() {
1597
+ search_impl<SL>(
1598
+ *this,
1599
+ *il,
1600
+ n,
1601
+ x,
1602
+ k,
1603
+ nullptr,
1604
+ nullptr,
1605
+ params ? params->quantizer_params : nullptr,
1606
+ distances,
1607
+ labels,
1608
+ false,
1609
+ s,
1610
+ do_parallel,
1611
+ &indexIVF_stats);
1612
+ });
1613
+ }
1614
+
1615
+ void IndexIVFRaBitQSSD::range_search(
1616
+ idx_t,
1617
+ const float*,
1618
+ float,
1619
+ RangeSearchResult*,
1620
+ const SearchParameters*) const {
1621
+ FAISS_THROW_MSG("IndexIVFRaBitQSSD: range search not supported");
1622
+ }
1623
+
1624
+ void IndexIVFRaBitQSSD::range_search_preassigned(
1625
+ idx_t,
1626
+ const float*,
1627
+ float,
1628
+ const idx_t*,
1629
+ const float*,
1630
+ RangeSearchResult*,
1631
+ bool,
1632
+ const IVFSearchParameters*,
1633
+ IndexIVFStats*) const {
1634
+ FAISS_THROW_MSG("IndexIVFRaBitQSSD: range search not supported");
1635
+ }
1636
+
1637
+ void IndexIVFRaBitQSSD::reconstruct(idx_t, float*) const {
1638
+ // IndexIVF::reconstruct would first ask for a direct map
1639
+ FAISS_THROW_MSG("IndexIVFRaBitQSSD: reconstruct not supported");
1640
+ }
1641
+
1642
+ void IndexIVFRaBitQSSD::reconstruct_n(idx_t, idx_t, float*) const {
1643
+ FAISS_THROW_MSG("IndexIVFRaBitQSSD: reconstruct not supported");
1644
+ }
1645
+
1646
+ void IndexIVFRaBitQSSD::search_and_reconstruct(
1647
+ idx_t,
1648
+ const float*,
1649
+ idx_t,
1650
+ float*,
1651
+ idx_t*,
1652
+ float*,
1653
+ const SearchParameters*) const {
1654
+ FAISS_THROW_MSG("IndexIVFRaBitQSSD: reconstruct not supported");
1655
+ }
1656
+
1657
+ void IndexIVFRaBitQSSD::search_and_return_codes(
1658
+ idx_t,
1659
+ const float*,
1660
+ idx_t,
1661
+ float*,
1662
+ idx_t*,
1663
+ uint8_t*,
1664
+ bool,
1665
+ const SearchParameters*) const {
1666
+ FAISS_THROW_MSG("IndexIVFRaBitQSSD: search_and_return_codes not supported");
1667
+ }
1668
+
1669
+ void IndexIVFRaBitQSSD::reconstruct_from_offset(int64_t, int64_t, float*)
1670
+ const {
1671
+ FAISS_THROW_MSG("IndexIVFRaBitQSSD: reconstruct not supported");
1672
+ }
1673
+
1674
+ size_t IndexIVFRaBitQSSD::remove_ids(const IDSelector&) {
1675
+ FAISS_THROW_MSG("IndexIVFRaBitQSSD: remove_ids not supported");
1676
+ }
1677
+
1678
+ void IndexIVFRaBitQSSD::update_vectors(int, const idx_t*, const float*) {
1679
+ FAISS_THROW_MSG("IndexIVFRaBitQSSD: update_vectors not supported");
1680
+ }
1681
+
1682
+ void IndexIVFRaBitQSSD::merge_from(Index&, idx_t) {
1683
+ FAISS_THROW_MSG("IndexIVFRaBitQSSD: merge_from not supported");
1684
+ }
1685
+
1686
+ void IndexIVFRaBitQSSD::copy_subset_to(
1687
+ IndexIVF&,
1688
+ InvertedLists::subset_type_t,
1689
+ idx_t,
1690
+ idx_t) const {
1691
+ FAISS_THROW_MSG("IndexIVFRaBitQSSD: copy_subset_to not supported");
1692
+ }
1693
+
1694
+ } // namespace faiss