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,301 @@
1
+ /*
2
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
3
+ *
4
+ * This source code is licensed under the MIT license found in the
5
+ * LICENSE file in the root directory of this source tree.
6
+ */
7
+
8
+ #pragma once
9
+
10
+ #include <cstdint>
11
+ #include <vector>
12
+
13
+ #include <faiss/Index.h>
14
+
15
+ namespace faiss {
16
+
17
+ /// parameters of the local joins, shared by DeterministicNNDescent and
18
+ /// NNDescentShard
19
+ struct NNDescentParams {
20
+ int K = 64; ///< neighbors per node
21
+ int R = 0; ///< reverse neighbors used per node; 0: 2 * K
22
+ /// new neighbors of each kind (neighbors, reverse neighbors) that a local
23
+ /// join uses; 0: all
24
+ int sample = 0;
25
+
26
+ int nreverse() const {
27
+ return R != 0 ? R : 2 * K;
28
+ }
29
+
30
+ int nsample() const {
31
+ return sample != 0 ? sample : K + nreverse();
32
+ }
33
+ };
34
+
35
+ /** A K-nearest-neighbor graph built by NN-descent, with a result that does
36
+ * not depend on the thread count.
37
+ *
38
+ * Dong, Charikar and Li, "Efficient K-Nearest Neighbor Graph Construction for
39
+ * Generic Similarity Measures", WWW 2011. The batch structure follows
40
+ * pyNNDescent in ParlayANN (Manohar et al., PPoPP 2024).
41
+ *
42
+ * - Initialization: random cluster trees. Each tree splits the points by
43
+ * their nearer of two random pivots, down to leaves of at most 512 points,
44
+ * and links each point to its K nearest in its leaf. With ntrees = 0, each
45
+ * node gets K random neighbors. Rows that stay short get random neighbors.
46
+ * - Rounds: a round reads a fixed copy of the graph. For each node u, a
47
+ * local join computes the distances between the members of the
48
+ * neighborhood of u (its K neighbors and R nearest reverse neighbors), for
49
+ * the pairs where at least one member is new (added by the previous
50
+ * round), and inserts each pair as a candidate in the rows of both
51
+ * members. The new row of a node holds the K best of its old row and of
52
+ * its candidates by (distance, id), with the smallest distance of each id.
53
+ * This set does not depend on the order of the candidates, so the rows do
54
+ * not depend on the thread count.
55
+ *
56
+ * The vectors are read in place for IndexFlat, decoded for
57
+ * IndexScalarQuantizer, and reconstructed for other storage types. The
58
+ * distances of a leaf and of a local join come from the inner products of
59
+ * the float vectors: from the nndescent::gram_upper_rows kernel on AVX2,
60
+ * AVX-512 and ARM NEON or SVE, else from BLAS. The values of a level do not
61
+ * depend on the thread count, but differ between levels. Distances are
62
+ * smaller-is-better: for METRIC_INNER_PRODUCT they are negated inner products.
63
+ * A distance that overflows to NaN becomes +inf. */
64
+ struct DeterministicNNDescent : NNDescentParams {
65
+ int ntrees = 8; ///< random cluster trees for init(); 0: random init
66
+ int max_rounds = 20; ///< maximum rounds of build()
67
+ float delta = 0.05f; ///< build() stops when fewer nodes change
68
+ int64_t seed = 1234;
69
+ bool verbose = false;
70
+
71
+ // the storage of init()
72
+ idx_t n = 0;
73
+ size_t d = 0;
74
+ MetricType metric_type = METRIC_L2;
75
+ /// n * K neighbors per node, sorted by (distance, id), -1 padded
76
+ std::vector<int32_t> ids;
77
+ std::vector<float> dis;
78
+
79
+ /// distance computations of the last init() or round()
80
+ size_t ndis = 0;
81
+
82
+ /// Initializes the graph over the ntotal vectors of storage.
83
+ void init(const Index& storage);
84
+
85
+ /// One round; returns the number of nodes whose row changed.
86
+ idx_t round(const Index& storage);
87
+
88
+ /// init(storage), then rounds until fewer than delta * n nodes change
89
+ void build(const Index& storage);
90
+
91
+ // internal state
92
+ /// n * K, nonzero for an entry added by the last init() or round()
93
+ std::vector<uint8_t> is_new;
94
+ /// order in which round() visits the nodes: the leaf order of the first
95
+ /// cluster tree, so that consecutive nodes share neighbors in the cache
96
+ std::vector<int32_t> order;
97
+
98
+ void check_params() const;
99
+ };
100
+
101
+ /** The rows of one process in an NN-descent round over a graph that is split
102
+ * between processes (for example a distributed build, after the
103
+ * per-partition builds).
104
+ *
105
+ * Graph ids are int64. Process p owns the ids owner_begin[p] ..
106
+ * owner_begin[p + 1] - 1 and holds their rows and vectors in that order. A
107
+ * round has four steps. Between the steps, the caller sends the lists to the
108
+ * other processes; each list is grouped by destination process, with one
109
+ * count per process.
110
+ * 1. reverse_edges(): the edges u -> v of the home rows, for the owner of v.
111
+ * 2. set_reverse_edges(): the received edges. Each home row keeps its R
112
+ * nearest reverse edges by (distance, source). The remote ids are the
113
+ * sorted ids that other processes own, of the neighborhoods that have a
114
+ * new member: a local join of a neighborhood without one computes no
115
+ * distances.
116
+ * 3. join(): with the vectors and the K-th distances of the remote ids, the
117
+ * local joins of the home rows, as in DeterministicNNDescent::round().
118
+ * join() inserts the candidates for home rows and returns the candidates
119
+ * for remote rows, the K best for each row. With select_rows(), several
120
+ * join() calls can each cover a range of the home rows, with the remote
121
+ * ids of that range only.
122
+ * 4. insert_candidates(): the candidates that the other processes sent, in
123
+ * any order, then end_round(), which returns the number of home rows
124
+ * that changed.
125
+ * With the same rows, a round gives the same rows as
126
+ * DeterministicNNDescent::round() on the whole graph, except for the order of
127
+ * equal distances. The result does not depend on the thread count or on the
128
+ * order in which the lists arrive.
129
+ *
130
+ * The candidates for a remote row can include ids that are already in the
131
+ * row: the owner drops them in insert_candidates(). A pair can get two
132
+ * distances that differ in the last bits: init() computes some distances
133
+ * directly and the local joins from the squared norms, and coded remote
134
+ * vectors differ from the home vectors. The cases below that give "the same
135
+ * rows" assume one value per pair; otherwise the rows can differ slightly,
136
+ * but are still the same in every run with the same input. */
137
+ struct NNDescentShard : NNDescentParams {
138
+ /// nhome() x K rows: graph ids sorted by (distance, id), -1 padded
139
+ std::vector<int64_t> ids;
140
+ std::vector<float> dis;
141
+ /// ids that other processes own, of the neighborhoods of this round that
142
+ /// have a new member
143
+ std::vector<int64_t> remote_ids;
144
+
145
+ /// distance computations of the join() calls of the round
146
+ size_t ndis = 0;
147
+
148
+ /// rows of the home ids; every entry is new. Every row id is -1 or in
149
+ /// [owner_begin[0], owner_begin[world]).
150
+ void set_rows(
151
+ int K,
152
+ MetricType metric_type,
153
+ size_t d,
154
+ int rank,
155
+ int world,
156
+ const int64_t* owner_begin,
157
+ const float* x,
158
+ const int64_t* ids,
159
+ const float* dis);
160
+
161
+ idx_t nhome() const;
162
+
163
+ /// edges u -> v grouped by the owner of v
164
+ void reverse_edges(
165
+ std::vector<int64_t>& counts,
166
+ std::vector<int64_t>& target,
167
+ std::vector<int64_t>& source,
168
+ std::vector<float>& edge_dis,
169
+ std::vector<uint8_t>& edge_new) const;
170
+
171
+ /// the received edges, whose targets are home ids and whose sources are
172
+ /// graph ids; computes remote_ids
173
+ void set_reverse_edges(
174
+ size_t n,
175
+ const int64_t* target,
176
+ const int64_t* source,
177
+ const float* edge_dis,
178
+ const uint8_t* edge_new);
179
+
180
+ /** Selects the home rows [begin, end) for the next join() and sets
181
+ * remote_ids to the remote ids of their neighborhoods that have a new
182
+ * member. set_reverse_edges() selects all home rows. join() calls on
183
+ * disjoint ranges that cover the home rows need only the remote ids of
184
+ * their range. With one distance per pair, they give the same rows as one
185
+ * join() on all rows. When a pair can get two distances (see above), a
186
+ * range can send a candidate to a remote row that one join() would cut,
187
+ * so the rows can differ slightly. */
188
+ void select_rows(idx_t begin, idx_t end);
189
+
190
+ /// number of remote ids that each process owns
191
+ void remote_counts(std::vector<int64_t>& counts) const;
192
+
193
+ /** Local joins of the selected home rows. For remote id i: its vector
194
+ * remote_x[i * d] and the K-th distance of its row remote_kth[i] (+inf if
195
+ * the row is short). Throws if a neighborhood id of the selected rows is
196
+ * not in remote_ids. Returns the candidates for remote rows grouped by
197
+ * owner: (target, candidate, distance), sorted by target, then by
198
+ * (distance, candidate). */
199
+ void join(
200
+ const float* remote_x,
201
+ const float* remote_kth,
202
+ std::vector<int64_t>& counts,
203
+ std::vector<int64_t>& target,
204
+ std::vector<int64_t>& candidate,
205
+ std::vector<float>& candidate_dis);
206
+
207
+ /// join() with float16 remote vectors, which take half the memory
208
+ void join_fp16(
209
+ const uint16_t* remote_x,
210
+ const float* remote_kth,
211
+ std::vector<int64_t>& counts,
212
+ std::vector<int64_t>& target,
213
+ std::vector<int64_t>& candidate,
214
+ std::vector<float>& candidate_dis);
215
+
216
+ /** join() with 8-bit remote codes, a quarter of the float memory.
217
+ * Component j of a remote vector is vmin[j] + (code + 0.5) / 255 *
218
+ * vdiff[j], as in the 8-bit ScalarQuantizer. */
219
+ void join_sq8(
220
+ const uint8_t* remote_codes,
221
+ const float* vmin,
222
+ const float* vdiff,
223
+ const float* remote_kth,
224
+ std::vector<int64_t>& counts,
225
+ std::vector<int64_t>& target,
226
+ std::vector<int64_t>& candidate,
227
+ std::vector<float>& candidate_dis);
228
+
229
+ /// sets remote_ids to the sorted ids of the home rows that other
230
+ /// processes own
231
+ void set_remote_ids_of_rows();
232
+
233
+ /** The rows with the original ids: home_original[i] for home id
234
+ * owner_begin[rank] + i, remote_original[j] for remote_ids[j]. out:
235
+ * nhome() x K, -1 padded. */
236
+ void original_ids(
237
+ const int64_t* home_original,
238
+ const int64_t* remote_original,
239
+ int64_t* out) const;
240
+
241
+ /** Inserts the candidates for home rows that other processes sent:
242
+ * (target, candidate, distance), with home targets and candidates that
243
+ * are graph ids. The caller can insert the candidates of each join() as
244
+ * they arrive, in any order, then call end_round(). */
245
+ void insert_candidates(
246
+ size_t n,
247
+ const int64_t* target,
248
+ const int64_t* candidate,
249
+ const float* candidate_dis);
250
+
251
+ /// ends the round; returns the number of home rows that changed
252
+ idx_t end_round();
253
+
254
+ // internal state, set by set_rows()
255
+ MetricType metric_type = METRIC_L2;
256
+ size_t d = 0;
257
+ int rank = 0;
258
+ /// world + 1 boundaries of the graph ids that each process owns
259
+ std::vector<int64_t> owner_begin;
260
+ /// nhome() x d home vectors; the caller keeps them alive
261
+ const float* x = nullptr;
262
+ /// nhome() x K flags of the rows
263
+ std::vector<uint8_t> is_new;
264
+
265
+ // state between the steps of a round
266
+ std::vector<int64_t> reverse_ids; ///< nhome() x nreverse(), -1 padded
267
+ std::vector<uint8_t> reverse_new; ///< flag of each reverse edge
268
+ std::vector<int64_t> next_ids; ///< rows after the merges
269
+ std::vector<float> next_dis;
270
+ std::vector<uint8_t> next_new;
271
+ idx_t selected_begin = 0; ///< home rows of the next join()
272
+ idx_t selected_end = 0;
273
+
274
+ /// remote vectors of join_impl(): exactly one of x, x16 and codes
275
+ struct RemoteVectors {
276
+ const float* x = nullptr;
277
+ const uint16_t* x16 = nullptr;
278
+ const uint8_t* codes = nullptr;
279
+ const float* vmin = nullptr;
280
+ const float* vdiff = nullptr;
281
+ };
282
+
283
+ void join_impl(
284
+ const RemoteVectors& rv,
285
+ const float* remote_kth,
286
+ std::vector<int64_t>& counts,
287
+ std::vector<int64_t>& target,
288
+ std::vector<int64_t>& candidate,
289
+ std::vector<float>& candidate_dis);
290
+
291
+ /// whether the neighborhood of home row t has a new member, so that its
292
+ /// local join computes distances
293
+ bool has_new_member(idx_t t) const;
294
+
295
+ /** The remote ids of the home rows [begin, end), sorted. With the
296
+ * reverse lists: the remote ids of the neighborhoods that have a new
297
+ * member, which are the only ones that a local join reads. */
298
+ void collect_remote_ids(bool with_reverse, idx_t begin, idx_t end);
299
+ };
300
+
301
+ } // namespace faiss
@@ -2048,8 +2048,8 @@ void HNSW::permute_entries(const idx_t* map) {
2048
2048
  }
