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,288 @@
1
+ /*
2
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
3
+ *
4
+ * This source code is licensed under the MIT license found in the
5
+ * LICENSE file in the root directory of this source tree.
6
+ */
7
+
8
+ #pragma once
9
+
10
+ #include <cstddef>
11
+ #include <cstdint>
12
+ #include <vector>
13
+
14
+ #include <faiss/IndexIVF.h>
15
+ #include <faiss/impl/RaBitQuantizer.h>
16
+
17
+ namespace faiss {
18
+
19
+ struct RaBitQSSDInvertedLists;
20
+
21
+ struct IVFRaBitQSSDSearchParameters : IVFSearchParameters {
22
+ /// overrides IndexIVFRaBitQSSD::use_hacc
23
+ bool use_hacc = true;
24
+ /// overrides IndexIVFRaBitQSSD::drain_alpha
25
+ float drain_alpha = 1.0f;
26
+ /// overrides IndexIVFRaBitQSSD::qd_per_thread
27
+ size_t qd_per_thread = 16;
28
+ };
29
+
30
+ /** IVF index whose RaBitQ codes are split between memory and an SSD
31
+ * (RaBitQ-SSD).
32
+ *
33
+ * Reference: "RaBitQ-SSD: Split Codes and Pipelined I/O for SSD-Resident
34
+ * Vector Search", Yuexuan Xu et al.
35
+ *
36
+ * Vectors are encoded with RaBitQuantizer relative to the center of their
37
+ * list, with nb_bits bits per dimension: a sign bit and nb_bits - 1 extra
38
+ * bits. The sign bits of the first mem_dim dimensions stay in memory; the
39
+ * other sign bits, the extra bits and the vector ids are stored in a file,
40
+ * see RaBitQSSDInvertedLists.
41
+ *
42
+ * The center of a list is its centroid in the coarse quantizer, times
43
+ * centroid_scales[list_no] with METRIC_INNER_PRODUCT. With this metric,
44
+ * IndexIVF trains the quantizer with spherical k-means, so the centroids
45
+ * have norm 1. When the norms of the vectors are far from 1, the residuals
46
+ * to such centroids are large and the error bound is loose. train()
47
+ * therefore sets the scale of each list: its center is the multiple of the
48
+ * centroid closest to the mean of the list's training vectors. The centroids
49
+ * are not rescaled. An inner-product index must be trained even if the
50
+ * caller filled its quantizer.
51
+ *
52
+ * Search. Each search thread takes one query at a time, runs the coarse
53
+ * quantizer on it and scans the probed lists in batches of 32 vectors. For
54
+ * each vector, FastScan over its in-memory bits gives a distance estimate and
55
+ * a lower bound (the RaBitQ error bound). Vectors whose lower bound does not
56
+ * exceed the current k-th distance are grouped by page, and the pages are
57
+ * queued by their smallest lower bound. Between batches, the search re-ranks
58
+ * the pages whose reads completed and submits the most promising queued
59
+ * pages, keeping at most qd_per_thread reads in flight. After the last list,
60
+ * the remaining reads are drained.
61
+ *
62
+ * The distance estimates assume randomly rotated vectors, as for all RaBitQ
63
+ * indexes: use the index inside an IndexPreTransform with
64
+ * HadamardRotation(d, seed, false).
65
+ *
66
+ * The index is created without inverted lists: call attach_file() before
67
+ * adding or searching vectors. index_factory accepts
68
+ * "IVF<nlist>,RaBitQSSD<nb_bits>_<mem_dim>", usually after the rotation:
69
+ * "HRk,IVF<nlist>,RaBitQSSD<nb_bits>_<mem_dim>". Unlike in "RaBitQfs<b>_<n>",
70
+ * the number after the underscore is mem_dim, not a block size.
71
+ *
72
+ * The index works only with RaBitQSSDInvertedLists, whose layout (sign bits
73
+ * in memory, records in pages of a file) is the point of the index. These
74
+ * lists hold no flat codes, so the IVF operations that move codes between
75
+ * inverted lists are not supported: merge_from, copy_subset_to, and the
76
+ * HStack, VStack and Slice inverted-lists wrappers.
77
+ *
78
+ * Not supported either: remove_ids, update_vectors, range search,
79
+ * reconstruction, search_and_return_codes and standalone codes (sa_encode).
80
+ * Search parameters max_codes, max_lists_num, ensure_topk_full and
81
+ * max_empty_result_buckets throw; inverted_list_context is not used.
82
+ * read_index supports IO_FLAG_READ_ONLY and IO_FLAG_ONDISK_SAME_DIR,
83
+ * and rejects IO_FLAG_SKIP_IVF_DATA and IO_FLAG_MMAP.
84
+ */
85
+ struct IndexIVFRaBitQSSD : IndexIVF {
86
+ /// most SSD reads a search thread can have in flight
87
+ static constexpr size_t kMaxReadsInFlight = 200;
88
+
89
+ /// encodes the vectors; its nb_bits is the total number of bits per
90
+ /// dimension, in [2, 9]
91
+ RaBitQuantizer rabitq;
92
+
93
+ /// dimensions whose sign bits stay in memory: a multiple of 64 in [64, d]
94
+ size_t mem_dim = 0;
95
+
96
+ /// use 16-bit look-up tables for the in-memory scan (accumulate_hacc);
97
+ /// if false, 8-bit tables
98
+ bool use_hacc = true;
99
+
100
+ /// after the last list, pages whose lower bound exceeds the
101
+ /// drain_alpha-quantile of the current results are not read. 1 keeps
102
+ /// the k-th distance as the threshold. Below 1, recall depends on the
103
+ /// load: only the pages still waiting to be read when the last list is
104
+ /// scanned are pruned this way, and more of them wait when the SSD is
105
+ /// saturated, so recall measured at low load overestimates it at high
106
+ /// load.
107
+ float drain_alpha = 1.0f;
108
+
109
+ /// SSD reads in flight per search thread, at most kMaxReadsInFlight
110
+ size_t qd_per_thread = 16;
111
+
112
+ /// squared norms of the centroids, needed to derive <q, c> and |q - c|
113
+ /// from the coarse distances when the index or the quantizer uses the
114
+ /// inner product. Set by train() and add().
115
+ std::vector<float> centroid_norms;
116
+
117
+ /// METRIC_INNER_PRODUCT only, empty otherwise: the codes of list l are
118
+ /// relative to centroid_scales[l] times centroid l of the quantizer. Set
119
+ /// by train() on an empty index. Reset the index and train it again
120
+ /// after changing the centroids.
121
+ std::vector<float> centroid_scales;
122
+
123
+ /** @param quantizer coarse quantizer, which must implement reconstruct.
124
+ * Tested with IndexFlat and IndexHNSWFlat. Raise the
125
+ * efSearch of an IndexHNSWFlat (e.g. to 256) before
126
+ * train() and add(): with the default, some vectors
127
+ * go to lists other than their nearest, which lowers
128
+ * recall at any nprobe short of nlist.
129
+ * @param d dimensionality, a multiple of 64
130
+ * @param nlist number of lists
131
+ * @param mem_dim dimensions whose sign bits stay in memory
132
+ * @param nb_bits bits per dimension, in [2, 9]
133
+ * @param metric METRIC_L2 or METRIC_INNER_PRODUCT
134
+ */
135
+ IndexIVFRaBitQSSD(
136
+ Index* quantizer,
137
+ size_t d,
138
+ size_t nlist,
139
+ size_t mem_dim,
140
+ uint8_t nb_bits,
141
+ MetricType metric = METRIC_L2);
142
+
143
+ IndexIVFRaBitQSSD();
144
+
145
+ IndexIVFRaBitQSSD(const IndexIVFRaBitQSSD&) = delete;
146
+ IndexIVFRaBitQSSD& operator=(const IndexIVFRaBitQSSD&) = delete;
147
+
148
+ /** Store the disk-resident part in a new file (created or truncated),
149
+ * replacing the inverted lists of an empty index. Its file system must
150
+ * support O_DIRECT.
151
+ */
152
+ void attach_file(const char* filename);
153
+
154
+ /// the inverted lists, or an exception if they are not of the right type
155
+ RaBitQSSDInvertedLists* get_ssd_invlists() const;
156
+
157
+ /// empty the index, including when inverted lists have not been attached
158
+ void reset() override;
159
+
160
+ /// sets centroid_norms and, for an empty METRIC_INNER_PRODUCT index,
161
+ /// centroid_scales
162
+ void train_encoder(idx_t n, const float* x, const idx_t* assign) override;
163
+
164
+ void add_core(
165
+ idx_t n,
166
+ const float* x,
167
+ const idx_t* xids,
168
+ const idx_t* precomputed_idx,
169
+ void* inverted_list_context = nullptr) override;
170
+
171
+ /// not supported: the codes are not stored as flat codes
172
+ void encode_vectors(
173
+ idx_t n,
174
+ const float* x,
175
+ const idx_t* list_nos,
176
+ uint8_t* codes,
177
+ bool include_listnos = false) const override;
178
+
179
+ /** Unlike IndexIVF::search, which runs the coarse quantizer on all the
180
+ * queries first, each search thread runs it on its own query, so that it
181
+ * overlaps the reads of the other threads. The queries are searched in
182
+ * parallel whatever the parallel_mode.
183
+ */
184
+ void search(
185
+ idx_t n,
186
+ const float* x,
187
+ idx_t k,
188
+ float* distances,
189
+ idx_t* labels,
190
+ const SearchParameters* params = nullptr) const override;
191
+
192
+ void search_preassigned(
193
+ idx_t n,
194
+ const float* x,
195
+ idx_t k,
196
+ const idx_t* assign,
197
+ const float* centroid_dis,
198
+ float* distances,
199
+ idx_t* labels,
200
+ bool store_pairs,
201
+ const IVFSearchParameters* params = nullptr,
202
+ IndexIVFStats* stats = nullptr) const override;
203
+
204
+ /// not supported
205
+ void range_search(
206
+ idx_t n,
207
+ const float* x,
208
+ float radius,
209
+ RangeSearchResult* result,
210
+ const SearchParameters* params = nullptr) const override;
211
+
212
+ /// not supported
213
+ void range_search_preassigned(
214
+ idx_t nx,
215
+ const float* x,
216
+ float radius,
217
+ const idx_t* keys,
218
+ const float* coarse_dis,
219
+ RangeSearchResult* result,
220
+ bool store_pairs = false,
221
+ const IVFSearchParameters* params = nullptr,
222
+ IndexIVFStats* stats = nullptr) const override;
223
+
224
+ /// not supported: the vectors are not stored, and their codes are
225
+ /// split between memory and the file
226
+ void reconstruct(idx_t key, float* recons) const override;
227
+
228
+ /// not supported, see reconstruct
229
+ void reconstruct_n(idx_t i0, idx_t ni, float* recons) const override;
230
+
231
+ /// not supported, see reconstruct
232
+ void search_and_reconstruct(
233
+ idx_t n,
234
+ const float* x,
235
+ idx_t k,
236
+ float* distances,
237
+ idx_t* labels,
238
+ float* recons,
239
+ const SearchParameters* params = nullptr) const override;
240
+
241
+ /// not supported, see reconstruct
242
+ void search_and_return_codes(
243
+ idx_t n,
244
+ const float* x,
245
+ idx_t k,
246
+ float* distances,
247
+ idx_t* labels,
248
+ uint8_t* recons,
249
+ bool include_listno = false,
250
+ const SearchParameters* params = nullptr) const override;
251
+
252
+ /// not supported, see reconstruct
253
+ void reconstruct_from_offset(int64_t list_no, int64_t offset, float* recons)
254
+ const override;
255
+
256
+ /// not supported
257
+ size_t remove_ids(const IDSelector& sel) override;
258
+
259
+ /// not supported
260
+ void update_vectors(int nv, const idx_t* idx, const float* v) override;
261
+
262
+ /// not supported
263
+ void merge_from(Index& otherIndex, idx_t add_id) override;
264
+
265
+ /// not supported
266
+ void copy_subset_to(
267
+ IndexIVF& other,
268
+ InvertedLists::subset_type_t subset_type,
269
+ idx_t a1,
270
+ idx_t a2) const override;
271
+
272
+ /// recompute centroid_norms from the quantizer
273
+ void update_centroid_norms();
274
+ };
275
+
276
+ /// Counters of IndexIVFRaBitQSSD searches, summed over all searches since
277
+ /// the last reset().
278
+ struct IndexIVFRaBitQSSDStats {
279
+ size_t n_pages_read = 0; ///< pages read from the file
280
+ size_t n_reranked = 0; ///< vectors re-ranked with their full code
281
+
282
+ void reset();
283
+ void add(const IndexIVFRaBitQSSDStats& other);
284
+ };
285
+
286
+ FAISS_API extern IndexIVFRaBitQSSDStats indexIVFRaBitQSSD_stats;
287
+
288
+ } // namespace faiss
@@ -586,6 +586,9 @@ void IndexIVFSQFastScan::search_preassigned(
586
586
  idx_t lo = direct_map.get(id);
587
587
  idx_t list_no = lo_listno(lo);
588
588
  idx_t offset = lo_offset(lo);
589
+ // callers that ask for store_pairs (eg.
590
+ // search_and_reconstruct) expect (list_no, offset) pairs
591
+ idx_t label = store_pairs ? lo : id;
589
592
 
590
593
  recombine_code(
591
594
  list_no,
@@ -597,11 +600,13 @@ void IndexIVFSQFastScan::search_preassigned(
597
600
 
598
601
  if (metric_type == METRIC_L2) {
599
602
  if (dis < heap_dis[0]) {
600
- maxheap_replace_top(k, heap_dis, heap_ids, dis, id);
603
+ maxheap_replace_top(
604
+ k, heap_dis, heap_ids, dis, label);
601
605
  }
602
606
  } else {
603
607
  if (dis > heap_dis[0]) {
604
- minheap_replace_top(k, heap_dis, heap_ids, dis, id);
608
+ minheap_replace_top(
609
+ k, heap_dis, heap_ids, dis, label);
605
610
  }
606
611
  }
607
612
  }
@@ -16,6 +16,7 @@
16
16
 
17
17
  #include <faiss/IndexFlat.h>
18
18
  #include <faiss/impl/AuxIndexStructures.h>
19
+ #include <faiss/impl/DeterministicNNDescent.h>
19
20
  #include <faiss/impl/FaissAssert.h>
20
21
  #include <faiss/impl/VisitedTable.h>
21
22
 
@@ -173,6 +174,26 @@ void IndexNNDescent::add(idx_t n, const float* x) {
173
174
  storage->add(n, x);
174
175
  ntotal = storage->ntotal;
175
176
 
177
+ if (nndescent.deterministic) {
178
+ FAISS_THROW_IF_NOT_FMT(
179
+ ntotal > nndescent.K,
180
+ "IndexNNDescent: need more than K = %d vectors",
181
+ nndescent.K);
182
+ // NNDescent::search indexes final_graph with int
183
+ FAISS_THROW_IF_NOT_MSG(
184
+ ntotal * nndescent.K < (idx_t(1) << 31),
185
+ "IndexNNDescent: ntotal * K must be < 2^31");
186
+ DeterministicNNDescent dnd;
187
+ dnd.K = nndescent.K;
188
+ dnd.max_rounds = nndescent.iter;
189
+ dnd.seed = nndescent.random_seed;
190
+ dnd.verbose = verbose;
191
+ dnd.build(*storage);
192
+ nndescent.final_graph = std::move(dnd.ids);
193
+ nndescent.ntotal = static_cast<int>(ntotal);
194
+ nndescent.has_built = true;
195
+ return;
196
+ }
176
197
  std::unique_ptr<DistanceComputer> dis(storage_distance_computer(storage));
177
198
  nndescent.build(*dis, static_cast<int>(ntotal), verbose);
178
199
  }
@@ -81,12 +81,175 @@ FlatCodesDistanceComputer* IndexRaBitQ::get_quantized_distance_computer(
81
81
 
82
82
  namespace {
83
83
 
84
+ // Whether resi.add_result would keep dis
85
+ template <class C>
86
+ bool beats_threshold(const ResultHandlerT<C>& resi, float dis) {
87
+ return C::cmp(resi.threshold, dis);
88
+ }
89
+
90
+ // Single-stage search: the estimate is the distance. It is the full distance
91
+ // for the multi-bit codes that range_search scans this way.
92
+ template <class ResultHandler>
93
+ struct OneStage {
94
+ RaBitQDistanceComputer& dc;
95
+ ResultHandler& resi;
96
+ const uint8_t* codes;
97
+ size_t code_size;
98
+
99
+ const uint8_t* code(size_t i) const {
100
+ return codes + i * code_size;
101
+ }
102
+
103
+ float estimate(size_t i) {
104
+ return dc.nb_bits == 1 ? dc.distance_to_code_1bit(code(i))
105
+ : dc.distance_to_code_full(code(i));
106
+ }
107
+
108
+ void estimate_batch_4(size_t i, float* dis) {
109
+ if (dc.nb_bits > 1) {
110
+ for (size_t j = 0; j < 4; j++) {
111
+ dis[j] = estimate(i + j);
112
+ }
113
+ return;
114
+ }
115
+ const uint8_t* batch[4] = {
116
+ code(i), code(i + 1), code(i + 2), code(i + 3)};
117
+ dc.distance_to_code_1bit_batch_4(batch, dis);
118
+ }
119
+
120
+ bool passes(size_t, float dis) const {
121
+ return beats_threshold(resi, dis);
122
+ }
123
+
124
+ void add(size_t i, float dis) {
125
+ resi.add_result(dis, i);
126
+ }
127
+ };
128
+
129
+ // Two-stage search of multi-bit codes: the full distance is computed only
130
+ // when the error bound of the 1-bit estimate reaches past the threshold.
131
+ template <class ResultHandler>
132
+ struct TwoStage {
133
+ RaBitQDistanceComputer& dc;
134
+ ResultHandler& resi;
135
+ const uint8_t* codes;
136
+ size_t code_size;
137
+ bool is_similarity;
138
+
139
+ const uint8_t* code(size_t i) const {
140
+ return codes + i * code_size;
141
+ }
142
+
143
+ float estimate(size_t i) {
144
+ return dc.distance_to_code_1bit(code(i));
145
+ }
146
+
147
+ void estimate_batch_4(size_t i, float* dis) {
148
+ const uint8_t* batch[4] = {
149
+ code(i), code(i + 1), code(i + 2), code(i + 3)};
150
+ dc.distance_to_code_1bit_batch_4(batch, dis);
151
+ }
152
+
153
+ bool passes(size_t i, float est_distance) const {
154
+ return dc.should_refine(
155
+ code(i), est_distance, resi.threshold, is_similarity);
156
+ }
157
+
158
+ void add(size_t i, float) {
159
+ resi.add_result(dc.distance_to_code_full(code(i)), i);
160
+ }
161
+ };
162
+
163
+ // Search without a selector, estimating four codes at a time
164
+ template <class Stage>
165
+ void scan_all(size_t ntotal, Stage& stage) {
166
+ size_t i = 0;
167
+ for (; i + 4 <= ntotal; i += 4) {
168
+ float dis[4];
169
+ stage.estimate_batch_4(i, dis);
170
+ for (size_t j = 0; j < 4; j++) {
171
+ if (stage.passes(i + j, dis[j])) {
172
+ stage.add(i + j, dis[j]);
173
+ }
174
+ }
175
+ }
176
+ for (; i < ntotal; i++) {
177
+ float dis = stage.estimate(i);
178
+ if (stage.passes(i, dis)) {
179
+ stage.add(i, dis);
180
+ }
181
+ }
182
+ }
183
+
184
+ // Search that tests the selector before each estimate
185
+ template <class InSelection, class Stage>
186
+ void scan_sel_first(
187
+ size_t ntotal,
188
+ const InSelection& in_selection,
189
+ Stage& stage) {
190
+ for (size_t i = 0; i < ntotal; i++) {
191
+ if (in_selection(i)) {
192
+ float dis = stage.estimate(i);
193
+ if (stage.passes(i, dis)) {
194
+ stage.add(i, dis);
195
+ }
196
+ }
197
+ }
198
+ }
199
+
200
+ // Search that tests the selector after the estimate while at most a third of
201
+ // the estimates in the last window passed, and before it otherwise. Testing
202
+ // after skips the selector for the codes that fail, but estimates codes that
203
+ // the selector would reject. The results are the same either way. Until the
204
+ // results fill up, every estimate passes, so the selector starts first.
205
+ // Testing after, codes are estimated four at a time; the window is a multiple
206
+ // of four, so the batches end on window boundaries.
207
+ template <class InSelection, class Stage>
208
+ void scan_sel_after_distance(
209
+ size_t ntotal,
210
+ const InSelection& in_selection,
211
+ Stage& stage) {
212
+ constexpr size_t window = 64;
213
+ bool sel_after = false;
214
+ size_t estimated = 0;
215
+ size_t passed = 0;
216
+ auto take = [&](size_t i, float dis) {
217
+ estimated++;
218
+ if (stage.passes(i, dis)) {
219
+ passed++;
220
+ if (!sel_after || in_selection(i)) {
221
+ stage.add(i, dis);
222
+ }
223
+ }
224
+ };
225
+ for (size_t i = 0; i < ntotal;) {
226
+ if (sel_after && i + 4 <= ntotal) {
227
+ float dis[4];
228
+ stage.estimate_batch_4(i, dis);
229
+ for (size_t j = 0; j < 4; j++, i++) {
230
+ take(i, dis[j]);
231
+ }
232
+ } else {
233
+ if (sel_after || in_selection(i)) {
234
+ take(i, stage.estimate(i));
235
+ }
236
+ i++;
237
+ }
238
+ if (estimated >= window) {
239
+ sel_after = 3 * passed <= window;
240
+ estimated = 0;
241
+ passed = 0;
242
+ }
243
+ }
244
+ }
245
+
84
246
  struct Run_search_with_dc_res {
85
247
  using T = void;
86
248
 
87
249
  uint8_t qb = 0;
88
250
  bool centered = false;
89
251
  uint8_t nb_bits = 1; // Number of bits per dimension
252
+ bool sel_after_distance = false;
90
253
 
91
254
  template <class BlockResultHandler>
92
255
  void f(BlockResultHandler& res, const IndexRaBitQ* index, const float* xq) {
@@ -95,11 +258,24 @@ struct Run_search_with_dc_res {
95
258
  typename BlockResultHandler::SingleResultHandler;
96
259
  const int d = index->d;
97
260
  size_t ex_bits = nb_bits - 1;
261
+ auto in_selection = [&res](size_t i) { return res.is_in_selection(i); };
262
+ auto scan = [&](auto& stage) {
263
+ if (res.sel == nullptr) {
264
+ scan_all(ntotal, stage);
265
+ } else if (sel_after_distance) {
266
+ scan_sel_after_distance(ntotal, in_selection, stage);
267
+ } else {
268
+ scan_sel_first(ntotal, in_selection, stage);
269
+ }
270
+ };
98
271
 
99
272
  #pragma omp parallel
100
273
  {
101
274
  std::unique_ptr<FlatCodesDistanceComputer> dc_base(
102
275
  index->get_quantized_distance_computer(qb, centered));
276
+ auto* dc = dynamic_cast<RaBitQDistanceComputer*>(dc_base.get());
277
+ FAISS_ASSERT_MSG(
278
+ dc, "Failed to cast to RaBitQDistanceComputer for search");
103
279
  SingleResultHandler resi(res);
104
280
  #pragma omp for
105
281
  for (int64_t q = 0; q < static_cast<int64_t>(res.nq); q++) {
@@ -108,56 +284,25 @@ struct Run_search_with_dc_res {
108
284
 
109
285
  if (ex_bits == 0) {
110
286
  // 1-bit: Standard single-stage search
111
- for (size_t i = 0; i < ntotal; i++) {
112
- if (res.is_in_selection(i)) {
113
- float dis = (*dc_base)(i);
114
- resi.add_result(dis, i);
115
- }
116
- }
287
+ OneStage<SingleResultHandler> stage{
288
+ *dc, resi, index->codes.data(), index->code_size};
289
+ scan(stage);
117
290
  } else {
118
291
  // Multi-bit: Two-stage search with adaptive filtering
119
292
  // Note: Even with query quantization (qb > 0), ex-bits
120
293
  // distance computation uses the float query to maintain
121
294
  // consistency with encoding-time factor computation. See
122
295
  // RaBitQuantizer.cpp for details.
123
- auto* dc = dynamic_cast<RaBitQDistanceComputer*>(
124
- dc_base.get());
125
- FAISS_THROW_IF_MSG(
126
- dc == nullptr,
127
- "Failed to cast to RaBitQDistanceComputer for two-stage search");
128
-
129
296
  bool is_similarity =
130
297
  is_similarity_metric(index->metric_type);
131
298
 
132
- for (size_t i = 0; i < ntotal; i++) {
133
- if (res.is_in_selection(i)) {
134
- const uint8_t* code =
135
- index->codes.data() + i * index->code_size;
136
-
137
- float est_distance =
138
- dc->distance_to_code_1bit(code);
139
-
140
- size_t code_size_base = (index->d + 7) / 8;
141
- const rabitq_utils::SignBitFactorsWithError*
142
- base_fac = reinterpret_cast<
143
- const rabitq_utils::
144
- SignBitFactorsWithError*>(
145
- code + code_size_base);
146
-
147
- bool should_refine =
148
- rabitq_utils::should_refine_candidate(
149
- est_distance,
150
- base_fac->f_error,
151
- dc->g_error,
152
- resi.threshold,
153
- is_similarity);
154
- if (should_refine) {
155
- float dist_full =
156
- dc->distance_to_code_full(code);
157
- resi.add_result(dist_full, i);
158
- }
159
- }
160
- }
299
+ TwoStage<SingleResultHandler> stage{
300
+ *dc,
301
+ resi,
302
+ index->codes.data(),
303
+ index->code_size,
304
+ is_similarity};
305
+ scan(stage);
161
306
  }
162
307
 
163
308
  resi.end();
@@ -180,9 +325,11 @@ void IndexRaBitQ::search(
180
325
  // Extract search parameters
181
326
  uint8_t used_qb = qb;
182
327
  bool used_centered = centered;
328
+ bool sel_after_distance = false;
183
329
  if (auto params = dynamic_cast<const RaBitQSearchParameters*>(params_in)) {
184
330
  used_qb = params->qb;
185
331
  used_centered = params->centered;
332
+ sel_after_distance = params->sel_after_distance;
186
333
  }
187
334
 
188
335
  const IDSelector* sel = (params_in != nullptr) ? params_in->sel : nullptr;
@@ -192,6 +339,7 @@ void IndexRaBitQ::search(
192
339
  r.qb = used_qb;
193
340
  r.centered = used_centered;
194
341
  r.nb_bits = rabitq.nb_bits; // Pass multi-bit info to functor
342
+ r.sel_after_distance = sel_after_distance;
195
343
 
196
344
  // Use Faiss framework for all cases (single-stage and two-stage)
197
345
  dispatch_knn_ResultHandler(
@@ -15,6 +15,11 @@ namespace faiss {
15
15
  struct RaBitQSearchParameters : SearchParameters {
16
16
  uint8_t qb = 4;
17
17
  bool centered = false;
18
+ // test sel after a code's distance rather than before it, while at most a
19
+ // third of the distances beat the threshold. Same results; it pays off
20
+ // when sel costs about 1.5x a distance or more. Used by search, not
21
+ // range_search. qb and centered above replace the index's own values.
22
+ bool sel_after_distance = false;
18
23
  };
19
24
 
20
25
  struct IndexRaBitQ : IndexFlatCodes {
@@ -92,7 +92,7 @@ size_t IndexRaBitQFastScan::remove_ids(const IDSelector& sel) {
92
92
  if (last_pos > 0) {
93
93
  const size_t last_block = ntotal / bbs;
94
94
  std::vector<uint8_t> zero_code(code_size, 0);
95
- for (size_t pos = last_pos; pos < bbs; pos++) {
95
+ for (size_t pos = last_pos; pos < static_cast<size_t>(bbs); pos++) {
96
96
  packer->pack_1(
97
97
  zero_code.data(), last_block * bbs + pos, codes.data());
98
98
  }
@@ -206,7 +206,8 @@ struct RaBitQHeapHandler
206
206
  const float bias = normalizers ? normalizers[2 * q + 1] : 0.0f;
207
207
 
208
208
  const size_t base_db_idx = this->j0 + b * 32;
209
- const size_t max_vectors = (base_db_idx < rabitq_index->ntotal)
209
+ const size_t max_vectors =
210
+ (base_db_idx < static_cast<size_t>(rabitq_index->ntotal))
210
211
  ? std::min<size_t>(32, rabitq_index->ntotal - base_db_idx)
211
212
  : 0;
212
213
 
@@ -294,7 +295,6 @@ struct RaBitQHeapHandler
294
295
  }
295
296
  }
296
297
 
297
- private:
298
298
  float compute_full_multibit_distance(size_t db_idx, size_t q) {
299
299
  const size_t ex_bits = rabitq_index->rabitq.nb_bits - 1;
300
300
  const size_t dim = rabitq_index->d;
@@ -391,8 +391,8 @@ void untransform_centroids(
391
391
 
392
392
  } // namespace
393
393
 
394
- SuperKMeans::SuperKMeans(int d, int k, const SuperKMeansParameters& cp_in)
395
- : cp(cp_in), d(d), k(k) {
394
+ SuperKMeans::SuperKMeans(int d_in, int k_in, const SuperKMeansParameters& cp_in)
395
+ : cp(cp_in), d(d_in), k(k_in) {
396
396
  FAISS_THROW_IF_NOT_MSG(d > 0, "SuperKMeans: d must be positive");
397
397
  FAISS_THROW_IF_NOT_MSG(k > 0, "SuperKMeans: k must be positive");
398
398
  FAISS_THROW_IF_NOT_MSG(