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,281 @@
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 <faiss/impl/optimal_kmeans/OptimalKMeans.h>
11
+
12
+ #include <cstddef>
13
+ #include <cstdint>
14
+ #include <memory>
15
+ #include <string>
16
+ #include <vector>
17
+
18
+ /** Compressed intermediate tables of the optimal k-means
19
+ * (contrib/optimal_kmeans/07_compressed.md).
20
+ *
21
+ * A table of 2^n entries is cut into blocks of 2^L entries. In each block, a
22
+ * fraction of the entries is stored exactly (cost and split); every other
23
+ * entry is replaced by a lower bound
24
+ *
25
+ * off(z) + gmin[group(z)] + code[z] * step[group(z)]
26
+ *
27
+ * rounded down to float32, where off(z) is an offset model (one value per
28
+ * popcount of z, plus a sum of point offsets o[j] over the bits j of z),
29
+ * gmin and step are per group of entries and code has q bits. An entry of a
30
+ * combination is exact when its winning split uses two exact entries; the
31
+ * others are recomputed when needed (OptimalKMeansExactEngine).
32
+ */
33
+
34
+ namespace faiss {
35
+
36
+ struct IOReader;
37
+ struct IOWriter;
38
+
39
+ /** Fixed layout of the blocks of 2^L entries: groups and code size.
40
+ *
41
+ * Group of an entry z: z is split into its sub-block t = z >> sub_bits and
42
+ * w = z & (2^sub_bits - 1). Within a sub-block, the entries of equal popcount
43
+ * are taken in increasing order and cut into groups of g entries. */
44
+ struct OptimalKMeansCodec {
45
+ int L = 0; ///< log2 of the block size
46
+ int g = 64; ///< entries per group
47
+ int q = 4; ///< bits per code: 0 (no code), 1, 2, 4 or 8
48
+ int sub_bits = 16; ///< log2 of the sub-blocks (min(sub_bits, L) is used)
49
+
50
+ // derived
51
+ int sb = 0; ///< min(sub_bits, L)
52
+ int L1 = 0; ///< low half of the offset model (L / 2)
53
+ size_t groups_per_sub = 0; ///< groups of a sub-block
54
+ size_t ngroups = 0; ///< groups of a block
55
+ std::vector<uint32_t> class_off; ///< first group of each popcount of w
56
+ std::vector<uint32_t> binom; ///< binomial coefficients C(i, j), 33 x 33
57
+
58
+ OptimalKMeansCodec() {}
59
+ OptimalKMeansCodec(int L, int g = 64, int q = 4, int sub_bits = 16);
60
+
61
+ /// group of entry z
62
+ uint32_t group(uint32_t z) const;
63
+ /// bytes of the codes of a block
64
+ size_t code_bytes() const;
65
+ };
66
+
67
+ /** One compressed block. The exact entries are listed by offset in an
68
+ * Elias-Fano code (low parts of ef_lbits bits packed in ef_lo, high parts in
69
+ * unary in the bit array ef_hi). */
70
+ struct OptimalKMeansCompressedBlock {
71
+ std::vector<double> C; ///< offset of each popcount (L + 1)
72
+ std::vector<float> gmin; ///< lower end of each group
73
+ std::vector<float> step; ///< code step of each group (q > 0)
74
+ std::vector<uint8_t> codes; ///< q bits per entry
75
+ // exact entries
76
+ uint64_t k = 0; ///< number of exact entries
77
+ int ef_lbits = 0; ///< low bits of the Elias-Fano code
78
+ std::vector<uint32_t> ef_lo; ///< packed low parts (+ 1 padding word)
79
+ std::vector<uint64_t> ef_hi; ///< unary high parts (+ 1 padding word)
80
+ std::vector<uint32_t> ef_samples; ///< start of every 64th bucket in ef_hi
81
+ std::vector<float> e_cost; ///< costs of the exact entries
82
+ std::vector<uint64_t> e_split; ///< splits of the exact entries
83
+ /// all the costs of the block are >= +0: the bounds are clamped to >= 0
84
+ bool clamp = false;
85
+ uint64_t ncert = 0; ///< certified entries (the exact ones are among them)
86
+
87
+ /// index of entry z among the exact entries, or -1
88
+ int64_t find(uint32_t z) const;
89
+ /// offsets of the exact entries (decoded Elias-Fano list)
90
+ std::vector<uint32_t> exact_offsets() const;
91
+ /// memory used by the block
92
+ size_t nbytes() const;
93
+
94
+ /// serialization (without e_split)
95
+ void write(IOWriter* f) const;
96
+ void read(IOReader* f);
97
+ };
98
+
99
+ struct OptimalKMeansDiskCacheState;
100
+
101
+ /** Memory budget of the blocks of levels stored on disk (09_disk_cache.md),
102
+ * shared by the levels of a run: the blocks loaded from their files (or
103
+ * just encoded) stay in memory until the budget is exceeded, then the
104
+ * oldest ones are released. */
105
+ struct OptimalKMeansDiskCache {
106
+ explicit OptimalKMeansDiskCache(size_t max_bytes = size_t(64) << 30);
107
+
108
+ size_t max_bytes;
109
+
110
+ size_t bytes() const; ///< blocks in memory
111
+ size_t peak_bytes() const; ///< maximum of bytes()
112
+ uint64_t loads() const; ///< blocks read from their files
113
+
114
+ std::shared_ptr<OptimalKMeansDiskCacheState> state;
115
+ };
116
+
117
+ struct OptimalKMeansLevelStorage;
118
+
119
+ /** A compressed table: the combination a + b -> c, 2^n entries in blocks
120
+ * of 2^codec.L. The blocks are filled by optimal_kmeans_encode_block
121
+ * (concurrent calls for different blocks are allowed). */
122
+ struct OptimalKMeansCompressedLevel {
123
+ int c = 0, a = 0, b = 0;
124
+ int n = 0, L = 0;
125
+ OptimalKMeansCodec codec;
126
+ std::vector<double> o; ///< point offsets of the offset model (L)
127
+ /// the 2^(n - L) blocks, if the level is in RAM
128
+ std::vector<OptimalKMeansCompressedBlock> blocks;
129
+
130
+ OptimalKMeansCompressedLevel() {}
131
+ OptimalKMeansCompressedLevel(
132
+ int c,
133
+ int a,
134
+ int b,
135
+ int n,
136
+ const OptimalKMeansCodec& codec);
137
+
138
+ /// point offsets of the level, before the first block is encoded
139
+ void set_offsets(const double* o);
140
+
141
+ /** Store the blocks in files of the directory dir (it must exist) instead
142
+ * of RAM: block s in dir/b<s>.blk, the splits of its exact entries in
143
+ * dir/b<s>.spl. The blocks are loaded on demand, within the budget of
144
+ * the cache. Before the first block is stored. */
145
+ void set_disk_cache(const char* dir, OptimalKMeansDiskCache* cache);
146
+ std::string dir; ///< empty: the level is in RAM
147
+
148
+ /// store block s (called by optimal_kmeans_encode_block; blk is moved)
149
+ void store_block(uint64_t s, OptimalKMeansCompressedBlock& blk);
150
+
151
+ #ifndef SWIG
152
+ /** Block s (read from its file if needed). The block stays valid while
153
+ * the pointer is held, even if the cache releases it. */
154
+ std::shared_ptr<const OptimalKMeansCompressedBlock> get_block(
155
+ uint64_t s) const;
156
+ #endif
157
+ /** Release block s from memory (disk mode, no-op in RAM mode): the
158
+ * combinations do not read it any more. It is read again from its file
159
+ * if needed (final step). */
160
+ void drop_block(uint64_t s);
161
+
162
+ /// split of the exact entry i of block s
163
+ uint64_t exact_split(uint64_t s, int64_t i) const;
164
+
165
+ /** Block s with the splits of its exact entries, serialized (to send it
166
+ * to another machine, 10_distributed.md). */
167
+ void serialize_block(uint64_t s, std::vector<uint8_t>& data) const;
168
+ /// store block s from the nbytes of data of serialize_block
169
+ void store_serialized_block(uint64_t s, size_t nbytes, const uint8_t* data);
170
+ /// sum of the point offsets of the bits of z (low half + high half)
171
+ double low_sum(uint32_t z) const;
172
+
173
+ /// stored value of entry Y (the cost if exact, else a lower bound)
174
+ float lower(uint64_t Y, bool* exact = nullptr) const;
175
+ bool is_exact(uint64_t Y) const;
176
+
177
+ size_t nbytes() const;
178
+ uint64_t nexact() const;
179
+ uint64_t ncert() const;
180
+ /// every block is clamped (all costs >= +0)
181
+ bool nonneg() const;
182
+
183
+ /// tables of low_sum (low and high halves of z)
184
+ std::vector<double> tlo, thi;
185
+ /// per block, set by store_block: exact entries, certified entries,
186
+ /// bytes, clamp flag
187
+ std::vector<uint64_t> block_k, block_ncert, block_nbytes;
188
+ std::vector<uint8_t> block_clamp;
189
+ std::shared_ptr<OptimalKMeansLevelStorage> storage; ///< disk mode
190
+ };
191
+
192
+ /** Lower bound of an entry from its offset, group bounds and code. */
193
+ float optimal_kmeans_lower_bound(
194
+ double off,
195
+ float gmin,
196
+ float step,
197
+ int code,
198
+ int q,
199
+ bool clamp);
200
+
201
+ /** Compress the block s of level `level` from its combination result
202
+ * (cost, split: 2^L entries).
203
+ *
204
+ * @param in_a, in_b input levels of the combination, for the
205
+ * certification; nullptr: T1 (every entry exact)
206
+ * @param f fraction of the entries stored exactly (chosen among
207
+ * the certified entries)
208
+ * @param final_other optional, for the last stored level: the other term of
209
+ * the final candidates, final_other[z] = B[U ^ S] for
210
+ * the entry S = (s << L) | z (U: the full set, B: the
211
+ * other table of the final combination). The exact
212
+ * entries are then those with the smallest final
213
+ * candidate value cost[z] + final_other[z], instead of
214
+ * the smallest residuals per popcount.
215
+ */
216
+ void optimal_kmeans_encode_block(
217
+ OptimalKMeansCompressedLevel* level,
218
+ uint64_t s,
219
+ const float* cost,
220
+ const uint64_t* split,
221
+ const OptimalKMeansCompressedLevel* in_a,
222
+ const OptimalKMeansCompressedLevel* in_b,
223
+ double f,
224
+ const float* final_other = nullptr);
225
+
226
+ /** Decoded values of block s (2^L floats) and optionally the mask of the
227
+ * exact entries. */
228
+ void optimal_kmeans_decode_block(
229
+ const OptimalKMeansCompressedLevel& level,
230
+ uint64_t s,
231
+ float* out,
232
+ uint8_t* exact = nullptr);
233
+
234
+ /** Parameters of the exact recomputation. */
235
+ struct OptimalKMeansExactEngineParams {
236
+ /// candidates of a row kept in memory at a time (larger rows take
237
+ /// several passes)
238
+ size_t max_candidates = size_t(1) << 22;
239
+ /// memory of the decoded blocks (rows over large sets decode whole
240
+ /// blocks)
241
+ size_t cache_bytes = size_t(16) << 30;
242
+ /// threads of the rows over large sets (0: OpenMP default)
243
+ int nthreads = 0;
244
+
245
+ OptimalKMeansExactEngineParams() {}
246
+ };
247
+
248
+ struct OptimalKMeansExactEngineState;
249
+
250
+ /** Exact values of the entries of compressed levels: rows over the level
251
+ * below, branch and bound with the stored lower bounds, recursive down to
252
+ * T1. The values computed are memoized. */
253
+ struct OptimalKMeansExactEngine {
254
+ /// t1: the single-cluster costs; levels in blocks of 2^L entries
255
+ OptimalKMeansExactEngine(
256
+ const OptimalKMeansCost1* t1,
257
+ int n,
258
+ int L,
259
+ const OptimalKMeansExactEngineParams& params =
260
+ OptimalKMeansExactEngineParams());
261
+ ~OptimalKMeansExactEngine();
262
+
263
+ /// make a level available (not owned; it must be complete and stay
264
+ /// valid while the engine is used)
265
+ void add_level(const OptimalKMeansCompressedLevel* level);
266
+
267
+ /** Row min over L subset of Y of (A[L] + B[Y ^ L], L), exact, with A
268
+ * the table of level a and B of level b (level 1 is T1). */
269
+ void row(uint64_t Y, int a, int b, float* cost, uint64_t* split);
270
+
271
+ /// exact cost and split of entry Y of level c
272
+ void value(int c, uint64_t Y, float* cost, uint64_t* split);
273
+
274
+ /// rows recomputed in level c so far
275
+ uint64_t rows(int c) const;
276
+
277
+ OptimalKMeansExactEngineParams params;
278
+ std::shared_ptr<OptimalKMeansExactEngineState> state;
279
+ };
280
+
281
+ } // namespace faiss
@@ -115,7 +115,7 @@ bool ReservoirRef::offer(int32_t id, uint16_t hash, uint16_t key) {
115
115
  return true;
116
116
  }