2049
2049
  assert(new_offsets[ntotal] == offsets[ntotal]);
2050
2050
  // swap everyone
2051
- std::swap(levels, new_levels);
2052
- std::swap(offsets, new_offsets);
2051
+ levels = std::move(new_levels);
2052
+ offsets = std::move(new_offsets);
2053
2053
  neighbors = std::move(new_neighbors);
2054
2054
  }
2055
2055
 
@@ -118,11 +118,11 @@ struct HNSW {
118
118
  std::vector<int> cum_nneighbor_per_level;
119
119
 
120
120
  /// level of each vector (base level = 1), size = ntotal
121
- std::vector<int> levels;
121
+ MaybeOwnedVector<int> levels;
122
122
 
123
123
  /// offsets[i] is the offset in the neighbors array where vector i is stored
124
124
  /// size ntotal + 1
125
- std::vector<size_t> offsets;
125
+ MaybeOwnedVector<size_t> offsets;
126
126
 
127
127
  /// neighbors[offsets[i]:offsets[i+1]] is the list of neighbors of vector i
128
128
  /// for all levels. this is where all storage goes.
@@ -55,10 +55,11 @@ struct IDSelectorContextDispatch {
55
55
  const IDSelector* sel;
56
56
  const IDSelectorWithContext* ctx_sel;
57
57
 
58
- IDSelectorContextDispatch(const IDSelector* sel, bool store_pairs)
59
- : sel(sel),
60
- ctx_sel((sel != nullptr && !store_pairs)
61
- ? dynamic_cast<const IDSelectorWithContext*>(sel)
58
+ IDSelectorContextDispatch(const IDSelector* sel_in, bool store_pairs)
59
+ : sel(sel_in),
60
+ ctx_sel((sel_in != nullptr && !store_pairs)
61
+ ? dynamic_cast<const IDSelectorWithContext*>(
62
+ sel_in)
62
63
  : nullptr) {}
63
64
 
64
65
  bool is_member(idx_t id, const IDScanContext& ctx) const {
@@ -144,6 +144,10 @@ struct NNDescent {
144
144
  int iter = 10; // number of iterations to iterate over
145
145
  int search_L = 0; // size of candidate pool in searching
146
146
  int random_seed = 2021; // random seed for generators
147
+ /// IndexNNDescent::add builds the graph with DeterministicNNDescent
148
+ /// (K, iter rounds, random_seed), so that it does not depend on the
149
+ /// thread count. S, R and L do not apply. Not serialized.
150
+ bool deterministic = false;
147
151
 
148
152
  int K; // K in KNN graph
149
153
  int d; // dimensions
@@ -271,8 +271,10 @@ int32_t medoid_and_validate(const Index& storage, float* norm_cv) {
271
271
  if (c == 0) {
272
272
  *norm_cv = 0;
273
273
  } else {
274
- const double mean = s1 / c;
275
- *norm_cv = std::sqrt(std::max(s2 / c - mean * mean, 0.0)) / mean;
274
+ const double norm_mean = s1 / c;
275
+ *norm_cv =
276
+ std::sqrt(std::max(s2 / c - norm_mean * norm_mean, 0.0)) /
277
+ norm_mean;
276
278
  }
277
279
  }
278
280
  return std::min_element(block_best.begin(), block_best.end())->second;
@@ -92,7 +92,7 @@ struct PiPNN {
92
92
  idx_t ntotal = 0;
93
93
 
94
94
  PiPNN() = default;
95
- explicit PiPNN(int R) : R(R) {}
95
+ explicit PiPNN(int R_in) : R(R_in) {}
96
96
 
97
97
  float effective_alpha(MetricType metric) const;
98
98
 
@@ -299,7 +299,7 @@ struct ReproduceWithHammingObjective : PermutationObjective {
299
299
  double dis_weight_factor_in)
300
300
  : nbits(nbits_in), dis_weight_factor(dis_weight_factor_in) {
301
301
  n = 1 << nbits;
302
- FAISS_THROW_IF_NOT(dis_table.size() == n * n);
302
+ FAISS_THROW_IF_NOT(dis_table.size() == static_cast<size_t>(n * n));
303
303
  set_affine_target_dis(dis_table);
304
304
  }
305
305
 
@@ -77,8 +77,6 @@ SignBitFactorsWithError compute_factors_from_intermediates(
77
77
  MetricType metric_type,
78
78
  bool compute_error) {
79
79
  constexpr float epsilon = std::numeric_limits<float>::epsilon();
80
- constexpr float kConstEpsilon =
81
- 1.9f; // Error bound constant from RaBitQ paper
82
80
  const float inv_d_sqrt =
83
81
  (d == 0) ? 1.0f : (1.0f / std::sqrt(static_cast<float>(d)));
84
82
 
@@ -22,6 +22,9 @@
22
22
  namespace faiss {
23
23
  namespace rabitq_utils {
24
24
 
25
+ /// constant of the RaBitQ error bound (RaBitQ paper, Theorem 3.2)
26
+ constexpr float kConstEpsilon = 1.9f;
27
+
25
28
  /** Base factors computed per database vector for RaBitQ distance computation.
26
29
  * Used by both 1-bit and multi-bit RaBitQ variants.
27
30
  * These can be stored either embedded in codes (IndexRaBitQ) or separately
@@ -87,6 +90,32 @@ struct QueryFactorsData {
87
90
  */
88
91
  FAISS_API extern const float Z_MAX_BY_QB[8];
89
92
 
93
+ // out[code] = base + sum of v_i for each set bit in code.
94
+ inline void write_subset_sum_lut(
95
+ float* out,
96
+ float base,
97
+ float v0,
98
+ float v1,
99
+ float v2,
100
+ float v3) {
101
+ out[0] = base;
102
+ out[1] = base + v0;
103
+ out[2] = base + v1;
104
+ out[3] = base + v0 + v1;
105
+ out[4] = base + v2;
106
+ out[5] = base + v0 + v2;
107
+ out[6] = base + v1 + v2;
108
+ out[7] = base + v0 + v1 + v2;
109
+ out[8] = base + v3;
110
+ out[9] = base + v0 + v3;
111
+ out[10] = base + v1 + v3;
112
+ out[11] = base + v0 + v1 + v3;
113
+ out[12] = base + v2 + v3;
114
+ out[13] = base + v0 + v2 + v3;
115
+ out[14] = base + v1 + v2 + v3;
116
+ out[15] = base + v0 + v1 + v2 + v3;
117
+ }
118
+
90
119
  /** Fast half-away rounding for non-negative RaBitQ quantization values.
91
120
  *
92
121
  * Contract: x must be finite, non-NaN, and in [0, 255.5). This is not a
@@ -419,9 +419,9 @@ struct RaBitQDistanceComputerNotQ final : RaBitQDistanceComputer {
419
419
 
420
420
  size_t scan_codes_multibit(
421
421
  size_t list_size,
422
- const uint8_t* codes,
422
+ const uint8_t* list_codes,
423
423
  const idx_t* ids,
424
- size_t code_size,
424
+ size_t list_code_size,
425
425
  idx_t list_no,
426
426
  bool store_pairs,
427
427
  const IDSelector* sel,
@@ -442,16 +442,16 @@ struct RaBitQDistanceComputerNotQ final : RaBitQDistanceComputer {
442
442
  idx_t id = store_pairs ? lo_build(list_no, j) : ids[j];
443
443
  if (!sel_dispatch.is_member(
444
444
  id, IDScanContext{ids, list_size, j})) {
445
- codes += code_size;
445
+ list_codes += list_code_size;
446
446
  continue;
447
447
  }
448
448
  }
449
449
 
450
450
  const auto* base_fac =
451
451
  reinterpret_cast<const SignBitFactorsWithError*>(
452
- codes + code_size_base);
452
+ list_codes + code_size_base);
453
453
  const float est_distance =
454
- distance_to_code_1bit_impl(codes, base_fac);
454
+ distance_to_code_1bit_impl(list_codes, base_fac);
455
455
 
456
456
  const bool should_refine = rabitq_utils::should_refine_candidate(
457
457
  est_distance,
@@ -461,7 +461,7 @@ struct RaBitQDistanceComputerNotQ final : RaBitQDistanceComputer {
461
461
  keep_max);
462
462
  if (should_refine) {
463
463
  handler.stats.scan_cnt++;
464
- const float dis = distance_to_code_full(codes);
464
+ const float dis = distance_to_code_full(list_codes);
465
465
  idx_t id = store_pairs ? lo_build(list_no, j) : ids[j];
466
466
 
467
467
  if ((keep_max ? dis > handler.threshold
@@ -471,7 +471,7 @@ struct RaBitQDistanceComputerNotQ final : RaBitQDistanceComputer {
471
471
  nup++;
472
472
  }
473
473
  }
474
- codes += code_size;
474
+ list_codes += list_code_size;
475
475
  }
476
476
 
477
477
  return nup;
@@ -676,9 +676,9 @@ struct RaBitQDistanceComputerQ final : RaBitQDistanceComputer {
676
676
 
677
677
  size_t scan_codes_multibit(
678
678
  size_t list_size,
679
- const uint8_t* codes,
679
+ const uint8_t* list_codes,
680
680
  const idx_t* ids,
681
- size_t code_size,
681
+ size_t list_code_size,
682
682
  idx_t list_no,
683
683
  bool store_pairs,
684
684
  const IDSelector* sel,
@@ -690,7 +690,8 @@ struct RaBitQDistanceComputerQ final : RaBitQDistanceComputer {
690
690
 
691
691
  auto scan = [&](auto multibit) {
692
692
  size_t nup = 0;
693
- for (size_t j = 0; j < list_size; j++, codes += code_size) {
693
+ for (size_t j = 0; j < list_size;
694
+ j++, list_codes += list_code_size) {
694
695
  if (sel != nullptr) {
695
696
  idx_t id = store_pairs ? lo_build(list_no, j) : ids[j];
696
697
  if (!sel_dispatch.is_member(
@@ -701,9 +702,9 @@ struct RaBitQDistanceComputerQ final : RaBitQDistanceComputer {
701
702
 
702
703
  const auto* base_fac =
703
704
  reinterpret_cast<const SignBitFactorsWithError*>(
704
- codes + code_size_base);
705
+ list_codes + code_size_base);
705
706
  float dis = distance_to_code_1bit_impl(
706
- codes, base_fac, code_size_base);
707
+ list_codes, base_fac, code_size_base);
707
708
 
708
709
  if constexpr (decltype(multibit)::value) {
709
710
  if (!rabitq_utils::should_refine_candidate(
@@ -714,7 +715,7 @@ struct RaBitQDistanceComputerQ final : RaBitQDistanceComputer {
714
715
  keep_max)) {
715
716
  continue;
716
717
  }
717
- dis = distance_to_code_full(codes);
718
+ dis = distance_to_code_full(list_codes);
718
719
  }
719
720
  handler.stats.scan_cnt++;
720
721
  idx_t id = store_pairs ? lo_build(list_no, j) : ids[j];
@@ -256,6 +256,112 @@ struct Top1BlockResultHandler : TopkBlockResultHandler<C, use_sel> {
256
256
  }
257
257
  };
258
258
 
259
+ /*****************************************************************
260
+ * Two best results handler.
261
+ * Keeps the two best results of each query, best first, without a heap.
262
+ *****************************************************************/
263
+
264
+ /** Insert a result into a pair sorted best first.
265
+ *
266
+ * Results are ordered by C::cmp2, as in the heaps: equal distances are
267
+ * ordered by id (the lower id first for CMax, the higher id first for CMin).
268
+ *
269
+ * @param dis distance of the result
270
+ * @param idx id of the result
271
+ * @param dis2 in/out: the two best distances, best first, size 2
272
+ * @param ids2 in/out: their ids (-1 for none), size 2
273
+ */
274
+ template <class C>
275
+ inline void top2_insert(
276
+ typename C::T dis,
277
+ typename C::TI idx,
278
+ typename C::T* dis2,
279
+ typename C::TI* ids2) {
280
+ if (C::cmp2(dis2[1], dis, ids2[1], idx)) {
281
+ const bool first = C::cmp2(dis2[0], dis, ids2[0], idx);
282
+ dis2[1] = first ? dis2[0] : dis;
283
+ ids2[1] = first ? ids2[0] : idx;
284
+ if (first) {
285
+ dis2[0] = dis;
286
+ ids2[0] = idx;
287
+ }
288
+ }
289
+ }
290
+
291
+ /** Top-2 search results: query i's two best results, best first, are stored
292
+ * at dis_tab[2 * i] and ids_tab[2 * i]. Queries with fewer than two results
293
+ * get C::neutral() and id -1. Results are admitted as in the heaps (strict
294
+ * comparison against the current second best, so NaN is never admitted) and
295
+ * equal distances are ordered as in top2_insert, so the results match the
296
+ * heap handler's.
297
+ */
298
+ template <class C, bool use_sel = false>
299
+ struct Top2BlockResultHandler : TopkBlockResultHandler<C, use_sel> {
300
+ using T = typename C::T;
301
+ using TI = typename C::TI;
302
+ using BlockResultHandler<C, use_sel>::i0;
303
+ using BlockResultHandler<C, use_sel>::i1;
304
+
305
+ Top2BlockResultHandler(
306
+ size_t nq_,
307
+ T* dis_tab_,
308
+ TI* ids_tab_,
309
+ const IDSelector* sel_ = nullptr)
310
+ : TopkBlockResultHandler<C, use_sel>(
311
+ nq_,
312
+ dis_tab_,
313
+ ids_tab_,
314
+ 2,
315
+ sel_) {}
316
+
317
+ struct SingleResultHandler : ResultHandlerT<C> {
318
+ Top2BlockResultHandler& hr;
319
+ using ResultHandlerT<C>::threshold;
320
+
321
+ T dis2[2];
322
+ TI ids2[2];
323
+ size_t current_idx = 0;
324
+
325
+ explicit SingleResultHandler(Top2BlockResultHandler& hr_) : hr(hr_) {}
326
+
327
+ /// begin results for query # i
328
+ void begin(const size_t current_idx_2) {
329
+ current_idx = current_idx_2;
330
+ threshold = dis2[0] = dis2[1] = C::neutral();
331
+ ids2[0] = ids2[1] = -1;
332
+ }
333
+
334
+ /// add one result for query i; threshold is the second best
335
+ bool add_result(T dis, TI idx) final {
336
+ if (C::cmp(threshold, dis)) {
337
+ top2_insert<C>(dis, idx, dis2, ids2);
338
+ threshold = dis2[1];
339
+ return true;
340
+ }
341
+ return false;
342
+ }
343
+
344
+ /// series of results for query i is done
345
+ void end() {
346
+ std::copy(dis2, dis2 + 2, hr.dis_tab + 2 * current_idx);
347
+ std::copy(ids2, ids2 + 2, hr.ids_tab + 2 * current_idx);
348
+ }
349
+ };
350
+
351
+ /// begin
352
+ void begin_multiple(size_t i0_in, size_t i1_in) final {
353
+ this->i0 = i0_in;
354
+ this->i1 = i1_in;
355
+ std::fill(this->dis_tab + 2 * i0, this->dis_tab + 2 * i1, C::neutral());
356
+ std::fill(this->ids_tab + 2 * i0, this->ids_tab + 2 * i1, TI(-1));
357
+ }
358
+
359
+ /// add results for query i0..i1 and j0..j1
360
+ /// Implemented in result_handler.cpp; dispatches via
361
+ /// with_selected_simd_levels to top2_add_results_tpl<C, use_sel, SL>.
362
+ void add_results(size_t j0, size_t j1, const T* dis_tab_2) final;
363
+ };
364
+
259
365
  /*****************************************************************
260
366
  * Heap based result handler
261
367
  *****************************************************************/
@@ -725,6 +831,9 @@ typename Consumer::T dispatch_knn_ResultHandler(
725
831
  if (k == 1) { \
726
832
  Top1BlockResultHandler<C, use_sel> res(nx, vals, ids, sel); \
727
833
  return consumer.template f<>(res, args...); \
834
+ } else if (k == 2) { \
835
+ Top2BlockResultHandler<C, use_sel> res(nx, vals, ids, sel); \
836
+ return consumer.template f<>(res, args...); \
728
837
  } else if (k < static_cast<size_t>(distance_compute_min_k_reservoir)) { \
729
838
  HeapBlockResultHandler<C, use_sel> res(nx, vals, ids, k, sel); \
730
839
  return consumer.template f<>(res, args...); \
@@ -792,6 +901,13 @@ void top1_add_results_tpl(
792
901
  size_t j1,
793
902
  const typename C::T* dis_tab);
794
903
 
904
+ template <class C, bool use_sel, SIMDLevel SL>
905
+ void top2_add_results_tpl(
906
+ Top2BlockResultHandler<C, use_sel>* self,
907
+ size_t j0,
908
+ size_t j1,
909
+ const typename C::T* dis_tab);
910
+
795
911
  template <class C, bool use_sel, SIMDLevel SL>
796
912
  void reservoir_add_results_tpl(
797
913
  ReservoirBlockResultHandler<C, use_sel>* self,