117
117
 
118
- Hyperplanes::Hyperplanes(int d, int m, int64_t seed) : d(d), m(m) {
118
+ Hyperplanes::Hyperplanes(int d_in, int m_in, int64_t seed) : d(d_in), m(m_in) {
119
119
  FAISS_THROW_IF_NOT_FMT(d >= 1, "Hyperplanes: d must be >= 1, got %d", d);
120
120
  FAISS_THROW_IF_NOT_FMT(
121
121
  m >= 1 && m <= 16, "Hyperplanes: m must be in [1, 16], got %d", m);
@@ -9,8 +9,10 @@
9
9
 
10
10
  // basic int types and size_t
11
11
  #include <atomic>
12
+ #include <cerrno>
12
13
  #include <cstdint>
13
14
  #include <cstdio>
15
+ #include <type_traits>
14
16
 
15
17
  #ifdef _WIN32
16
18
 
@@ -36,9 +38,6 @@
36
38
  (((*(p)) = _aligned_malloc((s), (a))), *(p) ? 0 : errno)
37
39
  #define posix_memalign_free _aligned_free
38
40
 
39
- // aligned should be in front of the declaration
40
- #define ALIGNED(x) __declspec(align(x))
41
-
42
41
  // redefine the GCC intrinsics with Windows equivalents
43
42
  #ifdef _MSC_VER
44
43
 
@@ -105,14 +104,6 @@ inline int __builtin_clzll(uint64_t x) {
105
104
  #endif // _MSC_VER
106
105
 
107
106
  #define FAISS_ALWAYS_INLINE __forceinline
108
-
109
- // MSVC uses pragma pack instead of __attribute__((packed))
110
- // Use FAISS_PACK_STRUCTS_BEGIN/END to wrap packed structure definitions
111
- #define FAISS_PACKED
112
- #define FAISS_RESTRICT __restrict
113
- #define FAISS_PACK_STRUCTS_BEGIN __pragma(pack(push, 1))
114
- #define FAISS_PACK_STRUCTS_END __pragma(pack(pop))
115
-
116
107
  #else
117
108
  /*******************************************************
118
109
  * Linux and OSX
@@ -121,22 +112,6 @@ inline int __builtin_clzll(uint64_t x) {
121
112
  #define FAISS_API
122
113
  #define posix_memalign_free free
123
114
 
124
- // aligned should be *in front* of the declaration, for compatibility with
125
- // windows
126
- #ifdef SWIG
127
- #define ALIGNED(x)
128
- #define FAISS_PACKED
129
- #define FAISS_RESTRICT
130
- #else
131
- #define ALIGNED(x) __attribute__((aligned(x)))
132
- #define FAISS_PACKED __attribute__((packed))
133
- #define FAISS_RESTRICT __restrict
134
- #endif
135
-
136
- // On non-Windows, FAISS_PACKED handles packing, so these are no-ops
137
- #define FAISS_PACK_STRUCTS_BEGIN
138
- #define FAISS_PACK_STRUCTS_END
139
-
140
115
  #define FAISS_ALWAYS_INLINE __attribute__((always_inline)) inline
141
116
 
142
117
  #endif
@@ -167,7 +142,24 @@ inline void atomic_fetch_add_relaxed(T& target, T value) {
167
142
  #if defined(__cpp_lib_atomic_ref) && __cpp_lib_atomic_ref >= 201806L
168
143
  std::atomic_ref<T>(target).fetch_add(value, std::memory_order_relaxed);
169
144
  #else
170
- __atomic_fetch_add(&target, value, __ATOMIC_RELAXED);
145
+ if constexpr (std::is_floating_point_v<T>) {
146
+ // The _n builtins reject a floating-point type, so accumulate with the
147
+ // generic compare-exchange builtin instead.
148
+ T expected;
149
+ __atomic_load(&target, &expected, __ATOMIC_RELAXED);
150
+ T desired;
151
+ do {
152
+ desired = expected + value;
153
+ } while (!__atomic_compare_exchange(
154
+ &target,
155
+ &expected,
156
+ &desired,
157
+ true,
158
+ __ATOMIC_RELAXED,
159
+ __ATOMIC_RELAXED));
160
+ } else {
161
+ __atomic_fetch_add(&target, value, __ATOMIC_RELAXED);
162
+ }
171
163
  #endif
172
164
  }
173
165
 
@@ -229,6 +221,33 @@ inline void atomic_fetch_add_relaxed(T& target, T value) {
229
221
 
230
222
  // clang-format on
231
223
 
224
+ /*******************************************************
225
+ * Packing and alignment
226
+ *******************************************************/
227
+
228
+ // ALIGNED goes *in front* of the declaration, for compatibility with MSVC.
229
+ // swigfaiss.swig defines _MSC_VER under SWIGWIN, so check SWIG first.
230
+ #if defined(SWIG)
231
+ #define ALIGNED(x)
232
+ #define FAISS_PACKED
233
+ #define FAISS_RESTRICT
234
+ #define FAISS_PACK_STRUCTS_BEGIN
235
+ #define FAISS_PACK_STRUCTS_END
236
+ #elif defined(_MSC_VER) // MSVC and clang-cl
237
+ #define ALIGNED(x) __declspec(align(x))
238
+ // Wrap packed structs in FAISS_PACK_STRUCTS_BEGIN/END for MSVC.
239
+ #define FAISS_PACKED
240
+ #define FAISS_RESTRICT __restrict
241
+ #define FAISS_PACK_STRUCTS_BEGIN __pragma(pack(push, 1))
242
+ #define FAISS_PACK_STRUCTS_END __pragma(pack(pop))
243
+ #else // GCC and Clang, including MinGW
244
+ #define ALIGNED(x) __attribute__((aligned(x)))
245
+ #define FAISS_PACKED __attribute__((packed))
246
+ #define FAISS_RESTRICT __restrict
247
+ #define FAISS_PACK_STRUCTS_BEGIN
248
+ #define FAISS_PACK_STRUCTS_END
249
+ #endif
250
+
232
251
  /*******************************************************
233
252
  * BIGENDIAN specific macros
234
253
  *******************************************************/
@@ -75,6 +75,11 @@ struct WrappedSearchResult {
75
75
  }
76
76
  };
77
77
 
78
+ /** Below this many codes, pq_distances_8bit_by_block is slower than the
79
+ * per-code kernel: each sum in memory waits for the store of the previous
80
+ * group of sub-quantizers. */
81
+ constexpr size_t kPQBlockMinCodes = 16;
82
+
78
83
  /** For each sub-quantizer, a block of codes reads one 1 KB table slice, which
79
84
  * stays in L1; code by code, a table larger than L1 makes every lookup an L1
80
85
  * miss. SL as in PQCodeDistanceScalar. */
@@ -540,7 +545,7 @@ struct IVFPQScanner : IVFPQScannerT<idx_t, METRIC_TYPE, PQCodeDist>,
540
545
  if constexpr (
541
546
  has_scalar_8bit_kernel<THE_SIMD_LEVEL>() &&
542
547
  std::is_same_v<typename PQCodeDist::PQDecoder, PQDecoder8>) {
543
- if (precompute_mode == 2 &&
548
+ if (precompute_mode == 2 && n >= kPQBlockMinCodes &&
544
549
  (SIMDConfig::scalar_gather || this->pq.M <= 64)) {
545
550
  pq_distances_8bit_by_block<THE_SIMD_LEVEL>(
546
551
  this->pq.M,
@@ -67,33 +67,33 @@ void QueryTables::init_query_L2() {
67
67
  }
68
68
 
69
69
  float QueryTables::precompute_list_tables() {
70
- float dis0 = 0;
70
+ float local_dis0 = 0;
71
71
  uint64_t t0;
72
72
  TIC;
73
73
  if (by_residual) {
74
74
  if (metric_type == METRIC_INNER_PRODUCT) {
75
- dis0 = precompute_list_tables_IP();
75
+ local_dis0 = precompute_list_tables_IP();
76
76
  } else {
77
- dis0 = precompute_list_tables_L2();
77
+ local_dis0 = precompute_list_tables_L2();
78
78
  }
79
79
  }
80
80
  init_list_cycles += TOC;
81
- return dis0;
81
+ return local_dis0;
82
82
  }
83
83
 
84
84
  float QueryTables::precompute_list_table_pointers() {
85
- float dis0 = 0;
85
+ float local_dis0 = 0;
86
86
  uint64_t t0;
87
87
  TIC;
88
88
  if (by_residual) {
89
89
  if (metric_type == METRIC_INNER_PRODUCT) {
90
90
  FAISS_THROW_MSG("not implemented");
91
91
  } else {
92
- dis0 = precompute_list_table_pointers_L2();
92
+ local_dis0 = precompute_list_table_pointers_L2();
93
93
  }
94
94
  }
95
95
  init_list_cycles += TOC;
96
- return dis0;
96
+ return local_dis0;
97
97
  }
98
98
 
99
99
  void QueryTables::init_list(idx_t list_no, float coarse_dis_in, int mode) {
@@ -112,7 +112,7 @@ float QueryTables::precompute_list_tables_IP() {
112
112
  // and dis0, the initial value
113
113
  ivfpq.quantizer->reconstruct(key, decoded_vec);
114
114
  // decoded_vec = centroid
115
- float dis0 = fvec_inner_product_dispatch(qi, decoded_vec, d);
115
+ float local_dis0 = fvec_inner_product_dispatch(qi, decoded_vec, d);
116
116
 
117
117
  if (polysemous_ht) {
118
118
  for (int i = 0; i < d; i++) {
@@ -120,11 +120,11 @@ float QueryTables::precompute_list_tables_IP() {
120
120
  }
121
121
  pq.compute_code(residual_vec, q_code.data());
122
122
  }
123
- return dis0;
123
+ return local_dis0;
124
124
  }
125
125
 
126
126
  float QueryTables::precompute_list_tables_L2() {
127
- float dis0 = 0;
127
+ float local_dis0 = 0;
128
128
 
129
129
  if (use_precomputed_table == 0 || use_precomputed_table == -1) {
130
130
  ivfpq.quantizer->compute_residual(qi, residual_vec, key);
@@ -135,7 +135,7 @@ float QueryTables::precompute_list_tables_L2() {
135
135
  }
136
136
 
137
137
  } else if (use_precomputed_table == 1) {
138
- dis0 = coarse_dis;
138
+ local_dis0 = coarse_dis;
139
139
 
140
140
  fvec_madd_dispatch(
141
141
  pq.M * pq.ksub,
@@ -150,7 +150,7 @@ float QueryTables::precompute_list_tables_L2() {
150
150
  }
151
151
 
152
152
  } else if (use_precomputed_table == 2) {
153
- dis0 = coarse_dis;
153
+ local_dis0 = coarse_dis;
154
154
 
155
155
  const MultiIndexQuantizer* miq =
156
156
  dynamic_cast<const MultiIndexQuantizer*>(ivfpq.quantizer);
@@ -188,14 +188,14 @@ float QueryTables::precompute_list_tables_L2() {
188
188
  }
189
189
  }
190
190
 
191
- return dis0;
191
+ return local_dis0;
192
192
  }
193
193
 
194
194
  float QueryTables::precompute_list_table_pointers_L2() {
195
- float dis0 = 0;
195
+ float local_dis0 = 0;
196
196
 
197
197
  if (use_precomputed_table == 1) {
198
- dis0 = coarse_dis;
198
+ local_dis0 = coarse_dis;
199
199
 
200
200
  const float* s = ivfpq.precomputed_table.data() + key * pq.ksub * pq.M;
201
201
  for (size_t m = 0; m < pq.M; m++) {
@@ -203,7 +203,7 @@ float QueryTables::precompute_list_table_pointers_L2() {
203
203
  s += pq.ksub;
204
204
  }
205
205
  } else if (use_precomputed_table == 2) {
206
- dis0 = coarse_dis;
206
+ local_dis0 = coarse_dis;
207
207
 
208
208
  const MultiIndexQuantizer* miq =
209
209
  dynamic_cast<const MultiIndexQuantizer*>(ivfpq.quantizer);
@@ -237,7 +237,7 @@ float QueryTables::precompute_list_table_pointers_L2() {
237
237
  // avoid with the tables pointers.
238
238
  }
239
239
 
240
- return dis0;
240
+ return local_dis0;
241
241
  }
242
242
 
243
243
  } // namespace pq_code_distance
@@ -22,6 +22,12 @@ namespace faiss {
22
22
  constexpr int TOP1_SIMD_LEVELS = (1 << int(SIMDLevel::NONE)) |
23
23
  (1 << int(SIMDLevel::AVX2)) | (1 << int(SIMDLevel::AVX512));
24
24
 
25
+ // Top-2: scalar fallback + AVX2 (8 lanes of best and second best), for CMax
26
+ // only: the AVX2 lanes keep the first of equal distances, which matches the
27
+ // CMax order of ids but not the CMin one.
28
+ constexpr int TOP2_SIMD_LEVELS =
29
+ (1 << int(SIMDLevel::NONE)) | (1 << int(SIMDLevel::AVX2));
30
+
25
31
  // Reservoir: scalar fallback + AVX512 compress path.
26
32
  // VPCOMPRESSPS/VPCOMPRESSD require AVX512F so there is no AVX2 path.
27
33
  // On non-AVX512 hosts the dispatch falls back to NONE automatically.
@@ -43,7 +49,8 @@ void top1_add_results_none(
43
49
  using T = typename C::T;
44
50
  using TI = typename C::TI;
45
51
 
46
- for (size_t qi = self->i0; qi < self->i1; qi++) {
52
+ #pragma omp parallel for if (self->i1 - self->i0 >= 16)
53
+ for (int64_t qi = self->i0; qi < static_cast<int64_t>(self->i1); qi++) {
47
54
  const T* dis_tab_i = dis_tab_in + (j1 - j0) * (qi - self->i0) - j0;
48
55
 
49
56
  // Hoist best_dis / best_idx into locals so the compiler keeps them in
@@ -63,6 +70,26 @@ void top1_add_results_none(
63
70
  }
64
71
  }
65
72
 
73
+ template <class C, bool use_sel>
74
+ void top2_add_results_none(
75
+ Top2BlockResultHandler<C, use_sel>* self,
76
+ size_t j0,
77
+ size_t j1,
78
+ const float* dis_tab_in) {
79
+ using TI = typename C::TI;
80
+ #pragma omp parallel for if (self->i1 - self->i0 >= 16)
81
+ for (int64_t qi = self->i0; qi < static_cast<int64_t>(self->i1); qi++) {
82
+ const float* dis_tab_i = dis_tab_in + (j1 - j0) * (qi - self->i0) - j0;
83
+ float* dis2 = self->dis_tab + 2 * qi;
84
+ TI* ids2 = self->ids_tab + 2 * qi;
85
+ for (size_t j = j0; j < j1; j++) {
86
+ if (C::cmp(dis2[1], dis_tab_i[j]) && self->is_in_selection(j)) {
87
+ top2_insert<C>(dis_tab_i[j], TI(j), dis2, ids2);
88
+ }
89
+ }
90
+ }
91
+ }
92
+
66
93
  template <class C, bool use_sel>
67
94
  void reservoir_add_results_none(
68
95
  ReservoirBlockResultHandler<C, use_sel>* self,
@@ -119,6 +146,14 @@ void reservoir_add_results_none(
119
146
  top1_add_results_none<C, use_sel>(self, j0, j1, dis_tab); \
120
147
  } \
121
148
  template <> \
149
+ void top2_add_results_tpl<C, use_sel, SIMDLevel::NONE>( \
150
+ Top2BlockResultHandler<C, use_sel> * self, \
151
+ size_t j0, \
152
+ size_t j1, \
153
+ const float* dis_tab) { \
154
+ top2_add_results_none<C, use_sel>(self, j0, j1, dis_tab); \
155
+ } \
156
+ template <> \
122
157
  void reservoir_add_results_tpl<C, use_sel, SIMDLevel::NONE>( \
123
158
  ReservoirBlockResultHandler<C, use_sel> * self, \
124
159
  size_t j0, \
@@ -152,6 +187,21 @@ void Top1BlockResultHandler<C, use_sel>::add_results(
152
187
  });
153
188
  }
154
189
 
190
+ template <class C, bool use_sel>
191
+ void Top2BlockResultHandler<C, use_sel>::add_results(
192
+ size_t j0,
193
+ size_t j1,
194
+ const T* dis_tab_2) {
195
+ if constexpr (use_sel || !C::is_max) {
196
+ top2_add_results_tpl<C, use_sel, SIMDLevel::NONE>(
197
+ this, j0, j1, dis_tab_2);
198
+ } else {
199
+ with_selected_simd_levels<TOP2_SIMD_LEVELS>([&]<SIMDLevel SL>() {
200
+ top2_add_results_tpl<C, use_sel, SL>(this, j0, j1, dis_tab_2);
201
+ });
202
+ }
203
+ }
204
+
155
205
  template <class C, bool use_sel>
156
206
  void ReservoirBlockResultHandler<C, use_sel>::add_results(
157
207
  size_t j0,
@@ -183,6 +233,23 @@ template void Top1BlockResultHandler<CMin<float, int64_t>, true>::add_results(
183
233
  size_t,
184
234
  const float*);
185
235
 
236
+ template void Top2BlockResultHandler<CMax<float, int64_t>, false>::add_results(
237
+ size_t,
238
+ size_t,
239
+ const float*);
240
+ template void Top2BlockResultHandler<CMax<float, int64_t>, true>::add_results(
241
+ size_t,
242
+ size_t,
243
+ const float*);
244
+ template void Top2BlockResultHandler<CMin<float, int64_t>, false>::add_results(
245
+ size_t,
246
+ size_t,
247
+ const float*);
248
+ template void Top2BlockResultHandler<CMin<float, int64_t>, true>::add_results(
249
+ size_t,
250
+ size_t,
251
+ const float*);
252
+
186
253
  template void ReservoirBlockResultHandler<CMax<float, int64_t>, false>::
187
254
  add_results(size_t, size_t, const float*);
188
255
  template void ReservoirBlockResultHandler<CMax<float, int64_t>, true>::